[Django]-How to mock info.context in Django / Graphene tests

3👍

You cannot pass in context value directly into self.query method.

What you need to do is create a test client, and then provide the test context value to use for the test.


from graphene.test import Client
from snapshottest import TestCase

from users.models import CustomUser
from .schema import schema

class SuperUser:
    is_superuser = True

class TestContext:
    user = SuperUser()

class TestGraphQLQueries(TestCase):
    """
    Test that GraphQL queries related to gardens work and throw errors appropriately
    """

    context_value = TestContext()

    def test_gardens_query(self):
        client = Client(schema, context_value=self.context_value)
        query = (
            """
            query {
                gardens {
                    id
                    name
                    owner {
                        id
                        email
                    }
                }
            }
            """
        )
        
        self.assertMatchSnapshot(client.execute(query))

0👍

You can set a graphene request’s user in the same way as setting it for Django, by using RequestFactory. As per my answer in Testing Graphene-Django the pattern is

from django.test import RequestFactory, TestCase
from graphene.test import Client


user = ... (fetch your test superuser)
api_query = """
        query {
            gardens {
                id
                name
                owner {
                    id
                    email
                }
            }
        }
        """
request_factory = RequestFactory()
context_value = request_factory.get('/api/')  # or use reverse() on your API endpoint
context_value.user = user
client = Client(schema)
executed = client.execute(api_query, context_value=context_value)
output_data = executed.get('data')

Leave a comment