3

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.

Tom
  • 727
  • 11
  • 26

1 Answers1

5

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?

Community
  • 1
  • 1
Bryan Oakley
  • 341,422
  • 46
  • 489
  • 636