gpt4 book ai didi

python - 如何使用 PyTest 在测试用例失败时捕获屏幕截图

转载 作者:行者123 更新时间:2023-12-04 16:45:03 26 4
gpt4 key购买 nike

目前,我正在使用以下解决方案在 PyTest 的每个测试函数结束时截取屏幕截图。如何确保仅在测试失败的情况下才截取屏幕截图?这是一个关于 PyTest 机制的问题。这个问题与 Selenium 或 appium 无关。

我在 Stackoverflow 上发现了类似的问题,但并不完全相同。为其他问题提供的解决方案不能回答我的问题。由于使用 PyTest 截取测试失败的屏幕截图是一个常见问题,因此我认为它值得一个单独且非常具体的答案。

@pytest.fixture(scope="function", autouse=True)
def take_screenshot(self, appium_driver):
yield
time.sleep(1)
current_filename_clean = os.path.basename(__file__).replace("test_", "").replace(".py", "")
current_test_name = os.environ.get("PYTEST_CURRENT_TEST").split(":")[-1].split(" ")[0].replace("test_", "")
appium_driver.get_screenshot_as_file(
f'test_reports/{current_filename_clean}_android_{current_test_name}_{datetime.today().strftime("%Y-%m-%d")}.png')

最佳答案

这是您的 conftest.py 的完整解决方案用于在 docker 容器中 headless 运行的文件:

import time
from datetime import datetime
import pytest
import os
from selenium import webdriver as selenium_webdriver
from selenium.webdriver.chrome.options import Options

# set up webdriver fixture
@pytest.fixture(scope='session')
def selenium_driver(request):
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

driver = selenium_webdriver.Chrome(options=chrome_options)
driver.set_window_size(1920, 1080)
driver.maximize_window()
driver.implicitly_wait(5)

yield driver
driver.quit()

# set up a hook to be able to check if a test has failed
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
# execute all other hooks to obtain the report object
outcome = yield
rep = outcome.get_result()

# set a report attribute for each phase of a call, which can
# be "setup", "call", "teardown"

setattr(item, "rep_" + rep.when, rep)

# check if a test has failed
@pytest.fixture(scope="function", autouse=True)
def test_failed_check(request):
yield
# request.node is an "item" because we use the default
# "function" scope
if request.node.rep_setup.failed:
print("setting up a test failed!", request.node.nodeid)
elif request.node.rep_setup.passed:
if request.node.rep_call.failed:
driver = request.node.funcargs['selenium_driver']
take_screenshot(driver, request.node.nodeid)
print("executing test failed", request.node.nodeid)

# make a screenshot with a name of the test, date and time
def take_screenshot(driver, nodeid):
time.sleep(1)
file_name = f'{nodeid}_{datetime.today().strftime("%Y-%m-%d_%H:%M")}.png'.replace("/","_").replace("::","__")
driver.save_screenshot(file_name)

关于python - 如何使用 PyTest 在测试用例失败时捕获屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60205391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com