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