Flask应用程序在测试时会随机拒绝连接
问题描述:
我有一个用Flask编写的API,并使用nosetests使用向API发送请求的请求来测试端点。在测试过程中,笔者随机得到一个错误Flask应用程序在测试时会随机拒绝连接
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())
一切都发生在本地主机和服务器监听127.0.0.1。我的猜测是,有太多的请求被发送到服务器,有些被拒绝,但我在调试日志中没有看到类似的东西。我还认为这可能是服务器进程在进行请求之前没有启动的问题,但是在启动服务器进程后,问题仍然存在。另一个尝试是让请求尝试通过设置requests.adapters.DEFAULT_RETRIES
来重试连接。那也行不通。
我试过在两台机器上运行测试,通常在两个机器上,在码头集装箱和这个问题似乎发生,无论他们运行的平台。
任何可能导致此问题的想法以及可以采取哪些措施解决问题?
答
事实证明,我的问题确实是服务器没有足够的时间启动的问题,所以测试会在它可以响应测试之前运行。我以为我试图用睡眠来解决这个问题,但是在创建过程之后意外地放置了它,而不是在开始过程之后。最后,改变
cls.server_process.start()
到
cls.server_process.start()
time.sleep(1)
固定的问题。