unittest.TestCase类中的app.client()对象是什么,为什么其看似可以调用POST方法

本文探讨了在Flask应用的单元测试中,`app.test_client().post()`方法的工作原理。`app.test_client()`返回一个test_client_class对象,它允许调用HTTP方法如POST。在内部,它涉及到`LoggingTestCase`类的`test_url_with_method`方法,创建视图类`MyView`,并通过`app.add_url_rule`设置POST请求的路由。最终,利用`url_for`和`_method`参数触发POST请求,并进行断言验证响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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请求进行断言,确认结果是否正确和匹配

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值