我有一个用 Flask 编写的 API,并且正在使用 Nose 测试来测试端点,使用请求向 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())
一切都发生在本地主机上,服务器正在监听 127.0.0.1。我的猜测是,发送到服务器的请求太多,有些请求被拒绝,但我在调试日志中没有看到类似的内容。我还认为这可能是服务器进程在发出请求之前未启动的问题,但在启动服务器进程后 sleep 问题仍然存在。另一种尝试是通过设置 requests.adapters.DEFAULT_RETRIES 来让请求尝试重试连接。这也不起作用。
我尝试在两台机器上正常运行测试以及在 Docker 容器中运行测试,无论运行在什么平台上,问题似乎都会发生。
对于可能导致此问题的原因以及可以采取哪些措施来解决它有什么想法吗?
最佳答案
事实证明,我的问题确实是服务器没有足够的时间启动的问题,因此测试将在它响应测试之前运行。我以为我曾尝试通过 sleep 来解决此问题,但不小心将其放置在创建进程之后而不是启动进程之后。最后,改变
cls.server_process.start()
至
cls.server_process.start()
time.sleep(1)
解决了问题。
关于python - Flask 应用程序在测试时随机拒绝连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42495976/