测试固件fixture(二):自动执行autouse
前言:
在一些场景下,需要自动去执行fixture前置操作,如一个测试模块中的测试用例必然会进行登录的前置操作,pytest的fixture提供了一个autouse参数,
设置为True即可进行自动执行fixture,而不需要显式的调用前置操作函数。
一、自动调用:

conftest.py import pytest @pytest.fixture(scope="class", autouse=True) def login(): print("this is login") return "login fixture"
test_1.py def test_1_a(): print("this is test_1_a") class Test1A: def test_1_b(self): print("this is test_1_b") def test_1_c(self): print("this is test_1_c")
test_2.py def test_2_a(): print("this is test_2_b") class Test2B: def test_2_b(self): print("this is test_2_b") def test_2_c(self, login): print("this is test_2_c") assert "login" in login
执行结果:
test_a\test_1.py this is login this is test_1_a .this is login this is test_1_b .this is test_1_c . test_b\test_2.py this is login this is test_2_b .this is login this is test_2_b .this is test_2_c . ============================== 6 passed in 0.02s ==============================
我们可以看到,test_1.py与test_2.py中,只有test_2.py中的test_2_c显示调用了login前置操作,但执行结果在每个class前,整个function区域前执行了一次。
注意:显示调用的同个login只能拿到其返回值。
总结:autouse会跟进scope参数指定的范围,自动执行前置操作。执行自动前置操作的情况下,显示调用的则只能拿到其返回值,而不执行其前置操作的其他
代码。
浙公网安备 33010602011771号