aboutsummaryrefslogtreecommitdiff
path: root/hooks/tests/conftest.py
blob: 72c7920466aa02608a5399f6cd33c518c8c6df29 (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
"""Pytest harness for the hook scripts under hooks/.

Hook filenames are hyphenated (git-commit-confirm.py, etc.), so they
cannot be imported by module name. `load_hook(filename)` loads them by
path via importlib, and inserts hooks/ onto sys.path first so each hook's
own `from _common import ...` resolves.
"""

import importlib.util
import sys
from pathlib import Path

import pytest

HOOKS_DIR = Path(__file__).resolve().parent.parent


def load_hook(filename: str):
    """Load a hook script by filename and return its module object.

    Inserts hooks/ onto sys.path (idempotently) so the hook's
    `from _common import ...` works, then loads the file by path under a
    sanitized module name.
    """
    hooks_dir = str(HOOKS_DIR)
    if hooks_dir not in sys.path:
        sys.path.insert(0, hooks_dir)

    path = HOOKS_DIR / filename
    mod_name = "hook_" + filename.replace("-", "_").replace(".py", "")
    spec = importlib.util.spec_from_file_location(mod_name, path)
    if spec is None or spec.loader is None:
        raise ImportError(f"could not load hook from {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


@pytest.fixture
def load_hook_fixture():
    return load_hook