pytest中如何模拟已通过pip安装的模块不可用的场景
问题解答
核心疑问说明
Python不存在存储「已安装但未导入的模块」的全局字典。Python的导入逻辑是运行时按sys.path的路径顺序逐个查找匹配的模块文件,不会提前扫描所有已安装模块存入字典,所以你想通过删除预存字典键的方式无法实现需求。
推荐实现方案
测试场景下最稳妥的方式是使用unittest.mock(Python 3.3+标准库自带)临时拦截导入,不会污染全局运行环境,测试结束后会自动恢复原状,示例代码如下:
import sys from unittest import mock def test_concurrent_log_handler_import_error(): # 临时拦截concurrent_log_handler的导入 with mock.patch.dict('sys.modules', {'concurrent_log_handler': None}): # 清理之前可能存在的模块缓存 sys.modules.pop('concurrent_log_handler', None) # 此处执行你要测试的应用代码 try: from concurrent_log_handler import ConcurrentRotatingFileHandler except ImportError as e: # 成功命中异常分支,可校验输出是否符合预期 print("你需要运行'pip install concurrent_log_handler'", file=sys.stderr)
如果需要完全模拟模块不存在的报错信息,可自定义触发导入异常的模拟类:
class DisabledModule: def __getattr__(self, attr): raise ImportError("No module named 'concurrent_log_handler'") with mock.patch.dict('sys.modules', {'concurrent_log_handler': DisabledModule()}): # 执行测试逻辑 pass
内容的提问来源于stack exchange,提问作者mike rodent
相关产品推荐
相关产品推荐

