2017-02-27 118 views
2

我有一個用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來重試連接。那也行不通。

我試過在兩臺機器上運行測試,通常在兩個機器上,在碼頭集裝箱和這個問題似乎發生,無論他們運行的平臺。

任何可能導致此問題的想法以及可以採取哪些措施解決問題?

回答

1

事實證明,我的問題確實是服務器沒有足夠的時間啓動的問題,所以測試會在它可以響應測試之前運行。我以爲我試圖用睡眠來解決這個問題,但是在創建過程之後意外地放置了它,而不是在開始過程之後。最後,改變

cls.server_process.start() 

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

固定的問題。