【问题标题】:Unit test to check for ungenerated migrations单元测试以检查未生成的迁移
【发布时间】:2015-10-20 17:27:30
【问题描述】:

是否有人编写了单元测试来验证他们的 Django 应用程序中是否存在未生成的迁移?我认为它应该看起来像:

  1. 致电python manage.py makemigrations
  2. 将结果抓取到可解析的对象中
  3. 验证"no migrations were found"
  4. 如果找到迁移,请列出它们,测试失败,并删除生成的文件

如果没有,我会写一个,这样我们的构建就会失败。

【问题讨论】:

    标签: python django unit-testing django-migrations


    【解决方案1】:

    从 Django 1.10 开始,makemigrations 管理命令包含了一个 --check 选项。如果缺少迁移,该命令将以非零状态退出。

    使用示例:

    ./manage.py makemigrations --check --dry-run
    

    文档:

    https://docs.djangoproject.com/en/2.0/ref/django-admin/#cmdoption-makemigrations-check

    【讨论】:

      【解决方案2】:

      这应该可以解决问题 - 没有刮擦。

      它会显示迁移的名称,但如果有疑问,您仍然需要在调试器中查看changes

      class MigrationsCheck(TestCase):
          def setUp(self):
              from django.utils import translation
              self.saved_locale = translation.get_language()
              translation.deactivate_all()
      
          def tearDown(self):
              if self.saved_locale is not None:
                  from django.utils import translation
                  translation.activate(self.saved_locale)
      
          def test_missing_migrations(self):
              from django.db import connection
              from django.apps.registry import apps
              from django.db.migrations.executor import MigrationExecutor
              executor = MigrationExecutor(connection)
              from django.db.migrations.autodetector import MigrationAutodetector
              from django.db.migrations.state import ProjectState
              autodetector = MigrationAutodetector(
                  executor.loader.project_state(),
                  ProjectState.from_apps(apps),
              )
              changes = autodetector.changes(graph=executor.loader.graph)
              self.assertEqual({}, changes)
      

      【讨论】:

        【解决方案3】:

        我会改用--dry-run flag 并测试它是否为空。

        【讨论】:

        • 啊,好主意,我没有意识到这存在。我会用我想出的测试代码更新你的答案
        【解决方案4】:

        您可以从https://github.com/django/django/blob/master/django/core/management/commands/makemigrations.py#L68 窃取一些代码。迁移到较新的 django 版本之后可能需要额外的 5 分钟

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-05
          • 1970-01-01
          • 1970-01-01
          • 2019-05-12
          • 1970-01-01
          • 2012-03-14
          相关资源
          最近更新 更多