Unit test objects in Python - the object is not written in the settings

I am testing testing units in Python with unittest. As I understand it, it unittestcalls a function setUpbefore each test, so the state of unit test objects is the same and the order in which the test runs does not matter.

Now I have this class that I am testing ...

#! usr/bin/python2

class SpamTest(object):

    def __init__(self, numlist = []):
        self.__numlist = numlist

    @property
    def numlist(self):
        return self.__numlist

    @numlist.setter
    def numlist(self, numlist):
        self.__numlist = numlist

    def add_num(self, num):
        self.__numlist.append(num)

    def incr(self, delta):
        self.numlist = map(lambda x: x + 1, self.numlist)

    def __eq__(self, st2):
        i = 0
        limit = len(self.numlist)

        if limit != len(st2.numlist):
            return False

        while i < limit:
            if self.numlist[i] != st2.numlist[i]:
                return False

            i += 1

        return True

with the following unit tests ...

#! usr/bin/python2

from test import SpamTest

import unittest

class Spammer(unittest.TestCase):

    def setUp(self):
        self.st = SpamTest()
        #self.st.numlist = [] <--TAKE NOTE OF ME!
        self.st.add_num(1)
        self.st.add_num(2)
        self.st.add_num(3)
        self.st.add_num(4)

    def test_translate(self):
        eggs = SpamTest([2, 3, 4, 5])
        self.st.incr(1)
        self.assertTrue(self.st.__eq__(eggs))

    def test_set(self):
        nl = [1, 4, 1, 5, 9]
        self.st.numlist = nl
        self.assertEqual(self.st.numlist, nl)

if __name__ == "__main__":
    tests = unittest.TestLoader().loadTestsFromTestCase(Spammer)
    unittest.TextTestRunner(verbosity = 2).run(tests)

This test fails for test_translate.

I can do two things to make the tests successful:

(1) Uncomment the second line in the setUp function. Or,

(2) Change the test names so that they run first translate. I noticed that unittestdoing tests in alphabetical order. By changing translateto, say, atranslatethat it is executed first, all tests are successfully executed.

(1) , , setUp self.st. (2), , , hey, on setUp self.st, , self.st test_set, test_translate.

, ?

+5
2

detes , Python Fredrik Lundh.

, . , , . - , , .

, , . , .

None __init__ , , :

class SpamTest(object):

    def __init__(self, numlist=None):
        if numlist is None:
            numlist = []         # this is the new instance -- the empty list
        self.__numlist = numlist
+10

, Python Mutable , : Python.

:

def __init__(self, numlist = []):

numlist , , SpamTest.

, , setUp, , , , .

, - , , None:

def __init__(self, numlist = None):
    if numlist is None:
        numlist = []
    self.__numlist = numlist

, , , , , .

+4

All Articles