DonMorton
DonMorton

Reputation: 403

Python individual unit tests seem to use same instantiated object

I wonder if someone can help me understand why objects instantiated within separate unittests are in fact the same, with the same id. This happens when I run the unittest from a python command line, but not when I run via py.test.

Am I wrong in thinking that these two test methods should be independent, and therefore have their own objects?

MyClass.py

class MyClass(object):

    def __init__(self, name=None):
        if name:
            self._name = name
        else:
            self._name = 'No Name'

    def get_name(self):
        return self._name

test_myclass.py

import unittest
import MyClass

class TestMyClass(unittest.TestCase):

    def test_works_with_none(self):
        m = MyClass.MyClass()
        print 'test_works_with_none id: ' + str(id(m))
        n = m.get_name()

        self.assertEqual(n, 'No Name')

    def test_works_with_name(self):

        m = MyClass.MyClass(name='Don')
        print 'test_works_with_name id: ' + str(id(m))
        n = m.get_name()
        self.assertEqual(n, 'Don')

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

python test_myclass.py

$ python test_myclass.py
test_works_with_name id: 139857431210832
.test_works_with_none id: 139857431210832
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

py.test -s

$ py.test -s
============================= test session starts ==============================
platform linux2 -- Python 2.7.9 -- py-1.4.25 -- pytest-2.6.3
collected 2 items 

test_myclass.py test_works_with_name id: 140612631892240
.test_works_with_none id: 140612631892624
.

=========================== 2 passed in 0.02 seconds ===========================

Upvotes: 0

Views: 167

Answers (1)

Michael Jaros
Michael Jaros

Reputation: 4681

The return value of id() is guaranteed to be unique only among all objects that exist at the same time. From the documentation:

Two objects with non-overlapping lifetimes may have the same id() value.

Consider this simplified example:

>>> a=object()
>>> b=object()
>>> id(a)
140585585143936
>>> id(b)
140585585143952
>>> del a
>>> del b
>>> a=object()
>>> id(a)
140585585143952
>>> del a
>>> b=object()
>>> id(b)
140585585143952

Upvotes: 1

Related Questions