Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test django model method __str__()

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?

like image 529
gintko Avatar asked Mar 16 '15 13:03

gintko


People also ask

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

Should I test Django models?

If the code in question is built into Django, don't test it. Examples like the fields on a Model or testing how the built-in template. Node renders included tags. If your model has custom methods, you should test that, usually with unit tests.

What is PK and ID in Django?

pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields.


1 Answers

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)
like image 60
alecxe Avatar answered Sep 23 '22 14:09

alecxe