pytest之fixture的作用域scope
原文链接:https://www.cnblogs.com/ctltest/p/14550167.html
前言:
我们知道,如果用setup和teardown系列,对于不同的作用域有不同的setup_XXX和teardown_XXX来对应。
那对于@pytest.fixture有没有这样的功能呢?答案是:有!那就是scope参数。
一、scope参数:
1、scope="function"时,其作用域的级别是测试函数和测试方法级。(注意:没有scope="method"这一说)。(l默认function)
2、scope="class"时,其作用域的级别是测试类。
3、scope="module"时,其作用域的级别是整个.py文件。
4、scope="session"时,其作用域的级别是会话级。
二、函数(方法)级:
见示例:
test_a.py
文件:test_a.py
import pytest
def test_1(login):
assert 3 == 3
print("this is test_1")
class TestA(object):
def test_a(self, login):
assert 1 == 1
print("this is test_a")
def test_a_1(self):
assert 2 == 2
print("this is test_a_1")
conftest.py
文件conftest.py
import pytest
@pytest.fixture(scope="function")
def login():
print("this is login ")
运行结果:
test_a.py::test_1 this is login
PASSED [ 33%]this is test_1
test_a.py::TestA::test_a this is login
PASSED [ 66%]this is test_a
test_a.py::TestA::test_a_1 PASSED [100%]this is test_a_1
我们可以看到,test_a.py文件中,测试函数test_1和测试方法test_a都将被@pytest.fixture装的login函数传入参数。
所以,他们执行前都执行了login函数。
结论:scope="function"时,是函数或方法级别的。会在测试函数或测试方法执行前执行。
二、类级别:
见示例:test_a.py和上面一样没变,我们改变conftest.py中fixture的scope参数,如下图:
文件conftest.py
import pytest
@pytest.fixture(scope="class")
def login():
print("this is login ")
执行结果如下:
test_a.py::test_1 this is login
PASSED [ 33%]this is test_1
test_a.py::TestA::test_a this is login
PASSED [ 66%]this is test_a
test_a.py::TestA::test_a_1 PASSED [100%]this is test_a_1
通过本例,我们可以看到,当scope="class"时,在所有测试函数执行前、测试类中所有测试方法执行前,执行了一次login()函数。
结论:当scope="class"时,对于不在类中的所有测试函数执行前执行一次,在类中的所有测试方法执行前执行一次。
三、模块级别
见示例:test_a.py和上面一样没变,我们改变conftest.py中fixture的scope参数,如下图:
import pytest
@pytest.fixture(scope="module")
def login():
print("this is login ")
执行结果:
test_a.py::test_1 this is login
PASSED [ 33%]this is test_1
test_a.py::TestA::test_a PASSED [ 66%]this is test_a
test_a.py::TestA::test_a_1 PASSED [100%]this is test_a_1
我们可以看到,test_a.py文件中,无论测试函数还是测试方法,在其执行前都执行了一边login()函数。
结论:若scope="module"时,测试模块(.py文件)在执行所有测试函数或方法前只执行一次前置动作。
四:会话级:
见示例:test_a.py不变,新增一个test_b.py。然后将fixture的scope参数改为:session.
文件:test_a.pyimport pytest
def test_1(login):
assert 3 == 3
print("this is test_1")
class TestA(object):
def test_a(self, login):
assert 1 == 1
print("this is test_a")
def test_a_1(self):
assert 2 == 2
print("this is test_a_1")
文件:test_b.py
import pytest
def test_2(login):
assert 3 == 3
print("this is test_2")
class TestB(object):
def test_b(self, login):
assert 1 == 1
print("this is test_b")
def test_b_1(self):
assert 2 == 2
print("this is test_b_1")
文件:conftest.phimport pytest
@pytest.fixture(scope="session")
def login():
print("this is login ")
执行结果:
test_a.py this is login
this is test_1
.this is test_a
.this is test_a_1
.
test_b.py this is test_2
.this is test_b
.this is test_b_1
.
我们可以看到,当scope设为session时,只是在整个会话中进行了一次前置操作login.(注:第一次执行哪个用,是遵循ASCII规则)。
结论:当scope设为session时,会在整个会话期间执行一次前置操作。
总之:scope使用什么值,需要考虑实际业务场景。