pycharm运行pytest参数化运行teardown错误
pycharm运行pytest参数化运行teardown错误
pycharm运行pytest参数化运行teardown错误
最近在学习pytest,遇到一个令人费解的问题,在使用pycharm中多次运行参数化的pytest之后,teardown的执行效果发生错误,让我们来看看是如何发生的吧。
参数化运行pytest
class TestC():def setup(self):print("start")def teardown(self):print("end")@pytest.mark.parametrize("data",[1,2,3,4,5,6,7,8,9,10])def test1(self,data):print(data)
这是一段简单的代码在运行test1方法打印前后会分别打印“start”和“end”,使用的参数化分别打印1到10
运行效果
test_cache.py::TestC::test1[1] start
1
PASSEDend
test_cache.py::TestC::test1[2] start
2
PASSEDend
test_cache.py::TestC::test1[3] start
3
PASSEDend
test_cache.py::TestC::test1[4] start
4
PASSEDend
......
这是正常的我们想要的效果,但是在多次使用pycharm运行pytest之后,异常出现了
......
test_cache.py::TestC::test1[8] endtest_cache.py::TestC::test1[9] endtest_cache.py::TestC::test1[10] end#忽略部分前后运行结果Process finished with exit code 0
start
1
PASSEDstart
2
PASSEDstart
3
PASSEDstart
......
对比发现,pycharm在后面的运行先帮我们执行了teardown的方法,这显然不是我们想要的运行顺序,我在项目中配置了pytest.ini生产allure报告的参数可能也会出现该问题,笔者认为应该是pycharm可能为了优化自己做了缓存,导致我们用pytest参数化的时候运行teardown会出现问题。
解决方法
使用命令行运行pytest
这样无论我们运行多少次都不会出现刚刚在pycharm中运行pytest的问题了。
bug复现
加上这句话会出现这个问题
不加的话就不会提前运行teardown方法
断点调试
使用断点调试后发现,运行顺序是没有问题的
end
start
test1
小结
可能不会影响到使用,但是在编写用例时确实是坑了我一把,欢迎大家在讨论区一起讨论,有错误的地方麻烦指出。