Context
我正在尝试为查询外部 API 的函数编写测试。这些函数向 API 发送请求、获取响应并处理它们。
在我的测试中,我想使用本地运行的模拟服务器来模拟外部 API。
到目前为止,模拟服务器已成功运行并响应自定义 GET 查询。
问题
外部 API 使用类型的对象进行响应<class 'dict'>
,虽然显然我可以从我的模拟服务器得到的只是类型的响应<class 'bytes'>
。模拟服务器从磁盘获取预定义的数据并通过流返回它们。由于我无法模拟外部 API,因此我的测试会因响应类型错误而引发错误消息。
以下是我的代码片段和一些解释。
1. 设置()函数:
setUp 函数在测试套件的开头运行。它负责在运行测试之前配置和运行服务器:
def setUp(self):
self.factory = APIRequestFactory()
# Configuring the mock server
self.mock_server_port = get_free_port()
self.mock_server = HTTPServer(('localhost', self.mock_server_port), MockServerRequestHandler)
# Run the mock server in a separate thread
self.mock_server_thread = Thread(target=self.mock_server.serve_forever)
self.mock_server_thread.setDaemon(True)
self.mock_server_thread.start()
2. MockServerClassHandler:
class MockServerRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if re.search(config.SYSTEM_STATUS_PATTERN, self.path):
# Response status code
self.send_response(requests.codes.ok)
# Response headers
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
# Purge response from a file and serve it
with open('/path/to/my-json-formatted-file') as data_file:
response_content = json.dumps(json.load(data_file))
# Writing to a stream that need bytes-like input
# https://docs.python.org/2/library/basehttpserver.html
self.wfile.write(response_content.encode('utf-8'))
return
据我了解官方文档 https://docs.python.org/2/library/basehttpserver.html, a 基本HTTP请求处理程序只能通过写入预定义的流来提供他的响应内容(wfile
)需要给它(我引用了一条错误消息)一个类似字节的变量。
所以我的问题是:
- 有没有办法让我的模拟服务器响应字节以外的其他类型的内容? (JSON、Python 字典...)
- 在我测试的函数中编写一段将字节变量转换为 Python 字典的代码是否安全,这样我就可以用我的模拟服务器测试它们?或者这违反了一些测试原则?
- 是否有另一种方法可以编写用 JSON 和 python 字典响应的服务器?