Skip to content

Commit

Permalink
Support deletion of Variables via patch.
Browse files Browse the repository at this point in the history
This supports some up-coming test changes in the fix for pex-tool#1422.
  • Loading branch information
jsirois committed Aug 28, 2021
1 parent 65f7c5e commit 192a6ba
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
15 changes: 12 additions & 3 deletions pex/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,11 +292,20 @@ def strip(self):

@contextmanager
def patch(self, **kw):
# type: (**str) -> Iterator[Dict[str, str]]
"""Update the environment for the duration of a context."""
# type: (**Optional[str]) -> Iterator[Dict[str, str]]
"""Update the environment for the duration of a context.
Any environment variable with a value of `None` will be removed from the environment if
present. The rest will be added to the environment or else updated if already present in
the environment.
"""
old_environ = self._environ
self._environ = self._environ.copy()
self._environ.update(kw)
for k, v in kw.items():
if v is None:
self._environ.pop(k, None)
else:
self._environ[k] = v
yield self._environ
self._environ = old_environ

Expand Down
22 changes: 22 additions & 0 deletions tests/test_variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,25 @@ def test_pex_vars_value_or(tmpdir):
"Expected the fallback to be validated, and in the case of PEX_ROOT, replaced with a "
"writeable tmp dir"
)


def test_patch():
v = Variables(environ=dict(PEX_VERBOSE="3", PEX_PYTHON="jython", PEX_EMIT_WARNINGS="True"))
assert v.PEX_VERBOSE == 3
assert v.PEX_PYTHON == "jython"
assert v.PEX_EMIT_WARNINGS is True
assert v.PEX_FORCE_LOCAL is False

with v.patch(PEX_VERBOSE="1", PEX_EMIT_WARNINGS=None, PEX_FORCE_LOCAL="True") as env:
assert env["PEX_VERBOSE"] == "1"
assert env["PEX_PYTHON"] == "jython"
assert "PEX_EMIT_WARNINGS" not in env
assert env["PEX_FORCE_LOCAL"] == "True"

assert v.PEX_VERBOSE == 1
assert v.PEX_PYTHON == "jython"
assert v.PEX_EMIT_WARNINGS is None

# If the assertion is flipped from `is True` to `is False` this test fails; so MyPy is just
# confused here about the statement being unreachable.
assert v.PEX_FORCE_LOCAL is True # type: ignore[unreachable]

0 comments on commit 192a6ba

Please sign in to comment.