【问题标题】:How to mock foreign key models of a model in django?如何在 django 中模拟模型的外键模型?
【发布时间】:2020-07-09 09:48:44
【问题描述】:

我有一个带有一对多地址字段的 django 'Customer' 模型。我想模拟地址模型,并将模拟分配给篮子模型并将其保存到测试数据库。 我目前正在使用类似的东西:

address_mock = Mock(spec=Address)
address_mock._state = Mock()
customer = Customer(address=address_mock)
customer.save()

但得到错误:

ValueError: Cannot assign "\<Mock spec='Address' id='72369632'\>": the current database router prevents this relation

我只是误解了模拟/测试数据库的工作原理吗?我不想为所有测试创建地址模型,并且该字段不可为空

【问题讨论】:

标签: python django unit-testing model mocking


【解决方案1】:

查看https://factoryboy.readthedocs.io/en/latest/orms.html 有了它,您可以像这样定义子工厂:

import factory
from faker import Factory
from address.models import Address
from customer.models import Customer 

fake = Factory.create()

class AddressFactory(factory.DjangoModelFactory):
    class Meta:
        model = Address

    street = factory.LazyAttribute(lambda _: fake.street_address())
    zip_code = factory.LazyAttribute(lambda _: fake.postcode())
    place = factory.LazyAttribute(lambda _: fake.city())


class CustomerFactory(factory.DjangoModelFactory):
    class Meta:
        model = Customer

    address = factory.SubFactory(AddressFactory)
    phone = factory.LazyAttribute(lambda _: fake.phone_number())

CustomerFactory() #this creates a customer with a address 
# or you can do this
address = AddressFactory()
customer.address = address
customer.save()
# or that way 
c = CustomerFactory(address=address)

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 2015-03-07
    • 2019-02-06
    • 1970-01-01
    • 2019-07-19
    • 2015-01-29
    • 2020-11-13
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多