Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate objects during a unit test's setup phase in Python

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?

like image 374
Steven Mercatante Avatar asked Sep 02 '25 10:09

Steven Mercatante


1 Answers

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.

like image 58
alecxe Avatar answered Sep 05 '25 00:09

alecxe