我有一些使用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呢?在
是的。您不必手动组装任何测试夹具或类似的东西。一切都像在项目目录中调用
pytest
一样运行。在方法1:
这是最好的方法,因为它允许您在测试失败时访问调试器
在
ipython
shell中使用:**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
您可以使用两个单元格:
第一个:
第二:
^{2}$你也可以在一个单元格上这样做,但你不会有代码高亮显示:
最好的方法是运行测试文件,然后手动组装fixture,然后简单地调用测试。这样做的问题是跟踪定义了默认fixture的模块,然后按照它们的依赖顺序调用它们。在
相关问题 更多 >
编程相关推荐