[英]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.