Merge branch 'master' into interrupt_exit_code

This commit is contained in:
int3l 2020-09-16 23:39:13 +03:00 committed by GitHub
commit 4ef3f957e3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
39 changed files with 605 additions and 216 deletions

View file

@ -30,6 +30,10 @@ def test_check_type_tag_failures(value):
check_type_tag(value)
def test_check_type_tag_success():
check_type_tag('file')
@pytest.mark.parametrize(
('config_obj', 'expected'), (
(
@ -110,15 +114,18 @@ def test_validate_config_main_ok():
assert not validate_config_main(('.pre-commit-config.yaml',))
def test_validate_config_old_list_format_ok(tmpdir):
def test_validate_config_old_list_format_ok(tmpdir, cap_out):
f = tmpdir.join('cfg.yaml')
f.write('- {repo: meta, hooks: [{id: identity}]}')
assert not validate_config_main((f.strpath,))
start = '[WARNING] normalizing pre-commit configuration to a top-level map'
assert cap_out.get().startswith(start)
def test_validate_warn_on_unknown_keys_at_repo_level(tmpdir, caplog):
f = tmpdir.join('cfg.yaml')
f.write(
'repos:\n'
'- repo: https://gitlab.com/pycqa/flake8\n'
' rev: 3.7.7\n'
' hooks:\n'

View file

@ -1,6 +1,8 @@
import os.path
from unittest import mock
import pytest
import pre_commit.constants as C
from pre_commit.commands.init_templatedir import init_templatedir
from pre_commit.envcontext import envcontext
@ -90,3 +92,49 @@ def test_init_templatedir_hookspath_set(tmpdir, tempdir_factory, store):
C.CONFIG_FILE, store, target, hook_types=['pre-commit'],
)
assert target.join('hooks/pre-commit').exists()
@pytest.mark.parametrize(
('skip', 'commit_retcode', 'commit_output_snippet'),
(
(True, 0, 'Skipping `pre-commit`.'),
(False, 1, f'No {C.CONFIG_FILE} file was found'),
),
)
def test_init_templatedir_skip_on_missing_config(
tmpdir,
tempdir_factory,
store,
cap_out,
skip,
commit_retcode,
commit_output_snippet,
):
target = str(tmpdir.join('tmpl'))
init_git_dir = git_dir(tempdir_factory)
with cwd(init_git_dir):
cmd_output('git', 'config', 'init.templateDir', target)
init_templatedir(
C.CONFIG_FILE,
store,
target,
hook_types=['pre-commit'],
skip_on_missing_config=skip,
)
lines = cap_out.get().splitlines()
assert len(lines) == 1
assert lines[0].startswith('pre-commit installed at')
with envcontext((('GIT_TEMPLATE_DIR', target),)):
verify_git_dir = git_dir(tempdir_factory)
with cwd(verify_git_dir):
retcode, output = git_commit(
fn=cmd_output_mocked_pre_commit_home,
tempdir_factory=tempdir_factory,
retcode=None,
)
assert retcode == commit_retcode
assert commit_output_snippet in output

View file

@ -3,6 +3,8 @@ import re
import sys
from unittest import mock
import re_assert
import pre_commit.constants as C
from pre_commit import git
from pre_commit.commands import install_uninstall
@ -54,8 +56,13 @@ def patch_sys_exe(exe):
def test_shebang_windows():
with patch_platform('win32'), patch_sys_exe('python'):
assert shebang() == '#!/usr/bin/env python'
def test_shebang_windows_drop_ext():
with patch_platform('win32'), patch_sys_exe('python.exe'):
assert shebang() == '#!/usr/bin/env python.exe'
assert shebang() == '#!/usr/bin/env python'
def test_shebang_posix_not_on_path():
@ -143,7 +150,7 @@ FILES_CHANGED = (
)
NORMAL_PRE_COMMIT_RUN = re.compile(
NORMAL_PRE_COMMIT_RUN = re_assert.Matches(
fr'^\[INFO\] Initializing environment for .+\.\n'
fr'Bash hook\.+Passed\n'
fr'\[master [a-f0-9]{{7}}\] commit!\n'
@ -159,7 +166,7 @@ def test_install_pre_commit_and_run(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_install_pre_commit_and_run_custom_path(tempdir_factory, store):
@ -171,7 +178,7 @@ def test_install_pre_commit_and_run_custom_path(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_install_in_submodule_and_run(tempdir_factory, store):
@ -185,7 +192,7 @@ def test_install_in_submodule_and_run(tempdir_factory, store):
assert install(C.CONFIG_FILE, store, hook_types=['pre-commit']) == 0
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_install_in_worktree_and_run(tempdir_factory, store):
@ -198,7 +205,7 @@ def test_install_in_worktree_and_run(tempdir_factory, store):
assert install(C.CONFIG_FILE, store, hook_types=['pre-commit']) == 0
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_commit_am(tempdir_factory, store):
@ -243,7 +250,7 @@ def test_install_idempotent(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def _path_without_us():
@ -297,7 +304,7 @@ def test_environment_not_sourced(tempdir_factory, store):
)
FAILING_PRE_COMMIT_RUN = re.compile(
FAILING_PRE_COMMIT_RUN = re_assert.Matches(
r'^\[INFO\] Initializing environment for .+\.\n'
r'Failing hook\.+Failed\n'
r'- hook id: failing_hook\n'
@ -316,10 +323,10 @@ def test_failing_hooks_returns_nonzero(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 1
assert FAILING_PRE_COMMIT_RUN.match(output)
FAILING_PRE_COMMIT_RUN.assert_matches(output)
EXISTING_COMMIT_RUN = re.compile(
EXISTING_COMMIT_RUN = re_assert.Matches(
fr'^legacy hook\n'
fr'\[master [a-f0-9]{{7}}\] commit!\n'
fr'{FILES_CHANGED}'
@ -342,7 +349,7 @@ def test_install_existing_hooks_no_overwrite(tempdir_factory, store):
# Make sure we installed the "old" hook correctly
ret, output = _get_commit_output(tempdir_factory, touch_file='baz')
assert ret == 0
assert EXISTING_COMMIT_RUN.match(output)
EXISTING_COMMIT_RUN.assert_matches(output)
# Now install pre-commit (no-overwrite)
assert install(C.CONFIG_FILE, store, hook_types=['pre-commit']) == 0
@ -351,7 +358,7 @@ def test_install_existing_hooks_no_overwrite(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert output.startswith('legacy hook\n')
assert NORMAL_PRE_COMMIT_RUN.match(output[len('legacy hook\n'):])
NORMAL_PRE_COMMIT_RUN.assert_matches(output[len('legacy hook\n'):])
def test_legacy_overwriting_legacy_hook(tempdir_factory, store):
@ -377,10 +384,10 @@ def test_install_existing_hook_no_overwrite_idempotent(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert output.startswith('legacy hook\n')
assert NORMAL_PRE_COMMIT_RUN.match(output[len('legacy hook\n'):])
NORMAL_PRE_COMMIT_RUN.assert_matches(output[len('legacy hook\n'):])
FAIL_OLD_HOOK = re.compile(
FAIL_OLD_HOOK = re_assert.Matches(
r'fail!\n'
r'\[INFO\] Initializing environment for .+\.\n'
r'Bash hook\.+Passed\n',
@ -401,7 +408,7 @@ def test_failing_existing_hook_returns_1(tempdir_factory, store):
# We should get a failure from the legacy hook
ret, output = _get_commit_output(tempdir_factory)
assert ret == 1
assert FAIL_OLD_HOOK.match(output)
FAIL_OLD_HOOK.assert_matches(output)
def test_install_overwrite_no_existing_hooks(tempdir_factory, store):
@ -413,7 +420,7 @@ def test_install_overwrite_no_existing_hooks(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_install_overwrite(tempdir_factory, store):
@ -426,7 +433,7 @@ def test_install_overwrite(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_uninstall_restores_legacy_hooks(tempdir_factory, store):
@ -441,7 +448,7 @@ def test_uninstall_restores_legacy_hooks(tempdir_factory, store):
# Make sure we installed the "old" hook correctly
ret, output = _get_commit_output(tempdir_factory, touch_file='baz')
assert ret == 0
assert EXISTING_COMMIT_RUN.match(output)
EXISTING_COMMIT_RUN.assert_matches(output)
def test_replace_old_commit_script(tempdir_factory, store):
@ -463,7 +470,7 @@ def test_replace_old_commit_script(tempdir_factory, store):
ret, output = _get_commit_output(tempdir_factory)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def test_uninstall_doesnt_remove_not_our_hooks(in_git_dir):
@ -476,7 +483,7 @@ def test_uninstall_doesnt_remove_not_our_hooks(in_git_dir):
assert pre_commit.exists()
PRE_INSTALLED = re.compile(
PRE_INSTALLED = re_assert.Matches(
fr'Bash hook\.+Passed\n'
fr'\[master [a-f0-9]{{7}}\] commit!\n'
fr'{FILES_CHANGED}'
@ -493,7 +500,7 @@ def test_installs_hooks_with_hooks_True(tempdir_factory, store):
)
assert ret == 0
assert PRE_INSTALLED.match(output)
PRE_INSTALLED.assert_matches(output)
def test_install_hooks_command(tempdir_factory, store):
@ -506,7 +513,7 @@ def test_install_hooks_command(tempdir_factory, store):
)
assert ret == 0
assert PRE_INSTALLED.match(output)
PRE_INSTALLED.assert_matches(output)
def test_installed_from_venv(tempdir_factory, store):
@ -533,7 +540,7 @@ def test_installed_from_venv(tempdir_factory, store):
},
)
assert ret == 0
assert NORMAL_PRE_COMMIT_RUN.match(output)
NORMAL_PRE_COMMIT_RUN.assert_matches(output)
def _get_push_output(tempdir_factory, remote='origin', opts=()):
@ -880,7 +887,7 @@ def test_prepare_commit_msg_legacy(
def test_pre_merge_commit_integration(tempdir_factory, store):
expected = re.compile(
output_pattern = re_assert.Matches(
r'^\[INFO\] Initializing environment for .+\n'
r'Bash hook\.+Passed\n'
r"Merge made by the 'recursive' strategy.\n"
@ -902,7 +909,7 @@ def test_pre_merge_commit_integration(tempdir_factory, store):
tempdir_factory=tempdir_factory,
)
assert ret == 0
assert expected.match(output)
output_pattern.assert_matches(output)
def test_install_disallow_missing_config(tempdir_factory, store):

View file

@ -939,7 +939,7 @@ def test_classifier_normalizes_filenames_on_windows_to_forward_slashes(tmpdir):
tmpdir.join('a/b/c').ensure()
with mock.patch.object(os, 'altsep', '/'):
with mock.patch.object(os, 'sep', '\\'):
classifier = Classifier((r'a\b\c',))
classifier = Classifier.from_config((r'a\b\c',), '', '^$')
assert classifier.filenames == ['a/b/c']
@ -947,7 +947,7 @@ def test_classifier_does_not_normalize_backslashes_non_windows(tmpdir):
with mock.patch.object(os.path, 'lexists', return_value=True):
with mock.patch.object(os, 'altsep', None):
with mock.patch.object(os, 'sep', '/'):
classifier = Classifier((r'a/b\c',))
classifier = Classifier.from_config((r'a/b\c',), '', '^$')
assert classifier.filenames == [r'a/b\c']

View file

@ -3,6 +3,8 @@ import re
import time
from unittest import mock
import re_assert
from pre_commit import git
from pre_commit.commands.try_repo import try_repo
from pre_commit.util import cmd_output
@ -43,7 +45,7 @@ def test_try_repo_repo_only(cap_out, tempdir_factory):
_run_try_repo(tempdir_factory, verbose=True)
start, config, rest = _get_out(cap_out)
assert start == ''
assert re.match(
config_pattern = re_assert.Matches(
'^repos:\n'
'- repo: .+\n'
' rev: .+\n'
@ -51,8 +53,8 @@ def test_try_repo_repo_only(cap_out, tempdir_factory):
' - id: bash_hook\n'
' - id: bash_hook2\n'
' - id: bash_hook3\n$',
config,
)
config_pattern.assert_matches(config)
assert rest == '''\
Bash hook............................................(no files to check)Skipped
- hook id: bash_hook
@ -71,14 +73,14 @@ def test_try_repo_with_specific_hook(cap_out, tempdir_factory):
_run_try_repo(tempdir_factory, hook='bash_hook', verbose=True)
start, config, rest = _get_out(cap_out)
assert start == ''
assert re.match(
config_pattern = re_assert.Matches(
'^repos:\n'
'- repo: .+\n'
' rev: .+\n'
' hooks:\n'
' - id: bash_hook\n$',
config,
)
config_pattern.assert_matches(config)
assert rest == '''\
Bash hook............................................(no files to check)Skipped
- hook id: bash_hook
@ -128,14 +130,14 @@ def test_try_repo_uncommitted_changes(cap_out, tempdir_factory):
start, config, rest = _get_out(cap_out)
assert start == '[WARNING] Creating temporary repo with uncommitted changes...\n' # noqa: E501
assert re.match(
config_pattern = re_assert.Matches(
'^repos:\n'
'- repo: .+shadow-repo\n'
' rev: .+\n'
' hooks:\n'
' - id: bash_hook\n$',
config,
)
config_pattern.assert_matches(config)
assert rest == 'modified name!...........................................................Passed\n' # noqa: E501

View file

@ -1,13 +1,16 @@
import os.path
import re
import stat
import sys
from unittest import mock
import pytest
import re_assert
from pre_commit import error_handler
from pre_commit.store import Store
from pre_commit.util import CalledProcessError
from testing.util import cmd_output_mocked_pre_commit_home
from testing.util import xfailif_windows
@pytest.fixture
@ -35,7 +38,7 @@ def test_error_handler_fatal_error(mocked_log_and_exit):
1,
)
assert re.match(
pattern = re_assert.Matches(
r'Traceback \(most recent call last\):\n'
r' File ".+pre_commit.error_handler.py", line \d+, in error_handler\n'
r' yield\n'
@ -43,8 +46,8 @@ def test_error_handler_fatal_error(mocked_log_and_exit):
r'in test_error_handler_fatal_error\n'
r' raise exc\n'
r'(pre_commit\.error_handler\.)?FatalError: just a test\n',
mocked_log_and_exit.call_args[0][2],
)
pattern.assert_matches(mocked_log_and_exit.call_args[0][2])
def test_error_handler_uncaught_error(mocked_log_and_exit):
@ -59,7 +62,7 @@ def test_error_handler_uncaught_error(mocked_log_and_exit):
mock.ANY,
3,
)
assert re.match(
pattern = re_assert.Matches(
r'Traceback \(most recent call last\):\n'
r' File ".+pre_commit.error_handler.py", line \d+, in error_handler\n'
r' yield\n'
@ -67,8 +70,8 @@ def test_error_handler_uncaught_error(mocked_log_and_exit):
r'in test_error_handler_uncaught_error\n'
r' raise exc\n'
r'ValueError: another test\n',
mocked_log_and_exit.call_args[0][2],
)
pattern.assert_matches(mocked_log_and_exit.call_args[0][2])
def test_error_handler_keyboardinterrupt(mocked_log_and_exit):
@ -83,7 +86,7 @@ def test_error_handler_keyboardinterrupt(mocked_log_and_exit):
mock.ANY,
130,
)
assert re.match(
pattern = re_assert.Matches(
r'Traceback \(most recent call last\):\n'
r' File ".+pre_commit.error_handler.py", line \d+, in error_handler\n'
r' yield\n'
@ -91,11 +94,17 @@ def test_error_handler_keyboardinterrupt(mocked_log_and_exit):
r'in test_error_handler_keyboardinterrupt\n'
r' raise exc\n'
r'KeyboardInterrupt\n',
mocked_log_and_exit.call_args[0][2],
)
pattern.assert_matches(mocked_log_and_exit.call_args[0][2])
def test_log_and_exit(cap_out, mock_store_dir):
tb = (
'Traceback (most recent call last):\n'
' File "<stdin>", line 2, in <module>\n'
'pre_commit.error_handler.FatalError: hai\n'
)
with pytest.raises(SystemExit):
error_handler._log_and_exit(
'msg', 1, error_handler.FatalError('hai'), "I'm a stacktrace",
@ -108,7 +117,7 @@ def test_log_and_exit(cap_out, mock_store_dir):
assert os.path.exists(log_file)
with open(log_file) as f:
logged = f.read()
expected = (
pattern = re_assert.Matches(
r'^### version information\n'
r'\n'
r'```\n'
@ -127,10 +136,12 @@ def test_log_and_exit(cap_out, mock_store_dir):
r'```\n'
r'\n'
r'```\n'
r"I'm a stacktrace\n"
r'```\n'
r'Traceback \(most recent call last\):\n'
r' File "<stdin>", line 2, in <module>\n'
r'pre_commit\.error_handler\.FatalError: hai\n'
r'```\n',
)
assert re.match(expected, logged)
pattern.assert_matches(logged)
def test_error_handler_non_ascii_exception(mock_store_dir):
@ -171,3 +182,29 @@ def test_error_handler_no_tty(tempdir_factory):
out_lines = out.splitlines()
assert out_lines[-2] == 'An unexpected error has occurred: ValueError: ☃'
assert out_lines[-1] == f'Check the log at {log_file}'
@xfailif_windows # pragma: win32 no cover
def test_error_handler_read_only_filesystem(mock_store_dir, cap_out, capsys):
# a better scenario would be if even the Store crash would be handled
# but realistically we're only targetting systems where the Store has
# already been set up
Store()
write = (stat.S_IWGRP | stat.S_IWOTH | stat.S_IWUSR)
os.chmod(mock_store_dir, os.stat(mock_store_dir).st_mode & ~write)
with pytest.raises(SystemExit):
with error_handler.error_handler():
raise ValueError('ohai')
output = cap_out.get()
assert output.startswith(
'An unexpected error has occurred: ValueError: ohai\n'
'Failed to write to log at ',
)
# our cap_out mock is imperfect so the rest of the output goes to capsys
out, _ = capsys.readouterr()
# the things that normally go to the log file will end up here
assert '### version information' in out

View file

@ -186,3 +186,8 @@ def test_no_git_env():
'GIT_SSH': '/usr/bin/ssh',
'GIT_SSH_COMMAND': 'ssh -o',
}
def test_init_repo_no_hooks(tmpdir):
git.init_repo(str(tmpdir), remote='dne')
assert not tmpdir.join('.git/hooks').exists()

View file

@ -1,15 +1,6 @@
from unittest import mock
from pre_commit.languages import docker
from pre_commit.util import CalledProcessError
def test_docker_is_running_process_error():
with mock.patch(
'pre_commit.languages.docker.cmd_output_b',
side_effect=CalledProcessError(1, (), 0, b'', None),
):
assert docker.docker_is_running() is False
def test_docker_fallback_user():

View file

@ -1,14 +1,19 @@
import os
import shutil
import sys
from unittest import mock
import pytest
import pre_commit.constants as C
from pre_commit import envcontext
from pre_commit import parse_shebang
from pre_commit.languages.node import get_default_version
from pre_commit.languages import node
from pre_commit.prefix import Prefix
from testing.util import xfailif_windows
ACTUAL_GET_DEFAULT_VERSION = get_default_version.__wrapped__
ACTUAL_GET_DEFAULT_VERSION = node.get_default_version.__wrapped__
@pytest.fixture
@ -45,3 +50,31 @@ def test_uses_default_when_node_and_npm_are_not_available(find_exe_mck):
def test_sets_default_on_windows(find_exe_mck):
find_exe_mck.return_value = '/path/to/exe'
assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT
@xfailif_windows # pragma: win32 no cover
def test_healthy_system_node(tmpdir):
tmpdir.join('package.json').write('{"name": "t", "version": "1.0.0"}')
prefix = Prefix(str(tmpdir))
node.install_environment(prefix, 'system', ())
assert node.healthy(prefix, 'system')
@xfailif_windows # pragma: win32 no cover
def test_unhealthy_if_system_node_goes_missing(tmpdir):
bin_dir = tmpdir.join('bin').ensure_dir()
node_bin = bin_dir.join('node')
node_bin.mksymlinkto(shutil.which('node'))
prefix_dir = tmpdir.join('prefix').ensure_dir()
prefix_dir.join('package.json').write('{"name": "t", "version": "1.0.0"}')
path = ('PATH', (str(bin_dir), os.pathsep, envcontext.Var('PATH')))
with envcontext.envcontext((path,)):
prefix = Prefix(str(prefix_dir))
node.install_environment(prefix, 'system', ())
assert node.healthy(prefix, 'system')
node_bin.remove()
assert not node.healthy(prefix, 'system')

View file

@ -8,6 +8,7 @@ import pre_commit.constants as C
from pre_commit.envcontext import envcontext
from pre_commit.languages import python
from pre_commit.prefix import Prefix
from pre_commit.util import make_executable
def test_read_pyvenv_cfg(tmpdir):
@ -141,3 +142,26 @@ def test_unhealthy_old_virtualenv(python_dir):
os.remove(prefix.path('py_env-default/pyvenv.cfg'))
assert python.healthy(prefix, C.DEFAULT) is False
def test_unhealthy_then_replaced(python_dir):
prefix, tmpdir = python_dir
python.install_environment(prefix, C.DEFAULT, ())
# simulate an exe which returns an old version
exe_name = 'python.exe' if sys.platform == 'win32' else 'python'
py_exe = prefix.path(python.bin_dir('py_env-default'), exe_name)
os.rename(py_exe, f'{py_exe}.tmp')
with open(py_exe, 'w') as f:
f.write('#!/usr/bin/env bash\necho 1.2.3\n')
make_executable(py_exe)
# should be unhealthy due to version mismatch
assert python.healthy(prefix, C.DEFAULT) is False
# now put the exe back and it should be healthy again
os.replace(f'{py_exe}.tmp', py_exe)
assert python.healthy(prefix, C.DEFAULT) is True

View file

@ -1,15 +1,39 @@
import os.path
from unittest import mock
import pytest
import pre_commit.constants as C
from pre_commit import parse_shebang
from pre_commit.languages import ruby
from pre_commit.prefix import Prefix
from pre_commit.util import cmd_output
from testing.util import xfailif_windows_no_ruby
from testing.util import xfailif_windows
@xfailif_windows_no_ruby
ACTUAL_GET_DEFAULT_VERSION = ruby.get_default_version.__wrapped__
@pytest.fixture
def find_exe_mck():
with mock.patch.object(parse_shebang, 'find_executable') as mck:
yield mck
def test_uses_default_version_when_not_available(find_exe_mck):
find_exe_mck.return_value = None
assert ACTUAL_GET_DEFAULT_VERSION() == C.DEFAULT
def test_uses_system_if_both_gem_and_ruby_are_available(find_exe_mck):
find_exe_mck.return_value = '/path/to/exe'
assert ACTUAL_GET_DEFAULT_VERSION() == 'system'
@xfailif_windows # pragma: win32 no cover
def test_install_rbenv(tempdir_factory):
prefix = Prefix(tempdir_factory.get())
ruby._install_rbenv(prefix)
ruby._install_rbenv(prefix, C.DEFAULT)
# Should have created rbenv directory
assert os.path.exists(prefix.path('rbenv-default'))
@ -18,7 +42,7 @@ def test_install_rbenv(tempdir_factory):
cmd_output('rbenv', '--help')
@xfailif_windows_no_ruby
@xfailif_windows # pragma: win32 no cover
def test_install_rbenv_with_version(tempdir_factory):
prefix = Prefix(tempdir_factory.get())
ruby._install_rbenv(prefix, version='1.9.3p547')

View file

@ -159,7 +159,28 @@ def test_try_repo(mock_store_dir):
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(

View file

@ -1,5 +1,4 @@
import os.path
import re
import shutil
import sys
from typing import Any
@ -8,6 +7,7 @@ from unittest import mock
import cfgv
import pytest
import re_assert
import pre_commit.constants as C
from pre_commit.clientlib import CONFIG_SCHEMA
@ -34,7 +34,6 @@ from testing.util import get_resource_path
from testing.util import skipif_cant_run_docker
from testing.util import skipif_cant_run_swift
from testing.util import xfailif_windows
from testing.util import xfailif_windows_no_ruby
def _norm_out(b):
@ -235,6 +234,7 @@ def test_run_a_docker_image_hook(tempdir_factory, store, hook_id):
)
@xfailif_windows # pragma: win32 no cover
def test_run_a_node_hook(tempdir_factory, store):
_test_hook_repo(
tempdir_factory, store, 'node_hooks_repo',
@ -260,7 +260,14 @@ def test_run_versioned_node_hook(tempdir_factory, store):
)
@xfailif_windows_no_ruby
@xfailif_windows # pragma: win32 no cover
def test_node_hook_with_npm_userconfig_set(tempdir_factory, store, tmpdir):
cfg = tmpdir.join('cfg')
cfg.write('cache=/dne\n')
with mock.patch.dict(os.environ, NPM_CONFIG_USERCONFIG=str(cfg)):
test_run_a_node_hook(tempdir_factory, store)
def test_run_a_ruby_hook(tempdir_factory, store):
_test_hook_repo(
tempdir_factory, store, 'ruby_hooks_repo',
@ -268,7 +275,7 @@ def test_run_a_ruby_hook(tempdir_factory, store):
)
@xfailif_windows_no_ruby
@xfailif_windows # pragma: win32 no cover
def test_run_versioned_ruby_hook(tempdir_factory, store):
_test_hook_repo(
tempdir_factory, store, 'ruby_versioned_hooks_repo',
@ -278,7 +285,7 @@ def test_run_versioned_ruby_hook(tempdir_factory, store):
)
@xfailif_windows_no_ruby
@xfailif_windows # pragma: win32 no cover
def test_run_ruby_hook_with_disable_shared_gems(
tempdir_factory,
store,
@ -524,7 +531,6 @@ def test_additional_dependencies_roll_forward(tempdir_factory, store):
assert 'mccabe' not in cmd_output('pip', 'freeze', '-l')[1]
@xfailif_windows_no_ruby # pragma: win32 no cover
def test_additional_ruby_dependencies_installed(tempdir_factory, store):
path = make_repo(tempdir_factory, 'ruby_hooks_repo')
config = make_config_from_repo(path)
@ -837,12 +843,12 @@ def test_too_new_version(tempdir_factory, store, fake_log_handler):
with pytest.raises(SystemExit):
_get_hook(config, store, 'bash_hook')
msg = fake_log_handler.handle.call_args[0][0].msg
assert re.match(
pattern = re_assert.Matches(
r'^The hook `bash_hook` requires pre-commit version 999\.0\.0 but '
r'version \d+\.\d+\.\d+ is installed. '
r'Perhaps run `pip install --upgrade pre-commit`\.$',
msg,
)
pattern.assert_matches(msg)
@pytest.mark.parametrize('version', ('0.1.0', C.VERSION))

View file

@ -1,5 +1,6 @@
import os.path
import sqlite3
import stat
from unittest import mock
import pytest
@ -12,6 +13,7 @@ from pre_commit.util import cmd_output
from testing.fixtures import git_dir
from testing.util import cwd
from testing.util import git_commit
from testing.util import xfailif_windows
def test_our_session_fixture_works():
@ -217,3 +219,27 @@ def test_select_all_configs_roll_forward(store):
def test_mark_config_as_used_roll_forward(store, tmpdir):
_simulate_pre_1_14_0(store)
test_mark_config_as_used(store, tmpdir)
@xfailif_windows # pragma: win32 no cover
def test_mark_config_as_used_readonly(tmpdir):
cfg = tmpdir.join('f').ensure()
store_dir = tmpdir.join('store')
# make a store, then we'll convert its directory to be readonly
assert not Store(str(store_dir)).readonly # directory didn't exist
assert not Store(str(store_dir)).readonly # directory did exist
def _chmod_minus_w(p):
st = os.stat(p)
os.chmod(p, st.st_mode & ~(stat.S_IWUSR | stat.S_IWOTH | stat.S_IWGRP))
_chmod_minus_w(store_dir)
for fname in os.listdir(store_dir):
assert not os.path.isdir(fname)
_chmod_minus_w(os.path.join(store_dir, fname))
store = Store(str(store_dir))
assert store.readonly
# should be skipped due to readonly
store.mark_config_used(str(cfg))
assert store.select_all_configs() == []