yq/pkg/yqlib/encoder_test.go

81 lines
1.9 KiB
Go
Raw Normal View History

//go:build !yq_nojson
package yqlib
import (
"bufio"
"bytes"
"strings"
"testing"
"github.com/mikefarah/yq/v4/test"
)
2023-04-13 04:53:14 +00:00
func yamlToJSON(t *testing.T, sampleYaml string, indent int) string {
t.Helper()
var output bytes.Buffer
writer := bufio.NewWriter(&output)
var jsonEncoder = NewJSONEncoder(indent, false, false)
inputs, err := readDocuments(strings.NewReader(sampleYaml), "sample.yml", 0, NewYamlDecoder(ConfiguredYamlPreferences))
if err != nil {
panic(err)
}
2023-04-11 05:33:32 +00:00
node := inputs.Front().Value.(*CandidateNode)
2023-04-13 04:34:34 +00:00
log.Debugf("%v", NodeToString(node))
2023-04-13 04:53:14 +00:00
// log.Debugf("Content[0] %v", NodeToString(node.Content[0]))
2023-04-13 04:34:34 +00:00
err = jsonEncoder.Encode(writer, node)
2020-11-19 11:11:26 +00:00
if err != nil {
panic(err)
}
writer.Flush()
return strings.TrimSuffix(output.String(), "\n")
}
func TestJSONEncoderPreservesObjectOrder(t *testing.T) {
var sampleYaml = `zabbix: winner
apple: great
banana:
- {cobra: kai, angus: bob}
`
var expectedJSON = `{
"zabbix": "winner",
"apple": "great",
"banana": [
{
"cobra": "kai",
"angus": "bob"
}
]
}`
2023-04-13 04:53:14 +00:00
var actualJSON = yamlToJSON(t, sampleYaml, 2)
test.AssertResult(t, expectedJSON, actualJSON)
}
2021-10-30 02:37:21 +00:00
func TestJsonNullInArray(t *testing.T) {
var sampleYaml = `[null]`
2023-04-13 04:53:14 +00:00
var actualJSON = yamlToJSON(t, sampleYaml, 0)
test.AssertResult(t, sampleYaml, actualJSON)
2021-10-30 02:37:21 +00:00
}
func TestJsonNull(t *testing.T) {
var sampleYaml = `null`
2023-04-13 04:53:14 +00:00
var actualJSON = yamlToJSON(t, sampleYaml, 0)
test.AssertResult(t, sampleYaml, actualJSON)
2021-10-30 02:37:21 +00:00
}
func TestJsonNullInObject(t *testing.T) {
var sampleYaml = `{x: null}`
2023-04-13 04:53:14 +00:00
var actualJSON = yamlToJSON(t, sampleYaml, 0)
test.AssertResult(t, `{"x":null}`, actualJSON)
2021-10-30 02:37:21 +00:00
}
func TestJsonEncoderDoesNotEscapeHTMLChars(t *testing.T) {
var sampleYaml = `build: "( ./lint && ./format && ./compile ) < src.code"`
var expectedJSON = `{"build":"( ./lint && ./format && ./compile ) < src.code"}`
2023-04-13 04:53:14 +00:00
var actualJSON = yamlToJSON(t, sampleYaml, 0)
test.AssertResult(t, expectedJSON, actualJSON)
}