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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With