@cached_property装饰方法的doctest未被检测,如何运行对应测试?
问题原因
doctest 默认仅会扫描模块级函数、类的普通方法、内置@property装饰属性的文档字符串提取测试用例。functools.cached_property返回的是独立的自定义类实例,不属于内置property类型,因此不会被 doctest 的默认扫描逻辑识别,导致对应的测试用例被跳过。
解决方案
这里提供两种可直接落地的修复方式:
- 方案1:无侵入式手动触发测试,无需修改原有类的装饰器定义,仅调整 doctest 调用逻辑即可
修改后的代码如下:
from functools import cached_property, cache import doctest class C1: def test_1(self): """ >>> C1().test_1() 'f' """ return "f" @property def test_2(self): """ >>> C1().test_2 'p' """ return "p" @cached_property def test_3(self): """ >>> C1().test_3 'cp' """ return "cp" @cache def test_4(self): """ >>> C1().test_4() 'c' """ return "c" if __name__ == "__main__": # 手动运行所有 cached_property 装饰属性的测试用例 for attr_name, attr_value in C1.__dict__.items(): if isinstance(attr_value, cached_property): doctest.run_docstring_examples( attr_value.__doc__, globals(), name=f"C1.{attr_name}", verbose=doctest.is_verbose() ) # 运行其余默认扫描的测试用例 doctest.testmod()
- 方案2:自定义兼容 doctest 扫描规则的 cached_property 装饰器,适合需要批量处理大量 cached_property 测试的场景
修改后的代码如下:
from functools import cached_property as origin_cached_property, cache import doctest # 自定义装饰器同时继承原cached_property功能和内置property类型 class cached_property(origin_cached_property, property): pass class C1: def test_1(self): """ >>> C1().test_1() 'f' """ return "f" @property def test_2(self): """ >>> C1().test_2 'p' """ return "p" @cached_property def test_3(self): """ >>> C1().test_3 'cp' """ return "cp" @cache def test_4(self): """ >>> C1().test_4() 'c' """ return "c" doctest.testmod()
两种方案执行python3 a.py -v后,都可以看到test_3的测试用例被正常执行,输出会新增对应的测试通过日志。
内容的提问来源于stack exchange,提问作者tomlla
相关产品推荐
相关产品推荐

