Django 测试环境缺少组和权限:但我在迁移中创建了它们

Django testing environment is missing Group and Permissions: but I created them in a migration

我正在尝试修复代码库中的一堆测试,这些测试由于没有权限而失败(例如:更新票证)。奇怪的是,我有一个创建 auth 组并向组添加适当权限的迁移。

我觉得我在 Django 的测试环境设置中遗漏了一些基本的东西——我认为它在 运行 测试之前应用迁移,并且 migrations 是首选方式在 fixtures 上,对于这样的事情,组应该始终 1. 存在并且 2. 拥有该权限。

迁移

from django.db import migrations
from django.core.management.sql import emit_post_migrate_signal

def create_groups(apps, schema_editor):
    # Ensure permissions and content types have been created.
    db_alias = schema_editor.connection.alias
    emit_post_migrate_signal(2, False, db_alias)

    Permission = apps.get_model("auth", "Permission")
    Group = apps.get_model("auth", "Group")

    # Create CC group
    permission = Permission.objects.get(
        codename="handle_ticket", content_type__model="ticket"
    )
    corps = Group.objects.create(name="CC")
    corps.permissions.add(permission)

def remove_groups(apps, schema_editor):
    Group = apps.get_model("auth", "Group")
    cc = Group.objects.filter(name="CC").delete()

class Migration(migrations.Migration):

    dependencies = [
        ("my_app", "previous"),
    ]

    operations = [
        migrations.RunPython(create_groups, remove_groups),
    ]

测试,因验证错误而失败。

def test_update_ticket(self):
        ticket = factories.TicketFactory(notes="Old notes")
        cc_group = Group.objects.get(name="CC")
        assignee = factories.UserFactory()
        assignee.groups.set([cc_group])
        self.client.force_login(assignee)

        result = self.client.post(
            reverse("ticket_update", args=[ticket.id]), data={"notes": "New notes"}
        )
        print(assignee.groups.all(), assignee.get_all_permissions(), assignee.has_perm("my_app.handle_ticket")) 
        #### PRINTS: Group(CC), QuerySet[], False 
        #### the QuerySet shouldn't be empty, and .has_perm should be True

多亏了评论,我发现问题是我重用了一个没有应用迁移的测试数据库。

要解决此问题,请检查您的 pytest.ini 文件并确保 --reuse-db 未写入 addopts 字段(注意:这可能 re-build 测试db 每次你 运行 一个测试,所以它可能会减慢你的测试速度),或者当你 运行 来自终端的测试时将 --create-db 添加到 pytest 命令(重建 db 这个特定的测试运行).