我尝试使用单元测试来测试Django REST API。这是测试用例的代码:
def test_orders_valid_data(self):
try:
o1 = md.ECare_Order.objects.create(order_id='aaaaa', created='2015-07-22',grand_total=120)
o2 = md.ECare_Order.objects.create(order_id='aaaaa', created='2015-07-10', grand_total=100)
o3 = md.ECare_Order.objects.create(order_id='bbbbb', created='2015-06-22', grand_total=90)
orders = [o1,o2,o3]
om1 = md.ECare_OrderMetric.objects.create(value=1,name='impression_order',order=o1)
om2 = md.ECare_OrderMetric.objects.create(value=1,name='impression_order',order=o2)
om3 = md.ECare_OrderMetric.objects.create(value=1,name='impression_order',order=o1)
om4 = md.ECare_OrderMetric.objects.create(value=1,name='impression_order',order=o3)
order_metrics = [om1,om2,om3,om4]
for o in orders:
o.save()
for o in order_metrics:
o.save()
r = requests.get("http://127.0.0.1:8000/analytics/v1/carters/engagement/order?window_days=30&end_date=08-08-2015")
self.assertTrue(json.loads(r.text)['order_emails'],2)
finally:
for o in orders:
o.delete()
for o in order_metrics:
o.delete()
问题是,当执行o.delete()
块中的finally
时,它会引发异常:
Traceback (most recent call last):
....
File "/home/roman/dev/python/awo100/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "/home/roman/dev/python/awo100/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
AppRegistryNotReady: Models aren't loaded yet.
create
和save
等所有其他操作都可以正常工作并创建和保存对象。如何解决这个问题?
答案 0 :(得分:0)
我通过添加
找到了解决方案import django
django.setup()