summaryrefslogtreecommitdiffstats
path: root/tests/main_test.py
blob: 6738df683d7c409cb18a5523b46a8923cf898662 (plain)
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
import argparse
import os.path
from unittest import mock

import pytest

import pre_commit.constants as C
from pre_commit import main
from pre_commit.errors import FatalError
from testing.auto_namedtuple import auto_namedtuple


@pytest.mark.parametrize(
    ('argv', 'expected'),
    (
        ((), ['f']),
        (('--f', 'x'), ['x']),
        (('--f', 'x', '--f', 'y'), ['x', 'y']),
    ),
)
def test_append_replace_default(argv, expected):
    parser = argparse.ArgumentParser()
    parser.add_argument('--f', action=main.AppendReplaceDefault, default=['f'])
    assert parser.parse_args(argv).f == expected


def _args(**kwargs):
    kwargs.setdefault('command', 'help')
    kwargs.setdefault('config', C.CONFIG_FILE)
    return argparse.Namespace(**kwargs)


def test_adjust_args_and_chdir_not_in_git_dir(in_tmpdir):
    with pytest.raises(FatalError):
        main._adjust_args_and_chdir(_args())


def test_adjust_args_and_chdir_in_dot_git_dir(in_git_dir):
    with in_git_dir.join('.git').as_cwd(), pytest.raises(FatalError):
        main._adjust_args_and_chdir(_args())


def test_adjust_args_and_chdir_noop(in_git_dir):
    args = _args(command='run', files=['f1', 'f2'])
    main._adjust_args_and_chdir(args)
    assert os.getcwd() == in_git_dir
    assert args.config == C.CONFIG_FILE
    assert args.files == ['f1', 'f2']


def test_adjust_args_and_chdir_relative_things(in_git_dir):
    in_git_dir.join('foo/cfg.yaml').ensure()
    in_git_dir.join('foo').chdir()

    args = _args(command='run', files=['f1', 'f2'], config='cfg.yaml')
    main._adjust_args_and_chdir(args)
    assert os.getcwd() == in_git_dir
    assert args.config == os.path.join('foo', 'cfg.yaml')
    assert args.files == [os.path.join('foo', 'f1'), os.path.join('foo', 'f2')]


def test_adjust_args_and_chdir_non_relative_config(in_git_dir):
    in_git_dir.join('foo').ensure_dir().chdir()

    args = _args()
    main._adjust_args_and_chdir(args)
    assert os.getcwd() == in_git_dir
    assert args.config == C.CONFIG_FILE


def test_adjust_args_try_repo_repo_relative(in_git_dir):
    in_git_dir.join('foo').ensure_dir().chdir()

    args = _args(command='try-repo', repo='../foo', files=[])
    assert args.repo is not None
    assert os.path.exists(args.repo)
    main._adjust_args_and_chdir(args)
    assert os.getcwd() == in_git_dir
    assert os.path.exists(args.repo)
    assert args.repo == 'foo'


FNS = (
    'autoupdate', 'clean', 'gc', 'hook_impl', 'install', 'install_hooks',
    'migrate_config', 'run', 'sample_config', 'uninstall',
)
CMDS = tuple(fn.replace('_', '-') for fn in FNS)


@pytest.fixture
def mock_commands():
    mcks = {fn: mock.patch.object(main, fn).start() for fn in FNS}
    ret = auto_namedtuple(**mcks)
    yield ret
    for mck in ret:
        mck.stop()


@pytest.fixture
def argparse_parse_args_spy():
    parse_args_mock = mock.Mock()

    original_parse_args = argparse.ArgumentParser.parse_args

    def fake_parse_args(self, args):
        # call our spy object
        parse_args_mock(args)
        return original_parse_args(self, args)

    with mock.patch.object(
        argparse.ArgumentParser, 'parse_args', fake_parse_args,
    ):
        yield parse_args_mock


def assert_only_one_mock_called(mock_objs):
    total_call_count = sum(mock_obj.call_count for mock_obj in mock_objs)
    assert total_call_count == 1


def test_overall_help(mock_commands):
    with pytest.raises(SystemExit):
        main.main(['--help'])


def test_help_command(mock_commands, argparse_parse_args_spy):
    with pytest.raises(SystemExit):
        main.main(['help'])

    argparse_parse_args_spy.assert_has_calls([
        mock.call(['help']),
        mock.call(['--help']),
    ])


def test_help_other_command(mock_commands, argparse_parse_args_spy):
    with pytest.raises(SystemExit):
        main.main(['help', 'run'])

    argparse_parse_args_spy.assert_has_calls([
        mock.call(['help', 'run']),
        mock.call(['run', '--help']),
    ])


@pytest.mark.parametrize('command', CMDS)
def test_all_cmds(command, mock_commands, mock_store_dir):
    main.main((command,))
    assert getattr(mock_commands, command.replace('-', '_')).call_count == 1
    assert_only_one_mock_called(mock_commands)


def test_try_repo(mock_store_dir):
    with mock.patch.object(main, 'try_repo') as patch:
        main.main(('try-repo', '.'))
    assert patch.call_count == 1


def test_init_templatedir(mock_store_dir):
    with mock.patch.object(main, 'init_templatedir') as patch:
        main.main(('init-templatedir', 'tdir'))

    assert patch.call_count == 1
    assert 'tdir' in patch.call_args[0]
    assert patch.call_args[1]['hook_types'] == ['pre-commit']
    assert patch.call_args[1]['skip_on_missing_config'] is True


def test_init_templatedir_options(mock_store_dir):
    args = (
        'init-templatedir',
        'tdir',
        '--hook-type',
        'commit-msg',
        '--no-allow-missing-config',
    )
    with mock.patch.object(main, 'init_templatedir') as patch:
        main.main(args)

    assert patch.call_count == 1
    assert 'tdir' in patch.call_args[0]
    assert patch.call_args[1]['hook_types'] == ['commit-msg']
    assert patch.call_args[1]['skip_on_missing_config'] is False


def test_help_cmd_in_empty_directory(
        in_tmpdir,
        mock_commands,
        argparse_parse_args_spy,
):
    with pytest.raises(SystemExit):
        main.main(['help', 'run'])

    argparse_parse_args_spy.assert_has_calls([
        mock.call(['help', 'run']),
        mock.call(['run', '--help']),
    ])


def test_expected_fatal_error_no_git_repo(in_tmpdir, cap_out, mock_store_dir):
    with pytest.raises(SystemExit):
        main.main([])
    log_file = os.path.join(mock_store_dir, 'pre-commit.log')
    cap_out_lines = cap_out.get().splitlines()
    assert (
        cap_out_lines[-2] ==
        'An error has occurred: FatalError: git failed. '
        'Is it installed, and are you in a Git repository directory?'
    )
    assert cap_out_lines[-1] == f'Check the log at {log_file}'