How to instantiate objects during a unit test's setup phase in Python
Question: I've been diving into unit testing with Python, but can't figure out how I'm
supposed to instantiate the object I want to test during the setup phase, and
end up with a new object for each test. For example, I have the following
class I want to test:

    
    
    class Cfg():
        data = {}
    
        def set(self, key, value):
            self.data[key] = value
    
        def get(self, key):
            return self.data.get(key, None)
    

For each unit test, I want a newly instantiated `Cfg` object. My tests look
like this:

    
    
    from cfg import Cfg
    
    class TestCfg():
        def setup(self):
            self.cfg = Cfg()
    
        def teardown(self):
            self.cfg = None
    
        def test_a(self):
            self.cfg.set('foo', 'bar')
            assert self.cfg.get('foo') == 'bar'
    
        def test_b(self):
            assert self.cfg.get('foo') == 'bar'
    

I don't understand why `test_b` passes. I expected `setup` and `tearDown` to
'reset' my `cfg` instance, but it seems that `cfg` is persisting between
tests. What am I doing wrong here and how can I achieve the expected behavior?


Answer: This is related to how you've written `Cfg` class. Move `data` initialization
into `__init__` method:

    
    
    class Cfg():
        def __init__(self):
            self.data = {}
    
        def set(self, key, value):
            self.data[key] = value
    
        def get(self, key):
            return self.data.get(key, None)
    

And, you'll see failing `test_b`.

