如何解决Django单元测试中的`model_bakery`生成的意外模型
我已经大量使用了model_bakery
(在此之前,model_mommy
),所以这个错误使我感到自己在服用疯药。
from model_bakery import baker
# BaseTestCase inherits from django.test.TestCase
# it creates a tenant object assigned to self.tenant in BaseTestCase.setUp
class TestSchemas(BaseTestCase):
def setUp(self):
super().setUp()
self.assertEqual(Tenant.objects.count(),1,"This one passes")
self.assertTrue(
Tenant.objects.filter(pk=self.tenant.pk).exists,"The only tenant I expect is here,persisted,and correct."
)
self.schema = baker.make(
"Schema",tenant=self.tenant,)
self.assertEqual(self.schema.tenant,self.tenant,"This also does not fail...")
# This is the failing assert
self.assertEqual(
Tenant.objects.count(),"This case fails. I _expect_ no additional Tenant objects to have been created."
)
from django.db import models
class Tenant(models.Model):
tenant_xid = models.BigIntegerField("Tenant ID",primary_key=True)
class Schema(models.Model):
form_schema_xid = models.BigIntegerField("schema ID",primary_key=True)
tenant = models.ForeignKey(
Tenant,models.CASCADE,db_column="tenant_xid",related_name="schemas"
)
如声明消息中所述,setUp
方法以一个Tenant
对象开始了我的预期。我使用baker
创建一个Schema
。我希望该模式使用现有的Tenant
,但它似乎正在创建第二个模式,如最终的断言所示,AssertionError: 2 != 1
我已将案件简化到最低限度,但我一直在努力了解正在发生的事情。模型上没有任何重写的方法,BaseTestCase
并没有做任何特别的事情...下一步我可以尝试什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。