I wrote some unit tests for a set of classes, and when I run them normally in PyCharm there's always a test that fails. If I try to observe the bug directly by placing a breakpoint where it would normally fail and then inspecting the variables, I find nothing, and when I step over the problem line it has no issue. However without the breakpoint it doesn't work. Debugging the issue indirectly, I found that the test object that is created in setUp is somehow not a new object; it is the same object that gets deleted in tearDown.
I have isolated the issue by rewriting and stripping down the tests and this is the result:
from collections import deque
from unittest import TestCase
class Habit:
durations = deque([], maxlen=8)
def duration(self):
try:
return self.durations[0]
except IndexError:
return 0
class TestHabit(TestCase):
class_ = Habit
def setUp(self):
self.task = self.class_()
def test_duration(self):
self.assertEqual(self.task.duration(), 0)
self.task.durations.append(9)
def tearDown(self):
del self.task
class TestBadHabit(TestHabit):
pass
When I run this code I get
Failure
Traceback (most recent call last):
File "C:\Users\hunte_000\PycharmProjects\sandbox\so.py", line 22, in test_duration
self.assertEqual(self.task.duration(), 0)
AssertionError: 9 != 0
In stripping it down I found that if I refactored durations
to be an integer instead of a deque, it works. It also works if I remove the last two lines.
The only solution I could think of was updating Python, but that didn't work.
I have a feeling I'm doing something wrong. Any idea what's going on?