如何在pytest中实现Django的setUpTestData等效功能,复用数据库状态提升测试速度
如何在pytest中实现Django的setUpTestData等效功能,复用数据库状态提升测试速度
我之前用过Django的TestCase.setUpTestData,它能大幅提升测试速度,这点我亲身体验过。不过我平时更习惯用pytest的fixture而不是TestCase类。最近我尝试做一个会话级(session-scope)的fixture,用来做所有测试都需要的数据库数据准备,结果却碰到了这个错误:
RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.
我跟着一个解决方案尝试过,但完全没效果。我用的是内存中的sqlite3数据库,想知道在Django+pytest的测试场景下,怎么才能存储并复用数据库状态呢?
我试过的代码是这样的:
@pytest.mark.django_db @pytest.fixture(scope='session') def thing(django_db_setup, django_db_blocker): del django_db_setup # Cannot be used with usefixtures(..) it won't work with django_db_blocker.unblock(): print('sleeping') Thing.objects.create(thing='hello')
我本来期望测试能成功运行,同时节省时间,但还是弹出了上面那个RuntimeError。(函数级的fixture是正常工作的,但那样根本没法节省测试执行时间)
备注:内容来源于stack exchange,提问作者Martin Thoma
相关产品推荐
相关产品推荐

