Temporarily updates the `os.environ` dictionary in-place. Similar to mockenv The `os.environ` dictionary is updated in-place so that the modification is sure to work in all situations. Args: remove: Environment variables to remove. update: Dictionary of environment variabl
(*remove, **update)
| 1789 | # from https://stackoverflow.com/a/34333710/9201239 |
| 1790 | @contextlib.contextmanager |
| 1791 | def mockenv_context(*remove, **update): |
| 1792 | """ |
| 1793 | Temporarily updates the `os.environ` dictionary in-place. Similar to mockenv |
| 1794 | |
| 1795 | The `os.environ` dictionary is updated in-place so that the modification is sure to work in all situations. |
| 1796 | |
| 1797 | Args: |
| 1798 | remove: Environment variables to remove. |
| 1799 | update: Dictionary of environment variables and values to add/update. |
| 1800 | """ |
| 1801 | env = os.environ |
| 1802 | update = update or {} |
| 1803 | remove = remove or [] |
| 1804 | |
| 1805 | # List of environment variables being updated or removed. |
| 1806 | stomped = (set(update.keys()) | set(remove)) & set(env.keys()) |
| 1807 | # Environment variables and values to restore on exit. |
| 1808 | update_after = {k: env[k] for k in stomped} |
| 1809 | # Environment variables and values to remove on exit. |
| 1810 | remove_after = frozenset(k for k in update if k not in env) |
| 1811 | |
| 1812 | try: |
| 1813 | env.update(update) |
| 1814 | [env.pop(k, None) for k in remove] |
| 1815 | yield |
| 1816 | finally: |
| 1817 | env.update(update_after) |
| 1818 | [env.pop(k) for k in remove_after] |
| 1819 | |
| 1820 | |
| 1821 | # --- pytest conf functions --- # |
no test coverage detected