|
| 1 | +from cfengine_cli.format import stringify_children_from_strings, stringify_children |
| 2 | + |
| 3 | + |
| 4 | +class MockNode: |
| 5 | + """Minimal stand-in for a tree-sitter Node used by stringify_children.""" |
| 6 | + |
| 7 | + def __init__(self, node_type, node_text=None, children=None): |
| 8 | + self.type = node_type |
| 9 | + self.text = node_text.encode("utf-8") if node_text is not None else None |
| 10 | + self.children = children or [] |
| 11 | + |
| 12 | +def _leaf(node_type, node_text=None): |
| 13 | + return MockNode(node_type, node_text or node_type) |
| 14 | + |
| 15 | +def test_stringify_children_from_strings(): |
| 16 | + assert stringify_children_from_strings([]) == "" |
| 17 | + assert stringify_children_from_strings(["foo"]) == "foo" |
| 18 | + assert stringify_children_from_strings(["(", "a", ")"]) == "(a)" |
| 19 | + assert stringify_children_from_strings(["(", "a", ",", "b", ")"]) == "(a, b)" |
| 20 | + assert stringify_children_from_strings(["(", "a", ",", ")"]) == "(a)" |
| 21 | + assert ( |
| 22 | + stringify_children_from_strings(["(", "a", ",", "b", ",", ")"]) |
| 23 | + == "(a, b)" |
| 24 | + ) |
| 25 | + assert stringify_children_from_strings(["a", "b", "c"]) == "a b c" |
| 26 | + assert stringify_children_from_strings(["a", ",", "b"]) == "a, b" |
| 27 | + assert stringify_children_from_strings(["(", ")"]) == "()" |
| 28 | + parts = ["(", "x", ",", "y", ",", "z", ")"] |
| 29 | + assert stringify_children_from_strings(parts) == "(x, y, z)" |
| 30 | + |
| 31 | +def test_stringify_children(): |
| 32 | + assert stringify_children([]) == "" |
| 33 | + assert stringify_children([_leaf("identifier", "foo")]) == "foo" |
| 34 | + |
| 35 | + nodes = [_leaf("string", '"a"'), _leaf(","), _leaf("string", '"b"')] |
| 36 | + assert stringify_children(nodes) == '"a", "b"' |
| 37 | + |
| 38 | + nodes = [_leaf("identifier", "lval"), _leaf("=>"), _leaf("string", '"rval"')] |
| 39 | + assert stringify_children(nodes) == 'lval => "rval"' |
| 40 | + |
| 41 | + nodes = [_leaf("("), _leaf("identifier", "x"), _leaf(")")] |
| 42 | + assert stringify_children(nodes) == "(x)" |
| 43 | + |
| 44 | + nodes = [ |
| 45 | + _leaf("{"), |
| 46 | + _leaf("string", '"a"'), |
| 47 | + _leaf(","), |
| 48 | + _leaf("string", '"b"'), |
| 49 | + _leaf("}"), |
| 50 | + ] |
| 51 | + assert stringify_children(nodes) == '{"a", "b"}' |
| 52 | + nodes = [ |
| 53 | + _leaf("identifier", "package_name"), |
| 54 | + _leaf("=>"), |
| 55 | + _leaf("string", '"nginx"'), |
| 56 | + ] |
| 57 | + |
| 58 | + assert stringify_children(nodes) == 'package_name => "nginx"' |
| 59 | + inner = MockNode( |
| 60 | + "call", |
| 61 | + children=[ |
| 62 | + _leaf("calling_identifier", "func"), |
| 63 | + _leaf("("), |
| 64 | + _leaf("string", '"arg"'), |
| 65 | + _leaf(")"), |
| 66 | + ], |
| 67 | + ) |
| 68 | + |
| 69 | + nodes = [_leaf("identifier", "x"), _leaf("=>"), inner] |
| 70 | + assert stringify_children(nodes) == 'x => func("arg")' |
0 commit comments