目前,我正在研究使用石墨烯来构建我的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()中的查询只是一大块文本,我不知道将来如何维护它。我或将来的其他开发人员必须阅读该文本,弄清楚它的含义,并在需要时更新它。
这应该是这样的吗?你们是怎么为石墨烯写单元测试的?
发布于 2017-12-12 06:00:14
我一直在编写包含用于查询的大文本块的测试,但我已经使粘贴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.这组‘’( { user { id firstName } } )之间的所有内容都是从GraphiQL中粘贴进来的,这使得它更容易根据需要进行更新。如果我做了导致测试失败的更改,我可以将查询从我的代码粘贴到GraphQL中,并且通常会修复该查询并将新查询粘贴回我的代码中。有意在这个粘贴的查询上没有Tab键,以便于重复粘贴。
https://stackoverflow.com/questions/45493295
复制相似问题