python config_error ai_generated true

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

ID: python/pytest-fixture-scope-conflict

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.6 active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 60% fail

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

  2. 90% fail

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