How do I pass this test?

I am trying to check return type on __repr__ . This is not a string, but what is it? What's going on 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 pass this test?

+4
source share
3 answers
 self.assertEqual("Dog named 'Fido'", repr(fido.get_self())) 

or simply

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

Otherwise, assertEqual correctly tells you that the string is not equal to the object. When it displays an error message, it uses repr for the object, so the error looks a bit confusing

+5
source

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

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

0
source

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

0
source

Source: https://habr.com/ru/post/1432260/


All Articles