Repository: daviskirk/climatecontrol

Issue:
Function to save and restore settings (for testing)
This should allow creating a pytest fixture which undoes all changes to the Settings object after the test is finished.

Instead of a function, a context manager could be used instead.

Discussion:

Patch:
diff --git a/README.rst b/README.rst
index 9df1ef9..2776c15 100644
--- a/README.rst
+++ b/README.rst
@@ -200,6 +200,29 @@ save it to a file like "cli.py" and then call it after installing click:
 whithout needing to set any env vars.
 
 
+Testing
+-------
+
+When testing your application, different behaviours often depend on settings
+taking on different values. Assuming that you are using a single `Settings`
+object accross multiple functions or modules, handling these settings changes
+in tests can be tricky.
+
+The settings object provides a simple method for modifying your settings object
+temporarily:
+
+.. code:: python
+
+   settings_map.update({'a': 1})
+   # Enter a temporary changes context block:
+   with settings_map.temporary_changes():
+       settings_map.update({'a': 1})
+       # Inside the context, the settings can be modified and used as you choose
+       print(settings_map['a'])  # outputs: 2
+   # After the context exits the settings map
+   print(settings_map['a'])  # outputs: 1
+
+
 .. |Build Status| image:: https://travis-ci.org/daviskirk/climatecontrol.svg?branch=master
    :target: https://travis-ci.org/daviskirk/climatecontrol
 .. |Coverage Status| image:: https://coveralls.io/repos/github/daviskirk/climatecontrol/badge.svg?branch=master
diff --git a/climatecontrol/settings_parser.py b/climatecontrol/settings_parser.py
index ab45c47..40b8bc8 100644
--- a/climatecontrol/settings_parser.py
+++ b/climatecontrol/settings_parser.py
@@ -1,6 +1,7 @@
 """Settings parser."""
 
 from abc import ABC, abstractmethod
+from contextlib import contextmanager
 import os
 import json
 import toml
@@ -312,6 +313,31 @@ class Settings(Mapping):
                 new_data[k] = parsed_v
         return new_data
 
+    @contextmanager
+    def temporary_changes(self):
+        """Open a context where any changes to the settings are rolled back on context exit.
+
+        This context manager can be used for testing or to temporarily change
+        settings.
+
+        Example:
+            >>> from climatecontrol.settings_parser import Settings
+            >>> settings = Settings()
+            >>> settings.update({'a': 1})
+            >>> with settings.temporary_changes():
+            ...     settings.update({'a': 2})
+            ...     assert settings['a'] == 2
+            >>> assert settings['a'] == 1
+
+        """
+        archived_settings = deepcopy(self._data)
+        archived_settings_files = deepcopy(self._settings_files)
+        archived_external_data = deepcopy(self.external_data)
+        yield self
+        self._data = archived_settings
+        self._settings_files = archived_settings_files
+        self.external_data = archived_external_data
+
 
 EnvSetting = NamedTuple('EnvSetting', [('name', str), ('value', Mapping[str, Any])])
 


Test patch:
diff --git a/tests/test_settings.py b/tests/test_settings.py
index 1e6a915..a72b635 100644
--- a/tests/test_settings.py
+++ b/tests/test_settings.py
@@ -244,6 +244,26 @@ def test_filters(mock_empty_os_environ):
     assert dict(settings_map) == {'subsection1': 'test1', 'subsection2': 'test2', 'subsection3': 'test3'}
 
 
+def test_temporary_changes():
+    """Test that temporary changes settings context manager works.
+
+    Within the context, settings should be changeable. After exit, the original
+    settings should be restored.
+
+    """
+    s = settings_parser.Settings()
+    s.update({'a': 1})
+    with s.temporary_changes():
+        # Change the settings within the context
+        s.update({'a': 2, 'b': 2})
+        s.settings_files.append('test')
+        assert s['a'] == 2
+        assert len(s.settings_files) == 1
+    # Check that outside of the context the settings are back to their old state.
+    assert s['a'] == 1
+    assert len(s.settings_files) == 0
+
+
 @pytest.mark.parametrize('use_method', [True, False])
 @pytest.mark.parametrize('option_name', ['config', 'settings'])
 @pytest.mark.parametrize('mode', ['config', 'noconfig', 'wrongfile', 'noclick'])