16

I trying to test __str__ method, and when trying to access it in my test it returns my model instance (I think it is)

def test_str_is_equal_to_title(self):
    """
    Method `__str__` should be equal to field `title`
    """
    work = Work.objects.get(pk=1)
    self.assertEqual(work.__str__, work.title)

And from test I get:

AssertionError: '<bound method Work.__str__ of <Work: Test title>>' != 'Test title'

How I should compare these 2 values to pass test?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
gintko
  • 697
  • 8
  • 16
  • 2
    Did you try `self.assertEqual(work.__str__(), work.title)`? Even better, `self.assertEqual(str(work), work.title)`? – thefourtheye Mar 16 '15 at 13:03

2 Answers2

36

According to the documentation:

Model.__str__()

The __str__() method is called whenever you call str() on an object.

You need to call str() on the model instance:

self.assertEqual(str(work), work.title)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I see, that this is an old topic, but I would like to ask, how would it be done to call it for all models? In the example he is testing `str()` only for the `Work` model, or am I wrong? – dsax7 Apr 10 '17 at 21:25
  • Is `__str__` called when `print` is evoked? – MadPhysicist Sep 11 '17 at 16:02
4

Alternatively, you may simply call it like:

model_instance.__str__()

pisapapiros
  • 355
  • 1
  • 2
  • 12