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

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

问题描述

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

我的用例是检查无法正确清理的代码:它将留下临时文件.在我的设置中,我将检查文件,在拆解中,我还将检查文件.如果有多余的文件,我希望测试失败.

解决方案

py.test夹具是从技术上讲达到目的的适当方法.

您只需要定义一个固定装置即可

@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声明夹具,将为同一模块中定义的每个测试功能自动调用夹具.

也就是说,有一个警告.在设置/拆卸时断言是一种有争议的做法.我的印象是py.test主要作者不喜欢它(我也不喜欢它,所以可能会使我自己的看法变色),因此您在前进时可能会遇到一些问题或粗暴的边缘./p>

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 are a technically adequate method to achieve your purpose.

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

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

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天全站免登陆