14.Testing API calls with django使用django测试API调用
Using unittest
If you want to unittest your API calls derive your test case from the class GraphQLTestCase.
如果您想对API调用进行unittest,那么从GraphQLTestCase类派生测试用例。
Your endpoint is set through the GRAPHQL_URL attribute on GraphQLTestCase. The default endpoint is GRAPHQL_URL = “/graphql/”.
端点是通过GraphQLTestCase上的GRAPHQL_URL属性设置的。默认端点是GRAPHQL_URL=“/GRAPHQL/”。
Usage:
用法:
import json
from graphene_django.utils.testing import GraphQLTestCase
class MyFancyTestCase(GraphQLTestCase):
def test_some_query(self):
response = self.query(
'''
query {
myModel {
id
name
}
}
''',
op_name='myModel'
)
content = json.loads(response.content)
# This validates the status code and if you get errors
# 这将验证状态代码以及是否出现错误
self.assertResponseNoErrors(response)
# Add some more asserts if you like
# 如果愿意,可以添加更多断言
...
def test_query_with_variables(self):
response = self.query(
'''
query myModel($id: Int!){
myModel(id: $id) {
id
name
}
}
''',
op_name='myModel',
variables={'id': 1}
)
content = json.loads(response.content)
# This validates the status code and if you get errors
# 这将验证状态代码以及是否出现错误
self.assertResponseNoErrors(response)
# Add some more asserts if you like
# 如果愿意,可以添加更多断言
...
def test_some_mutation(self):
response = self.query(
'''
mutation myMutation($input: MyMutationInput!) {
myMutation(input: $input) {
my-model {
id
name
}
}
}
''',
op_name='myMutation',
input_data={'my_field': 'foo', 'other_field': 'bar'}
)
# This validates the status code and if you get errors
# 这将验证状态代码以及是否出现错误
self.assertResponseNoErrors(response)
# Add some more asserts if you like
# 如果愿意,可以添加更多断言
...
Using pytest 使用pytest
To use pytest define a simple fixture using the query helper below
要使用pytest,请使用下面的查询助手定义一个简单的fixture
# Create a fixture using the graphql_query helper and `client` fixture from `pytest-django`.
#使用graphql查询助手和“pytest django”中的“client”fixture创建fixture。
import json
import pytest
from graphene_django.utils.testing import graphql_query
@pytest.fixture
def client_query(client):
def func(*args, **kwargs):
return graphql_query(*args, **kwargs, client=client)
return func
# Test you query using the client_query fixture
# 使用client_query fixture测试您的查询
def test_some_query(client_query):
response = client_query(
'''
query {
myModel {
id
name
}
}
''',
op_name='myModel'
)
content = json.loads(response.content)
assert 'errors' not in content