# HG changeset patch # User Aurélien Campéas # Date 1684319355 -7200 # Wed May 17 12:29:15 2023 +0200 # Node ID 0bcde104d20bd49feba387a9085fbea66c748c0d # Parent 4eedfca364188a4af32fa60c6545783c72f1d7cf io/boolean: add a boolean input type for convenience diff --git a/rework/io.py b/rework/io.py --- a/rework/io.py +++ b/rework/io.py @@ -69,6 +69,27 @@ return float(val) +class boolean(_iobase): + + def from_string(self, args): + return self.binary_decode(args) + + def binary_encode(self, args): + val = self.val(args) + if val is not None: + if not isinstance(val, (int, bool)): + raise TypeError( + f'value `{repr(val)}` is not a boolean' + ) + return str(val).encode('utf-8') + + def binary_decode(self, args): + val = args.get(self.name) + if val is None: + return + return True if val.lower() in (b'true', 'true') else False + + class string(_iobase): def from_string(self, args): diff --git a/tests/test_api.py b/tests/test_api.py --- a/tests/test_api.py +++ b/tests/test_api.py @@ -58,6 +58,7 @@ io.file('myfile.txt', required=True), io.number('weight'), io.datetime('birthdate'), + io.boolean('happy'), io.moment('sometime'), io.string('name'), io.string('option', choices=('foo', 'bar')), @@ -106,6 +107,7 @@ {'choices': None, 'name': 'myfile.txt', 'required': True, 'type': 'file'}, {'choices': None, 'name': 'weight', 'required': False, 'type': 'number'}, {'choices': None, 'name': 'birthdate', 'required': False, 'type': 'datetime'}, + {'choices': None, 'name': 'happy', 'required': False, 'type': 'boolean'}, {'choices': None, 'name': 'sometime', 'required': False, 'type': 'moment'}, {'choices': None, 'name': 'name', 'required': False, 'type': 'string'}, {'choices': ['foo', 'bar'], 'name': 'option', 'required': False, 'type': 'string'}, @@ -172,6 +174,7 @@ 'name': 'Babar', 'weight': 65, 'birthdate': dt(1973, 5, 20, 9), + 'happy': True, 'sometime': '(date "1973-5-20")', 'option': 'foo' } @@ -180,6 +183,7 @@ 'myfile.txt': b'some file', 'weight': 65, 'birthdate': dt(1973, 5, 20, 9, 0), + 'happy': True, 'sometime': dt(1973, 5, 20, 0, 0), 'name': 'Babar', 'option': 'foo' @@ -214,12 +218,14 @@ 'name': 'Babar', 'weight': 65, 'birthdate': '1973-5-20', + 'happy': True, 'sometime': '(date "1973-5-20")', 'option': 'foo' } t = api.schedule(engine, 'yummy', args2) assert t.input == { 'birthdate': dt(1973, 5, 20, 0, 0), + 'happy': True, 'sometime': dt(1973, 5, 20, 0, 0), 'myfile.txt': b'some file', 'name': 'Babar',