Python unit testing flask_restful - RequestParser

Viewed 648

I'm writing an API in Python and I'm using Flask-RESTFul. I have a Login method which receives Email and Password as request parameters, both are required:

class Login(Resource):

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

The code works just fine. If I try a request via Postman without request parameters, Flask-RESTFul sends a response error that Email and Password are required fields.

Now I want to write a unit test for this. The test should actually be pretty simple:

@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

The problem here is, that parse_args gets mocked and the functionality of Flask-RESTFul of raising error for the required fields is gone. That means, no error is returned if Email and Password have not been provided. How do I stub this functionality of RequestParser? I'm new in python, I could find only examples without Flask-RESTFul.

1 Answers

To have parse_args working in the test is necessarily to mock the global request and current_app from flask

@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')
Related