参数化
- 使用
@pytest.mark.parametrize(argnames, argvalues)
# 多个参数格式为:参数名后面跟对应的参数值
@pytest.mark.parametrize(("value", "result"), [("1111", "1111"), ("2222", "3333")],ids = ["case1","case2"])
pytest
class FooTestCase:
@pytest.mark.parametrize('value', (1, -3, 2, 0))
def test_not_larger_than_two(self, value):
assert value > 2
@pytest.mark.parametrize('a, b', [(2, 1), (10, 5)])
def test_greater(self, a, b):
assert a > b
或者
@pytest.mark.parametrize('value', (1, -3, 2, 0))
def test_not_larger_than_two(value):
assert value > 2
@pytest.mark.parametrize('a, b', [(2, 1), (10, 5)])
def test_greater(a, b):
assert a > b
预期失败
@pytest.mark.parametrize('a, b', [(2, 1), pytest.param(5, 10, marks=pytest.mark.xfail)])
def test_greater(a, b):
assert a > b
-
使用ddt(只有unittest可以用)
@ddt
旨在由TestCase子类使用,pytest运行时报错。
# unittest
import unittest
from ddt import *
@ddt
class FooTestCase(unittest.TestCase):
@data(1, -3, 2, 0)
def test_not_larger_than_two(self, value):
self.assertFalse(value > 2)
@data((2, 1), (10, 5))
def test_greater(self, value):
assert value[0] > value[1]
html格式报告
1、安装pytest-html
pip install pytest-html
2、pytest执行
pytest --html=路径/report.html
3、在当前目录会生成一个report.html的报告文件
报告独立显示(css合并到html中)
pytest --html=路径/report.html --self-contained-html
修改结果表格
from datetime import datetime
from py.xml import html
import pytest
def pytest_html_results_table_header(cells):
# pytest结果表头
cells.insert(2, html.th("Description")) # 描述加在第二列
cells.insert(1, html.th("Time", class_="sortable time", col="time")) # 时间加在第一列
cells.pop()
def pytest_html_results_table_row(report, cells):
# pytest结果行
cells.insert(2, html.td(report.description)) # 描述加在第二列
cells.insert(1, html.td(datetime.utcnow(), class_="col-time"))# 时间加在第一列
cells.pop()
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__)
重跑失败用例
1、安装pytest-rerunfailures
pip install pytest-rerunfailures
2、执行
pytest 文件 --rerun 3