【问题标题】:how to test a unit test using pytest django if there is a function defined but not the class?如果定义了函数但没有定义类,如何使用 pytest django 测试单元测试?
【发布时间】:2021-09-24 05:50:05
【问题描述】:
@api_view(['GET'])
def get_search(request):
    search_text = get_searchText()
    return Reponse({"search-txt":search_text})

这里search_txt是搜索文本的api,search_text是一个变量

我在下面尝试过,但无法测试上面的代码,

from django.test import TestCase, Client

class TestViews(TestCase):
    def setUp(self):
       self.client = Client()
       self.searchtxt_url = reverse('search-txt')
   
    def test_search_project(self):
       response.self.client.get(self.searchtxt_url)
       self.assertEquals(response.status_code, 200)

用 api 测试函数的可能方法是什么

【问题讨论】:

  • 1. search_txt is an api 在您粘贴的代码中没有 search_txt 这样的东西。 2、response.self.client.get(self.searchtxt_url)中的response是什么?它没有在您粘贴的代码中的任何地方定义。 3. 你想测试什么不清楚。您要测试 API get_search 吗?还是 API get_searchText

标签: django testing pytest pytest-django


【解决方案1】:

我猜你想写的是

def test_search_project(self):
    response = self.client.get(self.searchtxt_url)
    self.assertEquals(response.status_code, 200)

您必须将 self.searchtxt_url 的响应存储在 response 对象中,然后您可以断言其字段/值。

【讨论】:

  • 不,这无济于事,我已经尝试过了。我想做的是使用 pytest django 对搜索功能进行单元测试,其中我使用了搜索 api。
猜你喜欢
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-19
  • 1970-01-01
相关资源
最近更新 更多