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

时间:2017-04-23 12:55:24

标签: 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)

如果我评论任何一个测试,另一个通过,但两个一起失败。经过检查,似乎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)
好的,这很奇怪。我看了历史,在此之前:

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

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

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

1 个答案:

答案 0 :(得分:6)

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

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

相关问题