2

我正在为烧瓶应用程序编写单元测试。此应用程序公开 REST 端点并使用 flask_restful 库。

基本上,我的一个端点将向其他端点发出请求并进行一些处理。

通过 pytest 执行测试时,它返回此错误(注意:这在使用 curl 进行基本测试时有效):

   requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', 
   port=5000): Max retries exceeded with url: 
   /ctrlm/H_INFOEXPLH:05u3v/output/ 
   (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object 
   at 
   0x0486D090>: Failed to establish a new connection: [WinError 10061]

这是测试代码:

class RestTests(unittest.TestCase):
""" Test the rest module. """
    ############################
    #### setup and teardown ####
    ############################

    def setUp(self):
        """ Executed prior to each test """
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        app.config['THREADED'] = True

        self.client = app.test_client()

        # incident id:
        self.incident = "INC1863137"

        # ctrl-m job id :
        self.jobid_no_output = "server:0ceit"
        self.jobid_no_job = "server:0ceity"  # job format that will surely fail!

    def tearDown(self):
        """ executed after each testexecuted after each test """
        pass

    ###############
    #### tests ####
    ###############

    def test_ctrl_output(self):
        """ UAT 3 : ctrl-M job output is found. """
        response = self.client.post('/servnow/incident/{}'.format(self.incident),
                                data=json.dumps({'data': "This is just a json test"}),
                                headers={'Content-Type': 'application/json'}
                                )
        #print("DEBUGGGG!!!!!!!!!!!!!!!!!!! ===============> {}".format(response))
        self.assertIsNotNone(response)

好吧,也许用 setUp() 启动的烧瓶实例无法线程化......

在应用程序代码上,这是创建问题的代码:

    url = "http://127.0.0.1:5000{}".format(
        flask.url_for('joboutput', jobid=jobid))
    resp = requests.get(url).json()

好吧,我只是想从烧瓶中执行一个对 url 的查询......可能,我做错了......

请问你能帮帮我吗?

4

1 回答 1

0

Unittest 的 Flask 测试服务器是一种模拟。它不会创建侦听套接字。

因此,向自身发出请求是不可能的。

所以 :

url = "http://127.0.0.1:5000{}".format(
    flask.url_for('joboutput', jobid=jobid))
resp = requests.get(url).json()

将以上述异常结束:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', 
port=5000)
Failed to establish a new connection

只是没有创建套接字 127.0.0.1:5000。

好吧,这也让我觉得如果我无法测试我正在构建的解决方案是不正确的。我已经重建了它。

于 2017-10-19T11:46:36.977 回答