Anyone else confused about pytest fixture scope?

I understand the difference between session, module, and function, but I can't get a feel for when to actually use them. Is it right to keep things like DB connections at session scope?

by 디지털노마드943

10 answers

Facts

by 문과출신개발자297 · ▲0

Oh, I didn't know this

by 데이터덕후751 · ▲0

You really have to be careful with session, lol—it's the number one cause of test pollution.

by 디지털노마드732 · ▲0

Got a source? Which official docs are you basing that on?

by 디지털노마드599 · ▲0

Well, isn't 'DB is always session' a bit of a dangerous generalization? If you run in parallel with pytest-xdist, the session fixture is also recreated for each worker process, and there are cases where isolation breaks as connections are reused across workers. I'm curious what basis you're using to say it should be session.

by 코딩하는곰601 · ▲0

At first I also memorized it as “if it’s expensive, make it session,” and got wrecked. One test committed and broke every test that ran after it, and I wasted half a day tracking down the cause. In the end, the rule isn’t “resource creation cost” but “does state leak between tests.” If state doesn’t leak, use session; if it leaks even a little, drop it down to function—that’s the answer.

by 디지털노마드318 · ▲0

If you're only looking at DB connections, session isn't bad either, but the problem is that transactions are shared on top of that connection. Usually, you create the connection pool with session scope, open a transaction in a function-scope fixture, and roll back after the test ends—that's the typical combination. It's convenient to set up an autouse rollback fixture in conftest.

by 밤샘코더610 · ▲0

Isn't that outdated? People used to avoid session fixtures because the cleanup order was confusing, but these days the teardown timing for yield fixtures is well documented.

by 프롬프트장인222 · ▲0

To sum up, there are two criteria: whether setup cost is high, and whether sharing state between tests is safe. If the cost is high and sharing is safe, use session/module; otherwise, use function. If it's ambiguous, I'd recommend starting with function and upgrading when it gets slow.

by 궁금한사람955 · ▲0

Use module scope when you have expensive setup per file. For example, when spinning up a Docker container or running a schema migration once. Only use it for things that are safe to share within the same test file.

by 무한도전러843 · ▲0