Setting COLUMN environment variable using monkeypatch messes up output of run results
#11204
|
I have the need to capture output at a standard width. One option is to use @pytest.fixture(scope='function')
def mock_width(monkeypatch)
monkeypatch.setenv('COLUMNS', '120')I was hoping that I would be able to use @pytest.fixture(scope='function')
def mock_width(monkeypatch) -> None:
monkeypatch.setenv('COLUMNS', '120')
yield
monkeypatch.delenv('COLUMNS')Is my only option to use monkeypatch.setenv() at the beginning of every test function that tests terminal output, and monkeypatch.delenv() at the end. Or is there a better way? Thanks. |
Replies: 2 comments 1 reply
Yeah you will need to limit the scope where @contextmanager
def using_column_width(w: int):
mp = pytest.MonkeyPatch()
mp.setenv("COLUMNS", w)
try:
yield
finally:
mp.undo()
def test_foo():
with using_column_width(120):
... |
|
This is an interesting example of why environment-variable testing is not only about whether a variable was set, but also its scope and potential side effects. I’ve been working on an open-source configuration-coverage analyzer called ConfigReach: https://github.com/sauravsingla/ConfigReach One class of findings it looks for is test code that mutates the global environment in a potentially leaky way. More broadly, I’m interested in whether configuration-testing tools should distinguish between: configuration intentionally scoped to one test This kind of example is useful because configuration coverage and configuration isolation are closely related but not exactly the same problem. Would that distinction be useful to pytest users? |
Yeah you will need to limit the scope where
COLUMNSis set, so I suggest to write your own context manager: