Search code examples
pythonpython-unittest

python unittest : test adressing non existent properly does not fail as expected


I am learning Python unit testing using unittest module.
I stumbled accross a strange behavior. Consider this code :

import unittest
class Foo:
    pass
    
class FooTest(unittest.TestCase):
    def test_non_existent_property(self):
        foo = Foo()
        self.assertTrue(0, len(foo.class_name))
        
    def test_assigning_name(self):
        foo = Foo()
        foo.class_name = 'bar'
        self.assertEqual('bar', foo.class_name)
    
unittest.main()

The tests results are :

ERROR: test_non_existent_property (__main__.FooTest)  
----------------------------------------------------------------------  
Traceback (most recent call last):  
    File "<pyshell#28>", line 4, in test_non_existent_property  
AttributeError: 'Foo' object has no attribute 'class_name'  
----------------------------------------------------------------------  
Ran 2 tests in 0.037s  

FAILED (errors=1)  

The first test fails as expected.
But the second test passes, and this puzzles me.
Shouldn't it fail too ? Why doesn't it fail ?


Solution

  • You can add attributes after the class definition. Class Foo has no attribute 'class_name' as Class attribute. But you created 'class_name' in your test method as Instance attribute:

    foo.class_name = 'bar'
    

    All class instances don't have this attribute, only one used in the test has it. Thats why your second test passed.

    https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables https://www.tutorialsteacher.com/articles/class-attributes-vs-instance-attributes-in-python