Django 测试中导入函数中的 运行 db 查询是否有限制?
Is there a limitation on running db query in imported function in django tests?
我在视图中使用函数来查询数据库 (postgresql)、计算值和 return 列表列表。当我从 views.py 调用它时,我得到了预期的结果。当我从 test.py 调用它时,我得到空列表(不是错误,不是 None)。为了进行调查,我在视图函数中手动创建了列表列表,并且 returned 很好(因此 returned 值的导入或长度没有问题)。似乎如果我调用从进行数据库查询的视图导入的函数,并且它是从 TestCase 对象调用的,那么数据库查询就不会完成。为什么?
from django.test import TestCase
from <my app>.views import calc
import datetime
from pytz import timezone
class CalcTestCase(TestCase):
maxDiff = None
def test_calc_image(self):
start_time = datetime.datetime(2018, 9, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') )
finish_time = datetime.datetime(2018, 10, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') )
instance_type = "test"
output = calc(instance_type, start_time, finish_time)
test_output = [[test, values, in],[list, of, lists]]
self.assertEqual(output, test_output)
因为测试总是运行 来自空数据库。您需要在测试用例本身中为您的测试创建条目。参见 the testing docs。
我在视图中使用函数来查询数据库 (postgresql)、计算值和 return 列表列表。当我从 views.py 调用它时,我得到了预期的结果。当我从 test.py 调用它时,我得到空列表(不是错误,不是 None)。为了进行调查,我在视图函数中手动创建了列表列表,并且 returned 很好(因此 returned 值的导入或长度没有问题)。似乎如果我调用从进行数据库查询的视图导入的函数,并且它是从 TestCase 对象调用的,那么数据库查询就不会完成。为什么?
from django.test import TestCase
from <my app>.views import calc
import datetime
from pytz import timezone
class CalcTestCase(TestCase):
maxDiff = None
def test_calc_image(self):
start_time = datetime.datetime(2018, 9, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') )
finish_time = datetime.datetime(2018, 10, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') )
instance_type = "test"
output = calc(instance_type, start_time, finish_time)
test_output = [[test, values, in],[list, of, lists]]
self.assertEqual(output, test_output)
因为测试总是运行 来自空数据库。您需要在测试用例本身中为您的测试创建条目。参见 the testing docs。