lundi 1 juin 2015

how to mock a current_user proxy in Python flask_kwt

I have a model Maintenance which detects current user in its constructor:

def __init__(self, date_from, date_to, reason):
    self.date_from = date_from
    self.date_to = date_to
    self.reason = reason
    self.user = current_user

the current_user is an attribute which is set within the web app context after some authorization stuff. This attrubute comes from flask_jwt library:

from flask_jwt import current_user

So my model tests, which are outside the app context, always fail because the constructor fails.

So I need to mock this current_user attribute and make it just pick a user from DB without poking around.

    with mock.patch('asuno.rol.models.maintenance.current_user') as mock_current_user:
        mock_current_user = User.query.get(4)
        self.maintenance = Maintenance(self.now, self.tomorrow, "reason")
        db.session.add(self.maintenance)
        db.session.commit()

but the problem is that Python treats the mock_current_user that I assign a User object to differently from mock_current_user that is passed into the context manager. It thinks they are different variables.

And I cannot say

global mock_current_user
mock_current_user = User.query.get(4)

because I don't have any actual global variables here.

How do I work around this?

Aucun commentaire:

Enregistrer un commentaire