xref: /aosp_15_r20/external/pigweed/pw_console/py/console_prefs_test.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2021 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Tests for pw_console.console_app"""
15
16from pathlib import Path
17import tempfile
18import unittest
19
20import yaml
21
22# pylint: disable=protected-access
23from pw_console.console_prefs import (
24    ConsolePrefs,
25    _DEFAULT_CONFIG,
26)
27
28
29def _create_tempfile(content: str) -> Path:
30    with tempfile.NamedTemporaryFile(
31        prefix=f'{__package__}', delete=False
32    ) as output_file:
33        output_file.write(content.encode('UTF-8'))
34        return Path(output_file.name)
35
36
37class TestConsolePrefs(unittest.TestCase):
38    """Tests for ConsolePrefs."""
39
40    maxDiff = None
41
42    def test_load_no_existing_files(self) -> None:
43        prefs = ConsolePrefs(
44            project_file=False, project_user_file=False, user_file=False
45        )
46        self.assertEqual(_DEFAULT_CONFIG, prefs._config)
47        self.assertTrue(str(prefs.repl_history).endswith('pw_console_history'))
48        self.assertTrue(str(prefs.search_history).endswith('pw_console_search'))
49
50    def test_load_empty_file(self) -> None:
51        # Create an empty file
52        project_config_file = _create_tempfile('')
53        try:
54            prefs = ConsolePrefs(
55                project_file=project_config_file,
56                project_user_file=False,
57                user_file=False,
58            )
59            result_settings = {
60                k: v
61                for k, v in prefs._config.items()
62                if k in _DEFAULT_CONFIG.keys()
63            }
64            other_settings = {
65                k: v
66                for k, v in prefs._config.items()
67                if k not in _DEFAULT_CONFIG.keys()
68            }
69            # Check that only the default config was loaded.
70            self.assertEqual(_DEFAULT_CONFIG, result_settings)
71            self.assertEqual(0, len(other_settings))
72        finally:
73            project_config_file.unlink()
74
75    def test_load_project_file(self) -> None:
76        project_config = {
77            'pw_console': {
78                'ui_theme': 'light',
79                'code_theme': 'cool-code',
80                'swap_light_and_dark': True,
81            },
82        }
83        project_config_file = _create_tempfile(yaml.dump(project_config))
84        try:
85            prefs = ConsolePrefs(
86                project_file=project_config_file,
87                project_user_file=False,
88                user_file=False,
89            )
90            result_settings = {
91                k: v
92                for k, v in prefs._config.items()
93                if k in project_config['pw_console'].keys()
94            }
95            other_settings = {
96                k: v
97                for k, v in prefs._config.items()
98                if k not in project_config['pw_console'].keys()
99            }
100            self.assertEqual(project_config['pw_console'], result_settings)
101            self.assertNotEqual(0, len(other_settings))
102        finally:
103            project_config_file.unlink()
104
105    def test_load_project_and_user_file(self) -> None:
106        """Test user settings override project settings."""
107        project_config = {
108            'pw_console': {
109                'ui_theme': 'light',
110                'code_theme': 'cool-code',
111                'swap_light_and_dark': True,
112                'repl_history': '~/project_history',
113                'search_history': '~/project_search',
114            },
115        }
116        project_config_file = _create_tempfile(yaml.dump(project_config))
117
118        project_user_config = {
119            'pw_console': {
120                'ui_theme': 'nord',
121                'repl_history': '~/project_user_history',
122                'search_history': '~/project_user_search',
123            },
124        }
125        project_user_config_file = _create_tempfile(
126            yaml.dump(project_user_config)
127        )
128
129        user_config = {
130            'pw_console': {
131                'ui_theme': 'dark',
132                'search_history': '~/user_search',
133            },
134        }
135        user_config_file = _create_tempfile(yaml.dump(user_config))
136        try:
137            prefs = ConsolePrefs(
138                project_file=project_config_file,
139                project_user_file=project_user_config_file,
140                user_file=user_config_file,
141            )
142            # Set by the project
143            self.assertEqual(
144                project_config['pw_console']['code_theme'], prefs.code_theme
145            )
146            self.assertEqual(
147                project_config['pw_console']['swap_light_and_dark'],
148                prefs.swap_light_and_dark,
149            )
150
151            # Project user setting, result should not be project only setting.
152            project_history = project_config['pw_console']['repl_history']
153            assert isinstance(project_history, str)
154            self.assertNotEqual(
155                Path(project_history).expanduser(), prefs.repl_history
156            )
157
158            history = project_user_config['pw_console']['repl_history']
159            assert isinstance(history, str)
160            self.assertEqual(Path(history).expanduser(), prefs.repl_history)
161
162            # User config overrides project and project_user
163            self.assertEqual(
164                user_config['pw_console']['ui_theme'], prefs.ui_theme
165            )
166            self.assertEqual(
167                Path(user_config['pw_console']['search_history']).expanduser(),
168                prefs.search_history,
169            )
170            # ui_theme should not be the project_user file setting
171            project_user_theme = project_user_config['pw_console']['ui_theme']
172            self.assertNotEqual(project_user_theme, prefs.ui_theme)
173        finally:
174            project_config_file.unlink()
175            project_user_config_file.unlink()
176            user_config_file.unlink()
177
178
179if __name__ == '__main__':
180    unittest.main()
181