4

I'm trying to test the return type on __repr__. It's not a string so what is it? What's happening here?

import unittest
class MyClass(unittest.TestCase):
    class Dog(object):
            def __init__(self, initial_name):
                self._name = initial_name

            def get_self(self):
                return self

            def __repr__(self):
                return "Dog named '" + self._name + "'"

    def runTest(self):
        fido = self.Dog("Fido")
        self.assertEqual("Dog named 'Fido'", fido.get_self()) #Fails!

test=MyClass("runTest")
runner=unittest.TextTestRunner()
runner.run(test)

Running this gives:

FAIL: runTest (__main__.MyClass)
----------------------------------------------------------------------
Traceback (most recent call last):
   File "/home/xxxxx/fido.py", line 15, in runTest
     self.assertEqual("Dog named 'Fido'", fido.get_self())
   AssertionError: "Dog named 'Fido'" != Dog named 'Fido'

 ----------------------------------------------------------------------
 Ran 1 test in 0.006s

 FAILED (failures=1)

How can I get this test to pass?

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
hhbilly
  • 1,265
  • 10
  • 18

3 Answers3

5
self.assertEqual("Dog named 'Fido'", repr(fido.get_self()))

or just

self.assertEqual("Dog named 'Fido'", repr(fido))

Otherwise assertEqual is correctly telling you that the string is not equal to the object. When it renders the error message it uses repr on the object, so the error looks a bit confusing

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

repr return a string, but fido.get_self() return a Dog object, not a string.

When there is an assertion error, it uses "repr" to display a readable representation of your Dog instance.

MatthieuW
  • 2,292
  • 15
  • 25
0

Check the type of the comparison your assert does by doing print type(s). You are comparing __repr__ with str. To make it work compare both strings. See Difference between __str__ and __repr__ in Python

Community
  • 1
  • 1
Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65