python - 如何测试 Django 模型方法 __str__()

标签 python django testing django-models

我试图测试 __str__ 方法,当我试图在我的测试中访问它时,它返回我的模型实例(我认为是)

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)

从测试中我得到:

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

我应该如何比较这 2 个值才能通过测试?

最佳答案

根据documentation :

Model.__str__()

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

您需要在模型实例上调用 str():

self.assertEqual(str(work), work.title)

关于python - 如何测试 Django 模型方法 __str__(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29077509/

相关文章:

python - 在 Python 中跟踪 IP 地址

python - "output"到底是什么?

delphi - 在不修改源代码的情况下检查 Delphi 控件对象

android - 单元测试Android,从资源中获取字符串

ios - 我的核心数据实体在哪里?

python - 从当前时间获取小时

python - 在 R 中使用 system() 调用 python 以运行模拟 python 控制台的 python 脚本

python - 如何设置 DJANGO_SETTINGS_MODULE 环境变量?

python - django 'auto_now' 如何忽略指定字段的更新

django - 为什么 Django 发送了错误的电子邮件模板?