Modifying environment variables — Testpath 0.3 documentation

# Modifying environment variables

These functions allow you to temporarily modify the environment variables, which is often useful for testing code that calls other processes.

`testpath.` `modified_env`(changes, snapshot=True)

  Temporarily modify environment variables.

  Specify the changes as a dictionary mapping names to new values, using None as the value for names that should be deleted.

  Example use:

      with modified_env({'SHELL': 'bash', 'PYTHONPATH': None}):
          ...

  When the context exits, there are two possible ways to restore the environment. If snapshot is True, the default, it will reset the whole environment to its state when the context was entered. If snapshot is False, it will restore only the specific variables it modified, leaving any changes made to other environment variables in the context.

`testpath.` `temporary_env`(newenv)

  Completely replace the environment variables with the specified dict.

  Use as a context manager:

      with temporary_env({'PATH': my_path}):
          ...

`testpath.` `make_env_restorer`()

  Snapshot the current environment, return a function to restore that.

  This is intended to produce cleanup functions for tests. For example, using the `unittest.TestCase` API:

      def setUp(self):
          self.addCleanup(testpath.make_env_restorer())

  Any changes a test makes to the environment variables will be wiped out before the next test is run.