Ad

Mock A Token For Flask Unit Tests - Firebase-admin-python SDK

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad