2021-02-03 04:51:26 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
var variableOperatorScenarios = []expressionScenario{
|
2021-05-16 05:02:31 +00:00
|
|
|
{
|
|
|
|
skipDoc: true,
|
|
|
|
document: `{}`,
|
|
|
|
expression: `.a.b as $foo`,
|
|
|
|
expected: []string{
|
|
|
|
"D0, P[], (doc)::{}\n",
|
|
|
|
},
|
|
|
|
},
|
2021-02-03 04:51:26 +00:00
|
|
|
{
|
|
|
|
description: "Single value variable",
|
|
|
|
document: `a: cat`,
|
|
|
|
expression: `.a as $foo | $foo`,
|
|
|
|
expected: []string{
|
|
|
|
"D0, P[a], (!!str)::cat\n",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
|
|
|
description: "Multi value variable",
|
|
|
|
document: `[cat, dog]`,
|
|
|
|
expression: `.[] as $foo | $foo`,
|
|
|
|
expected: []string{
|
|
|
|
"D0, P[0], (!!str)::cat\n",
|
|
|
|
"D0, P[1], (!!str)::dog\n",
|
|
|
|
},
|
|
|
|
},
|
2021-02-04 01:39:04 +00:00
|
|
|
{
|
2021-02-04 01:44:03 +00:00
|
|
|
description: "Using variables as a lookup",
|
|
|
|
subdescription: "Example taken from [jq](https://stedolan.github.io/jq/manual/#Variable/SymbolicBindingOperator:...as$identifier|...)",
|
2021-02-04 01:39:04 +00:00
|
|
|
document: `{"posts": [{"title": "Frist psot", "author": "anon"},
|
2021-09-12 06:55:55 +00:00
|
|
|
{"title": "A well-written article", "author": "person1"}],
|
|
|
|
"realnames": {"anon": "Anonymous Coward",
|
|
|
|
"person1": "Person McPherson"}}`,
|
2021-02-04 01:39:04 +00:00
|
|
|
expression: `.realnames as $names | .posts[] | {"title":.title, "author": $names[.author]}`,
|
|
|
|
expected: []string{
|
|
|
|
"D0, P[], (!!map)::title: \"Frist psot\"\nauthor: \"Anonymous Coward\"\n",
|
|
|
|
"D0, P[], (!!map)::title: \"A well-written article\"\nauthor: \"Person McPherson\"\n",
|
|
|
|
},
|
|
|
|
},
|
2021-09-12 06:55:55 +00:00
|
|
|
{
|
|
|
|
description: "Using variables to swap values",
|
|
|
|
document: "a: a_value\nb: b_value",
|
|
|
|
expression: `.a as $x | .b as $y | .b = $x | .a = $y`,
|
|
|
|
expected: []string{
|
|
|
|
"D0, P[], (doc)::a: b_value\nb: a_value\n",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
{
|
2021-09-12 11:52:02 +00:00
|
|
|
description: "Use ref to reference a path repeatedly",
|
|
|
|
subdescription: "Note: You may find the `with` operator more useful.",
|
|
|
|
document: `a: {b: thing, c: something}`,
|
|
|
|
expression: `.a.b ref $x | $x = "new" | $x style="double"`,
|
2021-09-12 06:55:55 +00:00
|
|
|
expected: []string{
|
|
|
|
"D0, P[], (doc)::a: {b: \"new\", c: something}\n",
|
|
|
|
},
|
|
|
|
},
|
2021-02-03 04:51:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestVariableOperatorScenarios(t *testing.T) {
|
|
|
|
for _, tt := range variableOperatorScenarios {
|
|
|
|
testScenario(t, &tt)
|
|
|
|
}
|
2021-12-21 04:02:07 +00:00
|
|
|
documentOperatorScenarios(t, "variable-operators", variableOperatorScenarios)
|
2021-02-03 04:51:26 +00:00
|
|
|
}
|