用于数据迁移的Django pytest数据库访问

时间:2016-06-08 08:32:52

标签: python django pytest pytest-django

我使用Django (1.9.6)pytest (2.9.2)pytest-django (2.9.1)

我有一个如下所示的数据迁移:

# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-07 09:56
from __future__ import unicode_literals

from django.db import migrations


def create_groups(apps, schema_editor):
    Group = apps.get_model('auth', 'group')
    Permission = apps.get_model('auth', 'permission')

    group1 = Group.objects.create(name='grou1')
    group1_permissions = Permission.objects.filter(codename__in=[
        'add_app1_model',
        'add_app2_model',
        'custom_permission_app1_model'
    ])
    group1.permissions.add(*list(group1_permissions))

    group2 = Group.objects.create(name='group2')
    group2_permissions = Permission.objects.get(
        codename='custom_permission_app2_model'    
    )
    group2.permissions.add(*list(group2_permissions))


class Migration(migrations.Migration):

    dependencies = [
        ('app1', '0001'),
        ('app2', '0001')
    ]

    operations = [
        migrations.RunPython(create_groups)
    ]

当我执行py.test --create-db时,所有标有pytest.mark.django_db的测试都会在迁移的__fake__.DoesNotExist: Permission matching query does not exist.操作中提升get

解除迁移我发现create操作有效,但filter操作始终返回空,我的测试数据库已创建组,但没有任何权限与任何组相关联。

我不知道自己做错了什么?我所做的临时修复是将get更改为filter,这使迁移正常执行。在测试中,我有一个夹具,可以为用户分配所需的权限。因为我的所有代码都会检查权限,而不是用户属于某个组,我的所有测试都会通过。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,感谢@HåkenLid和他提供的Django issue。问题是Django创建的ContentTypes接收所有迁移完成时发出的信号。这就是为什么它没有找到权限,但它让我创建了组。

要解决这个问题,我们必须在数据迁移中手动发送信号。

data.table

在剪辑中,我们会在访问权限之前发送信号,并将最新的# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-07 09:56 from __future__ import unicode_literals from django.core.management.sql import emit_post_migrate_signal from django.db import migrations def create_groups(apps, schema_editor): # Send the signal to create the permissions db_alias = schema_editor.connection.alias try: # Django 1.9 emit_post_migrate_signal(2, False, db_alias) except TypeError: # Django < 1.9 try: # Django 1.8 emit_post_migrate_signal(2, False, 'default', db_alias) except TypeError: # Django < 1.8 emit_post_migrate_signal([], 2, False, 'default', db_alias) Group = apps.get_model('auth', 'group') Permission = apps.get_model('auth', 'permission') group1 = Group.objects.create(name='grou1') group1_permissions = Permission.objects.filter(codename__in=[ 'add_app1_model', 'add_app2_model', 'custom_permission_app1_model' ]) group1.permissions.add(*list(group1_permissions)) group2 = Group.objects.create(name='group2') group2_permissions = Permission.objects.get( codename='custom_permission_app2_model' ) group2.permissions.add(*list(group2_permissions)) class Migration(migrations.Migration): dependencies = [ ('app1', '0001'), ('app2', '0001'), ('contenttypes', '__latest__'), ('sites', '__latest__') ] operations = [ migrations.RunPython(create_groups) ] contenttypes个应用迁移作为依赖项。