Allure скриншот при ошибке python

automated-testing.info

Загрузка…

  • testomat.io управление авто тестами
  • Python
  • Реклама
  • Работа
  • Консультации
  • Обучение

I’m trying to attach screenshots to allure reports, now I’m using this code:

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    setattr(item, "rep_" + rep.when, rep)
    return rep


@pytest.fixture(scope="function")
def web_browser(request):
    # Open browser:
    b = webdriver.PhantomJS()

    # Return browser instance to test case:
    yield b

    # Do teardown (this code will be executed after each test):

    if request.node.rep_call.failed:
        # Make the screen-shot if test failed:
        try:
            # Make screen-shot for Allure report:
            allure.attach(str(request.function.__name__),
                          b.get_screenshot_as_png(),
                          type=AttachmentType.PNG)
        except:
            pass # just ignore

    # Close browser window:
    b.quit()

but it doesn’t work — I can’t see any screenshots in the reports when some tests failed.

I’ve tried:

allure.attach(request.function.__name__,
              b.get_screenshot_as_png(),
              type=AttachmentType.PNG)

allure.attach('screenshot' + str(uuid.uuid4()),
              b.get_screenshot_as_png(),
              type=allure.attachment_type.PNG)

allure.attach(b.get_screenshot_as_png(),
              name='screenshot',
              type=AttachmentType.PNG)

allure.attach(b.get_screenshot_as_png(),
              name='screenshot2',
              type=allure.attachment_type.PNG)

but nothing of this works…

Показанный ниже код будет автоматически делать скриншоты при неуспехе теста.
Он делает это только для Selenium тестов различая их по имени фикстуры
с Selenium webdriver browser — если вы используете другое имя то вам надо
поправить этот код.

Я использую allure для построения отчетов по тестам и данный код помещает
скриншот в отчет allure.

В итоге вы получите отчет похожий на приведеный на картинке выше.

Вы можете посмотреть на
полный код тестов.

Или узнать как с минимальными усилиями можно развернуть Selenium + Allure
конфигурацию для тестов
из моей статьи.

1 preparation

  1. Install Python
  2. Install pytest: PIP Install Pytest
  3. Install allure-pytest: PIP Install allure-pytest
  4. Install the command line tool:https://docs.qameta.io/allure/#_installing_a_commandline
    After the installation is completed, remember to match the environment variable, the verification is as follows:
  5. Install pycharm
  6. To do web automation: install Chrome browser, download chromedriver driver
  7. Install Selenium: PIP Install Selenium
  8. Create a project, write script
  9. After the test case fails, complete the screenshot and add it to the ALLure attachment
    (1) How to identify the failure of each test case: Use the hook function in pytest:pytest_runtest_makereport(item, call)
    (2) CONFTEST.PY implements the hook function in this file

2 basic method

test_case test.screeenshot.py file:

import allure
from selenium import webdriver
from selenium.webdriver.common.by import By

def test_baidu():
    # Create webdriver
    wd = webdriver.Chrome()
    #    
    wd.get('http://www.baidu.com')
    try:
        # Error code, intentionally failed
        wd.find_element(By.ID, 'xxx')
    except Exception as e:
        # If there are abnormalities during the operation step, then the use case fails, and complete the screenshot operation here
        img = wd.get_screenshot_as_png()
        # Show the screenshot on the Allure test report
        allure.attach(img, 'Failure screenshot', allure.attachment_type.PNG)

    # In the command line, enter the following command in turn:
    # Run pytest test case, generate test data under the ./report/allure-results
    # pytest -sv test_case/test_screenshot.py --alluredir ./report/allure-results --clean-alluredir
    # Find the test data, generate test report
    # allure generate ./report/allure-results -o ./report/allure-report --clean

3 Use the hook function

conftest.py file:

import allure
import pytest
from selenium import webdriver

driver = None   # Define a global DRIVER object

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    # When will the execution results of identifying use cases?
    # Rear treatment yield: indicates that the test case is executed
    outcome = yield
    rep = outcome.get_result()      # Get the results of the test case after completion
    if rep.when == 'call' and rep.failed:   # Judgment use case execution situation: being called and failed
        # Implement a screenshot and add it to the Allure attachment. The screenshot method needs to be used to use the Driver object.
        # If there are abnormalities during the operation step, then the use case fails, and complete the screenshot operation here
        img = driver.get_screenshot_as_png()
        # Show the screenshot on the Allure test report
        allure.attach(img, 'Failure screenshot', allure.attachment_type.PNG)

# Custom FIXTURE implementation of Driver initialization and assignment and return
@pytest.fixture(scope='session', autouse=True)
def init_driver():
    global driver   # Global variable, which is equivalent to assigning the above driver = None
    if driver is None:
        driver = webdriver.Chrome()
    return driver

test_case test.screeenshot.py file:

from selenium.webdriver.common.by import By

def test_baidu(init_driver):
    init_driver.get('http://www.baidu.com')
    init_driver.find_element(By.ID, 'xxx')

I don’t know how to add a plugins to the pytest-allure. I hope you can give me an example. I hope to hook the failure result of the case when the case fails and capture it in the allure report.
My code is as follows: conftest.py

# -*- coding: utf-8 -*-
import pytest
from allure.constants import AttachmentType
from selenium import webdriver

drvier = webdriver.Chrome()

@pytest.mark.hookwrapper(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item):
outcome = yield
rep = outcome.get_result()
setattr(item, "rep_" + rep.when, rep)
if rep.when == 'call':
    if rep.failed:
        png = item.name + '.png'
        pytest.allure.attach(png, drvier.get_screenshot_as_png(), type=AttachmentType.PNG)

The following is Main()

# coding=utf-8
import subprocess

import pytest

from conf import config_path

def action(case):
pytest.main(['-s', '-q', config_path.testcase_path + case+'.py', '--alluredir', config_path.report_path])

command_report = config_path.allurecmd_path +'allure generate ' + config_path.report_path + ' -o ' + config_path.report_path
print(command_report)
progress = subprocess.Popen(command_report, shell=True)
progress.wait()

if __name__ == '__main__':
   action('Login_test')

I hope you can help me solve this problem. thanks!

Понравилась статья? Поделить с друзьями:
  • Alight motion ошибка при проверки ссылки
  • Aliexpress ошибка таможенного оформления что
  • Aliexpress ошибка при оплате картой
  • Aliens vs predator ошибка при установке
  • Aliens vs predator dx11 ошибка