def test_choice(): n = compile(choice(when(choice(str, int), a), when(choice(float, ()), b))) assert n.apply(1) == a assert n.apply("one") == a assert n.apply(1.0) == b assert n.apply(()) == b
@match(MappingNode) def view(node): return MapView(node, LEAF_AS_PYTHON) @match(SequenceNode) def view(node): return ListView(node, LEAF_AS_PYTHON) @match(ScalarNode) def view(node): return node @match(MappingNode, choice(LEAF_AS_NODE, LEAF_AS_STRING, LEAF_AS_PYTHON)) def view(node, mode): return MapView(node, mode) @match(SequenceNode, choice(LEAF_AS_NODE, LEAF_AS_STRING, LEAF_AS_PYTHON)) def view(node, mode): return ListView(node, mode) @match(ScalarNode, LEAF_AS_NODE) def view(node, _): return node @match(ScalarNode, LEAF_AS_STRING)
def test_giant_switch(): OBJECT = Action("object") BAZ = Action("Baz") FOO_TYPE = Action("Foo") FOO_VALUE = Action("FOO") FOO_BAZ = Action("Foo, Baz") FOO_OBJECT = Action("Foo, object") OBJECT_THREE = Action("object, 3") OBJECT_OBJECT = Action("object, object") INTS = Action("ints") THREES = Action("threes") ONE_TO_FOUR = Action("1, 2, 3, 4") LIST_OF_INT = Action("list-of-int") LIST_OF_ZERO = Action("list-of-zero") TUPLE_OF_INT = Action("tuple-of-int") PAIRS = Action("PAIRS") frag = choice( when(object, OBJECT), when(Baz, BAZ), when(Foo, FOO_TYPE), when(FOO, FOO_VALUE), when(one(Foo, Baz), FOO_BAZ), when(one(Foo, object), FOO_OBJECT), when(one(Bar, 3), FOO_OBJECT), when(one(object, 3), OBJECT_THREE), when(one(object, object), OBJECT_OBJECT), when(one(int, many(int)), INTS), when(one(3, many(3)), THREES), when(one(1, 2, 3, 4), ONE_TO_FOUR), when([many(int)], LIST_OF_INT), when([0], LIST_OF_ZERO), when((int,), TUPLE_OF_INT), when(many(str, int), PAIRS) ) n = compile(frag) assert n.apply(Foo()) == FOO_TYPE assert n.apply(Bar()) == FOO_TYPE assert n.apply(Baz()) == BAZ assert n.apply(FOO) == FOO_VALUE assert n.apply(Foo(), Baz()) == FOO_BAZ assert n.apply(Foo(), 3) == FOO_OBJECT assert n.apply(Bar(), 3) == FOO_OBJECT assert n.apply(object(), object()) == OBJECT_OBJECT assert n.apply(3) == THREES assert n.apply(3, 3) == THREES assert n.apply(3, 3, 3) == THREES assert n.apply(3, 3, 3, 3) == THREES assert n.apply(1, 2, 3, 4) == ONE_TO_FOUR assert n.apply(0, 1, 2, 3) == INTS assert n.apply([1, 2, 3, 4]*100) == LIST_OF_INT assert n.apply([0]) == LIST_OF_ZERO assert n.apply((0,)) == TUPLE_OF_INT assert n.apply("one", 1, "two", 2, "three", 3) == PAIRS try: n.apply("one", 1, "two", 2, "three") assert False, "expected MatchError" except MatchError: pass
@match(int, str) def asdf(x, y): "d1" return 1, x, y @match(str, int) def asdf(x, y): "d2" return 2, x, y @match(3, opt(str)) def asdf(x, y="bleh"): "d3" return 3, x, y @match(choice(int, float)) def asdf(x): "d4" return 4, x @match(int) def asdf(x): "d5" return 5, x def test_asdf(): assert asdf(1, "two") == (1, 1, "two") assert asdf("one", 2) == (2, "one", 2) assert asdf(3) == (3, 3, "bleh") assert asdf(3, "fdsa") == (3, 3, "fdsa") assert asdf(3.14) == (4, 3.14)