【发布时间】:2017-07-18 16:04:45
【问题描述】:
我有一个用 Flask 编写的 API,并且正在使用鼻子测试来测试端点,使用请求向 API 发送请求。在测试过程中,我随机得到一个错误
ConnectionError: HTTPConnectionPool(host='localhost', port=5555): Max retries exceeded with url: /api (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fe4e794fd50>: Failed to establish a new connection: [Errno 111] Connection refused',))
此错误似乎仅在运行测试时发生,并且会随机影响无和所有测试之间的任何地方。我所有的测试都是从unittests.TestCase 的一个子类运行的:
class WebServerTests(unittest.TestCase):
# Args to run web server with
server_args = {'port': WEB_SERVER_PORT, 'debug': True}
# Process to run web server
server_process = multiprocessing.Process(
target=les.web_server.run_server, kwargs=server_args)
@classmethod
def setup_class(cls):
"""
Set up testing
"""
# Start server
cls.server_process.start()
@classmethod
def teardown_class(cls):
"""
Clean up after testing
"""
# Kill server
cls.server_process.terminate()
cls.server_process.join()
def test_api_info(self):
"""
Tests /api route that gives information about API
"""
# Test to make sure the web service returns the expected output, which at
# the moment is just the version of the API
url = get_endpoint_url('api')
response = requests.get(url)
assert response.status_code == 200, 'Status Code: {:d}'.format(
response.status_code)
assert response.json() == {
'version': module.__version__}, 'Response: {:s}'.format(response.json())
一切都发生在 localhost 上,服务器正在监听 127.0.0.1。我的猜测是太多的请求被发送到服务器并且一些被拒绝,但我在调试日志中没有看到类似的东西。我还认为这可能是在发出请求之前服务器进程没有启动的问题,但是在启动服务器进程后问题仍然存在。另一种尝试是通过设置requests.adapters.DEFAULT_RETRIES 让请求尝试重试连接。那也没用。
我已经尝试在两台机器上正常运行测试以及在 docker 容器中运行测试,但无论它们在哪个平台上运行,问题似乎都会发生。
对可能导致此问题的原因以及可以采取哪些措施来解决此问题有任何想法吗?
【问题讨论】:
标签: python unit-testing flask python-requests nose