我有一些使用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')
Run Code Online (Sandbox Code Playgroud)
当从shell调用测试时,这很好用,例如
$ py.test
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在python/ipython会话中运行它们; 尝试例如
tt = TestThing()
tt.test_something(tt.temp_dir())
Run Code Online (Sandbox Code Playgroud)
失败,因为temp_dir需要request传递一个对象.那么,如何在request注入对象的情况下调用夹具?
是的。您不必手动组装任何测试夹具或类似的东西。一切都像pytest在项目目录中调用一样运行。
这是最好的方法,因为如果您的测试失败,它可以让您访问调试器
在ipython外壳中使用:
**ipython**> run -m pytest prj/
这将运行prj/tests目录中的所有测试。
这将使您可以访问调试器,或者允许您设置程序中breakpoints是否有 a
import ipdb; ipdb.set_trace()( https://docs.pytest.org/en/latest/usage.html#setting-breakpoints )。
使用!pytest而test目录。这不会让您访问调试器。但是,如果您使用
**ipython**> !pytest --pdb
如果您的测试失败,它会将您放入调试器(子shell),因此您可以运行事后分析(https://docs.pytest.org/en/latest/usage.html#dropping-to- pdb-python-debugger-on-failures )
使用这些方法,你甚至可以在运行单个模块/ test_fuctions / TestClassesipython使用(https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests)
**ipython**> run -m pytest prj/tests/test_module1.py::TestClass1::test_function1
| 归档时间: |
|
| 查看次数: |
2276 次 |
| 最近记录: |