|
| 1 | +import json |
| 2 | + |
| 3 | +from django.http import HttpResponse |
| 4 | +from django.test import Client |
| 5 | +from django.test import TestCase |
| 6 | + |
| 7 | + |
| 8 | +class GraphQLTestCase(TestCase): |
| 9 | + """ |
| 10 | + Based on: https://www.sam.today/blog/testing-graphql-with-graphene-django/ |
| 11 | + """ |
| 12 | + |
| 13 | + # URL to graphql endpoint |
| 14 | + GRAPHQL_URL = '/graphql/' |
| 15 | + # Here you need to set your graphql schema for the tests |
| 16 | + GRAPHQL_SCHEMA = None |
| 17 | + |
| 18 | + @classmethod |
| 19 | + def setUpClass(cls): |
| 20 | + super(GraphQLTestCase, cls).setUpClass() |
| 21 | + |
| 22 | + if not cls.GRAPHQL_SCHEMA: |
| 23 | + raise AttributeError('Variable GRAPHQL_SCHEMA not defined in GraphQLTestCase.') |
| 24 | + |
| 25 | + cls._client = Client(cls.GRAPHQL_SCHEMA) |
| 26 | + |
| 27 | + def query(self, query, op_name=None, input_data=None): |
| 28 | + """ |
| 29 | + Args: |
| 30 | + query (string) - GraphQL query to run |
| 31 | + op_name (string) - If the query is a mutation or named query, you must |
| 32 | + supply the op_name. For annon queries ("{ ... }"), |
| 33 | + should be None (default). |
| 34 | + input_data (dict) - If provided, the $input variable in GraphQL will be set |
| 35 | + to this value |
| 36 | +
|
| 37 | + Returns: |
| 38 | + Response object from client |
| 39 | + """ |
| 40 | + body = {'query': query} |
| 41 | + if op_name: |
| 42 | + body['operation_name'] = op_name |
| 43 | + if input_data: |
| 44 | + body['variables'] = {'input': input_data} |
| 45 | + |
| 46 | + resp = self._client.post(self.GRAPHQL_URL, json.dumps(body), |
| 47 | + content_type='application/json') |
| 48 | + return resp |
| 49 | + |
| 50 | + def assertResponseNoErrors(self, resp): |
| 51 | + """ |
| 52 | + Assert that the call went through correctly. 200 means the syntax is ok, if there are no `errors`, |
| 53 | + the call was fine. |
| 54 | + :resp HttpResponse: Response |
| 55 | + """ |
| 56 | + content = json.loads(resp.content) |
| 57 | + self.assertEqual(resp.status_code, 200) |
| 58 | + self.assertNotIn('errors', list(content.keys())) |
| 59 | + |
| 60 | + def assertResponseHasErrors(self, resp): |
| 61 | + """ |
| 62 | + Assert that the call was failing. Take care: Even with errors, GraphQL returns status 200! |
| 63 | + :resp HttpResponse: Response |
| 64 | + """ |
| 65 | + content = json.loads(resp.content) |
| 66 | + self.assertIn('errors', list(content.keys())) |
0 commit comments