test.py 1.92 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

4
from serializer_utils.deserializer import Deserializable, Rule
Rolf H. B. van Kleef's avatar
Rolf H. B. van Kleef committed
5 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
from serializer_utils.annotations import abstract, discriminate


@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 48 49
if __name__ == '__main__':
    import sys
    import traceback

    from serializer_utils.deserializer import deserialize

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]