blob: 39c474a10fa85212c19b7665348381c29ed8f464 [file] [log] [blame]
Anthony Sottile8f615292022-01-15 19:24:05 -05001from __future__ import annotations
2
Mikhail Khvoinitsky1e87d592020-08-02 21:25:07 +03003import os
4import subprocess
5
6import pytest
7
8from pre_commit_hooks.destroyed_symlinks import find_destroyed_symlinks
9from pre_commit_hooks.destroyed_symlinks import main
Mikhail Khvoinitsky10c5e4e2021-06-23 03:10:13 +030010from testing.util import git_commit
Mikhail Khvoinitsky1e87d592020-08-02 21:25:07 +030011
12TEST_SYMLINK = 'test_symlink'
13TEST_SYMLINK_TARGET = '/doesnt/really/matters'
14TEST_FILE = 'test_file'
15TEST_FILE_RENAMED = f'{TEST_FILE}_renamed'
16
17
18@pytest.fixture
19def repo_with_destroyed_symlink(tmpdir):
20 source_repo = tmpdir.join('src')
21 os.makedirs(source_repo, exist_ok=True)
22 test_repo = tmpdir.join('test')
23 with source_repo.as_cwd():
24 subprocess.check_call(('git', 'init'))
25 os.symlink(TEST_SYMLINK_TARGET, TEST_SYMLINK)
26 with open(TEST_FILE, 'w') as f:
27 print('some random content', file=f)
28 subprocess.check_call(('git', 'add', '.'))
Mikhail Khvoinitsky10c5e4e2021-06-23 03:10:13 +030029 git_commit('-m', 'initial')
Mikhail Khvoinitsky1e87d592020-08-02 21:25:07 +030030 assert b'120000 ' in subprocess.check_output(
31 ('git', 'cat-file', '-p', 'HEAD^{tree}'),
32 )
33 subprocess.check_call(
34 ('git', '-c', 'core.symlinks=false', 'clone', source_repo, test_repo),
35 )
36 with test_repo.as_cwd():
37 subprocess.check_call(
38 ('git', 'config', '--local', 'core.symlinks', 'true'),
39 )
40 subprocess.check_call(('git', 'mv', TEST_FILE, TEST_FILE_RENAMED))
41 assert not os.path.islink(test_repo.join(TEST_SYMLINK))
42 yield test_repo
43
44
45def test_find_destroyed_symlinks(repo_with_destroyed_symlink):
46 with repo_with_destroyed_symlink.as_cwd():
47 assert find_destroyed_symlinks([]) == []
48 assert main([]) == 0
49
50 subprocess.check_call(('git', 'add', TEST_SYMLINK))
51 assert find_destroyed_symlinks([TEST_SYMLINK]) == [TEST_SYMLINK]
52 assert find_destroyed_symlinks([]) == []
53 assert main([]) == 0
54 assert find_destroyed_symlinks([TEST_FILE_RENAMED, TEST_FILE]) == []
55 ALL_STAGED = [TEST_SYMLINK, TEST_FILE_RENAMED]
56 assert find_destroyed_symlinks(ALL_STAGED) == [TEST_SYMLINK]
57 assert main(ALL_STAGED) != 0
58
59 with open(TEST_SYMLINK, 'a') as f:
60 print(file=f) # add trailing newline
61 subprocess.check_call(['git', 'add', TEST_SYMLINK])
62 assert find_destroyed_symlinks(ALL_STAGED) == [TEST_SYMLINK]
63 assert main(ALL_STAGED) != 0
64
65 with open(TEST_SYMLINK, 'w') as f:
66 print('0' * len(TEST_SYMLINK_TARGET), file=f)
67 subprocess.check_call(('git', 'add', TEST_SYMLINK))
68 assert find_destroyed_symlinks(ALL_STAGED) == []
69 assert main(ALL_STAGED) == 0
70
71 with open(TEST_SYMLINK, 'w') as f:
72 print('0' * (len(TEST_SYMLINK_TARGET) + 3), file=f)
73 subprocess.check_call(('git', 'add', TEST_SYMLINK))
74 assert find_destroyed_symlinks(ALL_STAGED) == []
75 assert main(ALL_STAGED) == 0