def test_converter_type(): """ Test parser converter type. """ def converter_to_int(val): """ Converts value to integer """ try: return int(val) except (ValueError, TypeError): return 0 checker = parsing.ConverterType( str, converter_function=lambda val: 'String of %s' % val) checker.validate('a string') checker.validate(10) checker.validate(True) checker.validate(None) checker.validate(-2.5) assert checker.update(10) == 'String of 10' assert checker.update(False) == 'String of False' assert checker.update('string') == 'String of string' checker = parsing.ConverterType(int, converter_function=converter_to_int) checker.validate(10) checker.validate(True) checker.validate(None) checker.validate(-2.5) assert checker.update(10) == 10 assert checker.update(True) == 1 assert checker.update(False) == 0 assert checker.update(-2.5) == -2 assert checker.update('44') == 44 assert checker.update('a') == 0
class Version22(Jsonable): """ Version1 with modified types for a and c. NB: To parse a dict from Version1 to Version22, modified fields a and c must be convertible using ConverterType in Version22. """ model = { 'a': parsing.ConverterType(str, converter_function=str), 'b': str, 'c': parsing.ConverterType(bool, converter_function=bool), 'd': bool, } def __init__(self, **kwargs): self.a = None self.b = None self.c = None self.d = None super(Version22, self).__init__(**kwargs)
class Version1(Jsonable): """ A Jsonable with fields a, b, c, d. NB: To parse a dict from Version22 to Version1, modified fields a and c must be convertible in Version1. using ConverterType in Version1. """ model = { 'a': parsing.ConverterType(int, converter_to_int), 'b': parsing.OptionalValueType(str), 'c': parsing.ConverterType(float, converter_function=float), 'd': parsing.DefaultValueType(bool, True), } def __init__(self, **kwargs): self.a = None self.b = None self.c = None self.d = None super(Version1, self).__init__(**kwargs)
class Version3(Jsonable): """ Version 1 with a modified, b removed, e added. To parse a dict between Version3 and Version1: - a must be convertible in both versions. - b must be optional in Version1. - e must be optional in Version3. """ model = { 'a': parsing.ConverterType(str, converter_function=str), 'c': float, 'd': bool, 'e': parsing.OptionalValueType(parsing.SequenceType(int)) } def __init__(self, **kwargs): self.a = None self.c = None self.d = None self.e = None super(Version3, self).__init__(**kwargs)