Flask接口单元测试报错:uwsgi模块无masterpid属性
问题原因
单元测试是通过Python直接运行的,而非在uWSGI进程环境中,此时uwsgi模块不存在masterpid属性——这个属性只有在uWSGI启动的进程内才会被初始化,因此uwsgi_tasks库在导入时触发了AttributeError。
解决方案
方案1:重构app.py的导入逻辑,兼容测试环境
在app.py中对uwsgi_tasks的导入做环境判断,避免在测试环境加载依赖uWSGI的代码:
# app.py try: # 先检查是否处于uWSGI运行环境 import uwsgi uwsgi.masterpid() from uwsgi_tasks import TaskExecutor, task # 这里放TaskExecutor的初始化等相关代码 except (AttributeError, ImportError): # 测试环境下的空实现,不影响单元测试 TaskExecutor = None # 模拟task装饰器的行为 def task(*args, **kwargs): def wrapper(func): return func return wrapper
方案2:在测试代码中Mock uwsgi模块
利用unittest.mock模拟uwsgi的masterpid方法,让uwsgi_tasks库能正常导入:
# test_common_services.py import sys from unittest import TestCase from unittest.mock import Mock class TestCommonServices(TestCase): def setUp(self): # 构造mock的uwsgi模块 mock_uwsgi = Mock() mock_uwsgi.masterpid.return_value = 1 # 返回非0值,跳过uwsgi_tasks的错误分支 sys.modules['uwsgi'] = mock_uwsgi # 现在可以正常导入app了 from app import OPERATIONS_CATALOG_SVC
或者用装饰器简化mock:
from unittest import TestCase from unittest.mock import patch @patch('uwsgi.masterpid') class TestCommonServices(TestCase): def setUp(self, mock_masterpid): mock_masterpid.return_value = 1 from app import OPERATIONS_CATALOG_SVC
方案3:拆分模块隔离依赖(可选)
如果OPERATIONS_CATALOG_SVC不依赖uwsgi_tasks的功能,将其拆分到独立的无依赖模块中,测试时直接导入该模块,绕过uwsgi_tasks的导入逻辑。
内容的提问来源于stack exchange,提问作者Jorge Barquero Villalobos
相关产品推荐
相关产品推荐

