[英]Testing Graphene-Django
目前我正在研究使用石墨烯来构建我的 Web 服务器 API。 我使用 Django-Rest-Framework 已经有一段时间了,想尝试一些不同的东西。
我已经弄清楚如何将它与我现有的项目连接起来,我可以通过键入类似的内容来测试来自 Graphiql UI 的查询
{
industry(id:10) {
name
description
}
}
现在,我想让单元/集成测试涵盖新的 API。 问题由此开始。
我正在检查石墨烯上测试查询/执行的所有文档/帖子都在做类似的事情
result = schema.execute("{industry(id:10){name, description}}")
assertEqual(result, {"data": {"industry": {"name": "Technology", "description": "blab"}}}
我的观点是 execute() 中的查询只是一大块文本,我不知道将来如何维护它。 我或将来的其他开发人员必须阅读该文本,弄清楚它的含义并在需要时更新它。
应该是这样吗? 你们如何为石墨烯编写单元测试?
我一直在编写测试,这些测试确实有一大块用于查询的文本,但我已经让从 GraphiQL 粘贴大块文本变得容易。 我一直在使用 RequestFactory 来允许我将用户与查询一起发送。
from django.test import RequestFactory, TestCase
from graphene.test import Client
def execute_test_client_api_query(api_query, user=None, variable_values=None, **kwargs):
"""
Returns the results of executing a graphQL query using the graphene test client. This is a helper method for our tests
"""
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, variable_values=variable_values, **kwargs)
return executed
class APITest(TestCase):
def test_accounts_queries(self):
# This is the test method.
# Let's assume that there's a user object "my_test_user" that was already setup
query = '''
{
user {
id
firstName
}
}
'''
executed = execute_test_client_api_query(query, my_test_user)
data = executed.get('data')
self.assertEqual(data['user']['firstName'], my_test_user.first_name)
...more tests etc. etc.
''' s ( { user { id firstName } }
) 之间的所有内容都是从 GraphiQL 粘贴进来的,这使得根据需要更容易更新。 如果我进行了导致测试失败的更改,我可以将代码中的查询粘贴到 GraphQL 中,并且通常会修复查询并将新查询粘贴回我的代码中。 在这个粘贴的查询上故意没有标签,以促进这种重复粘贴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.