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

Luc*_*uca 4 python python-unittest

我正在用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)
Run Code Online (Sandbox Code Playgroud)

如果我评论任何一个测试,另一个通过,但两个一起失败.经过检查,似乎该c对象在两个测试函数之间仍然存在,但为什么会这样呢?在该函数中,创建了新实例.这是unittest框架的一些"功能" 吗?

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)
Run Code Online (Sandbox Code Playgroud)

好的,这很奇怪.我看了历史,在此之前:

class MyClass(object):
    def __init__(self, data=defaultdict()):
        self.data = data
Run Code Online (Sandbox Code Playgroud)

当我这样初始化时,测试不起作用.它实际上现在有效.我必须删除这个没有保留的轨道.

有谁知道为什么这不起作用?但做得self.data = defaultdict()很好.

Jos*_*h J 6

这是因为您使用可变对象作为方法参数的默认值.该对象创建一次,然后在该方法的所有调用之间共享,而不管self包含哪个值.

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