|
| 1 | +// ================================================================= |
| 2 | +// |
| 3 | +// Copyright (C) 2018 Spatial Current, Inc. - All Rights Reserved |
| 4 | +// Released as open source under the MIT License. See LICENSE file. |
| 5 | +// |
| 6 | +// ================================================================= |
| 7 | + |
| 8 | +package dfl |
| 9 | + |
| 10 | +import ( |
| 11 | + "reflect" |
| 12 | + "testing" |
| 13 | +) |
| 14 | + |
| 15 | +import ( |
| 16 | + "github.com/pkg/errors" |
| 17 | +) |
| 18 | + |
| 19 | +func TestAttribute(t *testing.T) { |
| 20 | + |
| 21 | + ctx := Context{ |
| 22 | + "a": nil, |
| 23 | + "b": nil, |
| 24 | + "c": map[string]interface{}{"d": 10, "e": map[string]interface{}{"f": 100}}, |
| 25 | + "g": []int{10, 20, 30}, |
| 26 | + "h": map[string]interface{}{"i": []int{10, 20, 30, 40}}, |
| 27 | + "j": "bars", |
| 28 | + "k": []map[string]interface{}{ |
| 29 | + map[string]interface{}{"l": "m"}, |
| 30 | + }, |
| 31 | + } |
| 32 | + |
| 33 | + testCases := []TestCase{ |
| 34 | + NewTestCase("(@a?.d ?: 10) == 10", ctx, true), |
| 35 | + NewTestCase("@c?.d == 10", ctx, true), |
| 36 | + NewTestCase("@c.d == 10", ctx, true), |
| 37 | + NewTestCase("@c.e.f == 100", ctx, true), |
| 38 | + NewTestCase("@c.e?.f == 100", ctx, true), |
| 39 | + NewTestCase("@g[0] == 10", ctx, true), |
| 40 | + NewTestCase("@g[0:2] == [10,20]", ctx, true), |
| 41 | + NewTestCase("@h?.i[1:3] == [20,30]", ctx, true), |
| 42 | + NewTestCase("@h?.i[1:3] == [20,30]", ctx, true), |
| 43 | + NewTestCase("@j[0:3] == bar", ctx, true), |
| 44 | + NewTestCase("@j[:3] == bar", ctx, true), |
| 45 | + NewTestCase("@k[0]l == m", ctx, true), |
| 46 | + } |
| 47 | + |
| 48 | + for _, testCase := range testCases { |
| 49 | + node, err := Parse(testCase.Expression) |
| 50 | + if err != nil { |
| 51 | + t.Errorf(errors.Wrap(err, "Error parsing expression \""+testCase.Expression+"\"").Error()) |
| 52 | + continue |
| 53 | + } |
| 54 | + node = node.Compile() |
| 55 | + got, err := node.Evaluate(testCase.Context, FunctionMap{}) |
| 56 | + if err != nil { |
| 57 | + t.Errorf(errors.Wrap(err, "Error evaluating expression \""+testCase.Expression+"\"").Error()) |
| 58 | + } else if got != testCase.Result { |
| 59 | + t.Errorf("TestAttribute(%q) == %v (%q), want %v (%q)", testCase.Expression, got, reflect.TypeOf(got), testCase.Result, reflect.TypeOf(testCase.Result)) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments