pytest-dev / pytest-dev/pytest

capsys fixture cannot be used with a session-scoped fixture

Open
#2,704 7 comments 16 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic: fixtures type: enhancement type: feature-branch
Dominant language
Python
Stars
14.5k
Forks
3.4k
Avg merge
2d 9h
Merged PRs (30d)
35

Description

I have the following use-case: there is a class Auditor, which helps gather statistic about certain tests. This class is used via a fixture:

@pytest.fixture(scope="session")
def auditor():
    aud = Auditor()
    yield aud
    aud.display_summary()

The intention being that some tests would use this fixture, report their results to the Auditor singleton, and in the end of the testing session a report table is produced.

Unfortunately, currently this works only with -s flag, because otherwise all output is captured. Ideally I'd like to write the fixture function as

@pytest.fixture(scope="session")
def auditor(capsys):
    aud = Auditor()
    yield aud
    with capsys.disabled():
        aud.display_summary()

however doing so produces an error that capsys is a function-scope capture and cannot be used with a session-scope fixture.

I believe there should be a way to provide a session-scoped variant of capsys, so that it can be used from user-defined session-scoped fixtures.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the session-scoped fixture that requests capsys and the resulting scope error. Read the capture-fixture behavior and fixture-scope handling around this case, then determine how a session-scoped capture variant should interact with capsys.disabled(). Done means a session-scoped fixture can emit its final summary without requiring -s.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.