Skip to content

Commit

Permalink
Test singledispatch in isolated subprocess
Browse files Browse the repository at this point in the history
  • Loading branch information
deltamarnix committed Oct 8, 2024
1 parent 3797329 commit 12248cb
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 4 deletions.
3 changes: 2 additions & 1 deletion flopy4/singledispatch/plot.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from functools import singledispatch
from typing import Any


@singledispatch
def plot(obj, **kwargs):
def plot(obj, **kwargs) -> Any:
raise NotImplementedError(
"plot method not implemented for type {}".format(type(obj))
)
5 changes: 4 additions & 1 deletion flopy4/singledispatch/plot_int.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from typing import Any

from flopy4.singledispatch.plot import plot


@plot.register
def _(v: int, **kwargs):
def _(v: int, **kwargs) -> Any:
print(f"Plotting a model with kwargs: {kwargs}")
return v
54 changes: 52 additions & 2 deletions test/test_singledispatch.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,62 @@
import ast
import inspect
import subprocess
import sys
from importlib.metadata import entry_points

import pytest

from flopy4.singledispatch.plot import plot


def get_function_body(func):
source = inspect.getsource(func)
parsed = ast.parse(source)
for node in ast.walk(parsed):
if isinstance(node, ast.FunctionDef):
return ast.get_source_segment(source, node.body[0])
raise ValueError("Function body not found")


def run_test_in_subprocess(test_func):
def wrapper():
test_func_source = get_function_body(test_func)
test_code = f"""
import pytest
from importlib.metadata import entry_points
from flopy4.singledispatch.plot import plot
{test_func_source}
"""
result = subprocess.run(
[sys.executable, "-c", test_code], capture_output=True, text=True
)
if result.returncode != 0:
print(result.stdout)
print(result.stderr)
assert result.returncode == 0, f"Test failed: {test_func.__name__}"

return wrapper


@run_test_in_subprocess
def test_register_singledispatch_with_entrypoints():
eps = entry_points(group="flopy4", name="plot")
for ep in eps:
_ = ep.load()
ep.load()

# should not throw an error, because plot_int was loaded via entry points
plot(5)
return_val = plot(5)
assert return_val == 5
with pytest.raises(NotImplementedError):
plot("five")


@run_test_in_subprocess
def test_register_singledispatch_without_entrypoints():
# should throw an error, because plot_int was not loaded via entry points
with pytest.raises(NotImplementedError):
plot(5)
with pytest.raises(NotImplementedError):
plot("five")

0 comments on commit 12248cb

Please sign in to comment.