Я проверил эти вопросы о переполнении стека, написанные с использованием Selenium:
screenshot-on-test-case-failure-with- pytest и
сохранение-скриншотов-включая-тест-результаты
Я верю в способ инициализации тестов (
Код: Выделить всё
sync_playwright,browser,contextв conftest .py, чтобы делать снимки экрана после сбоя, но я не совсем разобрался в этом.
Основная цель этого вопроса — успешно получить снимки экрана в случае сбоя.
Мои примеры кода приведены ниже:
Код: Выделить всё
#sauceAutomation.py
from playwright.sync_api import Playwright, Page, expect, sync_playwright
import time
class SaucyAutomation:
def __init__(self):
self.playwright = sync_playwright().start()
self.browser = self.playwright.chromium.launch(headless=False,args=["--start-maximized"])
self.context = self.browser.new_context(no_viewport=False)
self.page = self.context.new_page()
self.environment = None
def login(self, username, password):
self.page.goto("https://www.saucedemo.com/")
self.page.locator("//input[@id='user-name']").fill(username)
self.page.locator("//input[@id='password']").fill(password)
self.page.locator("//input[@id='login-button']").click()
def burgerNavigate(self,menuItem):
self.page.locator("//button[@id='react-burger-menu-btn']").click()
self.page.locator("//a[@id='" + menuItem + "']").click()
def logout(self):
self.burgerNavigate("logout_sidebar_link")
## Done this way I could login and run multiple tests in the same page
# sauceDemo = SaucyAutomation()
# sauceDemo.login("standard_user", "secret_sauce")
def test_LoginLogout():
sauceDemo = SaucyAutomation()
sauceDemo.login("standard_user", "secret_sauce")
time.sleep(2)
sauceDemo.logout()
И вот мои попытки использовать conftest.py:
Код: Выделить всё
#conftest.py
import os.path
import pytest_html
import pytest
from playwright.sync_api import Playwright, Page, expect, sync_playwright
@pytest.fixture(scope="session")
def context(request):
playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False,args=["--start-maximized"])
context = browser.new_context(no_viewport=False)
page = context.new_page()
yield page
@pytest.hookimpl(tryfirst=True,wrapper=True )
def pytest_runtest_makereport(item, call):
pytest_html = item.config.pluginmanager.getplugin("html")
# execute all other hooks to obtain the report object
rep = yield # TestReport Object
screen_file = ''
extras = getattr(rep, "extras", [])
# we only look at actual failing test calls, not setup/teardown
if rep.when == "call" and rep.failed:
mode = "a" if os.path.exists("screenshots") else "w"
with open("screenshots", mode, encoding="utf-8") as f:
# let's also access a fixture for the fun of it
if "tmp_path" in item.fixturenames:
extra = " ({})".format(item.funcargs["tmp_path"])
else:
extra = ""
#page = item.funcargs["page"]
##screenshot_dir = "/screenshots/"
##screenshot_dir.mkdir(exist_ok=True)
#screen_file = item.nodeid + ".png"
#page.screenshot(path=screen_file)
#print("MyDriver = " + str(mydriver))
f.write(rep.nodeid + extra + "\n")
#extras.append(pytest_html.extras.image(screen_file))
return rep
Код: Выделить всё
def context()Код: Выделить всё
initПодробнее здесь: https://stackoverflow.com/questions/787 ... l-case-scr