Files
dvc/tests/utils/scriptify.py
T
Saugat Pachhai 198cdeec06 tests: scriptify function into module (#6619)
so that we can write tests having larger side-effects than
the run_copy that we use as a hack
2021-09-15 22:01:10 +03:00

37 lines
749 B
Python

import inspect
import sys
import textwrap
from pathlib import Path
SCRIPT_TEMPLATE = """\
#! {executable}
# AUTOGENERATED USING SCRIPTIFY FOR USE IN TESTS FOR DVC
{code}
if __name__ == "__main__":
import sys
_, *argv = sys.argv
func = {func!s}
func(*argv)
"""
def scriptify(func, path=None):
# you can use `breakpoint()` inside functions too
# just remember to run the test in `-s` mode.
code = textwrap.dedent(inspect.getsource(func))
executable = sys.executable
source = SCRIPT_TEMPLATE.format(
executable=executable, code=code, func=func.__name__
)
if not path:
return source, None
Path(path).write_text(source, encoding="utf-8")
return source, f"{executable} {path}"