-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix environment variable leak for unused formatters (#338)
* Add tests against environment pollution * Delay `rpy2` import until the formatter is requested
- Loading branch information
1 parent
a7a9f10
commit 7cead40
Showing
2 changed files
with
65 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import json | ||
import os | ||
import sys | ||
from subprocess import run | ||
from unittest import mock | ||
|
||
import pytest | ||
|
||
from jupyterlab_code_formatter.formatters import SERVER_FORMATTERS | ||
|
||
|
||
def test_env_pollution_on_import(): | ||
# should not pollute environment on import | ||
code = "; ".join( | ||
[ | ||
"from jupyterlab_code_formatter import formatters", | ||
"import json", | ||
"import os", | ||
"assert formatters", | ||
"print(json.dumps(os.environ.copy()))", | ||
] | ||
) | ||
result = run([sys.executable, "-c", f"{code}"], capture_output=True, text=True, check=True, env={}) | ||
environ = json.loads(result.stdout) | ||
assert set(environ.keys()) - {"LC_CTYPE"} == set() | ||
|
||
|
||
@pytest.mark.parametrize("name", SERVER_FORMATTERS) | ||
def test_env_pollution_on_importable_check(name): | ||
formatter = SERVER_FORMATTERS[name] | ||
# should not pollute environment on `importable` check | ||
with mock.patch.dict(os.environ, {}, clear=True): | ||
# invoke the property getter | ||
is_importable = formatter.importable | ||
# the environment should have no extra keys | ||
assert set(os.environ.keys()) == set() | ||
if not is_importable: | ||
pytest.skip(f"{name} formatter was not importable, the test may yield false negatives") |