【问题标题】:Flask application randomly refuses connections when testingFlask 应用程序在测试时随机拒绝连接
【发布时间】: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


    【解决方案1】:

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

    cls.server_process.start()
    

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

    修复了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      相关资源
      最近更新 更多