test.py 1.93 KB
Newer Older
Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
1
from time import sleep
2
from typing import Optional, List
Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
3

Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
4 5
from dict_deserializer.deserializer import Deserializable, Rule
from dict_deserializer.annotations import abstract, discriminate
Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34


@abstract
class ReceiptLine(Deserializable):
    pk: Optional[int]
    name: str
    t = 0

    def __repr__(self):
        return 'ReceiptLine(pk={}, name={}, t={})'\
            .format(self.pk, self.name, self.t)


@discriminate('type', 'transaction')
class TransactionLine(ReceiptLine):
    article_id: int
    amount: int

    def __repr__(self):
        return 'TransactionLine(super={}, article_id={}, amount={})'\
            .format(super(TransactionLine, self).__repr__(), self.article_id, self.amount)


@discriminate('type', 'refund')
class RefundLine(ReceiptLine):
    def __repr__(self):
        return 'RefundLine(super={})'.format(super(RefundLine, self).__repr__())


35 36
class Test(Deserializable):
    tf: Optional[ReceiptLine]
37
    ns: List[int]
38 39

    def __repr__(self):
40 41
        return 'Test(tf={},ns={})'\
            .format(self.tf.__repr__(), self.ns.__repr__())
42 43


Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
44 45 46 47
if __name__ == '__main__':
    import sys
    import traceback

Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
48
    from dict_deserializer.deserializer import deserialize
Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
49

50 51 52 53 54 55 56 57 58 59 60 61 62
    def print_result(function, *args, **kwargs):
        try:
            print(function(*args, **kwargs))
        except:
            sleep(0.05)
            print(traceback.format_exc(), file=sys.stderr)

    fns = [
        [Rule(ReceiptLine), {'type': 'transaction', 'name': 'asdf', 'article_id': 5, 'amount': 5}],
        [Rule(ReceiptLine), {'type': 'refund', 'name': 'asdf', 'pk': 5}],
        [Rule(ReceiptLine), {'type': 'other', 'name': 'asdf'}],
        [Rule(ReceiptLine), {'type': 'transaction'}],
        [Rule(ReceiptLine), {'type': 'transaction', 'name': 'asdf', 'pk': 'no'}],
63 64
        [Rule(Test), {'tf': {'type': 'refund', 'name': 'asdf', 'pk': 5},
                      'ns': [1, 2, 4, 7, 9]}]
65 66 67
    ]

    [print_result(deserialize, *entry) for entry in fns]