Debian Codegraph @

tests/test_config.py

raw
1 # -*- coding: utf-8 -*-
2 """Test the cli_helpers.config module."""
3
4 from __future__ import unicode_literals
5 import os
6
7 from unittest.mock import MagicMock
8 import pytest
9
10 from cli_helpers.compat import MAC, text_type, WIN
11 from cli_helpers.config import (
12 Config,
13 DefaultConfigValidationError,
14 get_system_config_dirs,
15 get_user_config_dir,
16 _pathify,
17 )
18 from .utils import with_temp_dir
19
20 APP_NAME, APP_AUTHOR = "Test", "Acme"
21 TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "config_data")
22 DEFAULT_CONFIG = {
23 "section": {
24 "test_boolean_default": "True",
25 "test_string_file": "~/myfile",
26 "test_option": "foobar✔",
27 },
28 "section2": {},
29 }
30 DEFAULT_VALID_CONFIG = {
31 "section": {
32 "test_boolean_default": True,
33 "test_string_file": "~/myfile",
34 "test_option": "foobar✔",
35 },
36 "section2": {},
37 }
38
39
40 def _mocked_user_config(temp_dir, *args, **kwargs):
41 config = Config(*args, **kwargs)
42 config.user_config_file = MagicMock(
43 return_value=os.path.join(temp_dir, config.filename)
44 )
45 return config
46
47
48 def test_user_config_dir():
49 """Test that the config directory is a string with the app name in it."""
50 if "XDG_CONFIG_HOME" in os.environ:
51 del os.environ["XDG_CONFIG_HOME"]
52 config_dir = get_user_config_dir(APP_NAME, APP_AUTHOR)
53 assert isinstance(config_dir, text_type)
54 assert config_dir.endswith(APP_NAME) or config_dir.endswith(_pathify(APP_NAME))
55
56
57 def test_sys_config_dirs():
58 """Test that the sys config directories are returned correctly."""
59 if "XDG_CONFIG_DIRS" in os.environ:
60 del os.environ["XDG_CONFIG_DIRS"]
61 config_dirs = get_system_config_dirs(APP_NAME, APP_AUTHOR)
62 assert isinstance(config_dirs, list)
63 assert config_dirs[0].endswith(APP_NAME) or config_dirs[0].endswith(
64 _pathify(APP_NAME)
65 )
66
67
68 @pytest.mark.skipif(not WIN, reason="requires Windows")
69 def test_windows_user_config_dir_no_roaming():
70 """Test that Windows returns the user config directory without roaming."""
71 config_dir = get_user_config_dir(APP_NAME, APP_AUTHOR, roaming=False)
72 assert isinstance(config_dir, text_type)
73 assert config_dir.endswith(APP_NAME)
74 assert "Local" in config_dir
75
76
77 @pytest.mark.skipif(not MAC, reason="requires macOS")
78 def test_mac_user_config_dir_no_xdg():
79 """Test that macOS returns the user config directory without XDG."""
80 config_dir = get_user_config_dir(APP_NAME, APP_AUTHOR, force_xdg=False)
81 assert isinstance(config_dir, text_type)
82 assert config_dir.endswith(APP_NAME)
83 assert "Library" in config_dir
84
85
86 @pytest.mark.skipif(not MAC, reason="requires macOS")
87 def test_mac_system_config_dirs_no_xdg():
88 """Test that macOS returns the system config directories without XDG."""
89 config_dirs = get_system_config_dirs(APP_NAME, APP_AUTHOR, force_xdg=False)
90 assert isinstance(config_dirs, list)
91 assert config_dirs[0].endswith(APP_NAME)
92 assert "Library" in config_dirs[0]
93
94
95 def test_config_reading_raise_errors():
96 """Test that instantiating Config will raise errors when appropriate."""
97 with pytest.raises(ValueError):
98 Config(APP_NAME, APP_AUTHOR, "test_config", write_default=True)
99
100 with pytest.raises(ValueError):
101 Config(APP_NAME, APP_AUTHOR, "test_config", validate=True)
102
103 with pytest.raises(TypeError):
104 Config(APP_NAME, APP_AUTHOR, "test_config", default=b"test")
105
106
107 def test_config_user_file():
108 """Test that the Config user_config_file is appropriate."""
109 config = Config(APP_NAME, APP_AUTHOR, "test_config")
110 assert get_user_config_dir(APP_NAME, APP_AUTHOR) in config.user_config_file()
111
112
113 def test_config_reading_default_dict():
114 """Test that the Config constructor will read in defaults from a dict."""
115 default = {"main": {"foo": "bar"}}
116 config = Config(APP_NAME, APP_AUTHOR, "test_config", default=default)
117 assert config.data == default
118
119
120 def test_config_reading_no_default():
121 """Test that the Config constructor will work without any defaults."""
122 config = Config(APP_NAME, APP_AUTHOR, "test_config")
123 assert config.data == {}
124
125
126 def test_config_reading_default_file():
127 """Test that the Config will work with a default file."""
128 config = Config(
129 APP_NAME,
130 APP_AUTHOR,
131 "test_config",
132 default=os.path.join(TEST_DATA_DIR, "configrc"),
133 )
134 config.read_default_config()
135 assert config.data == DEFAULT_CONFIG
136
137
138 def test_config_reading_configspec():
139 """Test that the Config default file will work with a configspec."""
140 config = Config(
141 APP_NAME,
142 APP_AUTHOR,
143 "test_config",
144 validate=True,
145 default=os.path.join(TEST_DATA_DIR, "configspecrc"),
146 )
147 config.read_default_config()
148 assert config.data == DEFAULT_VALID_CONFIG
149
150
151 def test_config_reading_configspec_with_error():
152 """Test that reading an invalid configspec raises and exception."""
153 with pytest.raises(DefaultConfigValidationError):
154 config = Config(
155 APP_NAME,
156 APP_AUTHOR,
157 "test_config",
158 validate=True,
159 default=os.path.join(TEST_DATA_DIR, "invalid_configspecrc"),
160 )
161 config.read_default_config()
162
163
164 @with_temp_dir
165 def test_write_and_read_default_config(temp_dir=None):
166 config_file = "test_config"
167 default_file = os.path.join(TEST_DATA_DIR, "configrc")
168 temp_config_file = os.path.join(temp_dir, config_file)
169
170 config = _mocked_user_config(
171 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file
172 )
173 config.read_default_config()
174 config.write_default_config()
175
176 user_config = _mocked_user_config(
177 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file
178 )
179 user_config.read()
180 assert temp_config_file in user_config.config_filenames
181 assert user_config == config
182
183 with open(temp_config_file) as f:
184 contents = f.read()
185 assert "# Test file comment" in contents
186 assert "# Test section comment" in contents
187 assert "# Test field comment" in contents
188 assert "# Test field commented out" in contents
189
190
191 @with_temp_dir
192 def test_write_and_read_default_config_from_configspec(temp_dir=None):
193 config_file = "test_config"
194 default_file = os.path.join(TEST_DATA_DIR, "configspecrc")
195 temp_config_file = os.path.join(temp_dir, config_file)
196
197 config = _mocked_user_config(
198 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file, validate=True
199 )
200 config.read_default_config()
201 config.write_default_config()
202
203 user_config = _mocked_user_config(
204 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file, validate=True
205 )
206 user_config.read()
207 assert temp_config_file in user_config.config_filenames
208 assert user_config == config
209
210 with open(temp_config_file) as f:
211 contents = f.read()
212 assert "# Test file comment" in contents
213 assert "# Test section comment" in contents
214 assert "# Test field comment" in contents
215 assert "# Test field commented out" in contents
216
217
218 @with_temp_dir
219 def test_overwrite_default_config_from_configspec(temp_dir=None):
220 config_file = "test_config"
221 default_file = os.path.join(TEST_DATA_DIR, "configspecrc")
222 temp_config_file = os.path.join(temp_dir, config_file)
223
224 config = _mocked_user_config(
225 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file, validate=True
226 )
227 config.read_default_config()
228 config.write_default_config()
229
230 with open(temp_config_file, "a") as f:
231 f.write("--APPEND--")
232
233 config.write_default_config()
234
235 with open(temp_config_file) as f:
236 assert "--APPEND--" in f.read()
237
238 config.write_default_config(overwrite=True)
239
240 with open(temp_config_file) as f:
241 assert "--APPEND--" not in f.read()
242
243
244 def test_read_invalid_config_file():
245 config_file = "invalid_configrc"
246
247 config = _mocked_user_config(TEST_DATA_DIR, APP_NAME, APP_AUTHOR, config_file)
248 config.read()
249 assert "section" in config
250 assert "test_string_file" in config["section"]
251 assert "test_boolean_default" not in config["section"]
252 assert "section2" in config
253
254
255 @with_temp_dir
256 def test_write_to_user_config(temp_dir=None):
257 config_file = "test_config"
258 default_file = os.path.join(TEST_DATA_DIR, "configrc")
259 temp_config_file = os.path.join(temp_dir, config_file)
260
261 config = _mocked_user_config(
262 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file
263 )
264 config.read_default_config()
265 config.write_default_config()
266
267 with open(temp_config_file) as f:
268 assert "test_boolean_default = True" in f.read()
269
270 config["section"]["test_boolean_default"] = False
271 config.write()
272
273 with open(temp_config_file) as f:
274 assert "test_boolean_default = False" in f.read()
275
276
277 @with_temp_dir
278 def test_write_to_outfile(temp_dir=None):
279 config_file = "test_config"
280 outfile = os.path.join(temp_dir, "foo")
281 default_file = os.path.join(TEST_DATA_DIR, "configrc")
282
283 config = _mocked_user_config(
284 temp_dir, APP_NAME, APP_AUTHOR, config_file, default=default_file
285 )
286 config.read_default_config()
287 config.write_default_config()
288
289 config["section"]["test_boolean_default"] = False
290 config.write(outfile=outfile)
291
292 with open(outfile) as f:
293 assert "test_boolean_default = False" in f.read()