微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

模拟 Django GenericForeignKey

如何解决模拟 Django GenericForeignKey

我正在尝试使用 Django GenericForeignKey structure 测试模型的 QuerySet,并想模拟它连接到的多个模型。但是,当我尝试使用其中一个模拟模型来证实 Flag 模型(一个带有 GenericForeignKey 的模型)时,会引发 TypeError: TypeError: Flag() got an unexpected keyword argument 'content_object'

我尝试了下面的代码,注释掉了 content_object 行,并且有效。但是稍后的部分测试需要该属性,因此忽略它不是一个可行的解决方案。

#models.py
class Flag(TimeStampedModel):
    text = models.TextField()
    content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()


#tests.py
...
    def setUp(self):
        self.quantity = 10
        text = ['foo','bar','baz','qux']
        for object_ in [mock.Mock(spec=ModelType1),mock.Mock(spec=ModelType2),mock.Mock(spec=ModelType3)]:
            for i in range(self.quantity):
                object_.pk = i
                f = Flag.objects.create(
                    text=random.choice(text),content_type=ContentType.objects.get_for_model(object_.__class__),object_id=object_.pk,content_object = object_
                )

我尝试将该行移出 create 函数并尝试在之后设置它,但这似乎会触发对象状态的错误

f.content_type = object_
f.save()

...
  File ".../python3.9/site-packages/django/contrib/contenttypes/fields.py",line 164,in get_content_type
    return ContentType.objects.db_manager(obj._state.db).get_for_model(
  File "...Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py",line 630,in __getattr__
    raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '_state'

Django==3.2.5,Python 3.9.5

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?