获取测试用例的执行状态,可以知道每个测试用例执行成功还是失败,或者是跳过,有了这些信息,我们可以做:
- 自己定制测试报告
- 当用例失败的时候截图。
参考 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 object
outcome = 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==2
def test_b():
assert 2==2
运行测试用例文件时候, 可以拿到结果。
app自动化错误时截图
根据上面的代码,来实现app执行失败时截图操作。
conftest.py 添加代码
from appium import webdriver
import pytest
import os
from appium.webdriver.webdriver import WebDriver
chromedriver= 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 object
outcome = 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:
"""
yield
if request.node.rep_call.failed:
import os,time
screenshots = os.path.join(os.path.dirname(os.path.abspath(__file__)),'screeshots')
if not os.path.exists(screenshots):
os.mkdir(screenshots)
casename:str = request.node.nodeid
print("执行测试用例的名字:",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)