summaryrefslogtreecommitdiff
path: root/mako/testing/helpers.py
blob: 77cca367251663cf525dd75c7fe01f061eac7480 (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
import contextlib
import pathlib
from pathlib import Path
import re
import time
from typing import Union
from unittest import mock


def flatten_result(result):
    return re.sub(r"[\s\r\n]+", " ", result).strip()


def result_lines(result):
    return [
        x.strip()
        for x in re.split(r"\r?\n", re.sub(r" +", " ", result))
        if x.strip() != ""
    ]


def make_path(
    filespec: Union[Path, str],
    make_absolute: bool = True,
    check_exists: bool = False,
) -> Path:
    path = Path(filespec)
    if make_absolute:
        path = path.resolve(strict=check_exists)
    if check_exists and (not path.exists()):
        raise FileNotFoundError(f"No file or directory at {filespec}")
    return path


def _unlink_path(path, missing_ok=False):
    # Replicate 3.8+ functionality in 3.7
    cm = contextlib.nullcontext()
    if missing_ok:
        cm = contextlib.suppress(FileNotFoundError)

    with cm:
        path.unlink()


def replace_file_with_dir(pathspec):
    path = pathlib.Path(pathspec)
    _unlink_path(path, missing_ok=True)
    path.mkdir(exist_ok=True)
    return path


def file_with_template_code(filespec):
    with open(filespec, "w") as f:
        f.write(
            """
i am an artificial template just for you
"""
        )
    return filespec


@contextlib.contextmanager
def rewind_compile_time(hours=1):
    rewound = time.time() - (hours * 3_600)
    with mock.patch("mako.codegen.time") as codegen_time:
        codegen_time.time.return_value = rewound
        yield