classification
Title: Call to another class's constructor in unittest.TestCase.setUp returns the same instance multiple times
Type: behavior Stage: resolved
Components: Library (Lib), Tests Versions: Python 2.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: awaltman, r.david.murray
Priority: normal Keywords:

Created on 2009-12-10 02:20 by awaltman, last changed 2009-12-10 02:46 by r.david.murray. This issue is now closed.

Files
File name Uploaded Description Edit
unittest_doesnt_reinstantiate_members.txt awaltman, 2009-12-10 02:20 Code and output
Messages (3)
msg96189 - (view) Author: Aaron Altman (awaltman) Date: 2009-12-10 02:20
Not sure if this is intended behavior.  I have a baseClass I'm writing
tests for.  My test architecture has an instance of this baseClass
assigned as a member of TestBaseClass(unittest.TestCase) in
TestBaseClass.setUp.

The problem occurs when tests in TestBaseClass modify state within the
member baseClass instance.  I think there should be a fresh new instance
of baseClass for every test that gets run, but the old state from the
last test is still there.

Example code and output from Python 2.6.2 attached.
msg96192 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2009-12-10 02:42
Yes, this working as intended.  Consider:

Python 2.7a1+ (trunk:76725, Dec  9 2009, 09:26:36)
[GCC 4.4.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class baseClass(object):
...     def __init__(self, testList=[]):
...         self.testList = testList
...     def insertItem(self):
...         self.testList.append("testing from baseClass")
...
>>> a = baseClass()
>>> b = baseClass()
>>> del b
>>> a.insertItem()
>>> print a.testList
['testing from baseClass']
>>> b = baseClass()
>>> print b.testList
['testing from baseClass']


See
http://docs.python.org/faq/design.html#why-are-default-values-shared-between-objects
for an explanation of why.
msg96193 - (view) Author: R. David Murray (r.david.murray) * (Python committer) Date: 2009-12-10 02:46
Heh, that first b = baseClass(); del b wasn't supposed to be there and
doesn't change the result, just in case you were wondering.
History
Date User Action Args
2009-12-10 02:46:30r.david.murraysetmessages: + msg96193
2009-12-10 02:42:22r.david.murraysetstatus: open -> closed
priority: normal
type: behavior


nosy: + r.david.murray
messages: + msg96192
resolution: not a bug
stage: resolved
2009-12-10 02:21:34awaltmansettitle: Call to another class's constructor in unittest.TestCase.setUp returns the same instance -> Call to another class's constructor in unittest.TestCase.setUp returns the same instance multiple times
2009-12-10 02:20:55awaltmancreate