pytes中fixture的scope: 决定可以在什么范围内共享fixture - 工作手记
source link: https://www.cnblogs.com/MyRecords/p/17374910.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
1fixture的scope
在@pytest.fixture(scope='xxx')中,scope的可选值有5个,以下是官网的描述
2 function级别的scope
添加如下代码到pytest.ini,便于输出日志
新建conftest.py文件,把fixture函数写入其中,便于后面fixture可以在多个py文件中的test函数中引用
conftest.py
pytest的fixture默认级别就是 funtion,因此可以不写scope参数
test_fixture.py
执行结果
注意,两个test函数中,list对象的id是不同的,虽然他们的内容都是相同的,这说明在这两个test函数中,他们各自独立地执行了一次fixture,拿到了各自的list对象
即
the default scope, the fixture is destroyed at the end of the test
3 class级别的scope
执行
注意,每个class里面都有2个test函数,同一个class里面的test函数,输出的list对象是相同的,
说明他们拿到的都是同一个list对象,生产list对象的fixture只执行了一次
不同的class的test函数,输出的list对象的id是不同的,说明在执行第2个class时,fixture又执行了一次,生成一个新的list对象
即
class: the fixture is destroyed during teardown of the last test in the class.
4 module级别的scope
test_fixture.py
test_fixture_2.py
执行
可以看到,同一个py文件里面,所有的test输出的list对象id是相同的,说明这些test共享了一个list对象
不同的py文件,test输出的id对象是不同的,说明不同的py文件各自独立执行了fixture,拿到了各自独立的list对象
5 session级别的scope
test_fixture.py test_fixture_2.py内容不变
执行
可以看到,不同py文件的test函数,都输出相同id的list对象,说明不同py文件的test,都共享了同一个list对象,fixture在整个测试绘画期间只执行了一次
即
the fixture is destroyed at the end of the test session
6 package级别的scope
首先我的目录结构如下
两个conftest文件的内容都是相同的
注意,每个目录下添加文件__init__.py,内容不用写。所谓package,就是包含__init__.py文件的目录
test_fixture_2.py test_fixyure.py内容与之前相同
test02目录下test_fixture_03.py
在test01 test02 同级目录下执行 pytest -k "fixture" -s -v
执行结果
可以看到 test01目录下所有的test输出id是相同的,test02目录下的test输出的id是不同的
这事,其他内容不变,把test02目录下的conftest.py删除,把test01下的conftest.py移动到test01 test02的同级目录中
再来执行
这时,你会看到所有的输出id都是相同的
这就有意思了,这里牵涉到一个conftest.py的范围的问题,conftest.py放在不同的目录下,它能影响的范围也是不同的
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK