一起运行时factory_boy创建测试失败,但单独运行时成功

时间:2019-01-08 06:04:54

标签: python django unit-testing django-testing factory-boy

我在项目中使用django创建了一个简单的基于位置的系统。因此,我为地址创建了一个表,并希望使用factory_boy播种数据。这是一个片段:

# Some snippet....

class StateFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = State

    name = factory.Faker('state')
    short_code = factory.Faker('state_abbr')
    country = factory.Iterator(Country.objects.all())


class CityFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = City

    name = factory.Faker('country')
    state = factory.Iterator(State.objects.all())

# end snippet..

所以我试图对此工厂进行测试,这是test_factories片段:

# Some snippet...

class StateFactoryTest(TestCase):
    def setUp(self):
        factories.CountryFactory.create()

    def test_create_many_states(self):
        total_states = 10
        factories.StateFactory.create_batch(total_states)
        self.assertEqual(models.State.objects.all().count(), total_states)


class CityFactoryTest(TestCase):
    def setUp(self):
        factories.CountryFactory.create()
        factories.StateFactory.create_batch(2)

    def test_create_many_cities(self):
        total_cities = 10
        factories.CityFactory.create_batch(total_cities)
        self.assertEqual(models.City.objects.all().count(), total_cities)

# end snippet...

如果我为每个测试用例运行测试,它将成功运行。但是,如果我同时运行所有测试,它将失败,并显示以下错误消息(每个测试类均类似):

======================================================================
ERROR: test_create_many_cities (abadfasdf.tests.apps.locations.test_factories.CityFactoryTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/abcd/miniconda3/envs/abadfasdf/lib/python3.7/site-packages/django/db/backends/utils.py", line 83, in _execute
    return self.cursor.execute(sql)
psycopg2.IntegrityError: insert or update on table "locations_state" violates foreign key constraint "locations_state_country_id_25677d21_fk_locations_country_id"
DETAIL:  Key (country_id)=(1) is not present in table "locations_country".

没有迁移/数据库错误。我认为问题在于TestCase如何回滚每个测试的数据,就好像所有 rolled-back 对象的PK存在而数据库本身没有数据一样。

那么,我可以做些什么来通过测试?还是我应该完全跳过测试?工厂本身可以工作。

0 个答案:

没有答案