执行操作时模拟 500 响应

Mocking a 500 response when an operation is performed

这是我目前的测试:

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)

我需要编写一个模拟程序,当使用 'https://localhost:1234/v1/' + bucket url 时,它将 return 一个 500 响应。这可以用 unittest 完成吗?如果可以,我如何或在哪里可以找到有关此的文档?我已经浏览过这个网站、unittest 文档和 Youtube,但找不到任何关于我想做的事情的具体内容。

我最终使用 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)