Flask OpenID unittest

这一生的挚爱 提交于 2019-12-24 04:23:50

问题


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.


回答1:


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



回答2:


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!



来源:https://stackoverflow.com/questions/21655601/flask-openid-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!