0

I have a Flask app that I use, Im working on authenticating all traffic to the server (except for /login and one more endpoint)

I implemented this using the @app.before_request decorator like so:

@app.before_request
def authenticate():
    if any(request.path in s for s in NO_AUTH_ENDPOINTS):
        return
    # authentication process....

This works fine, but then when I got to the flask unittests that were failing because of the auth, I didnt manage to patch that function and all the tests keep getting unauthorized error.

I tried the following:

@patch('authentication.authenticate')
def post(self, body, mock_auth, id=None, token='test_token', **params):
    mock_auth.return_value = None
    return self.app.post(self._get_url(id, params),
                         data=json.dumps(body),
                         follow_redirects=True,
                         content_type='application/json',
                         headers={'Token': token})

and also:

@patch('autoai.server.app.before_request')
def post(self, body, mock_request, id=None, token='test_token', **params):
    mock_request.return_value = None
    return self.app.post(self._get_url(id, params),
                         data=json.dumps(body),
                         follow_redirects=True,
                         content_type='application/json',
                         headers={'Token': token})

I use the flast test_app so that might be related, but I still cant figure out how to patch that begfore_request properly (self.app = app.test_client)

NotSoShabby
  • 3,316
  • 9
  • 32
  • 56
  • It might have to do with how you did your import in `app.post`. Can I see how you imported the `authenticate` function? – wholevinski Jul 10 '19 at 15:47
  • I dont import `app.post` directly, i import my server app and then set `self.app = myapp.test_client()`, that client implements the `post()` method by itself – NotSoShabby Jul 11 '19 at 10:23
  • You're right, I phrased that poorly and had a hunch it might be something related to this: https://docs.python.org/3/library/unittest.mock.html#where-to-patch After looking further I don't think it is. – wholevinski Jul 12 '19 at 10:52
  • You might want to have a look at this answer: https://stackoverflow.com/a/17377101/769971 It might eliminate the need for mocking the `authenticate` logic entirely. If not, let me know and I can help with the mocking code. I'm thinking move the logic out of the decorated function to another call and mock that one. – wholevinski Jul 12 '19 at 10:56

0 Answers0