pytest编写规范
- 测试文件以test_开头或者以_test结尾
- 测试类以Test开头并且不能带有init方法
- 测试函数以test_开头
创建demo文件 src/demo.py
def add(a,b):
return a + b
创建测试用例文件 testcase/test_demo.py
from src.demo import add
def test_add():
assert add(1,2)==3
assert add(1,-1)==3
assert add(3,4)==7
执行
pytest test_demo.py
pytest运行
pip install 插件名称
pytest-sugar:显示执行的进度条
pytest-assume:一次执行完,不会因某个测试用例的失败而告终
def test_add():
assert add(1, 2) == 3
assert add(1, 0) == 2
assert add(1, -1) == 0
执行结果:
可以看出上面 add(1, -1) == 0 没有被执行
使用pytest-assume
def test_add(self):
pytest.assume(add(1, 2) == 3)
pytest.assume(add(1, 0) == 2)
pytest.assume(add(1, -1) == 0)
设置用例的执行顺序
参考文档 https://pytest-ordering.readthedocs.io/en/develop/
- setup_module
- setup_class
- setup_method
- teardown_method
- teardown_class
- teardown_module
import logging
import pytest
logging.basicConfig(level=logging.DEBUG)
def setup_module():
logging.info("setup_module")
def teardown_module():
logging.info("teardown_module")
class TestPytestObject2:
def test_three(self):
assert [1,3]==[1,2]
def test_four(self):
assert {"1":"ss","2":"sss"}
class TestPytestObject:
@classmethod
def setup_class(self):
logging.info("setupclass")
def setup_method(self):
logging.info("setup")
@pytest.mark.run(order=2)
def test_one(self):
assert 1==1
@pytest.mark.run(order=1)
def test_two(self):
assert True == False
def teardown_method(self):
logging.info("teardown")
@classmethod
def tear_down(cls):
logging.info("teardown_class")
pytest-selenium
pytest-play
pytest-rerunfailures:重新运行失败的用例
执行方式
pytest -reruns 3 test-demo.py #3代表失败后重新运行的次数,如果加上正常运行的是4次