pytest session scoped fixtures

In pytest fixtures nuts and bolts, I noted that you can specify session scope so that a fixture will only run once per test session and be available across multiple test functions, classes, and modules.

In this post, I’m going to show a simple example so you can see it in action.

Here’s the table from the previous post:

function Run once per test
class Run once per class of tests
module Run once per module
session Run once per session

A separate file for fixtures,

With function, class, and module scope, it is completely reasonable for the fixture code to be in the same file as the tests.
But now suddenly, with session, that doesn’t make sense anymore.

We can put them in This is a special named file that pytest looks for.
The documentation says that it’s for local plugins, but we can use it for local fixtures as well. See the site for placement and scope of

Simple example of session scope fixtures

I think it’s clearest to just see this in action.

I’ve got 4 files:

    • 2 fixtures
    • my_own_session_run_at_beginning, an autouse fixture with session scope
    • some_resource, a normal non-autouse fixture with session scope
    • 2 simple test functions
    • test_alpha_1, has no named fixtures
    • test_alpha_2, has one named fixture, some_resource
    • similar to, but with unittest based tests
    • similar to, but with class based tests


Run with pytest -s -v

Mixing function, module, and session scope

Let’s say I’ve got:

  • a function scope fixture ‘resource_c’
  • that uses a module scoped fixture ‘fixture_b’
  • that uses a session scoped fixture ‘fixture_a’

This all works fine.
Also in this example, I’ve added a few autouse fixtures just for fun.

This seems reasonable to me.
What do you think will happen?


WARNING: you gotta use bigger and bigger scope

If you do this in the wrong order, things go haywire.

Let’s swap scope on a couple of items.

We will get some warning like this (or several):

So. Don’t do that.

Warning applies to built in fixtures

Pytest includes some built in fixtures. I believe all of them are function scoped.
This means that you cannot use them from anything other than functions or function scoped fixtures.

Taking it further

The code I’ve shown is for simple run at the beginning and end type fixtures.
However, there’s more you can do with session fixtures.
The site has a cool example, A session-fixture which can look at all collected tests.

What are you using session fixtures for?

I’d love to hear examples and use cases for session fixtures.
Please leave a comment or let me know @brianokken of how you are using them.


Leave a Reply