获取测试用例的执行状态,可以知道每个测试用例执行成功还是失败,或者是跳过,有了这些信息,我们可以做:
- 自己定制测试报告
- 当用例失败的时候截图。
参考 pytest 官网文档 https://docs.pytest.org/en/6.2.x/example/simple.html#making-test-result-information-available-in-fixtures
定义conftest.py 文件
编写conftest.py 文件
import pytest@pytest.hookimpl(tryfirst=True, hookwrapper=True)def pytest_runtest_makereport(item, call):# execute all other hooks to obtain the report objectoutcome = yield# 获取用例的执行结果rep = outcome.get_result()# 将执行结果保存到 item 属性中 req.when 执行时setattr(item, "rep_" + rep.when, rep)# 默认是function级别 执行测试用例的时候会自动调用@pytest.fixture(scope='function',autouse=True)def something(request):yield# 当用例执行失败的操作:if request.node.rep_call.failed:print("用例执行失败", request.node.nodeid)
编写测试用例文件
自动化测试用例文件不受影响,和原来的写法一致
def test_a():assert 1==2def test_b():assert 2==2
运行测试用例文件时候, 可以拿到结果。
app自动化错误时截图
根据上面的代码,来实现app执行失败时截图操作。
conftest.py 添加代码
from appium import webdriverimport pytestimport osfrom appium.webdriver.webdriver import WebDriverchromedriver= os.path.join(os.path.dirname(os.path.abspath(__file__)),'drivers/chromedriver.exe')@pytest.fixture(scope='session',autouse=True)def driver():desired_caps = {'platformName': 'Android', # 测试Android系统'platformVersion': '7.1.2', # Android版本 可以在手机的设置中关于手机查看'deviceName': '127.0.0.1:62001', # adb devices 命令查看 设置为自己的设备'automationName': 'UiAutomator2', # 自动化引擎'noReset': False, # 不要重置app的状态'fullReset': False, # 不要清理app的缓存数据'chromedriverExecutable': chromedriver, # chromedriver 对应的绝对路径'appPackage': "org.cnodejs.android.md", # 应用的包名'appActivity': ".ui.activity.LaunchActivity" # 应用的活动页名称}driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps)driver.implicitly_wait(5) # 全局的隐式等待时间yield driver # 将driver 传递出来driver.quit()@pytest.hookimpl(tryfirst=True, hookwrapper=True)def pytest_runtest_makereport(item, call):# execute all other hooks to obtain the report objectoutcome = yield# 获取用例的执行结果rep = outcome.get_result()# 将执行结果保存到 item 属性中 req.when 执行时setattr(item, "rep_" + rep.when, rep)@pytest.fixture(scope='function',autouse=True)def case_run(driver:webdriver,request):"""每个测试用例执行完成之后,如果执行失败截图,截图的名称为测试用例名称+时间格式:param request::return:"""yieldif request.node.rep_call.failed:import os,timescreenshots = os.path.join(os.path.dirname(os.path.abspath(__file__)),'screeshots')if not os.path.exists(screenshots):os.mkdir(screenshots)casename:str = request.node.nodeidprint("执行测试用例的名字:",casename)# 测试用例的名字# casename = casename.replace('.py::','_')filename = time.strftime('%Y_%m_%d_%H_%M_%S')+".png"screenshot_file = os.path.join(screenshots,filename)# 保存截图driver.save_screenshot(screenshot_file)

