def array(factory, vals): '''Decode string/value as list array :: (a -> Result e b) -> List a -> Result e (List b) >>> from pydecoder.primitives import to_int >>> array(to_int, [1, 2, 3]) Result(status='Ok', value=[1, 2, 3]) >>> array(to_int, None) Result(status='Error', value="'None' isn't list or tuple.") ''' if not isinstance(vals, (list, tuple)): return error(u('\'{}\' isn\'t list or tuple.').format(vals)) result = [] for val in vals: rv = factory(val) if is_error(rv): return rv result.append(value(rv)) return ok(result)
def test_and_then_run_next_decoder(): def dec(val): return ok(val - 1) rv = and_then(dec, to_int, 5) assert is_ok(rv) assert value(rv) == 4
def test_pipe_pass_value_trough_pipeline(): def inc(val): return ok(val + 1) rv = pipe([ inc, inc, inc, ], 1) assert is_ok(rv) assert value(rv) == 4
def test_to_string_returns_ok_result(val): rv = to_string(val) assert is_ok(rv) assert value(rv) == val
def test_to_bool_return_false_in_decoded_result(val): rv = to_bool(val) assert is_ok(rv) assert not value(rv)
def test_to_string_return_decoded_result(): rv = to_string('foo') assert is_ok(rv) assert value(rv) == 'foo'
def test_to_float_return_parsed_result(): rv = to_float('1.5') assert is_ok(rv) assert value(rv) == 1.5
def test_to_int_return_parsed_result(): rv = to_int('10') assert is_ok(rv) assert value(rv) == 10
def test_none_return_none_in_decoded_result(val): rv = null(val) assert is_ok(rv) assert value(rv) is None
def test_dmap_apply_function_to_decoded_val(): rv = dmap(lambda x: x + 1, to_int, '1') assert is_ok(rv) assert value(rv) == 2
def test_optional_return_default_value_in_result_if_value_isnt_found(data): rv = optional('y', ok, 'foo', getter(data)) # pylint: disable=no-value-for-parameter assert is_ok(rv) assert value(rv) == 'foo'
def test_optional_return_decoded_value_in_result(data): rv = optional('field', ok, 'foo', getter(data)) # pylint: disable=no-value-for-parameter assert is_ok(rv) assert equal(value(rv), data['field'])
def test_hardcoded_return_ok_result(): rv = hardcoded(2.5, None) assert is_ok(rv) assert value(rv) == 2.5
def test_required_return_ok_result(data): rv = required('field', ok, getter(data)) # pylint: disable=no-value-for-parameter assert is_ok(rv) assert equal(value(rv), data['field'])