codehitman codehitman - 1 year ago 226
Python Question

Why do I get an AttributeError with Python3.4's `unittest` library?

So here is my code:

import unittest

class Primes:
@staticmethod
def first(n):
<python code here>

class Test(unittest.TestCase):
def __init__(self):
pass
def assert_equals(self, l, m):
self.assertEqual(l, m)

Test = Test()
Test.assert_equals(Primes.first(1), [2])


Whenever I run my code, I get the following error:

Traceback (most recent call last):
File "firstNPrimes.py", line 37, in <module>
Test.assert_equals(Primes.first(1), [2])
File "firstNPrimes.py", line 34, in assert_equals
self.assertEqual(l, m)
File "/usr/lib/python3.4/unittest/case.py", line 796, in assertEqual
assertion_func = self._getAssertEqualityFunc(first, second)
File "/usr/lib/python3.4/unittest/case.py", line 777, in _getAssertEqualityFunc
asserter = self._type_equality_funcs.get(type(first))
AttributeError: 'Test' object has no attribute '_type_equality_funcs'


I don't understand what the problem is here.

Answer Source

You get the error because you're using unittest incorrectly. Per the example in the docs, your tests should look like:

import unittest

class TestPrimes(unittest.TestCase):

    def test_singlePrime_returnsListContainingTwo(self):
        self.assertEqual(Primes.first(1), [2])

    def test_whateverCase_expectedOutcome(self):
        self.assertEqual(Primes.first(...), ...)

if __name__ == '__main__':  # optional, but makes import and reuse easier
    unittest.main()

You can't just instantiate the test case class yourself and call the methods, that skips all of the test discovery and setup.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download