codehitman codehitman - 9 months ago 79
Python Question

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

So here is my code:

import unittest

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

class Test(unittest.TestCase):
def __init__(self):
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 "", line 37, in <module>
Test.assert_equals(Primes.first(1), [2])
File "", line 34, in assert_equals
self.assertEqual(l, m)
File "/usr/lib/python3.4/unittest/", line 796, in assertEqual
assertion_func = self._getAssertEqualityFunc(first, second)
File "/usr/lib/python3.4/unittest/", 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.


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

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