简体   繁体   English

setup_module()与py.test中的顶级语句有何不同?

[英]How is setup_module() different from top-level statements in py.test?

If I don't have any teardown, do I need to use setup_module, or can I just use top-level statements? 如果没有任何拆卸,是否需要使用setup_module,还是可以仅使用顶层语句?

=== test_1.py ===
foo = 3
def test_foo(): assert foo == 3

=== test_2.py 
def setup_module(m): m.foo = 3
def test_foo(): assert foo == 3

Will py.test execute all the top-level statements in order, and before it executes the first test? py.test会在执行第一个测试之前按顺序执行所有顶级语句吗?

Thanks! 谢谢!

It seems like py.test will evaluate your top-level-statements before any test, so test_1.py will work. 似乎py.test将在进行任何测试之前评估您的顶级语句,因此test_1.py可以工作。

However, when you are writing tests, it is generally not a good idea to have any top-level-statements. 但是,在编写测试时,拥有任何顶级语句通常不是一个好主意。 You should try to structure your tests into Test Cases (a Class that holds your related test code) and which tests specific features of your application. 您应该尝试将测试构造为测试用例(一个包含相关测试代码的类),并测试应用程序的特定功能。 So, if you take your code ( test_2.py ) and turn it into a Test Case, it will look something like this: 因此,如果您采用代码( test_2.py )并将其转换为测试用例,它将看起来像这样:

def setup_module(module):
    module.TestFoo.foo = 3

class TestFoo:
    def test_foo(self):
        assert self.foo == 3

This way, you can keep adding all the related tests to TestFoo and even add more than one TestCase per module (although it's usually best to have each TestCase in it's own file). 这样,您可以继续将所有相关测试添加到TestFoo ,甚至为每个模块添加一个以上TestCase (尽管通常最好将每个TestCase放在自己的文件中)。

Regarding your teardown_module question, you only need a teardown when you need to restore the application state to its initial state (removing newly created items, etc) or to clean up hanging connections (closing files, sockets, etc). 关于teardown_module问题,仅在需要将应用程序状态恢复到其初始状态(删除新创建的项等)或清理挂起的连接(关闭文件,套接字等)时才需要进行拆卸 In this case, since your setup_module is not doing anything that needs any clean up, teardown is not needed and py.test won't complain the lack of it. 在这种情况下,由于setup_module不会做任何需要清理的事情,因此不需要拆卸 ,而py.test不会抱怨它缺少它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM