我有一些Postgres存储过程,我的Selenium测试将依赖它们。在开发中,我通过脚本中的一行来加载它们:
cat stored_procedures.sql | python manage.py dbshell
这在单元测试时不起作用,因为会从头开始创建一个新的数据库。如何在运行单元测试之前将保存在文件中的存储过程加载到测试数据库中?
我有一些Postgres存储过程,我的Selenium测试将依赖它们。在开发中,我通过脚本中的一行来加载它们:
cat stored_procedures.sql | python manage.py dbshell
这在单元测试时不起作用,因为会从头开始创建一个新的数据库。如何在运行单元测试之前将保存在文件中的存储过程加载到测试数据库中?
./manage.py makemigrations --empty myApp
将您的SQL代码添加到操作列表中
operations = [
migrations.RunSQL('RAW SQL CODE')
]
import os
from django.core.management import BaseCommand
from django.db import connection
from applications.cardo.utils import perform_query
from backend.settings import BASE_DIR
class Command(BaseCommand):
help = 'Loads all database scripts'
def handle(self, **options):
db_scripts_path = os.path.join(BASE_DIR, 'scripts', 'database_scripts')
utils_path = os.path.join(db_scripts_path, 'utils.sql')
with open(utils_path, mode='r') as f:
sql_query = f.read()
with connection.cursor() as cursor:
cursor.execute(sql_query)
python manage.py load_database_scripts
脚本将被加载。
有了像这样的帮助函数
def load():
with django_db_blocker.unblock():
call_command('load_database_scripts')
在测试套件运行之前,只需调用此加载函数即可。