模拟用于烧瓶单元测试的令牌-firebase-admin-python SDK [英] Mock a token for flask unit tests - firebase-admin-python SDK

查看:74
本文介绍了模拟用于烧瓶单元测试的令牌-firebase-admin-python SDK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用firebase-admin-python SDK来处理iOS应用和Flask后端(python)之间的身份验证.这是我的后端身份验证端点,遵循 firebase指南:

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:
        ...

如何模拟fir_token进行单元测试?我还应该如何模拟auth.verify_id_token,这样我就不需要实际连接到Firebase服务器了?

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?

推荐答案

将逻辑放在接口后面.

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.

然后确保在单元测试期间您的代码使用MockTokenVerifier.

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

还可以创建模拟ID令牌,并存入Admin SDK的各个部分,以使auth.verify_id_token()在测试期间正常运行(请参见

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.

这篇关于模拟用于烧瓶单元测试的令牌-firebase-admin-python SDK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆