pytest中token的一种处理方法

在某个场景中,各个接口经常需要使用到token,而且接口对频繁登录做了防抖,无法频繁调用。考虑了很多方法,发现总是有一些或多或少的弊端,这里在conftest中定义了一个钩子函数用于处理token。

复制代码
@pytest.fixture(scope="module")
def auth_tokens(refresh_threshold=600):  # 假设刷新阈值为10分钟
    tokens = {}
    def get_or_refresh_token(username):
        token_info = tokens.get(username)
        if not token_info or (time.time() - token_info['timestamp']) > refresh_threshold:
            logger.info(f"没有获取到该账号{username}的token,或者token已过期,重新获取token中")
            token = login_user(username, '222222').response.json()['data']['accessToken']
            tokens[username] = {'token': token, 'timestamp': time.time()}
        logger.info(f"{username}的token为{tokens[username]['token']}")
        return tokens[username]['token']
    return get_or_refresh_token

作用域定义为模块级,在整个模块中只执行一次。

定义了一个get_or_refresh_token闭包,该闭包负责根据用户名获取或刷新token。虽然auth_tokens fixture在模块级别只实例化一次,但是它返回的闭包(get_or_refresh_token)能够对每个传入的用户名进行独立的操作,确保每个账号的token都是根据需要获取或刷新的。

相关推荐
我的xiaodoujiao1 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
她说..1 天前
策略模式+工厂模式实现单接口适配多审核节点
java·spring boot·后端·spring·简单工厂模式·策略模式
沛沛老爹1 天前
Web开发者转型AI:多模态Agent视频分析技能开发实战
前端·人工智能·音视频
David凉宸1 天前
vue2与vue3的差异在哪里?
前端·javascript·vue.js
坚持就完事了1 天前
Java的OOP
java·开发语言
笔画人生1 天前
Cursor + 蓝耘API:用自然语言完成全栈项目开发
前端·后端
像少年啦飞驰点、1 天前
零基础入门 Spring Boot:从“Hello World”到可部署微服务的完整学习路径
java·spring boot·微服务·编程入门·后端开发
AC赳赳老秦1 天前
外文文献精读:DeepSeek翻译并解析顶会论文核心技术要点
前端·flutter·zookeeper·自动化·rabbitmq·prometheus·deepseek
小宇的天下1 天前
Calibre 3Dstack --每日一个命令day18【floating_trace】(3-18)
服务器·前端·数据库
undsky_1 天前
【RuoYi-SpringBoot3-Pro】:将 AI 编程融入传统 java 开发
java·人工智能·spring boot·ai·ai编程