strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
https://strawberry.rocks/docs/django
MIT License
420 stars 122 forks source link

Testing guide #151

Open AriaMoradi opened 2 years ago

AriaMoradi commented 2 years ago

Strawberry provides a guide on testing: https://strawberry.rocks/docs/operations/testing That guide doesn't work in a django context, for example tests need to use django.test.TestCase for model and database support and mutations and queries might need access to a request object for handling authentication, language and other stuff.

Can someone share some test examples please? Also I believe a page in docs/references will be helpful to users of this package.

Upvote & Fund

Fund with Polar

nrbnlulu commented 2 years ago

@AriaMoradi I believe it is fairly simple.
You have two main choices:

I prefer the latter because it is more real in the django domain. In my library I think you can find a good example.

aodelreal commented 2 years ago

Hello, in my app I use this base test class:

from typing import Dict

from django.test import TestCase, Client

class GRAPHQLBaseTestClass(TestCase):

    URL = '/my-graphql-url'

    def setUp(self) -> None:
        self.client = Client()

    def make_query(self, query: str, with_assert: bool = True) -> Dict:
        response = self.client.post(
            self.URL,
            data={'query': query},
            content_type='application/json'
        )
        if with_assert:
            self.assertEqual(response.status_code, 200)
        return response.json()

Then use it like:

class TestGetMe(GRAPHQLBaseTestClass):

    def setUp(self):
        super(TestGetMe, self).setUp()
        ... some setup

    def test_should_get_me(self):

        query = """
        query {
          me {
            name
          }
        }
        """
        response_data = self.make_query(query)
        my_name = response_data['data']['me']['name']
        self.assertEqual(my_name, 'Arturo')

This can be modified to allow queries with operationName and variables.