Debian Codegraph @

brian2/tests/test_preferences.py

raw
1 from io import StringIO
2
3 import pytest
4 from numpy import float32, float64
5 from numpy.testing import assert_equal
6
7 from brian2 import amp, restore_initial_state, volt
8 from brian2.core.preferences import (
9 BrianGlobalPreferences,
10 BrianGlobalPreferencesView,
11 BrianPreference,
12 DefaultValidator,
13 PreferenceError,
14 )
15
16
17 @pytest.mark.codegen_independent
18 def test_defaultvalidator():
19 # Test that the default validator checks the class
20 validator = DefaultValidator(5)
21 assert validator(3)
22 assert not validator("3")
23 validator = DefaultValidator("astring")
24 assert validator("another")
25 assert not validator(3)
26 # test that the default validator checks the units
27 validator = DefaultValidator(3 * volt)
28 assert validator(2 * volt)
29 assert not validator(1 * amp)
30
31
32 @pytest.mark.codegen_independent
33 def test_brianpreference():
34 # check default args
35 pref = BrianPreference(1.0 / 3, "docs")
36 assert not pref.validator(1)
37 assert pref.docs == "docs"
38 assert pref.default == 1.0 / 3
39 assert pref.representor(pref.default) == repr(1.0 / 3)
40
41
42 @pytest.mark.codegen_independent
43 def test_preference_name_checking():
44 """
45 Test that you cannot set illegal preference names.
46 """
47 gp = BrianGlobalPreferences()
48
49 # Name that starts with an underscore
50 with pytest.raises(PreferenceError):
51 gp.register_preferences(
52 "dummy",
53 "dummy doc",
54 _notalegalname=BrianPreference(True, "some preference"),
55 )
56
57 # Name that clashes with a method name
58 with pytest.raises(PreferenceError):
59 gp.register_preferences(
60 "dummy", "dummy doc", update=BrianPreference(True, "some preference")
61 )
62
63 gp.register_preferences(
64 "a", "dummy doc", b=BrianPreference(True, "some preference")
65 )
66
67 # Trying to register a subcategory that would shadow a preference
68 with pytest.raises(PreferenceError):
69 gp.register_preferences(
70 "a.b", "dummy doc", name=BrianPreference(True, "some preference")
71 )
72
73 gp.register_preferences(
74 "b.c", "dummy doc", name=BrianPreference(True, "some preference")
75 )
76
77 # Trying to register a preference that clashes with an existing category
78 with pytest.raises(PreferenceError):
79 gp.register_preferences(
80 "b", "dummy doc", c=BrianPreference(True, "some preference")
81 )
82
83
84 @pytest.mark.codegen_independent
85 def test_brianglobalpreferences():
86 # test that pre-setting a nonexistent preference in a subsequently
87 # existing base name raises an error at the correct point
88 gp = BrianGlobalPreferences()
89
90 # This shouldn't work, in user code only registered preferences can be set
91 with pytest.raises(PreferenceError):
92 gp.__setitem__("a.b", 5)
93
94 # This uses the method that is used when reading preferences from a file
95 gp._set_preference("a.b", 5)
96 gp._set_preference("a.c", 5)
97 with pytest.raises(PreferenceError):
98 gp.register_preferences("a", "docs for a", b=BrianPreference(5, "docs for b"))
99 # test that post-setting a nonexistent preference in an existing base
100 # name raises an error
101 gp = BrianGlobalPreferences()
102 gp.register_preferences("a", "docs for a", b=BrianPreference(5, "docs for b"))
103 with pytest.raises(PreferenceError):
104 gp.__setitem__("a.c", 5)
105 # Test pre and post-setting some correct names but valid and invalid values
106 gp = BrianGlobalPreferences()
107 gp._set_preference("a.b", 5)
108 gp.register_preferences(
109 "a",
110 "docs for a",
111 b=BrianPreference(5, "docs for b"),
112 c=BrianPreference(1 * volt, "docs for c"),
113 d=BrianPreference(0, "docs for d", validator=lambda x: x >= 0),
114 e=BrianPreference(float64, "docs for e", representor=lambda x: x.__name__),
115 )
116 assert gp["a.c"] == 1 * volt
117 gp["a.c"] = 2 * volt
118 with pytest.raises(PreferenceError):
119 gp.__setitem__("a.c", 3 * amp)
120 gp["a.d"] = 2.0
121 with pytest.raises(PreferenceError):
122 gp.__setitem__("a.d", -1)
123 gp["a.e"] = float32
124 with pytest.raises(PreferenceError):
125 gp.__setitem__("a.e", 0)
126 # test backup and restore
127 gp._backup()
128 gp["a.d"] = 10
129 assert gp["a.d"] == 10
130 gp._restore()
131 assert gp["a.d"] == 2.0
132 # test that documentation and as_file generation runs without error, but
133 # don't test for values because we might change the organisation of it
134 assert len(gp.get_documentation())
135 gp.as_file
136 gp.defaults_as_file
137 # test that reading a preference file works as expected
138 pref_file = StringIO(
139 """
140 # a comment
141 a.b = 10
142 [a]
143 c = 5*volt
144 d = 1
145 e = float64
146 """
147 )
148 gp.read_preference_file(pref_file)
149 assert gp["a.b"] == 10
150 assert gp["a.c"] == 5 * volt
151 assert gp["a.d"] == 1
152 assert gp["a.e"] == float64
153 # test that reading a badly formatted prefs file fails
154 pref_file = StringIO(
155 """
156 [a
157 b = 10
158 """
159 )
160 with pytest.raises(PreferenceError):
161 gp.read_preference_file(pref_file)
162 # test that reading a well formatted prefs file with an invalid value fails
163 pref_file = StringIO(
164 """
165 a.b = 'oh no, not a string'
166 """
167 )
168 with pytest.raises(PreferenceError):
169 gp.read_preference_file(pref_file)
170 # assert that writing the prefs to a file and loading them gives the
171 # same values
172 gp = BrianGlobalPreferences()
173 gp.register_preferences(
174 "a",
175 "docs for a",
176 b=BrianPreference(5, "docs for b"),
177 )
178 gp._backup()
179 gp["a.b"] = 10
180 str_modified = gp.as_file
181 str_defaults = gp.defaults_as_file
182 gp["a.b"] = 15
183 gp.read_preference_file(StringIO(str_modified))
184 assert gp["a.b"] == 10
185 gp.read_preference_file(StringIO(str_defaults))
186 assert gp["a.b"] == 5
187 # check that load_preferences works, but nothing about its values
188 gp = BrianGlobalPreferences()
189 gp.load_preferences()
190
191 # Check that resetting to default preferences works
192 gp = BrianGlobalPreferences()
193 gp.register_preferences("a", "docs for a", b=BrianPreference(5, "docs for b"))
194 assert gp["a.b"] == 5
195 gp["a.b"] = 7
196 assert gp["a.b"] == 7
197 gp.reset_to_defaults()
198 assert gp["a.b"] == 5
199
200
201 @pytest.mark.codegen_independent
202 def test_preference_name_access():
203 """
204 Test various ways of accessing preferences
205 """
206
207 gp = BrianGlobalPreferences()
208
209 gp.register_preferences(
210 "main", "main category", name=BrianPreference(True, "some preference")
211 )
212 gp.register_preferences(
213 "main.sub", "subcategory", name2=BrianPreference(True, "some preference")
214 )
215
216 gp.register_preferences("main.sub_no_pref", "subcategory without preference")
217 gp.register_preferences(
218 "main.sub_no_pref.sub",
219 "deep subcategory",
220 name=BrianPreference(True, "some preference"),
221 )
222
223 # Keyword based access
224 assert gp["main.name"]
225 assert gp["main.sub.name2"]
226 assert gp["main.sub_no_pref.sub.name"]
227 gp["main.name"] = False
228 gp["main.sub.name2"] = False
229 gp["main.sub_no_pref.sub.name"] = False
230
231 # Attribute based access
232 assert not gp.main.name # we set it to False above
233 assert not gp.main.sub.name2
234 assert not gp.main.sub_no_pref.sub.name
235 gp.main.name = True
236 gp.main.sub.name2 = True
237 gp.main.sub_no_pref.sub.name = True
238
239 # Mixed access
240 assert gp.main["name"]
241 assert gp["main"].name
242 assert gp.main["sub"].name2
243 assert gp["main"].sub["name2"]
244
245 # Accessing categories
246 assert isinstance(gp["main"], BrianGlobalPreferencesView)
247 assert isinstance(gp["main.sub"], BrianGlobalPreferencesView)
248 assert isinstance(gp.main, BrianGlobalPreferencesView)
249 assert isinstance(gp.main.sub, BrianGlobalPreferencesView)
250
251 # Setting categories shouldn't work
252 with pytest.raises(PreferenceError):
253 gp.__setitem__("main", None)
254 with pytest.raises(PreferenceError):
255 gp.__setattr__("main", None)
256 with pytest.raises(PreferenceError):
257 gp.main.__setitem__("sub", None)
258 with pytest.raises(PreferenceError):
259 gp.main.__setattr__("sub", None)
260
261 # Neither should deleting categories or preferences
262 with pytest.raises(PreferenceError):
263 gp.__delitem__("main")
264 with pytest.raises(PreferenceError):
265 gp.__delattr__("main")
266 with pytest.raises(PreferenceError):
267 gp.main.__delitem__("name")
268 with pytest.raises(PreferenceError):
269 gp.main.__delattr__("name")
270 with pytest.raises(PreferenceError):
271 gp.main.__delitem__("sub")
272 with pytest.raises(PreferenceError):
273 gp.main.__delattr__("sub")
274
275 # Errors for accessing non-existing preferences
276 with pytest.raises(KeyError):
277 gp["main.doesnotexist"]
278 with pytest.raises(KeyError):
279 gp["nonexisting.name"]
280 # Note that it is important to raise AttributeError here, since some tools like
281 # Google Collab check for a `.shape` attribute to display debugging information
282 # for numpy arrays. More generally, a call like `hasattr(gp, "main.doesnotexist")`
283 # would fail with an error instead of returning `False`
284 with pytest.raises(AttributeError):
285 gp.main.doesnotexist
286 with pytest.raises(AttributeError):
287 gp.nonexisting.name
288
289 # Check dictionary functionality
290 for name, value in gp.items():
291 assert gp[name] == value
292
293 for name, value in gp.main.items():
294 assert gp.main[name] == value
295
296 assert len(gp) == 3 # three preferences in total
297 assert len(gp["main"]) == 3 # all preferences are in the main category
298 assert len(gp["main.sub"]) == 1 # one preference in main.sub
299
300 assert "main.name" in gp
301 assert "name" in gp["main"]
302 assert "name2" in gp["main.sub"]
303 assert not "name" in gp["main.sub"]
304
305 gp["main.name"] = True
306 gp.update({"main.name": False})
307 assert not gp["main.name"]
308
309 gp.main.update({"name": True})
310 assert gp["main.name"]
311
312 # Class based functionality
313 assert "main" in dir(gp)
314 assert "sub" in dir(gp.main)
315 assert "name" in dir(gp.main)
316
317 # Check that the fiddling with getattr and setattr did not destroy the
318 # access to standard attributes
319 assert len(gp.prefs)
320 assert gp.main._basename == "main"
321
322 # Check that acessing internal attributes work
323 assert len(gp.prefs.__doc__)
324
325
326 @pytest.mark.codegen_independent
327 def test_str_repr():
328 # Just test whether str and repr do not throw an error and return something
329 gp = BrianGlobalPreferences()
330 gp.register_preferences(
331 "main", "main category", name=BrianPreference(True, "some preference")
332 )
333
334 assert len(str(gp))
335 assert len(repr(gp))
336 assert len(str(gp.main))
337 assert len(repr(gp.main))
338
339
340 if __name__ == "__main__":
341 for t in [
342 test_defaultvalidator,
343 test_brianpreference,
344 test_brianglobalpreferences,
345 test_preference_name_checking,
346 test_preference_name_access,
347 ]:
348 t()
349 restore_initial_state()