简体   繁体   中英

setUp function is not called before every unit test in python

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM