使用pytest fixture的测试可以交互运行吗?

2024-10-08 21:20:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些使用pytest和fixture编写的测试,例如:

class TestThing:
    @pytest.fixture()
    def temp_dir(self, request):
        my_temp_dir = tempfile.mkdtemp()
        def fin():
            shutil.rmtree(my_temp_dir)
        request.addfinalizer(fin)
        return my_temp_dir
    def test_something(self, temp_dir)
        with open(os.path.join(temp_dir, 'test.txt'), 'w') as f:
            f.write('test')

当从shell调用测试时,这种方法工作得很好

^{pr2}$

但是我不知道如何在python/ipython会话中运行它们;比如

tt = TestThing()
tt.test_something(tt.temp_dir())

失败,因为temp_dir需要传递request对象。那么,如何在注入request对象的情况下调用fixture呢?在


Tags: 对象testselfpytestrequestmydefdir
3条回答

是的。您不必手动组装任何测试夹具或类似的东西。一切都像在项目目录中调用pytest一样运行。在

方法1:

这是最好的方法,因为它允许您在测试失败时访问调试器

ipythonshell中使用:

**ipython**> run -m pytest prj/

这将运行prj/tests目录中的所有测试。在

这将允许您访问调试器,或者允许您设置breakpoints,如果您有 import ipdb; ipdb.set_trace()在您的程序(https://docs.pytest.org/en/latest/usage.html#setting-breakpoints)中。在

方法2:

在测试目录中使用!pytest。这不会给你访问调试器的权限。但是,如果使用

**ipython**> !pytest --pdb

如果测试失败,它会将您放入调试器(subshell),这样您就可以运行事后分析(https://docs.pytest.org/en/latest/usage.html#dropping-to-pdb-python-debugger-on-failures


使用这些方法,您甚至可以使用(https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests)在ipython中运行单独的模块/测试功能/测试类

**ipython**> run -m pytest prj/tests/test_module1.py::TestClass1::test_function1

您可以使用两个单元格:

第一个:

def test_something():
    assert True

第二:

^{2}$

你也可以在一个单元格上这样做,但你不会有代码高亮显示:

from tempfile import mktemp

test_code = """
def test_something():
    assert True
"""

test_file = mktemp('.py', 'test_')
open(test_file, 'wb').write(test_code)

!pytest $test_file

最好的方法是运行测试文件,然后手动组装fixture,然后简单地调用测试。这样做的问题是跟踪定义了默认fixture的模块,然后按照它们的依赖顺序调用它们。在

相关问题 更多 >

    热门问题