【问题标题】:Why does Pytest create a new class instance for each test method?为什么 Pytest 会为每个测试方法创建一个新的类实例?
【发布时间】:2021-09-13 01:01:03
【问题描述】:

当我注意到标题为"Grouping multiple tests in a class" 的部分时,我正在阅读 Pytest 文档。下面有一段需要注意的是,每个测试方法都会获得类实例的唯一副本。Pytest 提供了一个反例来说明为什么共享类实例是一个坏主意。

我不太明白这个例子。你能帮我理解这个例子的意义吗?

"""
Something to be aware of when grouping tests inside classes is that each test has a 
unique instance of the class. Having each test share the same class instance would be 
very detrimental to test isolation and would promote poor test practices. 
This is outlined below:
"""


# content of test_class_demo.py
class TestClassDemoInstance:
    def test_one(self):
        assert 0

    def test_two(self):
        assert 0
$ pytest -k TestClassDemoInstance -q
FF                                                                   [100%]
================================= FAILURES =================================
______________________ TestClassDemoInstance.test_one ______________________

self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef>

    def test_one(self):
>       assert 0
E       assert 0

test_class_demo.py:3: AssertionError
______________________ TestClassDemoInstance.test_two ______________________

self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef>

    def test_two(self):
>       assert 0
E       assert 0

test_class_demo.py:6: AssertionError
========================= short test summary info ==========================
FAILED test_class_demo.py::TestClassDemoInstance::test_one - assert 0
FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0
2 failed in 0.12s

标签: unit-testing pytest isolation


【解决方案1】:

上面的例子表明:

Something to be aware of when grouping tests inside classes is that each test has a 
unique instance of the class.
______________________ TestClassDemoInstance.test_one ______________________

self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef>

    def test_one(self):
>       assert 0
E       assert 0

test_class_demo.py:3: AssertionError
______________________ TestClassDemoInstance.test_two ______________________

self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef>

但是,test_onetest_two 中的 TestClassDemoInstance 都指向同一个对象地址。如果两个对象的地址不同来表示对象的唯一性,这个例子会更清楚。

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 2016-12-24
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多