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?
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.
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.
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.
According to the documentation:
Model.__str__()
The
__str__()
method is called whenever you callstr()
on an object.
You need to call str()
on the model instance:
self.assertEqual(str(work), work.title)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With