pytest fixture-在带有usefixture的类和模块中使用fixture
有时测试函数不需要直接访问fixture对象。例如,测试可能需要使用空目录作为当前工作目录进行操作,但不关心具体目录。下面介绍如何使用标准的tempfile和pytest fixture来实现它。我们将fixture的创建分离到一个conftest.py文件中:
# content of conftest.py
import os
import tempfile
import pytest
@pytest.fixture
def cleandir():
with tempfile.TemporaryDirectory() as newpath:
old_cwd = os.getcwd()
os.chdir(newpath)
yield
os.chdir(old_cwd)并通过usefixtures标记在测试模块中声明它的使用:
# content of test_setenv.py
import os
import pytest
@pytest.mark.usefixtures("cleandir")
class TestDirectoryInit:
def test_cwd_starts_empty(self):
assert os.listdir(os.getcwd()) == []
with open("myfile", "w") as f:
f.write("hello")
def test_cwd_again_starts_empty(self):
assert os.listdir(os.getcwd()) == []对于usefixture标记,在执行每个测试方法时需要cleandir fixture,就像为每个测试方法指定了一个cleandir函数参数一样。让我们运行它来验证我们的fixture被激活,并且测试通过:
$ pytest -q
.. [100%]
2 passed in 0.12s你可以像这样指定多个fixture:
@pytest.mark.usefixtures("cleandir", "anotherfixture")
def test():
...你可以在测试模块级别使用pytestmark来指定fixture的使用:
pytestmark = pytest.mark.usefixtures("cleandir")也可以将项目中所有测试所需的fixture放入一个ini文件中:
# content of pytest.ini
[pytest]
usefixtures = cleandir