简体   繁体   中英

How to mock foreign key models of a model in django?

I have a django 'Customer' model with an Address one-to-many field. I want to mock the address model, and assign the mock to the basket model and save that to the test database. I am currently using something like:

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

but get the error:

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

am I just misunderstanding how mock/the test db works? I don't want to have to create an address model for all my tests, and the field is not nullable

Check out https://factoryboy.readthedocs.io/en/latest/orms.html with it you can define sub factories like so:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM