Skip to content

Commit

Permalink
document run_in_file and improve tests
Browse files Browse the repository at this point in the history
  • Loading branch information
luto committed Jul 16, 2024
1 parent a1fd088 commit 7b54dd6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
15 changes: 10 additions & 5 deletions src/shellinspector/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,15 @@ class ShellinspectorPyContext:
env: dict


def run_in_file(filename, si_context, code):
source = Path(filename).read_bytes()
node = ast.parse(source, filename)
def run_in_file(filename: Path, si_context: dict, code: str):
"""
Load the python code within `filename` and run the given python code within.
Additionally, set all values in si_context as global variables. The code
within `code` must be a single function call. Its return value will be
returned by this function.
"""
with open(filename) as f:
node = ast.parse(f.read(), filename)

call_ast = ast.parse(code)

Expand All @@ -56,14 +62,13 @@ def run_in_file(filename, si_context, code):
)

node.body.append(call)

ast.fix_missing_locations(node)
obj = compile(node, filename=filename, mode="exec")

globalz = {
"context": si_context,
}

obj = compile(node, filename=filename, mode="exec")
exec(obj, globalz, globalz)

return globalz["_return_value"]
Expand Down
7 changes: 7 additions & 0 deletions tests/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from shellinspector.runner import LocalShell
from shellinspector.runner import RemoteShell
from shellinspector.runner import RunnerEvent
from shellinspector.runner import ShellinspectorPyContext
from shellinspector.runner import ShellRunner
from shellinspector.runner import disable_color
from shellinspector.runner import get_localshell
Expand Down Expand Up @@ -659,6 +660,12 @@ def fake_run_in_file(filename, si_context, code):
), event

assert run_in_file.call_count == 1
assert run_in_file.call_args[0][0] == Path("virtual.ispec.py")
context = run_in_file.call_args[0][1]
assert isinstance(context, ShellinspectorPyContext)
assert isinstance(context.applied_example, dict)
assert context.env["HOME"] == "/root"
assert run_in_file.call_args[0][2] == "return_true()"


def test_runner_python_fail(mocker, make_runner, ssh_config):
Expand Down

0 comments on commit 7b54dd6

Please sign in to comment.