执行操作时模拟500响应

时间:2019-02-14 14:28:30

标签: python testing mocking python-unittest

这是我到目前为止的测试:

test_500(self):

    client = ClientConfiguration(token=token, url=url)
    client.url = 'https://localhost:1234/v1/' + bucket

    keys = None        

    try:
        get_bucket = json.loads(str(client.get_bucket(bucket)))
        result = get_bucket['result']
    except Exception as e:
        expected_status_code = 500
        failure_message = "Expected status code %s but got status code %s" % (expected_status_code, e)
        self.assertEquals(e, expected_status_code, failure_message)

我需要编写一个模拟,当使用500 url时将返回一个'https://localhost:1234/v1/' + bucket响应。可以使用unittest完成吗,如果可以,我如何或在哪里可以找到有关此文件的文档?我浏览过该网站,单元测试文档和Youtube,找不到我想要做的事情。

1 个答案:

答案 0 :(得分:0)

我最终使用this来创建测试。

最终结果是:

@responses.activate
test_500(self):

    responses.add(responses.GET, 'https://localhost:1234/v1/' + bucket,
        json={'error': 'server error'}, status=500)

    client = ClientConfiguration(token=token, url=url)
    client.url = 'https://localhost:1234/v1/'

    keys = None        

    try:
        get_bucket = json.loads(str(client.get_bucket(bucket)))
        result = get_bucket['result']
except Exception as e:
        expected_status_code = 500
        failure_message = "Expected status code %s but got status code %s" % (expected_status_code, e)
        self.assertEquals(e, expected_status_code, failure_message)