Python unittest swaps object instances between tests

I am writing some unit tests in Python and it seems that my tests are somehow sharing objects between test functions, which seems strange. So, I have something like:

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)

      

If I comment on either test the other will pass, but both will fail together. On the exam, it seems that the object is being c

persisted between the two test functions, but why should that be? New instances are created in the function. Is this some "feature" out of the box 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)

      

OK, this is weird. I looked at history and before that I got this:

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

      

And the tests didn't work when I initialized this. It works now. I must have deleted this without tracking.

Does anyone know why this is not working? but the execution is self.data = defaultdict()

fine.

+3


source to share


1 answer


This is because you used a mutable object as the default for the method parameter. The object is created once and then divided among all calls to this method, no matter what value it self

contains.



http://python-guide-pt-br.readthedocs.io/en/latest/writing/gotchas/

+5


source







All Articles