pytest固件测试可以交互式运行吗?

15

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

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中调用测试时,这个很好用,例如:

 $ py.test

但我不知道如何在Python/IPython会话中运行它们;尝试类似于

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

失败是因为temp_dir需要传递一个request对象。那么,如何使用注入request对象的fixture?


我自己没有尝试过,但是:http://ipython.org/ipython-doc/dev/interactive/tutorial.html#system-shell-commands让我相信你只需要在前面加上!(例如!py.test)就可以在iPython中运行... - Dair
运行 py.test 需要你在包含测试脚本的目录中,这在很大程度上破坏了它的目的。此外,它也不允许你访问回溯和 Python 交互式调试器,而直接交互地运行函数才是真正的目的。 - keflavich
啊,好的。对不起。 - Dair
请查看此处:https://dev59.com/P18d5IYBdhLWcg3waxvo#48739098 - alpha_989
5个回答

15

是的,您不必手动组装任何测试固件或类似的内容。一切都像在项目目录中调用pytest一样运行。

方法1:

这是最好的方法,因为它让您在测试失败时可以访问调试器。

ipython shell中使用:

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

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

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

方法2:

在测试目录中使用!pytest。这不会让您访问调试器。但是,如果您使用

**ipython**> !pytest --pdb

如果您有一个测试失败,它将把您带入调试器(子shell),以便您可以运行后期分析。(https://docs.pytest.org/en/latest/usage.html#dropping-to-pdb-python-debugger-on-failures


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

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


2
你可以绕过 pytest.fixture 装饰器,直接调用包装的测试函数。
tmp = tt.temp_dir.__pytest_wrapped__.obj(request=...)

访问内部内容是不好的,但在必要时可以使用...


0
我现在使用的最佳方法远非理想,就是运行测试文件,手动组装夹具,然后调用测试。问题在于要找到定义默认夹具的模块,并按其依赖关系的顺序调用它们。

0

你可以使用两个单元格来实现这个功能:

第一个:

def test_something():
    assert True

第二个:

from tempfile import mktemp
test_file = mktemp('.py', 'test_')
open(test_file, 'wb').write(_i) # write last cell input

!pytest $test_file

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

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

-3
简单的答案是你不想从Python中交互式地运行py.test。大多数人都会设置一些与他们的文本编辑器或IDE集成的方式来运行py.test并解析它的输出。但实际上,它是一个命令行工具,应该这样使用。
另外,你可能想要查看内置的tmpdir fixture: http://pytest.org/latest/tmpdir.html,因为你似乎正在重新发明它。

1
在IPython中运行单个测试并添加和调试测试非常好、方便和省时。 - Abram
你可以做到这一点。请参见下面链接:https://dev59.com/P18d5IYBdhLWcg3waxvo#48739098 - alpha_989
这不准确,所以我更喜欢它被删除。 - Robert P. Goldman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接