python 单元测试在测试之间共享对象实例

python unittest sharing object instances between tests

我正在 Python 中编写一些单元测试,似乎我的测试以某种方式在测试函数之间共享对象,这看起来很奇怪。所以,我有类似的东西:

import unittest 

class TestMyMethods(unittest.TestCase):

    def test_create(self):
        c = MyClass()
        c.create_customer('Luca')
        self.assertEqual(len(c.data), 1)

    def test_connect(self):
        c = MyClass()
        c.connect_customer('Angela', 'Peter')
        self.assertEqual(len(c.data), 2)

如果我注释掉任何一个测试,另一个通过但两个一起失败。经过检查,似乎 c 对象在两个测试函数之间持续存在,但为什么会这样呢?在函数中创建新实例。这是来自 unittest 框架的一些 "feature" 吗?

from collections import defaultdict
class MyClass(object):
    def __init__(self):
        self.data = defaultdict()

    def create_customer(self, cust):
        if cust not in self.data:
            self.data[cust] = list()

    def connect_customer(self, a, b):
        if a not in self.data:
            self.data[a] = list()

        if b not in self.data:
            self.data[b] = list()

        self.data[a].append(b)

好吧,这很奇怪。我看了历史,在我有这个之前:

class MyClass(object):
    def __init__(self, data=defaultdict()):
        self.data = data

当我像这样初始化时,测试不工作。它现在确实有效。我一定是删除了这个没有跟踪。

有谁知道为什么这不起作用?但是 self.data = defaultdict() 没问题。

这是因为您使用可变对象作为方法参数的默认值。该对象创建一次,然后在该方法的所有调用中共享,无论 self 包含哪个值。

https://python-guide.readthedocs.io/en/latest/writing/gotchas/