问题
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.
回答1:
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.
回答2:
Your methods look fine to me, and mimic what I see in the example code provided through the help function.
import unittest help(unittest)
I have the same problem using a debs build in a virtual box working in a python 2.7 environment. For some reason only the assertEqual method is problematic. assertAlmostEqual (scientific assert equal), assertSequenceEqual, assertItemEqual, etc. have no problems.
Since you are subclassing unittest.TestCase the class you define is inheriting all the methods of unittest.TestCase class, including the method assertEqual.
for your code I can run (from the command line in python 2.7):
import testing_code as t
test_object = t.Test()
t.assertSequenceEqual([4,5,6] , [4,5,6])
t.assertNotEqual(4,7)
and no problems... I get your same errors trying a simple assertEqual method. I don't think this is a code structure/misuse of unittest problem, and am pretty sure this is an environment/build problem. I decided i needed an assert equal as a method on my class so i just made a simple one:
def AssertEqual(self, a, b):
if a!=b:
msg= 'inputs unequal: a, b:', a, b
raise ValueError, msg
来源:https://stackoverflow.com/questions/38944798/why-do-i-get-an-attributeerror-with-python3-4s-unittest-library