Skip to content

Commit 7f6dc9d

Browse files
authored
better error message when missing or not a model object (#22)
1 parent c5acced commit 7f6dc9d

File tree

3 files changed

+20
-12
lines changed

3 files changed

+20
-12
lines changed

doc/whats_new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ Bug fixes
1111

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

1517
v0.1.0 (8 October 2017)
1618
-----------------------

xsimlab/tests/test_xr_accessor.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import numpy as np
44

55
from xsimlab import xr_accessor, create_setup
6+
from xsimlab.xr_accessor import _maybe_get_model_from_context
67

78

89
def test_filter_accessor():
@@ -297,10 +298,6 @@ def test_run_multi(self):
297298

298299

299300
def test_create_setup(model, input_dataset):
300-
with pytest.raises(TypeError) as excinfo:
301-
create_setup()
302-
assert "No context on context stack" in str(excinfo.value)
303-
304301
expected = xr.Dataset()
305302
actual = create_setup(model=model)
306303
xr.testing.assert_identical(actual, expected)
@@ -327,12 +324,14 @@ def test_create_setup(model, input_dataset):
327324
xr.testing.assert_identical(ds, input_dataset)
328325

329326

330-
def test_model_context(model):
327+
def test_get_model_from_context(model):
331328
with pytest.raises(TypeError) as excinfo:
332-
create_setup()
333-
assert "No context on context stack" in str(excinfo.value)
329+
_maybe_get_model_from_context(None)
330+
assert "no model found in context" in str(excinfo.value)
334331

335-
expected = xr.Dataset()
336-
with model:
337-
actual = create_setup(model=model)
338-
xr.testing.assert_identical(actual, expected)
332+
with model as m:
333+
assert _maybe_get_model_from_context(None) is m
334+
335+
with pytest.raises(TypeError) as excinfo:
336+
_maybe_get_model_from_context('not a model')
337+
assert "is not an instance of xsimlab.Model" in str(excinfo.value)

xsimlab/xr_accessor.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,14 @@ def _maybe_get_model_from_context(model):
3131
none supplied.
3232
"""
3333
if model is None:
34-
return Model.get_context()
34+
try:
35+
return Model.get_context()
36+
except TypeError:
37+
raise TypeError("no model found in context")
38+
39+
if not isinstance(model, Model):
40+
raise TypeError("%s is not an instance of xsimlab.Model" % model)
41+
3542
return model
3643

3744

0 commit comments

Comments
 (0)