引言
unittest框架和pytest框架编写的测试用例执行顺序,默认根据ACSII码的顺序加载测试用例,数字与字母的顺序为:0~9,A~Z,a~z。
1.对于类来说,class TestAxx 会优先于class TestBxx被执行。
2.对于方法来说,test_aaa()方法会有优先于test_bbb()被执行。
3.对于方法来说,test_01()方法会优先test_aa执行
对于测试目录与测试文件来说,unittest同样是按照这个规则来加载测试用例的。
没有排序执行:
import pytest
class Test_Pytest():
@classmethod
def setUpClass(cls):
print("setup_class方法执行1次")
@classmethod
def tearDownClass(cls):
print("teardown_class方法执行1次")
def setup(self):
print("setup 第多次")
def teardown(self):
print("teardown 第多次")
def setup_method(self):
print("setup_method方法执行多次")
def teardown_method(self):
print("teardown_method方法执行多次")
def test_two(self):
print('test2')
def test_one(self):
print('test1')
def test_1(self):
print('testb')
def test_a(self):
print('testa')
if __name__=="__main__":
pytest.main(['-s -v','test_class.py'])
pytest.main()
结果:
test_class.py::Test_Pytest::test_two setup_method方法执行多次
setup 第多次
PASSED [ 25%]test2
teardown 第多次
teardown_method方法执行多次test_class.py::Test_Pytest::test_one setup_method方法执行多次
setup 第多次
PASSED [ 50%]test1
teardown 第多次
teardown_method方法执行多次
test_class.py::Test_Pytest::test_1 setup_method方法执行多次
setup 第多次
PASSED [ 75%]testb
teardown 第多次
teardown_method方法执行多次
test_class.py::Test_Pytest::test_a setup_method方法执行多次
setup 第多次
PASSED [100%]testa
teardown 第多次
teardown_method方法执行多次
改用例执行顺序的插件
通过@pytest.mark.run(order=1)控制执行顺序
但前天需要下载插件:
- 命令行窗口输入:
pip install pytest-ordering
- 查看安装版本:
pip show pytest-ordering
import pytest
class Test_Pytest():
@classmethod
def setUpClass(cls):
print("setup_class方法执行1次")
@classmethod
def tearDownClass(cls):
print("teardown_class方法执行1次")
def setup(self):
print("setup 第多次")
def teardown(self):
print("teardown 第多次")
def setup_method(self):
print("setup_method方法执行多次")
def teardown_method(self):
print("teardown_method方法执行多次")
def test_two(self):
print('test2')
@pytest.mark.run(order=2)
def test_one(self):
print('test1')
@pytest.mark.run(order=1)
def test_1(self):
print('testb')
def test_a(self):
print('testa')
if __name__=="__main__":
pytest.main(['-s -v','test_class.py'])
结果:
test_class.py::Test_Pytest::test_1 setup_method方法执行多次
setup 第多次
PASSED [ 25%]testb
teardown 第多次
teardown_method方法执行多次
test_class.py::Test_Pytest::test_one setup_method方法执行多次
setup 第多次
PASSED [ 50%]test1
teardown 第多次
teardown_method方法执行多次
test_class.py::Test_Pytest::test_two setup_method方法执行多次
setup 第多次
PASSED [ 75%]test2
teardown 第多次
teardown_method方法执行多次
test_class.py::Test_Pytest::test_a setup_method方法执行多次
setup 第多次
PASSED [100%]testa
teardown 第多次
teardown_method方法执行多次