mardi 7 juillet 2015

Monkey patch not working with Flask and authentication

I have a simple application in Flask with basic authentication.

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == 'username' and password == 'password'

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated


@app.route("/")
@requires_auth
def index():
    return render_template('index.html')

And I would like to test my application that bypass the authentication. So, this is what I come up with but not working.

@patch('server.check_auth') @patch('server.request.authorization') def test_index(self, mock_auth, mock_check_auth): mock_auth.return_value = True mock_check_auth.return_value = True

res = self.app.get('/')

self.assertTrue('<form' in res.data)
self.assertTrue('action="/upload"' in res.data)
self.assertEquals(200, res.status_code)

I get this error.

name = 'request'

    def _lookup_req_object(name):
        top = _request_ctx_stack.top
        if top is None:
>           raise RuntimeError('working outside of request context')
E           RuntimeError: working outside of request context

Aucun commentaire:

Enregistrer un commentaire