Skip to content

Commit

Permalink
better error message when missing or not a model object (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
benbovy committed Nov 20, 2017
1 parent c5acced commit 7f6dc9d
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 12 deletions.
2 changes: 2 additions & 0 deletions doc/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ Bug fixes

- Fix misinterpreted tuples passed as ``allowed_dims`` argument of
``Variable`` init (:issue:`17`).
- Better error message when a Model instance is expected but no object
is found or a different object is provided (:issue:`13`).

v0.1.0 (8 October 2017)
-----------------------
Expand Down
21 changes: 10 additions & 11 deletions xsimlab/tests/test_xr_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import numpy as np

from xsimlab import xr_accessor, create_setup
from xsimlab.xr_accessor import _maybe_get_model_from_context


def test_filter_accessor():
Expand Down Expand Up @@ -297,10 +298,6 @@ def test_run_multi(self):


def test_create_setup(model, input_dataset):
with pytest.raises(TypeError) as excinfo:
create_setup()
assert "No context on context stack" in str(excinfo.value)

expected = xr.Dataset()
actual = create_setup(model=model)
xr.testing.assert_identical(actual, expected)
Expand All @@ -327,12 +324,14 @@ def test_create_setup(model, input_dataset):
xr.testing.assert_identical(ds, input_dataset)


def test_model_context(model):
def test_get_model_from_context(model):
with pytest.raises(TypeError) as excinfo:
create_setup()
assert "No context on context stack" in str(excinfo.value)
_maybe_get_model_from_context(None)
assert "no model found in context" in str(excinfo.value)

expected = xr.Dataset()
with model:
actual = create_setup(model=model)
xr.testing.assert_identical(actual, expected)
with model as m:
assert _maybe_get_model_from_context(None) is m

with pytest.raises(TypeError) as excinfo:
_maybe_get_model_from_context('not a model')
assert "is not an instance of xsimlab.Model" in str(excinfo.value)
9 changes: 8 additions & 1 deletion xsimlab/xr_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@ def _maybe_get_model_from_context(model):
none supplied.
"""
if model is None:
return Model.get_context()
try:
return Model.get_context()
except TypeError:
raise TypeError("no model found in context")

if not isinstance(model, Model):
raise TypeError("%s is not an instance of xsimlab.Model" % model)

return model


Expand Down

0 comments on commit 7f6dc9d

Please sign in to comment.