python config_error ai_generated true

作用域不匹配:您尝试使用'session'作用域的请求对象访问'function'作用域的fixture 'db'

ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'session' scoped request object

ID: python/pytest-fixture-scope-conflict

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
3.6 active

根因分析

pytest中,高作用域fixture(如session)请求低作用域fixture(如function)时,pytest无法保证低作用域fixture的生命周期,从而报错。

English

在pytest中,一个较高作用域的fixture(如session)尝试请求一个较低作用域的fixture(如function),导致pytest无法提供正确的实例,因为较低作用域的fixture会在测试结束后销毁。

generic

解决方案

  1. 90% 成功率
    在fixture定义中修改scope参数,例如:@pytest.fixture(scope='session') def db(): ... 改为 @pytest.fixture(scope='function') def db(): ...
  2. 70% 成功率
    def session_fixture(request):
        db = request.getfixturevalue('db')
        return db

无效尝试

常见但无效的做法:

  1. 60% 失败

    如果fixture本身需要每个测试独立状态,改为session会导致状态污染,且仍然无法解决根本的依赖关系错误。

  2. 90% 失败

    autouse只影响自动应用,不改变作用域依赖,错误依旧存在。