【问题标题】:Unit test an external facing function单元测试面向外部的功能
【发布时间】:2017-03-14 02:13:16
【问题描述】:

我正在尝试为我的 Django 应用程序的面向外部的 api 编写单元测试用例。我有一个名为Dummy 的模型,它有两个字段tempcontent。第三方调用以下函数来获取content 字段。 temp 是索引唯一键。

@csrf_exempt
def fetch_dummy_content(request):
    try:
        temp = request.GET.get("temp")
        dummy_obj = Dummy.objects.get(temp=temp)
    except Dummy.DoesNotExist:
        content = 'Object not found.'
    else:
        content = dummy_obj.content

    return HttpResponse(content, content_type='text/plain')

我有以下单元测试用例。

def test_dummy_content(self):
    params = {
        'temp': 'abc'
    }
    dummy_obj = mommy.make(
        'Dummy',
        temp='abc',
        content='Hello World'
    )
    response = self.client.get(
        '/fetch_dummy_content/',
        params=params
    )
    self.assertEqual(response.status_code, 200)
    self.assertEqual(response.content, 'Hello World')

每次我运行测试用例时,它都会进入exception 并返回Object not found. 而不是Hello World。经过进一步调试,我发现视图函数内部请求对象的temp 始终为None,即使我将它传递给params

我可能遗漏了一些东西并且无法弄清楚。测试这些功能的正确方法是什么。

【问题讨论】:

    标签: django api unit-testing nose


    【解决方案1】:

    There's no params parameter for the get 或客户端上的任何其他功能,您可能会想到data

    response = self.client.get(
        '/fetch_dummy_content/',
        data=params
    )
    

    反正这是第二个参数,所以你也可以self.client.get('/fetch_dummy_content/', params)

    环境中包含任何未知参数,这解释了为什么您没有因使用错误名称而出错。

    【讨论】:

    • 非常感谢老兄。
    猜你喜欢
    • 2019-11-24
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多