|
| 1 | +import contextlib |
| 2 | +import os |
| 3 | +import unittest |
| 4 | + |
| 5 | +from alertaclient.api import Client |
| 6 | +from alertaclient.config import Config |
| 7 | + |
| 8 | + |
| 9 | +@contextlib.contextmanager |
| 10 | +def mod_env(*remove, **update): |
| 11 | + """ |
| 12 | + See https://stackoverflow.com/questions/2059482#34333710 |
| 13 | +
|
| 14 | + Temporarily updates the ``os.environ`` dictionary in-place. |
| 15 | +
|
| 16 | + The ``os.environ`` dictionary is updated in-place so that the modification |
| 17 | + is sure to work in all situations. |
| 18 | +
|
| 19 | + :param remove: Environment variables to remove. |
| 20 | + :param update: Dictionary of environment variables and values to add/update. |
| 21 | + """ |
| 22 | + env = os.environ |
| 23 | + update = update or {} |
| 24 | + remove = remove or [] |
| 25 | + |
| 26 | + # List of environment variables being updated or removed. |
| 27 | + stomped = (set(update.keys()) | set(remove)) & set(env.keys()) |
| 28 | + # Environment variables and values to restore on exit. |
| 29 | + update_after = {k: env[k] for k in stomped} |
| 30 | + # Environment variables and values to remove on exit. |
| 31 | + remove_after = frozenset(k for k in update if k not in env) |
| 32 | + |
| 33 | + try: |
| 34 | + env.update(update) |
| 35 | + [env.pop(k, None) for k in remove] |
| 36 | + yield |
| 37 | + finally: |
| 38 | + env.update(update_after) |
| 39 | + [env.pop(k) for k in remove_after] |
| 40 | + |
| 41 | + |
| 42 | +class CommandsTestCase(unittest.TestCase): |
| 43 | + |
| 44 | + def setUp(self): |
| 45 | + pass |
| 46 | + |
| 47 | + def test_env_vars(self): |
| 48 | + |
| 49 | + config = Config(config_file=None) |
| 50 | + self.assertEqual(config.options['config_file'], '~/.alerta.conf') |
| 51 | + |
| 52 | + with mod_env( |
| 53 | + ALERTA_CONF_FILE='~/.alerta.test.conf', |
| 54 | + ALERTA_DEFAULT_PROFILE='test-profile', |
| 55 | + ALERTA_ENDPOINT='http://foo/bar/baz', |
| 56 | + ALERTA_API_KEY='test-key', |
| 57 | + REQUESTS_CA_BUNDLE='', |
| 58 | + CLICOLOR='', |
| 59 | + DEBUG='1' |
| 60 | + ): |
| 61 | + |
| 62 | + # conf file |
| 63 | + config = Config(config_file=None) |
| 64 | + self.assertEqual(config.options['config_file'], '~/.alerta.test.conf', os.environ) |
| 65 | + config = Config(config_file='/dev/null') |
| 66 | + self.assertEqual(config.options['config_file'], '/dev/null') |
| 67 | + |
| 68 | + # profile |
| 69 | + config = Config(config_file=None) |
| 70 | + config.get_config_for_profle() |
| 71 | + self.assertEqual(config.options['profile'], 'test-profile', os.environ) |
| 72 | + |
| 73 | + # endpoint |
| 74 | + self.client = Client() |
| 75 | + self.assertEqual(self.client.endpoint, 'http://foo/bar/baz') |
| 76 | + |
| 77 | + # api key |
| 78 | + self.assertEqual(config.options['key'], 'test-key') |
0 commit comments