| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
package libyaml |
| 7 |
|
| 8 |
import ( |
| 9 |
"fmt" |
| 10 |
"reflect" |
| 11 |
"testing" |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
func checkNode(t *testing.T, node *Node, wantMap map[string]any, path string) { |
| 16 |
t.Helper() |
| 17 |
|
| 18 |
|
| 19 |
if kindStr, ok := wantMap["kind"].(string); ok { |
| 20 |
var expectedKind Kind |
| 21 |
switch kindStr { |
| 22 |
case "Scalar": |
| 23 |
expectedKind = ScalarNode |
| 24 |
case "Sequence": |
| 25 |
expectedKind = SequenceNode |
| 26 |
case "Mapping": |
| 27 |
expectedKind = MappingNode |
| 28 |
} |
| 29 |
if node.Kind != expectedKind { |
| 30 |
t.Fatalf("%s: got kind %v; want %v", path, node.Kind, expectedKind) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
if wantTag, ok := wantMap["tag"].(string); ok { |
| 36 |
if node.Tag != wantTag { |
| 37 |
t.Fatalf("%s: got tag %q; want %q", path, node.Tag, wantTag) |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
if wantValue, ok := wantMap["value"].(string); ok { |
| 43 |
if node.Value != wantValue { |
| 44 |
t.Fatalf("%s: got value %q; want %q", path, node.Value, wantValue) |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
if wantContent, ok := wantMap["content"].([]any); ok { |
| 50 |
if len(node.Content) != len(wantContent) { |
| 51 |
t.Fatalf("%s: got %d children; want %d", path, len(node.Content), len(wantContent)) |
| 52 |
} |
| 53 |
for i, wantChild := range wantContent { |
| 54 |
if wantChildMap, ok := wantChild.(map[string]any); ok { |
| 55 |
childPath := fmt.Sprintf("%s[%d]", path, i) |
| 56 |
checkNode(t, node.Content[i], wantChildMap, childPath) |
| 57 |
} |
| 58 |
} |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
func TestRepresenter(t *testing.T) { |
| 63 |
RunTestCases(t, "representer.yaml", map[string]TestHandler{ |
| 64 |
"represent-scalar": func(t *testing.T, tc TestCase) { |
| 65 |
t.Helper() |
| 66 |
|
| 67 |
r := NewRepresenter(DefaultOptions) |
| 68 |
doc := r.Represent("", reflect.ValueOf(tc.From)) |
| 69 |
|
| 70 |
if doc == nil || doc.Kind != DocumentNode { |
| 71 |
t.Fatal("expected DocumentNode") |
| 72 |
} |
| 73 |
if len(doc.Content) == 0 { |
| 74 |
t.Fatal("expected content in document") |
| 75 |
} |
| 76 |
node := doc.Content[0] |
| 77 |
|
| 78 |
|
| 79 |
wantMap := tc.Want.(map[string]any) |
| 80 |
checkNode(t, node, wantMap, "root") |
| 81 |
}, |
| 82 |
|
| 83 |
"represent-collection": func(t *testing.T, tc TestCase) { |
| 84 |
t.Helper() |
| 85 |
|
| 86 |
r := NewRepresenter(DefaultOptions) |
| 87 |
doc := r.Represent("", reflect.ValueOf(tc.From)) |
| 88 |
|
| 89 |
if doc == nil || doc.Kind != DocumentNode { |
| 90 |
t.Fatal("expected DocumentNode") |
| 91 |
} |
| 92 |
if len(doc.Content) == 0 { |
| 93 |
t.Fatal("expected content in document") |
| 94 |
} |
| 95 |
node := doc.Content[0] |
| 96 |
|
| 97 |
|
| 98 |
wantMap := tc.Want.(map[string]any) |
| 99 |
checkNode(t, node, wantMap, "root") |
| 100 |
}, |
| 101 |
}) |
| 102 |
} |