1

目前我正在研究使用石墨烯来构建我的 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() 中的查询只是一大块文本,我不知道将来如何维护它。我或将来的其他开发人员必须阅读该文本,弄清楚其含义并在需要时对其进行更新。

这应该是这样的吗?你们如何为石墨烯编写单元测试?

4

1 回答 1

3

我一直在编写有大量文本用于查询的测试,但是我可以很容易地从 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 中,并且通常会修复查询并将新查询粘贴回我的代码中。在这个粘贴的查询上故意没有制表符,以方便这种重复粘贴。

于 2017-12-11T22:00:13.923 回答