配置PyTest测试Flask应用时遇TypeError:不支持Flask对象减法运算
Flask+PyTest配置时出现TypeError的解决办法
错误现象
配置PyTest测试Flask应用时,触发TypeError:unsupported operand type(s) for -: 'Flask' and 'Flask'
问题定位
查看conftest.py中的test_app fixture代码,存在明显语法错误:
app - init_app()
这里误将赋值运算符=写成了减号-,导致尝试对两个Flask实例执行减法运算,直接触发类型错误。
修正代码
将conftest.py中的错误行修正为赋值操作即可解决问题,同时优化test_db fixture确保上下文正确:
from application import init_app, db @pytest.fixture(scope="module") def test_app(): """fixture for testing the application""" app = init_app() # 替换-为= app.config.from_object("app.config.TestingConfig") with app.app_context(): yield app @pytest.fixture(scope="module") def test_db(test_app): # 关联test_app依赖,确保在应用上下文内操作 """fixture for cleaning and initializing the database""" with test_app.app_context(): db.create_all() yield db db.session.remove() db.drop_all()
额外说明
原test_db fixture未绑定应用上下文,可能导致数据库操作时找不到Flask实例,添加test_app依赖并在上下文内执行操作,可避免后续出现上下文相关报错。
内容的提问来源于stack exchange,提问作者Graham Patrick
相关产品推荐
相关产品推荐

