I am trying to test my backend, written in Django 2.2.2 and Python 3. I created some graphql queries which are definitely working when testing with the graphql web interface. When testing with pytest and the graphene test client, however, these queries would always hang indefinitely. I put together a reproducible example which is actually based on the code example from the 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
This example behaves in the same way (stalls forever, no errors). I am using the latest graphene-django (2.3.2) and pytest (4.6.3). I should probably also mention that I'm running this inside a Docker container. Any ideas why this happens? Is this a bug in the graphene-django library?
I found the answer myself after a while digging through the documentation. Pytest needs permission to use the database. So the issue is solved by simply adding the pytest mark @pytest.mark.django_db
before the test. As an alternative the whole module can be marked to allow database access by using pytestmark = pytest.mark.django_db
. See pytest-django docs.
The documentation says the tests will fail if db access is not granted, so I would not expect them to stall forever.