What if you could save minutes on every test run by sharing one setup smartly?
Why Shared expensive resource patterns in PyTest? - Purpose & Use Cases
Imagine you have a big database or a complex server setup that your tests need to use. You run each test one by one, and every time, you start and stop this heavy setup manually.
This manual way is slow because starting and stopping the resource takes a lot of time. It's also easy to make mistakes, like forgetting to clean up or accidentally changing the resource state, which breaks other tests.
Shared expensive resource patterns let you set up the resource once and share it across many tests safely. This saves time and avoids errors by managing the resource automatically and cleanly.
def test1(): setup_db() # test code teardown_db() def test2(): setup_db() # test code teardown_db()
@pytest.fixture(scope='session') def db(): setup_db() yield teardown_db() def test1(db): # test code def test2(db): # test code
It enables running many tests faster and more reliably by sharing costly setups without repeating work.
Think of running tests that need a web server. Instead of starting the server for each test, you start it once for all tests, saving minutes and avoiding server crashes.
Manual setup of expensive resources slows tests and causes errors.
Shared resource patterns set up once and reuse safely.
Tests run faster and more reliably with less manual work.