cookiecutter

Форк
0
/
test_get_user_config.py 
167 строк · 5.7 Кб
1
"""Tests to verify correct work with user configs and system/user variables inside."""
2

3
import os
4
import shutil
5

6
import pytest
7

8
from cookiecutter import config
9
from cookiecutter.exceptions import InvalidConfiguration
10

11

12
@pytest.fixture(scope='module')
13
def user_config_path():
14
    """Fixture. Return user config path for current user."""
15
    return os.path.expanduser('~/.cookiecutterrc')
16

17

18
@pytest.fixture(scope='function')
19
def back_up_rc(user_config_path):
20
    """
21
    Back up an existing cookiecutter rc and restore it after the test.
22

23
    If ~/.cookiecutterrc is pre-existing, move it to a temp location
24
    """
25
    user_config_path_backup = os.path.expanduser('~/.cookiecutterrc.backup')
26

27
    if os.path.exists(user_config_path):
28
        shutil.copy(user_config_path, user_config_path_backup)
29
        os.remove(user_config_path)
30

31
    yield
32
    # Remove the ~/.cookiecutterrc that has been created in the test.
33
    if os.path.exists(user_config_path):
34
        os.remove(user_config_path)
35

36
    # If it existed, restore the original ~/.cookiecutterrc.
37
    if os.path.exists(user_config_path_backup):
38
        shutil.copy(user_config_path_backup, user_config_path)
39
        os.remove(user_config_path_backup)
40

41

42
@pytest.fixture
43
def custom_config():
44
    """Fixture. Return expected custom configuration for future tests validation."""
45
    return {
46
        'default_context': {
47
            'full_name': 'Firstname Lastname',
48
            'email': 'firstname.lastname@gmail.com',
49
            'github_username': 'example',
50
            'project': {
51
                'description': 'description',
52
                'tags': [
53
                    'first',
54
                    'second',
55
                    'third',
56
                ],
57
            },
58
        },
59
        'cookiecutters_dir': '/home/example/some-path-to-templates',
60
        'replay_dir': '/home/example/some-path-to-replay-files',
61
        'abbreviations': {
62
            'gh': 'https://github.com/{0}.git',
63
            'gl': 'https://gitlab.com/{0}.git',
64
            'bb': 'https://bitbucket.org/{0}',
65
            'helloworld': 'https://github.com/hackebrot/helloworld',
66
        },
67
    }
68

69

70
@pytest.mark.usefixtures('back_up_rc')
71
def test_get_user_config_valid(user_config_path, custom_config) -> None:
72
    """Validate user config correctly parsed if exist and correctly formatted."""
73
    shutil.copy('tests/test-config/valid-config.yaml', user_config_path)
74
    conf = config.get_user_config()
75

76
    assert conf == custom_config
77

78

79
@pytest.mark.usefixtures('back_up_rc')
80
def test_get_user_config_invalid(user_config_path) -> None:
81
    """Validate `InvalidConfiguration` raised when provided user config malformed."""
82
    shutil.copy('tests/test-config/invalid-config.yaml', user_config_path)
83
    with pytest.raises(InvalidConfiguration):
84
        config.get_user_config()
85

86

87
@pytest.mark.usefixtures('back_up_rc')
88
def test_get_user_config_nonexistent() -> None:
89
    """Validate default app config returned, if user does not have own config."""
90
    assert config.get_user_config() == config.DEFAULT_CONFIG
91

92

93
@pytest.fixture
94
def custom_config_path() -> str:
95
    """Fixture. Return path to custom user config for tests."""
96
    return 'tests/test-config/valid-config.yaml'
97

98

99
def test_specify_config_path(mocker, custom_config_path, custom_config) -> None:
100
    """Validate provided custom config path should be respected and parsed."""
101
    spy_get_config = mocker.spy(config, 'get_config')
102

103
    user_config = config.get_user_config(custom_config_path)
104
    spy_get_config.assert_called_once_with(custom_config_path)
105

106
    assert user_config == custom_config
107

108

109
def test_default_config_path(user_config_path) -> None:
110
    """Validate app configuration. User config path should match default path."""
111
    assert user_config_path == config.USER_CONFIG_PATH
112

113

114
def test_default_config_from_env_variable(
115
    monkeypatch, custom_config_path, custom_config
116
) -> None:
117
    """Validate app configuration. User config path should be parsed from sys env."""
118
    monkeypatch.setenv('COOKIECUTTER_CONFIG', custom_config_path)
119

120
    user_config = config.get_user_config()
121
    assert user_config == custom_config
122

123

124
def test_force_default_config(mocker, custom_config_path) -> None:
125
    """Validate `default_config=True` should ignore provided custom user config."""
126
    spy_get_config = mocker.spy(config, 'get_config')
127

128
    user_config = config.get_user_config(custom_config_path, default_config=True)
129

130
    assert user_config == config.DEFAULT_CONFIG
131
    assert not spy_get_config.called
132

133

134
def test_expand_user_for_directories_in_config(monkeypatch) -> None:
135
    """Validate user pointers expanded in user configs."""
136

137
    def _expanduser(path):
138
        return path.replace('~', 'Users/bob')
139

140
    monkeypatch.setattr('os.path.expanduser', _expanduser)
141

142
    config_file = 'tests/test-config/config-expand-user.yaml'
143

144
    user_config = config.get_user_config(config_file)
145
    assert user_config['replay_dir'] == 'Users/bob/replay-files'
146
    assert user_config['cookiecutters_dir'] == 'Users/bob/templates'
147

148

149
def test_expand_vars_for_directories_in_config(monkeypatch) -> None:
150
    """Validate environment variables expanded in user configs."""
151
    monkeypatch.setenv('COOKIES', 'Users/bob/cookies')
152

153
    config_file = 'tests/test-config/config-expand-vars.yaml'
154

155
    user_config = config.get_user_config(config_file)
156
    assert user_config['replay_dir'] == 'Users/bob/cookies/replay-files'
157
    assert user_config['cookiecutters_dir'] == 'Users/bob/cookies/templates'
158

159

160
def test_specify_config_values() -> None:
161
    """Validate provided custom config values should be respected."""
162
    replay_dir = 'Users/bob/cookies/custom-replay-dir'
163
    custom_config_updated = {**config.DEFAULT_CONFIG, 'replay_dir': replay_dir}
164

165
    user_config = config.get_user_config(default_config={'replay_dir': replay_dir})
166

167
    assert user_config == custom_config_updated
168

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.