【发布时间】:2020-05-02 22:18:11
【问题描述】:
当我运行将数据插入数据库的 Django 测试时,它将插入到我的本地 db.sqlite3 并在测试完成时保留它。我不希望这种情况发生,也不应该是according to the docs:
无论测试通过还是失败,测试数据库都是 执行完所有测试后销毁。
我的单元测试:
from unittest import TestCase
from web.constants import USER_TYPE_CONTRACTOR
from web.models import User
class LoginTestCase(TestCase):
def setUp(self):
self.demo_user_1_username = 'c2'
User.objects.create(username=self.demo_user_1_username, password='c12345678')
def test_user_defaults_to_contractor(self):
demo_user_1 = User.objects.get(username=self.demo_user_1_username)
self.assertEqual(demo_user_1.user_type, USER_TYPE_CONTRACTOR)
def doCleanups(self):
"""Delete demo data from database"""
# I needed to do this as workaround
# demo_user_1 = User.objects.get(username=self.demo_user_1_username)
# demo_user_1.delete()
用户c2现在在db.sqlite3中,所以当我再次运行测试时,它失败了,因为用户名c2已经存在。
我已尝试在settings.py 中执行此操作:
DATABASES = {
'default': dj_database_url.config(conn_max_age=600)
}
DATABASES['default']['TEST'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
}
但是test_db.sqlite3 没有创建。
我如何使用内存中的 sqlite3 数据库,以便在测试时不会影响我的本地数据库?
【问题讨论】:
-
我不知道这是否是您的问题的原因,但您引用的文档建议在使用数据库访问运行测试时使用
django.test.TestCase而不是unittest.TestCase。
标签: python django sqlite django-testing django-database