diff --git a/python/sunbeam/__init__.py b/python/sunbeam/__init__.py index 7c00eea4e..29fc9729b 100644 --- a/python/sunbeam/__init__.py +++ b/python/sunbeam/__init__.py @@ -1,4 +1,5 @@ from .sunbeam import parse +from .libsunbeam import action __version__ = '0.0.1' __license__ = 'GNU General Public License version 3' diff --git a/python/sunbeam/sunbeam.cpp b/python/sunbeam/sunbeam.cpp index a8c29c21f..0fe2f0f5d 100644 --- a/python/sunbeam/sunbeam.cpp +++ b/python/sunbeam/sunbeam.cpp @@ -15,6 +15,14 @@ py::class_< EclipseState >( "EclipseState", py::no_init ) .add_property( "title", &EclipseState::getTitle ) ; +void (ParseContext::*ctx_update)(const std::string&, InputError::Action) = &ParseContext::update; py::class_< ParseContext >( "ParseContext" ) + .def( "update", ctx_update ) + ; + +py::enum_< InputError::Action >( "action" ) + .value( "throw", InputError::Action::THROW_EXCEPTION ) + .value( "warn", InputError::Action::WARN ) + .value( "ignore", InputError::Action::IGNORE ) ; } diff --git a/python/sunbeam/sunbeam.py b/python/sunbeam/sunbeam.py index c41a4177f..20e5b86db 100644 --- a/python/sunbeam/sunbeam.py +++ b/python/sunbeam/sunbeam.py @@ -3,5 +3,27 @@ import libsunbeam as lib class EclipseState(lib.EclipseState): pass -def parse(path): - return lib.parse(path, lib.ParseContext()) +def _parse_context(actions): + ctx = lib.ParseContext() + + if actions is None: + return ctx + + # this might be a single tuple, in which case we unpack it and repack it + # into a list. If it's not a tuple we assume it's an iterable and just + # carry on + try: + key, action = actions + except ValueError: + pass + else: + actions = [(key, action)] + + for key, action in actions: + ctx.update(key, action) + + return ctx + + +def parse(path, actions = None): + return lib.parse(path, _parse_context(actions)) diff --git a/tests/parse.py b/tests/parse.py index fa471f47d..951fca57e 100644 --- a/tests/parse.py +++ b/tests/parse.py @@ -12,3 +12,25 @@ class TestParse(unittest.TestCase): def testParse(self): spe3 = sunbeam.parse(self.spe3) self.assertEqual('SPE 3 - CASE 1', spe3.title) + + def testParseWithAction(self): + action = ("PARSE_RANDOM_SLASH", sunbeam.action.ignore) + spe3 = sunbeam.parse(self.spe3, action) + self.assertEqual('SPE 3 - CASE 1', spe3.title) + + def testParseWithMultipleActions(self): + actions = [ ("PARSE_RANDOM_SLASH", sunbeam.action.ignore), + ("FOO", sunbeam.action.warn), + ("PARSE_RANDOM_TEXT", sunbeam.action.throw) ] + + spe3 = sunbeam.parse(self.spe3, actions) + self.assertEqual('SPE 3 - CASE 1', spe3.title) + + def testThrowOnInvalidAction(self): + actions = [ ("PARSE_RANDOM_SLASH", 3.14 ) ] + + with self.assertRaises(TypeError): + sunbeam.parse(self.spe3, actions) + + with self.assertRaises(ValueError): + sunbeam.parse(self.spe3, "PARSE_RANDOM_SLASH")