pytest的fixture scope
上一篇 /
下一篇 2017-07-06 17:15:07
/ 个人分类:Pytest
fixture scope有fuction,module,class和session。function:每个test都运行,默认是function的scope class:每个class的所有test只运行一次 module:每个module的所有test只运行一次 session:每个session只运行一次
看例子:
basic.py
import pytest
class MyCalc():
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
return self.a+self.b
@pytest.fixture(scope='function')
def before_module():
calc = MyCalc(3,4)
print('-----------------')
print(calc)
print('-----------------')
return calc.add()
print('---before module---\n')
test_1.py
from pytest_example.fixture_scope.basic import before_module
def test_one(before_module):
print('test one\n')
assert 7 == before_module
# assert 0
def test_two(before_module):
print('test two\n')
assert 5 == before_module
运行结果:
>pytest -v -s test_1.py
============================= test session starts =============================
platform. win32 --
Python 2.7.13, pytest-3.1.2, py-1.4.34, pluggy-0.4.0 -- c:\python27\python.exe
cachedir: .cache
rootdir: C:\Users\pytest_example\fixture_scope, inifile:
collected 2 items
test_1.py::test_one -----------------
<pytest_example.fixture_scope.basic.MyCalc instance at 0x03AD6968>
-----------------
test one
PASSED
test_1.py::test_two -----------------
<pytest_example.fixture_scope.basic.MyCalc instance at 0x03ACD4B8>
-----------------
test two
FAILED
================================== FAILURES ===================================
__________________________________ test_two ___________________________________
before_module = 7
def test_two(before_module):
print('test two\n')
> assert 5 == before_module
E assert 5 == 7
test_1.py:10: AssertionError
===================== 1 failed, 1 passed in 0.06 seconds ======================
可以看到创建了两个MyCalc对象
将
@pytest.fixture(scope='function')改为@pytest.fixture(scope='module')
运行结果:
pytest -v -s test_1.py
============================= test session starts =============================
platform. win32 -- Python 2.7.13, pytest-3.1.2, py-1.4.34, pluggy-0.4.0 -- c:\python27\python.exe
cachedir: .cache
rootdir: C:\Users\pytest_example\fixture_scope, inifile:
collected 2 items
test_1.py::test_one -----------------
<pytest_example.fixture_scope.basic.MyCalc instance at 0x03F16968>
-----------------
test one
PASSED
test_1.py::test_two test two
FAILED
================================== FAILURES ===================================
__________________________________ test_two ___________________________________
before_module = 7
def test_two(before_module):
print('test two\n')
> assert 5 == before_module
E assert 5 == 7
test_1.py:10: AssertionError
===================== 1 failed, 1 passed in 0.08 seconds ======================
可以看到只产生了一个MyCalc对象
收藏
举报
TAG: