有人能给我指出一个资源,它展示了如何在单元测试期间查询Django测试数据库的特定表吗
我有以下测试代码:
from django.test import TestCase
from users.models import User
class DisputeAssignerTestSuite(TestCase):
databases = [
'default',
'read_replica',
]
@classmethod
def setUpTestData(cls):
cls.users = UserFactory.create_batch(50)
def test_firstOne(self):
print(users)
print(User.objects.all())
用户工厂代码:
import factory
from faker import Factory
import pytz
from users.models import User
faker = Factory.create()
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
django_get_or_create = ('first_name', 'last_name', 'timezone', 'locale')
first_name = factory.LazyAttribute(lambda _: faker.first_name())
last_name = factory.LazyAttribute(lambda _: faker.last_name())
display_name = factory.LazyAttribute(lambda _: _.first_name + " " + _.last_name)
timezone = factory.LazyAttribute(lambda _: faker.timezone())
locale = factory.LazyAttribute(lambda _: faker.random_choices(elements=('en-au', 'en-us', 'de-de', 'fr-fr'), length=1))
password = factory.LazyAttribute(lambda _: faker.password(length=12))
last_login = factory.LazyAttribute(lambda _: faker.past_datetime(start_date="-60d", tzinfo=pytz.timezone(faker.timezone())))
is_superuser = factory.LazyAttribute(lambda _: faker.boolean(50))
email = factory.LazyAttribute(lambda _: faker.email())
username = factory.LazyAttribute(lambda _: _.email)
is_staff = factory.LazyAttribute(lambda _: faker.boolean(50))
is_active = factory.LazyAttribute(lambda _: faker.boolean(50))
date_joined = factory.LazyAttribute(lambda _: faker.past_datetime(start_date="-1y", tzinfo=pytz.timezone(faker.timezone())))
我不明白,我如何在Django为这个测试用例运行创建的测试数据库中查询用户表,例如,验证其内容是否符合某些特定要求(例如,是否有特定名字的用户等)
当我写作时:
print(User.objects.all())
我得到生产数据库的输出
救命啊
更新:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': global_config['postgresql']['database'],
'USER': global_config['postgresql']['user'],
'PASSWORD': global_config.get('postgresql', 'password'),
'HOST': global_config['postgresql']['host'],
'PORT': global_config['postgresql']['port'],
'CONN_MAX_AGE': 30,
'TEST': {
'NAME': 'mytestdatabase',
},
'OPTIONS': {
'connect_timeout': 60,
'sslmode': 'prefer'
},
},
'read_replica': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': global_config['postgresql']['database_read_replica'],
'USER': global_config['postgresql']['user_read_replica'],
'PASSWORD': global_config.get('postgresql', 'password_read_replica'),
'HOST': global_config['postgresql']['host_read_replica'],
'PORT': global_config['postgresql']['port_read_replica'],
'CONN_MAX_AGE': 30,
'TEST': {
'MIRROR': 'default',
},
'OPTIONS': {
'connect_timeout': 60,
'sslmode': 'prefer'
},
}
REPLICA_DATABASES = ['read_replica',]
DATABASE_ROUTERS = [
'multidb.PinningReplicaRouter',
]
在对这个问题进行了大量修补之后,我终于发现,用于数据库路由的“multidb.PinningReplicaRouter”中间件是问题的根源。在Django 2.2.11和;在我的例子中,Python3.7阻止了查询到测试数据库的正确路由,反而破坏了PROD/DEV隔离层,写入了???(很难说,因为我不能做回读)和从PROD数据库回读
我已经解决了这个问题,在我想要运行的测试套件前面包含了以下装饰程序:
希望这对将来的人有好处
相关问题 更多 >
编程相关推荐