上一篇介绍了fixture的简单用法,也介绍了如何使用fixture的内容,举了个例子,不同的用例使用到登录的场景,如果不同文件夹的用例使用到相同的fixture应该怎么办呢?如果再写一个fixture就会比较麻烦,那么强大的pytest肯定不会让我们这样麻烦的,只会让我们更加方便。这里就要引入新的知识点conftest.py文件 conftest.pyconftest.py文件属于fixture中的共享配置文件,有以下几个特点:
比如:有一个测试场景,存在两个用例目录,这两个目录下的用例,有的使用到了登录方法和清除数据的方法,有的没有用到。这里就可以通过把两个方法都放到conftest.py文件中 # conftest.py import pytest @pytest.fixture() def login(): print('输入用户名,密码,完成登陆') @pytest.fixture() def clear(): print('清除用例数据内容!!') 创建好两个fixture内容后,然后直接在我们的用例中调用就行了 先看下目录内容,这样更加清楚conftest.py执行内容 auto_test # 项目名称 --- test_01 # 用例文件夹 --- test__01.py # 用例文件 --- __init__.py ---test_02 # 用例文件夹 --- test__02.py # 用例文件 --- __init__.py conftest.py # conftest.py文件
然后分别在两个用例文件下编写测试用例 # test__01.py import pytest class Test_01: def test_01(self,login): print('需要用到登录功能') print('----用例01---') def test_02(self,clear): print('不需要登录功能') print('----用例02---') def test_03(self, login): print('需要用到登录功能') print('----用例03---') if __name__ == '__main__': pytest.main(['-s','test__01.py']) # test__02.py import pytest class Test_02: def test_01(self, login): print('需要用到登录功能') print('----用例01---') def test_02(self, clear): print('不需要登录功能') print('----用例02---') def test_03(self, login): print('需要用到登录功能') print('----用例03---') if __name__ == '__main__': pytest.main(['-s','test__02.py']) 然后进入到auto目录下,直接执行代码pytest -s 查看执行结果。
发现配置conftest.py中fixture已经全部都生效了,我们也可以通过--setup--show来查看详细的执行过程 无论是单独执行用例还是全部执行用例,都可以进行执行fixture内容
今天简单的介绍了conftest.py文件的作用,其实主要还是fixture的内容知识。
|
|