可以用pytest夹具进行交互式测试吗?

时间:2014-11-10 09:00:44

标签: python pytest

我有一些使用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对象的灯具?

5 个答案:

答案 0 :(得分:2)

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

方法一:

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

ipython shell中使用:

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

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

这将允许您访问调试器,或者如果您有,则允许您设置breakpoints 您的计划import ipdb; ipdb.set_trace())中的!pytest

方法2:

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

ipython

如果您的测试失败,它会让您进入调试器(子shell),因此您可以运行事后分析(https://docs.pytest.org/en/latest/usage.html#setting-breakpoints

使用这些方法,您甚至可以使用https://docs.pytest.org/en/latest/usage.html#dropping-to-pdb-python-debugger-on-failures)在 **ipython**> run -m pytest prj/tests/test_module1.py::TestClass1::test_function1 中运行单个模块/ test_fuctions / TestClasses

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://01-2345-6789"]];

答案 1 :(得分:0)

我所拥有的最好的方法是只运行测试文件,然后手动组装灯具,然后简单地调用测试。这个问题是跟踪定义默认夹具的模块,然后按顺序调用它们。

答案 2 :(得分: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 :(得分:0)

您可以绕过pytest.fixture装饰器,直接调用包装的测试函数。

tmp = tt.temp_dir.__pytest_wrapped__.obj(request=...)

访问内部组件很不好,但是当您需要时...

答案 4 :(得分:-1)

简单的答案是你不想从python以交互方式运行py.test。大多数人与他们的文本编辑器或IDE建立了一些集成,以运行py.test并解析它的输出。但实际上它是一个命令行工具,应该如何使用它。

作为副节点,您可能需要查看内置的tmpdir灯具:http://pytest.org/latest/tmpdir.html因为您似乎正在重新发明这个。