我有3个不同的应用程序,如果我运行
,每个应用程序都有unittestpython manage.py test categories coupons stores
我会得到
IntegrityError(1452, 'Cannot add or update a child row: a foreign key constraint fails (`test_gocoupons`.`coupons_coupon`, CONSTRAINT `store_id_refs_id_bf6c0d9e` FOREIGN KEY (`store_id`) REFERENCES `stores_store` (`id`))'))
但是,如果我单独运行它们就可以了。
这是所有测试用例都使用的测试混合:
# G is a function to create fixtures see django-dynamic-fixtures
class GoCouponsTestCaseMixin(object):
categories = []
stores = []
coupons = []
offers = []
def setUp(self):
self.categories.append(G(Category))
self.stores.append(G(Store, is_active=True))
# make sure we generate enough coupons for page 2
for i in range(1, settings.COUPON_PAGE_SIZE + 10):
coupon = G(Coupon, title='free', store=self.stores[0], is_active=True)
CouponCategory.objects.create(coupon=coupon, category=self.categories[0])
Offer.objects.create(start=timezone.now() + timedelta(days=-10), expire=timezone.now() + timedelta(days=10), coupon=coupon)
self.coupons.append(coupon)
Stacktrace显示此行导致问题:
coupon = G(Coupon, title='free', store=self.stores[0], is_active=True)
答案 0 :(得分:1)
看起来它是由django-dynamic-fixtures引起的,添加了几个查询以使对象看起来像是提交插入查询。
class GoCouponsTestCaseMixin(object):
categories = []
stores = []
coupons = []
offers = []
def setUp(self):
self.categories.append(G(Category))
self.stores.append(G(Store, is_active=True))
# manually querying the objects fixed it
store = Store.objects.first()
category = Category.objects.first()
# make sure we generate enough coupons for page 2
for i in range(1, settings.COUPON_PAGE_SIZE + 10):
coupon = G(Coupon, title='free', store=store, is_active=True)
CouponCategory.objects.create(coupon=coupon, category=category)
Offer.objects.create(start=timezone.now() + timedelta(days=-10), expire=timezone.now() + timedelta(days=10), coupon=coupon)
self.coupons.append(coupon)