Skip to content

Custom GraphQL Test Case

This is a custom test case for testing GraphQL queries in Django using the graphene library. It extends the django.test.TestCase and provides a method to execute GraphQL queries.

python
from django.test import TestCase
from entities.schemas import schema as gql_schema
import pytest
import asyncio
from functools import wraps


class GraphQLTestCaseMeta(type):

    def __new__(cls, name, bases, attrs):
        cls.DATA_SETUP = False
        for attr_name, attr_value in attrs.items():
            if attr_name.startswith("test_") and callable(attr_value):
                attrs[attr_name] = cls._wrap_test(attr_value)
        return super().__new__(cls, name, bases, attrs)

    @classmethod
    def _wrap_test(cls, test_func):
        if not asyncio.iscoroutinefunction(test_func):

            @wraps(test_func)
            def wrapper(self, *args, **kwargs):
                if hasattr(self, "setup_data") and not cls.DATA_SETUP:
                    cls.DATA_SETUP = True
                    self.setup_data()
                test_func(self, *args, **kwargs)

            return wrapper

        @wraps(test_func)
        async def wrapper(self, *args, **kwargs):
            if hasattr(self, "setup_data") and not cls.DATA_SETUP:
                cls.DATA_SETUP = True
                self.setup_data()
            return await test_func(self, *args, **kwargs)

        return wrapper


class GraphQLTestCase(TestCase, metaclass=GraphQLTestCaseMeta):

    pass

Usage

python

class LocationTest(GraphQLTestCase):

    def setup_data(self):
        """
        Setup method to prepare data for the tests.
        This can be overridden in subclasses to provide specific data.
        """
        # Example setup code, can be customized
        print("Setting up data for LocationTest")
        pass

    @pytest.mark.asyncio
    async def test_location_query(self):
        query = """
        query {
            ...
        }
        """
        response = await gql_schema.execute(query)
        print(response.errors)
        self.assertIsNone(response.errors)

    @pytest.mark.asyncio
    async def test_location_query_2(self):
        query = """
        query {
           ...
        }
        """
        response = await gql_schema.execute(query)
        print(response.errors)
        self.assertIsNone(response.errors)