Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False negative error: ScopeMismatch must not be raised for Factories as fixtures used in fixtures with a higher scope #9235

Closed
simon-liebehenschel opened this issue Oct 24, 2021 · 2 comments
Labels
topic: fixtures anything involving fixtures directly or indirectly

Comments

@simon-liebehenschel
Copy link

Problem explanation

ScopeMismatch must not be raised for Factories as fixtures used in fixtures with a higher scope. I am forced to set scope="module" for my factories, but this is nonsense: factories always return a new value. In general, setting any scope for a factory use redundant and unnecessary: scope affects nothing for factories as fixtures. Please correct me if I am wrong.

Expected behavior

Allow writing factories as fixtures without scope and use them in fixtures with any scope.

Sample failing code:

import random

import pytest


@pytest.fixture()
def make_customer_record():
    def _make_customer_record():
        return {"name": random.random(), "orders": []}

    return _make_customer_record


@pytest.fixture(autouse=True, scope="module")
def create_customers(make_customer_record) -> None:
    customer_1 = make_customer_record()
    customer_2 = make_customer_record()
    customer_3 = make_customer_record()
    print(f"\n{customer_1}, {customer_2}, {customer_3}")


def test_customers():
    ...

Sample working code:

The same as above, but set scope for the factory fixture:

@pytest.fixture(scope="module")` 
def make_customer_record():

Versions

Pytest: 6.2.5
Python: 3.9
OS: Lubuntu 20.04

@Zac-HD Zac-HD added the topic: fixtures anything involving fixtures directly or indirectly label Oct 27, 2021
@asottile
Copy link
Member

the scope mismatch error looks correct to me, you have a module scoped fixture is requesting a function scoped fixture -- the lifetimes would mismatch (fixtures must only request equal or greater scopes)

you should adjust your make_customer_record fixture to be either scope='session' or scope='module'

@nicoddemus
Copy link
Member

To complement:

The default scope is function, so the mismatch is correct as @asottile commented.

Allow writing factories as fixtures without scope and use them in fixtures with any scope.

Yes those are what we called invocation scoped fixtures however at the time we couldn't really ship them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: fixtures anything involving fixtures directly or indirectly
Projects
None yet
Development

No branches or pull requests

4 participants