blob: e4bd07ca75c2ca4e5e4356a1ab3c561154ad9bbf [file] [log] [blame]
Anthony Sottile8f615292022-01-15 19:24:05 -05001from __future__ import annotations
2
Ville Skyttä391ae302021-01-08 17:36:55 +02003import os
4
5import pytest
6
7from pre_commit_hooks.check_shebang_scripts_are_executable import \
8 _check_git_filemode
9from pre_commit_hooks.check_shebang_scripts_are_executable import main
10from pre_commit_hooks.util import cmd_output
11
12
13def test_check_git_filemode_passing(tmpdir):
14 with tmpdir.as_cwd():
15 cmd_output('git', 'init', '.')
16
17 f = tmpdir.join('f')
18 f.write('#!/usr/bin/env bash')
19 f_path = str(f)
20 cmd_output('chmod', '+x', f_path)
21 cmd_output('git', 'add', f_path)
22 cmd_output('git', 'update-index', '--chmod=+x', f_path)
23
24 g = tmpdir.join('g').ensure()
25 g_path = str(g)
26 cmd_output('git', 'add', g_path)
27
28 files = [f_path, g_path]
29 assert _check_git_filemode(files) == 0
30
31 # this is the one we should trigger on
32 h = tmpdir.join('h')
33 h.write('#!/usr/bin/env bash')
34 h_path = str(h)
35 cmd_output('git', 'add', h_path)
36
37 files = [h_path]
38 assert _check_git_filemode(files) == 1
39
40
41def test_check_git_filemode_passing_unusual_characters(tmpdir):
42 with tmpdir.as_cwd():
43 cmd_output('git', 'init', '.')
44
45 f = tmpdir.join('mañana.txt')
46 f.write('#!/usr/bin/env bash')
47 f_path = str(f)
48 cmd_output('chmod', '+x', f_path)
49 cmd_output('git', 'add', f_path)
50 cmd_output('git', 'update-index', '--chmod=+x', f_path)
51
52 files = (f_path,)
53 assert _check_git_filemode(files) == 0
54
55
56def test_check_git_filemode_failing(tmpdir):
57 with tmpdir.as_cwd():
58 cmd_output('git', 'init', '.')
59
60 f = tmpdir.join('f').ensure()
61 f.write('#!/usr/bin/env bash')
62 f_path = str(f)
63 cmd_output('git', 'add', f_path)
64
65 files = (f_path,)
66 assert _check_git_filemode(files) == 1
67
68
69@pytest.mark.parametrize(
70 ('content', 'mode', 'expected'),
71 (
72 pytest.param('#!python', '+x', 0, id='shebang with executable'),
73 pytest.param('#!python', '-x', 1, id='shebang without executable'),
74 pytest.param('', '+x', 0, id='no shebang with executable'),
75 pytest.param('', '-x', 0, id='no shebang without executable'),
76 ),
77)
78def test_git_executable_shebang(temp_git_dir, content, mode, expected):
79 with temp_git_dir.as_cwd():
80 path = temp_git_dir.join('path')
81 path.write(content)
82 cmd_output('git', 'add', str(path))
83 cmd_output('chmod', mode, str(path))
84 cmd_output('git', 'update-index', f'--chmod={mode}', str(path))
85
86 # simulate how identify chooses that something is executable
87 filenames = [path for path in [str(path)] if os.access(path, os.X_OK)]
88
89 assert main(filenames) == expected