Question

I'm trying to write a unit test for my flask app for OpenID but upon calling

oid.try_login(<oid provider>, <params>)

I get an error:

RuntimeError: <class 'flask.testing.FlaskClient'> does not support redirect to external targets

So, like every good SO user, I looked around for some solutions:

  1. Disguise oid provider using the NoExtRef flask extension. I'm not sure if this is possible at the app level since I assume flask-openid messes around with the oid url (and it just redirected me to the original page when I tried it). But this seems quite ugly since I'm making a code change strictly for a unittest.
  2. Create my own oid server but this might still be an external redirect (I'll try this later as soon as I get desperate enough).

I guess another alternative is to ignore writing unit tests for login and just set the user in Flask.g using the awesome Flask test framework. But I'd prefer to keep the login unit tests.

Was it helpful?

Solution

There is an alternative - monkey-patch the open-id extension's try_login method:

class LoginTestMonkeyPatch(object):
    def __init__(self, oid=None, default_response=None):
        self.response = default_response
        if oid is not None:
            self.init(oid)

    def init(self, oid):
        oid.try_login = self.try_login


    def try_login(self, *args, **kwargs):
        # Do whatever you want to do here

OTHER TIPS

If you are patching the login, you may not be testing it.

I had the same problem. For me the best solution was to disable the "log in required" part of the view.

I don't know if you are using Flask Login, but if you are you can bypass the @login_required so that you don't even need to worry about trying to login the user with something like:

def setUp
   env = Environments(app)
   env.from_object('config.Testing')
   lm = LoginManager()
   lm.init_app(app)
   self.app = app.test_client()

Just a thought, I hope this helps you or someone else :)

P.S. This is my first post on Stack Overflow. Thanks to all the many posters that have helped me so much!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top