Python Unittest:确保对象不包含来自上一次运行的数据

Python Unittest:确保对象不包含来自上一次运行的数据,python,python-3.x,python-unittest,Python,Python 3.x,Python Unittest,我正在使用setUp从我创建的类创建一个新对象。我的理解是,该函数将在测试用例中的每个测试之前执行,这将导致为每个测试创建新对象。这似乎不是正在发生的事情;至少在我的测试中没有 这是我的班级: class Entity: def __init__(self, entities = []): self.entities = entities def add(self, entity: str): if entity not in self.enti

我正在使用
setUp
从我创建的类创建一个新对象。我的理解是,该函数将在测试用例中的每个测试之前执行,这将导致为每个测试创建新对象。这似乎不是正在发生的事情;至少在我的测试中没有

这是我的班级:

class Entity:
    def __init__(self, entities = []):
        self.entities = entities

    def add(self, entity: str):
        if entity not in self.entities:
            self.entities.append(entity)
以下是相应的测试:

import unittest
from entity import Entity

class EntityTestCase(unittest.TestCase):
    def setUp(self):
        self.entity = Entity()
        print("Starting Entites = {}".format(self.entity.entities))

    def testA(self):
        self.entity.add("Foo")
        self.assertEqual(self.entity.entities, ["Foo"])

    def testB(self):
        self.entity.add("Bar")
        self.assertEqual(self.entity.entities, ["Bar"])

if __name__ == '__main__':
    unittest.main()
我希望
testA
testB
将从新的
实体
对象开始。也就是说,我希望
Entity.entities
是每个测试的全新列表

我使用
python-m unittest discover-v
运行测试,结果如下:

$ python -m unittest discover -v
testA (test_entity.EntityTestCase) ... Starting Entites = []
ok
testB (test_entity.EntityTestCase) ... Starting Entites = ['Foo']
FAIL

======================================================================
FAIL: testB (test_entity.EntityTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/julioguzman/Sites/Foobar/test_entity.py", line 15, in testB
    self.assertEqual(self.entity.entities, ["Bar"])
AssertionError: Lists differ: ['Foo', 'Bar'] != ['Bar']

First differing element 0:
'Foo'
'Bar'

First list contains 1 additional elements.
First extra element 1:
'Bar'

- ['Foo', 'Bar']
+ ['Bar']

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)
如您所见,
testB
testA
中的数据开始。这不是期望的行为,尽管它可能是预期的行为

如何确保每次测试的对象都“干净”?为什么会发生这种情况?

你有

class Entity:
    def __init__(self, entities = []):
        self.entities = entities
其中,默认参数实例化一次,从而导致此常见问题

只需修改
\uuuuu init\uuuuuu
即可使用代理项值并指定全新列表(如果是):

class Entity:
    def __init__(self, entities=NotImplemented):
        if entities is NotImplemented:
            self.entities = []
        else:
            self.entities = entities
另一方面,这也是编写单元测试的原因之一:它们还测试类是否以预期的行为正确创建。当
设置
清楚地显示它创建了一个全新的对象时,这不是测试的问题-错误在于它执行了一些意想不到的操作的实现