2017-08-03 37 views
0

目前我正在研究使用石墨烯来构建我的Web服务器API。我一直在使用Django-Rest-Framework一段时间,并想尝试一些不同的东西。测试Graphene-Django

我想通了如何与我现有的项目线它了,我可以测试从Graphiql UI查询,通过输入类似

{ 
    industry(id:10) { 
     name 
     description 
    } 
} 

现在,我想有由单元覆盖的新API /集成测试。在这里,问题就开始了。

所有的文档/后我对测试查询检查/石墨烯的执行做这样的事情

result = schema.execute("{industry(id:10){name, description}}") 
assertEqual(result, {"data": {"industry": {"name": "Technology", "description": "blab"}}} 

我的观点是,在查询的执行()仅仅是文本的一大块,我不要我不知道我将来如何维护它。我或将来的其他开发人员必须阅读该文本,弄清楚它的含义并在需要时进行更新。

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

回答

1

我一直在写测试,对于查询确实有很大的文本块,但是我已经很容易将它粘贴到来自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/') 
    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中,并且经常修复查询并将新查询粘贴回我的代码中。在粘贴的查询中有意没有标签,以方便重复粘贴。