Reputation: 13723
This is my code that tests the class School
:
class SchoolTest(unittest.TestCase):
def setUp(self):
# assertCountEqual is py3, py2 only knowns assetItemsEqual
if not hasattr(self, 'assertCountEqual'):
self.assertCountEqual = self.assertItemsEqual
self.school = School("Haleakala Hippy School")
def test_an_empty_school(self):
for n in range(1, 9):
self.assertCountEqual(set(), self.school.grade(n))
def test_add_student(self):
self.school.add("Aimee", 2)
self.assertCountEqual(("Aimee",), self.school.grade(2))
I want to create a new School
object before every test. When I run the tests, I end up with the following error:
def test_an_empty_school(self):
for n in range(1, 9):
self.assertCountEqual(set(), self.school.grade(n))
AssertionError: Element counts were not equal:
First has 0, Second has 1: 'Aimee'
It means that the second test is called first and the new object is not created, that's why the first test fails.
If I comment any of them and run the tests, it passes regardless of which one I comment.
I feel like I am missing one fundamental thing.
What am I doing wrong?
Just in case, School
class:
class School():
_db = dict()
def __init__(self, name):
self.name = name
@property
def db(self):
return self._db
def add(self, student, grade):
if grade not in self._db:
self._db[grade] = set()
self._db[grade].add(student)
def grade(self, grade):
if grade not in self._db:
return set()
return self._db[grade]
def sort(self):
sorted_list = []
for grade in self._db:
sorted_list.append((grade, tuple(self._db[grade])))
return sorted_list
Upvotes: 2
Views: 2147
Reputation: 55599
The problem is that that School._db
is an attribute on the class, not on an instance, so modifications to School._db
survive between test runs.
You should make _db an instance attribute by initialising it School.__ init __
class School():
def __init__(self, name):
self.name = name
self._db = dict()
Upvotes: 3