From 089ee1992598a4d7527ef8a4c0742cad2047c306 Mon Sep 17 00:00:00 2001 From: Andrej Rypo Date: Fri, 19 Jan 2024 22:03:53 +0100 Subject: [PATCH] node wrapper and node builder test --- tests/iterators.phpt | 2 + tests/nodes.phpt | 90 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 tests/nodes.phpt diff --git a/tests/iterators.phpt b/tests/iterators.phpt index 9f2e02d..8c79524 100644 --- a/tests/iterators.phpt +++ b/tests/iterators.phpt @@ -44,6 +44,8 @@ Environment::setup(); $to->setParent($from); }; + // Tree from here: + // https://en.wikipedia.org/wiki/Tree_traversal $root = $f; $edge($f, $b); $edge($b, $a); diff --git a/tests/nodes.phpt b/tests/nodes.phpt new file mode 100644 index 0000000..b1f4cee --- /dev/null +++ b/tests/nodes.phpt @@ -0,0 +1,90 @@ + new Node($data)); + + // Tree from here: + // https://en.wikipedia.org/wiki/Tree_traversal + $root = $builder->node('F', [ + $builder->node('B', [ + $builder->node('A'), + $builder->node('D', [ + $builder->node('C'), + $builder->node('E'), + ]), + ]), + $builder->node('G', [ + $builder->node('I', [ + $builder->node('H'), + ]), + ]), + ]); + + // pre-order + $str = []; + foreach ($root as $node) { + $str[] = $node->data(); + } + Assert::same('F,B,A,D,C,E,G,I,H', implode(',', $str)); + + + // Tree from here: + // https://en.wikipedia.org/wiki/Tree_traversal + $data = [ + 'data' => 'F', + 'children' => [ + [ + 'data' => 'B', + 'children' => [ + [ + 'data' => 'A', + ], + [ + 'data' => 'D', + 'children' => [ + [ + 'data' => 'C', + ], + [ + 'data' => 'E', + ], + ], + ], + ], + ], + [ + 'data' => 'G', + 'children' => [ + [ + 'data' => 'I', + 'children' => [ + [ + 'data' => 'H', + ], + ], + ], + ], + ], + ], + ]; + $wrapper = new TreeWrapper(fn(array $raw) => new Node($raw['data']), fn(array $raw) => $raw['children'] ?? null); + $root = $wrapper->wrap($data); + + // pre-order + $str = []; + foreach ($root as $node) { + $str[] = $node->data(); + } + Assert::same('F,B,A,D,C,E,G,I,H', implode(',', $str)); +})();