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

I want a rule that will prevent people from doing from sys import stderr, stdout #321

Open
webknjaz opened this issue Jan 4, 2025 · 0 comments
Labels
enhancement New feature or request

Comments

@webknjaz
Copy link
Contributor

webknjaz commented Jan 4, 2025

Rule request

Description

$sbj, basically. Specifically, in the regular runtime code, not so much in tests.

Rationale

I sometimes forget about this and have something like

from sys import stderr
...
...
...
def run_my_cmd():
    print('Some error msg', file=stderr)

And so I want to test this with capsys in a while, not immediately after writing that code. Next thing I know, I write a test that looks like

def test_error_output(capsys: pytest.CaptureFixture[str]) -> None:
    run_my_cmd()

    captured_outputs = capsys.readouterr()
    assert captured_outputs.err == 'Some error msg\n'

I run it, and immediately get puzzled as to why it captures an empty string. Eventually, I remember that from .. import .., re-read the pytest docs and realize that it patches the sys module's attributes stderr and stdout. So when I import it using from sys import stderr, stderr becomes a module-scoped reference to that native IO object. This means that pytest patching the sys module does not influence the fact that the runtime code references that unpatched IO object.
And pytest silently fails to intercept stderr/stdout.

It seems so obvious once you get through all the troubleshooting steps, but is frustrating at first. It's an easy mistake to make. Hence, the motivation — I think that such a rule is well within the scope of this plugin.

@webknjaz webknjaz added the enhancement New feature or request label Jan 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant