使用 pytest 进行测试时,石墨烯查询无限期挂起

Graphene query hangs indefinitely when testing with pytest

我正在尝试测试我的后端,它是用 Django 2.2.2 和 Python 3 编写的。我创建了一些 graphql 查询,这些查询在使用 graphql 网络界面进行测试时绝对有效。然而,当使用 pytest 和石墨烯测试客户端进行测试时,这些查询总是会无限期地挂起。我整理了一个可重现的示例,它实际上基于 graphene-django documentation.

中的代码示例

test_example.py:

import pytest
import graphene
from graphene_django import DjangoObjectType
from graphene.test import Client
from django.db import models

class UserModel(models.Model):
    name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

class User(DjangoObjectType):
    class Meta:
        model = UserModel

class Query(graphene.ObjectType):
    users = graphene.List(User)

    def resolve_users(self, info):
        return UserModel.objects.all()


schema = graphene.Schema(query=Query)
client = Client(schema)


def test_user():
    query = '''
    query {
      users {
        name,
        lastName
      }
    }
    '''
    result = client.execute(query)
    assert 0 # dummy assert

此示例的行为方式相同(永远停止,没有错误)。我正在使用最新的 graphene-django (2.3.2) 和 pytest (4.6.3)。我可能还应该提到我在 Docker 容器中 运行 这个。为什么会发生这种情况的任何想法?这是 graphene-django 库中的错误吗?

经过一段时间的文档挖掘,我自己找到了答案。 Pytest 需要使用数据库的权限。于是在测试前简单的加上pytest标记@pytest.mark.django_db就解决了这个问题。作为替代方案,可以使用 pytestmark = pytest.mark.django_db 将整个模块标记为允许数据库访问。参见 pytest-django docs

文档说如果不授予数据库访问权限,测试将失败,所以我不希望它们永远停止。