You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pytest编写测试确保函数及参数的类型注解不被修改?

实现思路与测试代码

完全不需要用mock,直接利用Python函数内置的__annotations__属性就能实现类型注解的校验——Python会把函数的参数和返回值类型注解存储在这个字典里,我们只需要编写pytest用例断言这个字典的内容符合预期即可。

具体实现步骤:

  • 导入需要测试的目标函数
  • 编写测试函数,逐一校验__annotations__字典中的参数注解和返回值注解

示例测试代码:

# 假设你的函数在my_module.py中
from my_module import func

def test_func_type_annotations():
    # 校验参数注解存在且类型正确
    assert 'num' in func.__annotations__
    assert func.__annotations__['num'] is int
    
    assert 'item' in func.__annotations__
    assert func.__annotations__['item'] is str
    
    # 校验返回值注解存在且类型正确
    assert 'return' in func.__annotations__
    assert func.__annotations__['return'] is list

如果其他开发者修改了参数/返回值的类型注解,或者删除了注解,这个测试用例会直接失败,达到你想要的防护效果。

内容的提问来源于stack exchange,提问作者Nataliia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:42:51