aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_config_file.py
blob: 6718a94ac6af8f798d6f9d844fcbf4af46b08379 (plain) (blame)
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
import json
from pathlib import Path

import pytest

from config_file.config_file import ConfigFile
from config_file.exceptions import MissingKeyError
from config_file.parsers.abstract_parser import AbstractParser

SUPPORTED_FILE_TYPES = ["ini", "json", "yaml", "toml"]


@pytest.fixture(params=SUPPORTED_FILE_TYPES)
def template_and_config_file(request, template_file):
    def func(template_name: str = "default", parser: AbstractParser = None):
        template = template_file(request.param, template_name)
        return template, ConfigFile(template, parser=parser)

    return func


@pytest.fixture(params=SUPPORTED_FILE_TYPES)
def templated_config_file(template_and_config_file):
    def func(template_name: str = "default", parser: AbstractParser = None):
        return template_and_config_file(template_name, parser)[1]

    return func


def test_that_config_file_is_initialized_correctly(template_and_config_file):
    template_file, config = template_and_config_file()

    assert config.path == template_file
    assert config.stringify() == template_file.read_text()
    assert isinstance(config._ConfigFile__parser, AbstractParser)


def test_that_a_tidle_in_the_config_path_expands_to_the_absolute_path():
    config_name = "temp.ini"
    config_path = "~/" + config_name

    try:
        Path(config_path).expanduser().touch()
        assert ConfigFile(config_path).path == Path.home() / config_name
    finally:
        Path(config_path).expanduser().unlink()


@pytest.mark.skip(msg="needs fixing up")
@pytest.mark.parametrize("path", ["", "invalid", "invalid.conf"])
def test_invalid_path_raises_value_error(path):
    with pytest.raises(ValueError):
        ConfigFile(path)


def test_that_config_file_can_save(template_and_config_file):
    template_file, config = template_and_config_file()

    config.set("header_one.number_key", 25)
    config.save()

    assert config.stringify() == template_file.read_text()


def test_that_config_file_can_restore_the_original(
    templated_config_file, template_original_file
):
    config = templated_config_file()
    original_file = template_original_file(config.path)

    config.set("header_one.number_key", 5)
    config.restore_original()

    assert config.stringify() == original_file.read_text()


def test_missing_config_file_during_restore(templated_config_file):
    config = templated_config_file()

    with pytest.raises(FileNotFoundError) as error:
        config.restore_original()

    assert "file to restore to does not exist" in str(error)


@pytest.mark.parametrize(
    "key, expected_result",
    [
        ("header_one", True),
        ("header_one.number_key", True),
        ("header_one.blah", False),
    ],
)
def test_that_config_file_can_find_sections_and_keys(
    templated_config_file, key, expected_result
):
    config = templated_config_file()
    assert config.has(key) == expected_result


@pytest.mark.parametrize(
    "section_key, value, parse_type, return_type, default, file_name, file_contents",
    [
        (
            "calendar.sunday_index",
            0,
            True,
            None,
            False,
            "config.ini",
            "[calendar]\nsunday_index = 0\n\n",
        ),
        (
            "calendar.sunday_index",
            "0",
            False,
            None,
            False,
            "config.ini",
            "[calendar]\nsunday_index = 0\n\n",
        ),
        (
            "calendar.sunday_index",
            0,
            False,
            None,
            False,
            "config.json",
            json.dumps({"calendar": {"sunday_index": 0}}),
        ),
        (
            "calendar.missing",
            "my default value",
            False,
            None,
            "my default value",
            "config.json",
            json.dumps({"calendar": 5}),
        ),
        (
            "calendar.sunday_index",
            0,
            False,
            int,
            False,
            "config.ini",
            "[calendar]\nsunday_index = 0\n\n",
        ),
    ],
)
def test_that_config_file_can_get(
    tmpdir,
    section_key,
    value,
    return_type,
    parse_type,
    file_name,
    file_contents,
    default,
):
    config_path = tmpdir / file_name
    config_path.write_text(file_contents, encoding="utf-8")
    config = ConfigFile(config_path)

    ret_val = config.get(section_key, parse_types=parse_type, default=default)
    if return_type is not None:
        assert return_type(ret_val) == value
    else:
        assert ret_val == value


@pytest.mark.parametrize(
    "key", ["header_one.number_key", "header_one"]
)
def test_that_config_file_can_delete(templated_config_file, key):
    config = templated_config_file()

    config.delete(key)

    assert config.has(key) is False


@pytest.mark.parametrize(
    "key", ["", 0, False, {}, "header_one.does_not_exist"]
)
def test_that_config_file_raises_missing_key_error_on_invalid_input_or_missing_key(
    templated_config_file, key
):
    config = templated_config_file()

    with pytest.raises(MissingKeyError):
        config.delete(key)


# def test_that_custom_parser_can_be_used(template_and_config_file):
#     class CustomParser(AbstractParser):
#         def __init__(self, file_contents):
#             super().__init__(file_contents)
#
#         def parse(self, file_contents: str):
#             return file_contents
#
#         def get(self, key, parse_types=True):
#             return key
#
#         def set(self, key, value):
#             return key, value
#
#         def delete(self, section_key):
#             return section_key
#
#         def has(self, section_key: str) -> bool:
#             return True
#
#         def stringify(self) -> str:
#             return str(self.parsed_content)
#
#     template_file, config = template_and_config_file(parser=CustomParser)
#
#     assert isinstance(config._ConfigFile__parser, CustomParser)
#     assert config.get("key") == "key"
#     assert config.set("key", "value") == ("key", "value")
#     assert config.delete("section_key") == "section_key"
#     assert config.has("blah")
#     assert config.stringify() == template_file.read_text()