我有一些使用 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 session 中运行它们;尝试例如
tt = TestThing()
tt.test_something(tt.temp_dir())
失败,因为 temp_dir
需要传递一个 request
对象。那么,如何调用带有注入(inject)的request
对象的fixture呢?
最佳答案
是的。您不必手动组装任何测试装置或类似的东西。一切运行就像在项目目录中调用 pytest
一样。
方法一:
这是最好的方法,因为它可以让您在测试失败时访问调试器
在 ipython
shell 中使用:
**ipython**> 运行-m pytest prj/
这将在 prj/tests
目录中运行所有测试。
这将使您能够访问调试器,或者允许您设置断点
,如果您有
导入 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)
使用这些方法,您甚至可以使用 ( https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests ) 在 ipython
中运行单个模块/test_fuctions/TestClasses
**ipython**> 运行-m pytest prj/tests/test_module1.py::TestClass1::test_function1
关于python - 使用 pytest fixtures 的测试可以交互运行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26840034/