我在任何地方都没有看到 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>]
你知道为什么我的 fixture 只在 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,
}
},
最佳答案
那是因为 TransactionTestCase
在实例的 setUp
方法中加载了固定装置,所以它的子类包括 LiveServerTestCase
做同样的事情 - 除了 TestCase
,每个类使用单个原子事务并加载 setUpClass
中的固定装置以加速测试执行。此行为已添加到 #20392 中.
这对您来说意味着您应该将所有与数据库相关的代码从 setupClass
移动到 LiveServerTestCase
子类中的 setUp
:
class FrontendLiveTest(LiveServerTestCase):
def setUp(self):
# the transaction is opened, fixtures are loaded
assert Event.objects.exists()
注意事项
如果您尝试将 TestCase
的原子事务与 LiveServerTestCase
的后台线程混合:如 LiveServerTestCase
文档所述,
It inherits from
TransactionTestCase
instead ofTestCase
because the threads don't share the same transactions (unless if using in-memorysqlite
) and each thread needs to commit all their transactions so that the other thread can see the changes.
关于python - Django : fixtures object not retrievable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50609171/