Skip to content

Commit 22bac3d

Browse files
authored
Use context managers to change *ns* in tests (#228)
1 parent 664e540 commit 22bac3d

File tree

7 files changed

+113
-79
lines changed

7 files changed

+113
-79
lines changed

src/basilisp/cli.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,13 @@ def run(file_or_code, code, in_ns):
9999
"""Run a Basilisp script or a line of code, if it is provided."""
100100
basilisp.init()
101101
ctx = compiler.CompilerContext()
102-
ns_var = runtime.set_current_ns(in_ns)
103-
ns: runtime.Namespace = ns_var.value
104102
eof = object()
105103

106-
if code:
107-
print(compiler.lrepr(eval_str(file_or_code, ctx, ns.module, eof)))
108-
else:
109-
print(compiler.lrepr(eval_file(file_or_code, ctx, ns.module)))
104+
with runtime.ns_bindings(in_ns) as ns:
105+
if code:
106+
print(compiler.lrepr(eval_str(file_or_code, ctx, ns.module, eof)))
107+
else:
108+
print(compiler.lrepr(eval_file(file_or_code, ctx, ns.module)))
110109

111110

112111
@cli.command(short_help='run tests in a Basilisp project')

src/basilisp/lang/runtime.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import functools
23
import importlib
34
import itertools
@@ -755,6 +756,37 @@ def set_current_ns(ns_name: str,
755756
return ns_var
756757

757758

759+
@contextlib.contextmanager
760+
def ns_bindings(ns_name: str,
761+
module: types.ModuleType = None,
762+
ns_var_name: str = _NS_VAR_NAME,
763+
ns_var_ns: str = _NS_VAR_NS):
764+
"""Context manager for temporarily changing the value of basilisp.core/*ns*."""
765+
symbol = sym.Symbol(ns_name)
766+
ns = Namespace.get_or_create(symbol, module=module)
767+
ns_var = Maybe(Var.find(sym.Symbol(ns_var_name, ns=ns_var_ns))) \
768+
.or_else_raise(lambda: RuntimeException(f"Dynamic Var {sym.Symbol(ns_var_name, ns=ns_var_ns)} not bound!"))
769+
770+
try:
771+
ns_var.push_bindings(ns)
772+
yield ns_var.value
773+
finally:
774+
ns_var.pop_bindings()
775+
776+
777+
@contextlib.contextmanager
778+
def remove_ns_bindings(ns_var_name: str = _NS_VAR_NAME,
779+
ns_var_ns: str = _NS_VAR_NS):
780+
"""Context manager to pop the most recent bindings for basilisp.core/*ns* after
781+
completion of the code under management."""
782+
ns_var = Maybe(Var.find(sym.Symbol(ns_var_name, ns=ns_var_ns))) \
783+
.or_else_raise(lambda: RuntimeException(f"Dynamic Var {sym.Symbol(ns_var_name, ns=ns_var_ns)} not bound!"))
784+
try:
785+
yield
786+
finally:
787+
ns_var.pop_bindings()
788+
789+
758790
def get_current_ns(ns_var_name: str = _NS_VAR_NAME,
759791
ns_var_ns: str = _NS_VAR_NS) -> Namespace:
760792
"""Get the value of the dynamic variable `*ns*` in the current thread."""

0 commit comments

Comments
 (0)