Python单元测试和restfulrequestparser

2024-04-26 19:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个API,并且正在使用Flask-RESTFul。我有一个登录方法,它接收电子邮件密码作为请求参数,两者都是必需的:

class Login(Resource):

    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('email', required=True)
        self.parser.add_argument('password', required=True)

代码运行得很好。如果我在没有请求参数的情况下通过邮递员尝试请求,Flask RESTFul将发送一个响应错误,即电子邮件和密码是必填字段

现在我想为此编写一个单元测试。测试实际上应该非常简单:

@mock.patch('flask_restful.reqparse.RequestParser.parse_args')
class TestLoginMethods(unittest.TestCase):

    def test_post_body_missing(self, parse_args):
        self.login = Login()
        self.login.post()
        # TODO: should assert error when Email and Password not found in request

这里的问题是,parse_args被模拟,Flask RESTFul为所需字段引发错误的功能消失了这意味着,如果未提供电子邮件和密码,则不会返回任何错误。如何存根RequestParser的此功能?我是python新手,我只能找到没有RESTFul的示例


Tags: selfrestfulparser密码flask参数parse电子邮件
1条回答
网友
1楼 · 发布于 2024-04-26 19:21:16

parse_args在测试中工作必然是模仿来自flask的全局requestcurrent_app

@mock.patch('flask_restful.reqparse.request')
@mock.patch('flask_restful.reqparse.current_app')
class TestLoginMethods(unittest.TestCase):
    def setUp(self):
        self.login = Login()

    def tearDown(self):
        pass

    def test_post_request_without_email(self, mock_request, mock_current_app):
        try:
            self.login.post()
        except Exception as e:
            self.assertTrue(isinstance(e, BadRequest))
            self.assertEqual(e.data['message']['email'], 'Missing required parameter in the JSON body or the post '
                                                         'body or the query string')

相关问题 更多 >