Mock a token for flask unit tests - firebase-admin-python SDK

狂风中的少年 提交于 2020-02-04 03:11:52

问题


I am using the firebase-admin-python SDK to handle authentication between an iOS app and a flask backend (python). This is my backend authentication endpoint, following the firebase guide:

from flask import request
from firebase_admin import auth


def get():
    """accessed via '/api/authtoken' """
    try:
        fir_token = request.headers["Authorization"]
        decoded_token = auth.verify_id_token(fir_token)
        fir_auth_id = decoded_token["uid"]
    except:
        ...

How do I mock the fir_token for a unit test? How do I also mock auth.verify_id_token such that I don't need to actually connect to the firebase server?


回答1:


Put the logic behind an interface.

class TokenVerifier(object):
    def verify(self, token):
        raise NotImplementedError()


class FirebaseTokenVerifier(TokenVerifier):
    def verify(self, token):
        return auth.verify_id_token(token)


class MockTokenVerifier(TokenVerifier):
    def verify(self, token):
         # Return mock object that will help pass your tests.
         # Or raise an error to simulate token validation failures.

Then make sure during unit tests your code uses the MockTokenVerifier.

It is also possible to create mock ID tokens, and stub out parts of the Admin SDK so that the auth.verify_id_token() runs normally during tests (see unit tests of the SDK). But I prefer the above solution since it's easier, cleaner and doesn't require messing with the internals of the SDK.



来源:https://stackoverflow.com/questions/57434415/mock-a-token-for-flask-unit-tests-firebase-admin-python-sdk

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