18

我正在尝试使用 factory_boy 测试两个 Django 模型之间的多对多关系。factory_boy 文档似乎没有讨论这个问题,我无法弄清楚我做错了什么。当我运行第一个测试时,我收到错误“AttributeError: 'Pizza' object has no attribute 'topping'”。我在第二次测试中遇到了类似的错误。

当我在调试器中运行测试时,我可以看到一个“toppings”对象,但它不明白如何从中获取名称。我是否正确定义了 PizzaFactory 的 _prepare 方法?当您具有多对多关系时,如何从另一个表访问一个表中的名称?

谢谢。

模型.py:

from django.db import models

class Topping(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class Pizza(models.Model):
    name = models.CharField(max_length=100)
    toppings = models.ManyToManyField(Topping)

    def __unicode__(self):
        return self.name

工厂.py:

import factory
from models import Topping, Pizza

class ToppingFactory(factory.Factory):
    name = 'mushrooms'

class PizzaFactory(factory.Factory):
    name = 'Vegetarian'

    @classmethod
    def _prepare(cls, create, **kwargs):
        topping = ToppingFactory()
        pizza = super(PizzaFactory, cls)._prepare(create, **kwargs)
        pizza.toppings.add(topping)
        return pizza

测试.py

from django.test import TestCase
import factory
from app.models import Topping, Pizza
from app.factories import ToppingFactory, PizzaFactory

class FactoryTestCase(TestCase):

    def test_pizza_has_mushrooms(self):
        pizza = PizzaFactory()
        self.assertTrue(pizza.topping.name, 'mushrooms')

    def test_mushrooms_on_pizza(self):
        topping = ToppingFactory()
        self.assertTrue(topping.pizza.name, 'Vegetarian')
4

2 回答 2

30

我相信你需要使用@factory.post_generation装饰器:

class PizzaFactory(factory.Factory):
    name = 'Vegetarian'

    @factory.post_generation
    def toppings(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of groups were passed in, use them
            for topping in extracted:
                self.toppings.add(topping)

然后你会在 tests.py 中调用它pizza = PizzaFactory.create(toppings=(topping1, topping2, tooping3))

来自https://factoryboy.readthedocs.org/en/latest/recipes.html

于 2013-11-20T10:41:52.770 回答
6

只需使用混合器:

from mixer.backend.django import mixer

# Generate toppings randomly
pizza = mixer.blend(Pizza, toppings=mixer.RANDOM)

# Set toppings
toppings = mixer.cycle(3).blend(Topping)
pizza = mixer.blend(Pizza, toppings=toppings)

# Generate toppings with name=tomato
pizze = mixer.blend(Pizza, toppings__name='tomato')

简单、可配置、更快、无模式、声明性,您可以在一些测试中得到您想要的。

于 2014-04-30T12:24:09.150 回答