在 py.test 中的每个测试之前和之后运行代码? [英] Run code before and after each test in py.test?

查看:29
本文介绍了在 py.test 中的每个测试之前和之后运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的测试套件中的每个测试之前和之后运行额外的设置和拆卸检查.我看过固定装置,但不确定它们是否是正确的方法.我需要在每次测试之前运行设置代码,并且需要在每次测试之后运行拆卸检查.

I want to run additional setup and teardown checks before and after each test in my test suite. I've looked at fixtures but not sure on whether they are the correct approach. I need to run the setup code prior to each test and I need to run the teardown checks after each test.

我的用例是检查未正确清理的代码:它会留下临时文件.在我的设置中,我将检查文件,在拆卸中我也会检查文件.如果有额外的文件,我希望测试失败.

My use-case is checking for code that doesn't cleanup correctly: it leaves temporary files. In my setup, I will check the files and in the teardown I also check the files. If there are extra files I want the test to fail.

推荐答案

py.test fixtures 是一种技术上足够的方法来实现你的目的.

py.test fixtures are a technically adequate method to achieve your purpose.

你只需要像这样定义一个fixture:

You just need to define a fixture like that:

@pytest.fixture(autouse=True)
def run_around_tests():
    # Code that will run before your test, for example:
    files_before = # ... do something to check the existing files
    # A test function will be run at this point
    yield
    # Code that will run after your test, for example:
    files_after = # ... do something to check the existing files
    assert files_before == files_after

通过使用 autouse=True 声明您的装置,它将为同一模块中定义的每个测试函数自动调用.

By declaring your fixture with autouse=True, it will be automatically invoked for each test function defined in the same module.

也就是说,有一个警告.在设置/拆卸时断言是一种有争议的做法.我的印象是 py.test 的主要作者不喜欢它(我也不喜欢它,所以这可能会影响我自己的看法),所以你在前进的过程中可能会遇到一些问题或粗糙的边缘.

That said, there is one caveat. Asserting at setup/teardown is a controversial practice. I'm under the impression that the py.test main authors do not like it (I do not like it either, so that may colour my own perception), so you might run into some problems or rough edges as you go forward.

这篇关于在 py.test 中的每个测试之前和之后运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆