简体   繁体   English

Python 单元测试失败的请求

[英]Python unit testing a request that fails

I'm trying to test a http call that is supposed to fail but I want to return a value.我正在尝试测试应该失败但我想返回一个值的 http 调用。 However the test I do doesn't pass in the coverage:但是我所做的测试没有通过覆盖范围:

    def callAPI(self, tokenURL:str):
    requestBuilder: RequestBuilder = RequestBuilder()

    try:
        response = requestBuilder.get(tokenURL)
        return response.json()
        # return "content"
    except Exception as err:
        Logger.error("An error occured while trying to call API "+ err)
        return None

This is my test function:这是我的测试 function:

@responses.activate
def testCallDemFails():
  responses.add(
    responses.GET, 'http://calldem.com/api', json="{'err'}", status=500)

  with pytest.raises(Exception):
    demConfig = DemConfig()
    resp = demConfig.callAPI('http://callAPI.com/api/1/foobar')
    print("testCallAPIFail", resp)
    assert resp == None

The requestBuilder.get method just return a request.get function. requestBuilder.get 方法只返回一个 request.get function。 When I execute the function, I don't even have the testAPI fail.当我执行 function 时,我什至没有 testAPI 失败。 Do you have any ideas?你有什么想法?

It looks like the test function is not wiring up the request URL you are using to the response URL you are expecting.看起来测试 function 没有将您正在使用的请求 URL 连接到您期望的响应 URL。 http://callAPI.com/api/1/foobar does not match http://calldem.com/api , nor is the test response configured as a regex match which would enable the sub-path matching that is implied by the example code. http://callAPI.com/api/1/foobarhttp://calldem.com/api //calldem.com/api 不匹配,测试响应也未配置为正则表达式匹配,这将启用示例所暗示的子路径匹配代码。 I am guessing that the response being returned by the misconfigured URL mapping is JSON parseable (or None), therefore the exception is never being raised.我猜测错误配置的 URL 映射返回的响应是 JSON 可解析(或无),因此永远不会引发异常。

If you try the following test code, does it work?:如果您尝试以下测试代码,它是否有效?:

import re

@responses.activate
def testCallDemFails():
  responses.add(
    responses.GET, re.compile('http://callAPI.com/api/.*'), json="{'err'}", status=500)

  with pytest.raises(Exception):
    demConfig = DemConfig()
    resp = demConfig.callAPI('http://callAPI.com/api/1/foobar')
    print("testCallAPIFail", resp)
    assert resp == None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM