【问题标题】:What's the best way to load stored procedures into the Django unit test database?将存储过程加载到 Django 单元测试数据库的最佳方法是什么?
【发布时间】:2017-02-16 18:30:15
【问题描述】:

我有一些我的 selenium 测试将依赖的 Postgres 存储过程。在开发中,我用脚本中的一行加载它们:

cat stored_procedures.sql | python manage.py dbshell

这在单元测试时不起作用,因为新数据库是从头开始创建的。如何在运行单元测试之前将保存在文件中的存储过程加载到测试数据库中?

【问题讨论】:

    标签: django postgresql unit-testing selenium stored-procedures


    【解决方案1】:

    我认为你有几种方法可以做到这一点。在我看来,最好的解决方案 - 使用您的自定义 SQL 添加迁移。将来,您不仅在开发阶段,而且在生产阶段都需要这种迁移。因此,如果您将更改存储到数据库中的几个地方,部署过程将不清楚。

    其他方式 - 只是将 SQL 的执行添加到 testCase 的 setUp 方法中。

    其他迁移

    您应该创建一个新的空迁移./manage.py makemigrations --empty myApp

    将您的 SQL 代码添加到 operations 列表中

    operations = [ migrations.RunSQL('RAW SQL CODE') ]

    【讨论】:

    • 非常感谢——这看起来很完美。
    • 这看起来不错,谢谢,但如果您决定删除所有迁移并重新创建架构,自动生成它会更好
    【解决方案2】:

    另一个解决方案是创建一个执行所需 SQL 查询的管理命令,然后在测试开始时执行此命令。 以下是我的情况: 管理命令:

    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')
    

    您只需在测试套件运行之前调用此加载函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多