It doesn't seem possible to create multiple model instances using separate calls to prepare_recipe() within a SimpleTestCase if the recipe uses seq(). This triggers a database call to m.objects.count() in https://github.com/model-bakers/model_bakery/blob/main/model_bakery/recipe.py#L37 which is disallowed inside a SimpleTestCase.
I didn't find this issue documented anywhere, although I may have missed it. It seems at least surprising if not a bug to have a database call in prepare_recipe() since the purpose of that method is to instantiate but not save a model instance. If it turns out this is not fixable, perhaps adding documentation regarding this caveat is appropriate.
Expected behavior
The prepare_recipe() method is always usable within SimpleTestCase.
Actual behavior
The use of prepare_recipe() within SimpleTestCase fails when the recipe contains a seq() and is called more than once.
Reproduction Steps
# models.py
from django.db import models
class MyModel(models.Model):
my_field = models.IntegerField()
# baker_recipes.py
from model_bakery.recipe import Recipe, seq
from .models import MyModel
my_model = Recipe(MyModel, my_field=seq(1))
# tests.py
from django.test import SimpleTestCase
from model_bakery import baker
class MyTest(SimpleTestCase):
def test_my_model(self):
# This test errors due to the db query to m.objects.count() in:
# https://github.com/model-bakers/model_bakery/blob/main/model_bakery/recipe.py#L37
# Note that baker.prepare_recipe('myapp.my_model', _quantity=2) would work in this simple example,
# but more complex situations may need instances created at separate points in the test
baker.prepare_recipe('myapp.my_model')
baker.prepare_recipe('myapp.my_model')
Versions
Python: 3.8.6
Django: 3.0.11
Model Bakery: 1.2.1
It doesn't seem possible to create multiple model instances using separate calls to
prepare_recipe()within aSimpleTestCaseif the recipe usesseq(). This triggers a database call tom.objects.count()in https://github.com/model-bakers/model_bakery/blob/main/model_bakery/recipe.py#L37 which is disallowed inside aSimpleTestCase.I didn't find this issue documented anywhere, although I may have missed it. It seems at least surprising if not a bug to have a database call in
prepare_recipe()since the purpose of that method is to instantiate but not save a model instance. If it turns out this is not fixable, perhaps adding documentation regarding this caveat is appropriate.Expected behavior
The
prepare_recipe()method is always usable withinSimpleTestCase.Actual behavior
The use of
prepare_recipe()withinSimpleTestCasefails when the recipe contains aseq()and is called more than once.Reproduction Steps
Versions
Python: 3.8.6
Django: 3.0.11
Model Bakery: 1.2.1