2017-08-03 82 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中,並且經常修復查詢並將新查詢粘貼回我的代碼中。在粘貼的查詢中有意沒有標籤,以方便重複粘貼。