codecamp

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


pytest fixture-按fixture实例自动分组测试
pytest fixture-重写各种级别的fixture
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }