unittest.TestCase類中的app.client()對象是什麼,爲什麼其看似可以調用POST方法

class LoginTest(unittest.TestCase):



    def setUp(self):

        app.testing = True

        self.client = app.test_client()



    def tearDown(self):

        pass



    def test_empty_username_password(self):

        response = app.test_client().post('/login', data={})

        json_data = response.data

        json_dict = json.loads(json_data)



        self.assertIn('errcode', json_dict, '數據格式返回錯誤')

        self.assertEqual(json_dict['errcode'], -2, '狀態碼返回錯誤')

觀察代碼,response = app.test_client().post('/login', data={"username": "aaaaa", "password": "12343”})中,app.test_client()返回的是一個類當前客戶端的test_client_class類對象,如無則返回flask.testing基類

其中,當前的test_client的response_class會作爲參數傳入,response_class就等於Response類對象(response_class = Response)。具體可參見源碼定義:

def test_client(self, use_cookies=True):

    """Creates a test client for this application.  For information about unit testing head over to :ref:`testing`.



    Note that if you are testing for assertions or exceptions in your application code, you must set ``app.testing = True`` in order for the exceptions to propagate to the test client.  Otherwise, the exception will be handled by the application (not visible to the test client) and the only indication of an AssertionError or other exception will be a 500 status code response to the test client.  See the :attr:`testing` attribute.  For example::

        app.testing = True

        client = app.test_client()



    cls = self.test_client_class

    if cls is None:

        from flask.testing import FlaskClient as cls

    return cls(self, self.response_class, use_cookies=use_cookies)

此處test_client()調用後返回的是類對象,裏面的post方法指向的是class LoggingTestCase(FlaskTestCase)這一單元測試類其中的test_url_with_method(self)方法。


class LoggingTestCase(FlaskTestCase):



def test_url_with_method(self):

    from flask.views import MethodView

    app = flask.Flask(__name__)

    class MyView(MethodView):

        def get(self, id=None):

            if id is None:

                return 'List'

            return 'Get %d' % id

        def post(self):

            return 'Create'

    myview = MyView.as_view('myview')

    app.add_url_rule('/myview/', methods=['GET'],

                     view_func=myview)

    app.add_url_rule('/myview/<int:id>', methods=['GET'],

                     view_func=myview)

    app.add_url_rule('/myview/create', methods=['POST'],

                     view_func=myview)



    with app.test_request_context():

        self.assert_equal(flask.url_for('myview', _method='GET'),

                          '/myview/')

        self.assert_equal(flask.url_for('myview', id=42, _method='GET'),

                          '/myview/42')

        self.assert_equal(flask.url_for('myview', _method='POST'),

                          '/myview/create')

test_url_with_method(self)方法中定義了一個視圖類  class MyView(MethodView),視圖類有一個post方法,返回’Create’,執行調用MyView類的as_view()方法,返回一個view對象並賦值給myview的實例對象,

執行app.add_url_rule('/myview/create', methods=['POST'], view_func=myview)添加映射,會調用 with app.test_request_context()方法。

最終還是調用了flask.url_for('myview', _method='POST’),提交post請求進行斷言,確認結果是否正確和匹配

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章