【问题标题】:Testing Django GraphQL API with database使用数据库测试 Django GraphQL API
【发布时间】:2020-04-22 19:15:09
【问题描述】:

我正在使用

from graphene_django.utils.testing import GraphQLTestCase

实现我的测试。但是,来自

的结果
class PeopleTests(GraphQLTestCase):
  GRAPHQL_SCHEMA = schema

  def test_all_person_query_admin_token(self):

    response = self.query(
        '''
       query getPersons{
            persons{
            firstName,
            lastName
            }
        }
        ''',
        op_name='persons',
        headers={'HTTP_AUTHORIZATION': f'JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTY2MTk4Mzg5LCJvcmlnSWF0IjoxNTY2MTk4MDg5fQ.P4u7PNKPLFsc4dvhBLw-EfuN8jg2d-lqdZjWruEDlpc'}
    )

总是返回一个空的 Person 列表。我在Django Test Database looks empty while test is runnin 中读到这是 GraphQLTestCase 继承自 TestCase 的结果。这篇文章很旧(2012 年),但我似乎找不到任何关于如何使用合适的测试数据库的文档。

对不起,如果我错过了什么,答案很明显。

谢谢

【问题讨论】:

    标签: python django unit-testing graphene-python graphene-django


    【解决方案1】:

    请确保在使用 GraphQL 获取数据之前创建人员。也许您需要添加一些固定装置或添加setUp 方法来添加一些条目。以下是我使用 Pytest 测试 Graphene-Django API 的方法。

    @pytest.mark.django_db
    class TestBlogSchema(TestCase):
    
        def setUp(self):
           self.client = Client(schema)
           self.blog = mixer.blend(Blog)
    
        def test_single_blog_query(self):
           response = self.client.execute(single_blog_query, variables={"id": self.blog.id})
           response_blog = response.get("data").get("blog")
    
           assert response_blog["id"] == str(self.blog.id)
    

    您可以从here查看完整示例

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 2021-07-28
      • 2011-09-09
      • 2017-10-10
      • 2022-08-02
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2011-11-12
      相关资源
      最近更新 更多