yq/pkg/yqlib/operators_test.go

92 lines
2.1 KiB
Go
Raw Normal View History

2020-11-03 23:48:43 +00:00
package yqlib
import (
"bufio"
"bytes"
2020-11-06 03:37:01 +00:00
"container/list"
2020-11-03 23:48:43 +00:00
"fmt"
"os"
2020-11-06 01:11:38 +00:00
"strings"
2020-11-03 23:48:43 +00:00
"testing"
"github.com/mikefarah/yq/v4/test"
)
type expressionScenario struct {
description string
document string
expression string
expected []string
2020-11-06 00:45:18 +00:00
skipDoc bool
2020-11-03 23:48:43 +00:00
}
func testScenario(t *testing.T, s *expressionScenario) {
2020-11-06 03:37:01 +00:00
var results *list.List
var err error
if s.document != "" {
results, err = EvaluateStream("sample.yaml", strings.NewReader(s.document), s.expression)
} else {
results, err = EvaluateExpression(s.expression)
2020-11-03 23:48:43 +00:00
}
2020-11-06 03:37:01 +00:00
if err != nil {
t.Error(err)
2020-11-03 23:48:43 +00:00
return
}
test.AssertResultComplexWithContext(t, s.expected, resultsToString(results), fmt.Sprintf("exp: %v\ndoc: %v", s.expression, s.document))
}
func documentScenarios(t *testing.T, title string, scenarios []expressionScenario) {
f, err := os.Create(fmt.Sprintf("doc/%v.md", title))
if err != nil {
panic(err)
}
defer f.Close()
w := bufio.NewWriter(f)
w.WriteString(fmt.Sprintf("# %v\n", title))
w.WriteString(fmt.Sprintf("## Examples\n"))
printer := NewPrinter(false, true, false, 2, true)
for index, s := range scenarios {
2020-11-06 00:45:18 +00:00
if !s.skipDoc {
2020-11-03 23:48:43 +00:00
2020-11-06 00:45:18 +00:00
if s.description != "" {
w.WriteString(fmt.Sprintf("### %v\n", s.description))
} else {
w.WriteString(fmt.Sprintf("### Example %v\n", index))
}
if s.document != "" {
w.WriteString(fmt.Sprintf("sample.yml:\n"))
w.WriteString(fmt.Sprintf("```yaml\n%v\n```\n", s.document))
}
if s.expression != "" {
w.WriteString(fmt.Sprintf("Expression\n"))
w.WriteString(fmt.Sprintf("```bash\nyq '%v' < sample.yml\n```\n", s.expression))
}
2020-11-03 23:48:43 +00:00
2020-11-06 00:45:18 +00:00
w.WriteString(fmt.Sprintf("Result\n"))
var output bytes.Buffer
2020-11-06 03:37:01 +00:00
var results *list.List
var err error
if s.document != "" {
results, err = EvaluateStream("sample.yaml", strings.NewReader(s.document), s.expression)
} else {
results, err = EvaluateExpression(s.expression)
}
2020-11-06 00:45:18 +00:00
printer.PrintResults(results, bufio.NewWriter(&output))
2020-11-03 23:48:43 +00:00
2020-11-06 00:45:18 +00:00
w.WriteString(fmt.Sprintf("```yaml\n%v```\n", output.String()))
2020-11-03 23:48:43 +00:00
2020-11-06 00:45:18 +00:00
if err != nil {
panic(err)
}
2020-11-03 23:48:43 +00:00
}
}
w.Flush()
}