Skip to main content
 首页 » 编程设计

python之Flask 应用程序在测试时随机拒绝连接

2025年02月15日9JeffreyZhao

我有一个用 Flask 编写的 API,我正在使用 nosetests 测试端点,使用 requests 向 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。我的猜测是向服务器发送了太多请求,有些请求被拒绝,但我在调试日志中没有看到类似的内容。我还认为这可能是服务器进程在发出请求之前没有启动的问题,但是在启动服务器进程后这个问题仍然存在。另一种尝试是通过设置 requests.adapters.DEFAULT_RETRIES 让请求尝试重试连接。那也没用。

我已经尝试在两台机器上正常运行测试和在 docker 容器中运行测试,无论运行它们的平台如何,问题似乎都会发生。

对于可能导致此问题的原因以及可以采取什么措施来解决它有什么想法吗?

请您参考如下方法:

事实证明,我的问题确实是服务器没有足够的时间启动的问题,所以测试会在它响应测试之前运行。我以为我曾尝试通过 sleep 来解决此问题,但不小心将其放置在创建流程之后而不是启动流程之后。最终,改变

cls.server_process.start() 

到

cls.server_process.start() 
time.sleep(1) 

解决了这个问题。