File: test_loader.py

package info (click to toggle)
python-pyfunceble 4.2.29.dev-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,108 kB
  • sloc: python: 27,413; sh: 142; makefile: 27
file content (637 lines) | stat: -rw-r--r-- 20,855 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
"""
The tool to check the availability or syntax of domain, IP or URL.

::


    ██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
    ██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
    ██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
    ██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
    ██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
    ╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Tests of our configuration loader.

Author:
    Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks:
    https://pyfunceble.github.io/special-thanks.html

Contributors:
    https://pyfunceble.github.io/contributors.html

Project link:
    https://github.com/funilrys/PyFunceble

Project documentation:
    https://docs.pyfunceble.com

Project homepage:
    https://pyfunceble.github.io/

License:
::


    Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024 Nissar Chababy

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import copy
import os
import tempfile
import unittest

import yaml
from box import Box

from PyFunceble.config.loader import ConfigLoader

try:
    import pyf_test_dataset
except ModuleNotFoundError:  # pragma: no cover
    from .. import pyf_test_dataset

import PyFunceble.storage


class TestConfigLoader(unittest.TestCase):
    """
    Provides the test of our configuration loader.
    """

    def setUp(self) -> None:
        """
        Setups everything needed by the tests.
        """

        self.our_config = Box(copy.deepcopy(pyf_test_dataset.DEFAULT_CONFIG))

        self.default_config_file = tempfile.NamedTemporaryFile(delete=False)
        self.overwrite_config_file = tempfile.NamedTemporaryFile(delete=False)
        self.config_file = tempfile.NamedTemporaryFile(delete=False)

        self.merge_upstream = False

        self.config_loader = ConfigLoader()

        self.config_loader.merge_upstream = self.merge_upstream
        self.config_loader.path_to_default_config = self.default_config_file.name
        self.config_loader.path_to_overwrite_config = self.overwrite_config_file.name
        self.config_loader.path_to_config = self.config_file.name

    def tearDown(self) -> None:
        """
        Destroys everything initiated by the tests.
        """

        self.config_file.close()
        self.default_config_file.close()
        self.overwrite_config_file.close()

        os.unlink(self.config_file.name)
        os.unlink(self.default_config_file.name)
        os.unlink(self.overwrite_config_file.name)

        del self.our_config
        del self.default_config_file
        del self.config_file
        del self.merge_upstream
        del self.config_loader

    def test_is_already_loader(self) -> None:
        """
        Tests the method which let us know if the configuration was already
        loaded.
        """

        PyFunceble.storage.CONFIGURATION = self.our_config

        expected = True
        actual = self.config_loader.is_already_loaded()

        self.assertEqual(expected, actual)

    def test_is_not_already_loaded(self) -> None:
        """
        Tests the method which let us know if the configuration was already
        loaded for the case that it was not loaded yet.
        """

        expected = False
        actual = self.config_loader.is_already_loaded()

        self.assertEqual(expected, actual)

    def test_set_custom_config(self) -> None:
        """
        Tests the method which let us set the custom configuration to work with.
        """

        given = {"hello": "world"}
        expected = {"hello": "world"}

        self.config_loader.custom_config = given
        actual = self.config_loader.custom_config

        self.assertEqual(expected, actual)

    def test_set_custom_config_config_already_loaded(self) -> None:
        """
        Tests the method which let us set the custom configuration to work with.

        In this case, we want the loader to reload (itself). So we basically
        tests that the reload occurs.
        """

        self.default_config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.default_config_file.seek(0)

        self.config_file.write(yaml.dump(self.our_config).encode())
        self.config_file.seek(0)

        PyFunceble.storage.CONFIGURATION = self.our_config

        given = {"hello": "world"}
        expected = {"hello": "world"}

        self.config_loader.custom_config = given
        actual = self.config_loader.custom_config

        self.assertEqual(expected, actual)

        expected = "world"
        actual = PyFunceble.storage.CONFIGURATION["hello"]

        self.assertEqual(expected, actual)

    def test_set_custom_config_config_already_loaded_merging_active(self) -> None:
        """
        Tests the method which let us set the custom configuration to work with.

        In this case, we want the loader to reload (itself). So we basically
        tests that the reload occurs. And that nothing has changed if the
        merging is authorized
        """

        self.default_config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.default_config_file.seek(0)

        self.config_file.write(yaml.dump(self.our_config).encode())
        self.config_file.seek(0)

        self.config_loader.merge_upstream = True

        PyFunceble.storage.CONFIGURATION = copy.deepcopy(self.our_config)
        PyFunceble.storage.CONFIGURATION["cli_testing"]["display_mode"]["dots"] = True

        given = {"hello": "world"}
        expected = {"hello": "world"}

        self.config_loader.custom_config = given
        actual = self.config_loader.custom_config

        self.assertEqual(expected, actual)

        expected = "world"
        actual = PyFunceble.storage.CONFIGURATION["hello"]

        self.assertEqual(expected, actual)

        self.config_file.seek(0)

        expected = copy.deepcopy(self.our_config.to_dict())
        actual = yaml.safe_load(self.config_file)

        self.assertEqual(expected, actual)

    def test_set_custom_config_not_dict(self) -> None:
        """
        Tests the method which let us set the custom configuration to work with
        for the case that the given custom configuration is not a
        :py:class:`dict`.
        """

        given = "Hello, World!"

        self.assertRaises(
            TypeError, lambda: self.config_loader.set_custom_config(given)
        )

    def test_set_custom_config_previously_given(self) -> None:
        """
        Tests the method which let us set the custom configuration to work with
        for the case that the given custom configuration is not a
        :py:class:`dict`.
        """

        given = {"Hello": "World!"}
        given2 = {"World!": "Hello"}

        self.config_loader.set_custom_config(given)
        self.config_loader.set_custom_config(given2)

        expected = {"Hello": "World!", "World!": "Hello"}
        actual = self.config_loader.custom_config

        self.assertEqual(expected, actual)

    def test_set_merge_upstream(self) -> None:
        """
        Tests the method which let us authorize the merging of upstream inside
        the local one.
        """

        given = True
        expected = True

        self.config_loader.merge_upstream = given

        actual = self.config_loader.merge_upstream

        self.assertEqual(expected, actual)

    def test_set_merge_upstream_return(self) -> None:
        """
        Tests the method which let us authorize the merging of upstream inside
        the local one.

        In this case, we just want to be sure that the response is correct.
        """

        given = True

        actual = self.config_loader.set_merge_upstream(given)

        self.assertIsInstance(actual, ConfigLoader)

    def test_set_merge_upstream_not_bool(self) -> None:
        """
        Tests the method which let us authorize the merging of upstream inside
        the local one for the case that the given value is not a boolean.
        """

        given = "Hello, World!"

        self.assertRaises(
            TypeError,
            lambda: self.config_loader.set_merge_upstream(given),
        )

    def test_get_config_file_content(self) -> None:
        """
        Tests the method which let us get the content of the configuration file.
        """

        self.config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.config_file.seek(0)

        expected = self.our_config.to_dict()

        actual = self.config_loader.get_config_file_content()

        self.assertEqual(expected, actual)

    def test_get_config_file_content_yaml_issue(self) -> None:
        """
        Tests the method which let us get the content of the configuration file.

        This case try to reproduce the issue we met because of my inattention.
        """

        self.default_config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.default_config_file.seek(0)

        self.config_file.write(yaml.dump(self.our_config).encode())
        self.config_file.seek(0)

        expected = self.our_config.to_dict()

        actual = self.config_loader.get_config_file_content()

        self.assertEqual(expected, actual)

    def test_get_config_file_already_exists(self) -> None:
        """
        Tests the method which let us get the content of the configuration file
        for the case that the configuration was already loaded.
        """

        self.config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.config_file.seek(0)

        PyFunceble.storage.CONFIGURATION = Box({"hello": "world"})

        expected = self.our_config.to_dict()
        actual = self.config_loader.get_config_file_content()

        self.assertEqual(expected, actual)

    def test_get_config_file_but_empty(self) -> None:
        """
        Tests the method which let us get the content of the configuration file
        for the case it is empty.
        """

        self.default_config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.default_config_file.seek(0)

        self.config_file.write("".encode())
        self.config_file.seek(0)

        expected = self.our_config
        actual = self.config_loader.get_config_file_content()

        self.assertEqual(expected, actual)

    def test_get_configured_value_not_loaded(self) -> None:
        """
        Tests the method which let us get the configured value.

        In this test, we check for the case that configuration is not
        loaded yet.
        """

        given = "cli_testing.display_mode.colour"

        self.assertRaises(
            RuntimeError, lambda: self.config_loader.get_configured_value(given)
        )

    def test_get_configured_value_not_found(self) -> None:
        """
        Tests the method which let us get the configured value.

        In this test, we check for the case that the wanted index does not
        exists.
        """

        PyFunceble.storage.CONFIGURATION = self.our_config

        given = "hello_world_hello"

        self.assertRaises(
            ValueError, lambda: self.config_loader.get_configured_value(given)
        )

    def test_get_configured_value(self) -> None:
        """
        Tests the method which let us get the configured value.

        In this test, we check for the case that configuration is not
        loaded yet.
        """

        self.config_loader.set_custom_config(self.our_config).start()

        given = "cli_testing.testing_mode.syntax"
        actual = self.config_loader.get_configured_value(given)

        self.assertIsInstance(actual, bool)

    def test_start_and_destroy(self) -> None:
        """
        Tests the methods which loads, put everything together and destroy
        the configuration.
        """

        self.config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.config_file.seek(0)

        given_custom = {"this_is_a_custom": "test"}
        self.config_loader.set_custom_config(given_custom)

        response = self.config_loader.start()

        self.assertIsInstance(response, ConfigLoader)

        expected_with_custom = dict(
            copy.deepcopy(self.our_config.to_dict()), **given_custom
        )
        self.assertEqual(
            expected_with_custom,
            PyFunceble.storage.CONFIGURATION,
        )

        expected_indexes = ["http_codes", "links"]

        for index in expected_indexes:
            # Tests if correctly stored.
            expected = copy.deepcopy(self.our_config[index])
            actual = getattr(PyFunceble.storage, index.upper())

            self.assertEqual(expected, actual)

        response = self.config_loader.destroy()

        self.assertIsInstance(response, ConfigLoader)

        expected_custom = dict()  # pylint: disable=use-dict-literal
        actual = self.config_loader.custom_config

        self.assertEqual(expected_custom, actual)

        expected_indexes = ["http_codes", "links"]
        expected = dict()  # pylint: disable=use-dict-literal

        for index in expected_indexes:
            actual = getattr(PyFunceble.storage, index.upper())

            self.assertEqual(expected, actual)

    def test_conditional_switch_autocontinue_ci_active(self) -> None:
        """
        Tests the method which let us switch some of our values based on
        some assumption.

        In this test, we check the the autocontinue is getting activated if we
        are under CI.
        """

        given = copy.deepcopy(self.our_config)
        given["cli_testing"]["ci"]["active"] = True
        given["cli_testing"]["autocontinue"] = False

        expected = copy.deepcopy(given)
        expected["cli_testing"]["autocontinue"] = True

        actual = self.config_loader.conditional_switch(given)

        self.assertEqual(expected, actual)

    def test_conditional_switch_autocontinue_ci_not_active(self) -> None:
        """
        Tests the method which let us switch some of our values based on
        some assumption.

        In this test, we check the the autocontinue is getting activated if we
        are under CI.
        """

        given = copy.deepcopy(self.our_config)
        given["cli_testing"]["ci"]["active"] = False
        given["cli_testing"]["autocontinue"] = False

        expected = copy.deepcopy(given)

        actual = self.config_loader.conditional_switch(given)

        self.assertEqual(expected, actual)

    def test_conditional_switch_lookup_timeout_less_than_zero(self) -> None:
        """
        Tests the method which let us switch some of our values based on
        some assumption.

        In this test, we check the the lookup timeout is getting switched to 5
        when the given value is lower than 0.
        """

        given = copy.deepcopy(self.our_config)
        given["lookup"]["timeout"] = -1.34

        expected = copy.deepcopy(given)
        expected["lookup"]["timeout"] = 5

        actual = self.config_loader.conditional_switch(given)

        self.assertEqual(expected, actual)

    def test_conditional_switch_platform_testing_mode(self) -> None:
        """
        Tests the method which let us switch some of our values based on
        some assumption.

        In this test, we check that no files is being generated if we
        are under such testing mode.
        """

        given = copy.deepcopy(self.our_config)
        given["cli_testing"]["testing_mode"]["platform_contribution"] = True
        given["cli_testing"]["file_generation"]["no_file"] = False
        given["cli_testing"]["display_mode"]["dots"] = False
        given["cli_testing"]["autocontinue"] = True
        given["cli_testing"]["inactive_db"] = True
        given["cli_testing"]["mining"] = True
        given["cli_testing"]["local_network"] = True
        given["cli_testing"]["preload_file"] = True
        given["cli_testing"]["display_mode"]["percentage"] = True

        expected = copy.deepcopy(given)
        expected["cli_testing"]["file_generation"]["no_file"] = True
        expected["cli_testing"]["file_generation"]["no_file"] = True
        expected["cli_testing"]["display_mode"]["dots"] = True
        expected["cli_testing"]["autocontinue"] = False
        expected["cli_testing"]["inactive_db"] = False
        expected["cli_testing"]["mining"] = False
        expected["cli_testing"]["local_network"] = False
        expected["cli_testing"]["preload_file"] = False
        expected["cli_testing"]["display_mode"]["percentage"] = False

        actual = self.config_loader.conditional_switch(given)

        self.assertEqual(expected, actual)

    def test_overwite_file_found(self) -> None:
        """
        Tests the loading of the configuration file for the case the an
        overwrite file is given.
        """

        given = {"Hello": "World!"}

        self.overwrite_config_file.write(yaml.dump(given).encode())
        self.overwrite_config_file.seek(0)

        self.config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.config_file.seek(0)

        response = self.config_loader.start()

        self.assertIsInstance(response, ConfigLoader)

        expected_with_overwrite = dict(
            copy.deepcopy(self.our_config.to_dict()), **given
        )
        self.assertEqual(
            expected_with_overwrite,
            PyFunceble.storage.CONFIGURATION,
        )

        self.assertTrue("Hello" in PyFunceble.storage.CONFIGURATION)

    def test_overwite_file_found_but_empty(self) -> None:
        """
        Tests the loading of the configuration file for the case the an
        overwrite file is given but is empty.
        """

        given = {}

        self.overwrite_config_file.write(yaml.dump(given).encode())
        self.overwrite_config_file.seek(0)

        self.config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.config_file.seek(0)

        response = self.config_loader.start()

        self.assertIsInstance(response, ConfigLoader)

        expected = self.our_config.to_dict()

        self.assertEqual(
            expected,
            PyFunceble.storage.CONFIGURATION,
        )

    def test_overwite_file_found_but_overwrote_by_custom(self) -> None:
        """
        Tests the loading of the configuration file for the case the an
        overwrite file is given, but the custom configuration is also given.

        When the custom configuration is given, it overwrites everything,
        including the overwrites file.
        """

        given = {"Hello": "World"}

        self.overwrite_config_file.write(yaml.dump(given).encode())
        self.overwrite_config_file.seek(0)

        given_custom = {"Hello": "Funilrys!"}
        self.config_loader.set_custom_config(given_custom)

        self.config_file.write(yaml.dump(self.our_config.to_dict()).encode())
        self.config_file.seek(0)

        response = self.config_loader.start()

        self.assertIsInstance(response, ConfigLoader)

        expected_with_custom = dict(
            copy.deepcopy(self.our_config.to_dict()), **given_custom
        )
        self.assertEqual(
            expected_with_custom,
            PyFunceble.storage.CONFIGURATION,
        )

        self.assertTrue(PyFunceble.storage.CONFIGURATION["Hello"] == "Funilrys!")


if __name__ == "__main__":
    unittest.main()