我没有看到LiveServerTestCase没有加载灯具的任何地方,但是当我执行以下操作时:
class FrontTest(LiveServerTestCase):
fixtures = ['event.json']
@classmethod
def setUpClass(cls):
super().setUpClass()
print(Event.objects.all())
输出结果为:
Using existing test database for alias 'default'...
[]
当我使用TestCase
class FrontTest(TestCase):
fixtures = ['event.json']
@classmethod
def setUpClass(cls):
super().setUpClass()
print(Event.objects.all())
输出是:
[<Event: event search>]
你知道为什么我的夹具只在TestCase中加载吗?我真的很想使用Selenium。谢谢!
PS:event.json :
{
"model": "mezzanine_agenda.event",
"pk": 1,
"fields": {
"comments_count": 0,
"keywords_string": "",
"rating_count": 0,
"rating_sum": 0,
"rating_average": 0.0,
"site": 1,
"title": "event search",
"slug": "event-search",
"_meta_title": "",
"description": "event search",
"gen_description": true,
"created": "2018-05-25T15:49:55.223Z",
"updated": "2018-05-25T15:49:55.257Z",
"status": 2,
"publish_date": "2018-05-25T15:49:32Z",
"expiry_date": null,
}
},
答案 0 :(得分:1)
首先,遗憾的是,Django忽略了它找不到的固定装置。您看到的错误意味着Django无法找到fixture文件并因警告而失败:https://code.djangoproject.com/ticket/18990
以下是Django如何找到灯具:settings.FIXTURE_DIRS
fixtures
的文件夹中的所有应用程序目录下查找。基于此,请查看您的文件所在的位置,并且可以解决此问题
这是fixture_dirs
的Django代码:
@cached_property
def fixture_dirs(self):
"""
Return a list of fixture directories.
The list contains the 'fixtures' subdirectory of each installed
application, if it exists, the directories in FIXTURE_DIRS, and the
current directory.
"""
dirs = []
fixture_dirs = settings.FIXTURE_DIRS
if len(fixture_dirs) != len(set(fixture_dirs)):
raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.")
for app_config in apps.get_app_configs():
app_label = app_config.label
app_dir = os.path.join(app_config.path, 'fixtures')
if app_dir in fixture_dirs:
raise ImproperlyConfigured(
"'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label)
)
if self.app_label and app_label != self.app_label:
continue
if os.path.isdir(app_dir):
dirs.append(app_dir)
dirs.extend(list(fixture_dirs))
dirs.append('')
dirs = [upath(os.path.abspath(os.path.realpath(d))) for d in dirs]
return dirs
答案 1 :(得分:1)
那是因为TransactionTestCase
在实例'setUp
方法中加载了fixture,所以它的子类包括LiveServerTestCase
也是一样的 - 除了TestCase
,它使用单个原子事务类并加载setUpClass
中的灯具以加速测试执行。此行为已添加到#20392。
对您来说意味着您应该将setupClass
子类中的所有数据库相关代码从setUp
移动到LiveServerTestCase
:
class FrontendLiveTest(LiveServerTestCase):
def setUp(self):
# the transaction is opened, fixtures are loaded
assert Event.objects.exists()
如果您尝试将TestCase
s原子事务与LiveServerTestCase
个后台线程混合起来:如LiveServerTestCase
docs中所述,
它继承自
TransactionTestCase
而不是TestCase
,因为线程不共享相同的事务(除非使用内存中sqlite
)并且每个线程都需要提交所有事务这样其他线程就可以看到变化。