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
This commit is contained in:
Saugat Pachhai
2021-09-15 22:01:10 +03:00
committed by GitHub
parent e049c4bab1
commit 198cdeec06
3 changed files with 52 additions and 8 deletions
+36
View File
@@ -0,0 +1,36 @@
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}"