Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Unittest and object initialization

My Python version is 3.5.1

I have a simple code (tests.py):

import unittest

class SimpleObject(object):
    array = []

class SimpleTestCase(unittest.TestCase):

    def test_first(self):
        simple_object = SimpleObject()
        simple_object.array.append(1)

        self.assertEqual(len(simple_object.array), 1)

    def test_second(self):
        simple_object = SimpleObject()
        simple_object.array.append(1)

        self.assertEqual(len(simple_object.array), 1)

if __name__ == '__main__':
    unittest.main()

If I run it with command 'python tests.py' I will get the results:

.F
======================================================================
FAIL: test_second (__main__.SimpleTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests.py", line 105, in test_second
    self.assertEqual(len(simple_object.array), 1)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.003s

FAILED (failures=1)

Why it is happening? And how to fix it. I expect that each tests run will be independent (each test should pass), but it is not as we can see.

like image 977
Tom Avatar asked Dec 20 '25 19:12

Tom


1 Answers

The array is shared by all instances of the class. If you want the array to be unique to an instance you need to put it in the class initializer:

class SimpleObject(object):
    def __init__(self):
        self.array = []

For more information take a look at this question: class variables is shared across all instances in python?

like image 102
Bryan Oakley Avatar answered Dec 22 '25 11:12

Bryan Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!