yq/pkg/yqlib/encoder_test.go

75 lines
1.7 KiB
Go
Raw Permalink Normal View History

package yqlib
import (
"bufio"
"bytes"
"strings"
"testing"
"github.com/mikefarah/yq/v4/test"
)
func yamlToJSON(sampleYaml string, indent int) string {
var output bytes.Buffer
writer := bufio.NewWriter(&output)
2022-07-27 02:26:22 +00:00
var jsonEncoder = NewJSONEncoder(indent, false)
2021-12-21 04:02:07 +00:00
inputs, err := readDocuments(strings.NewReader(sampleYaml), "sample.yml", 0, NewYamlDecoder())
if err != nil {
panic(err)
}
node := inputs.Front().Value.(*CandidateNode).Node
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"
}
]
}`
var actualJSON = yamlToJSON(sampleYaml, 2)
test.AssertResult(t, expectedJSON, actualJSON)
}
2021-10-30 02:37:21 +00:00
func TestJsonNullInArray(t *testing.T) {
var sampleYaml = `[null]`
var actualJSON = yamlToJSON(sampleYaml, 0)
test.AssertResult(t, sampleYaml, actualJSON)
2021-10-30 02:37:21 +00:00
}
func TestJsonNull(t *testing.T) {
var sampleYaml = `null`
var actualJSON = yamlToJSON(sampleYaml, 0)
test.AssertResult(t, sampleYaml, actualJSON)
2021-10-30 02:37:21 +00:00
}
func TestJsonNullInObject(t *testing.T) {
var sampleYaml = `{x: null}`
var actualJSON = yamlToJSON(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"}`
var actualJSON = yamlToJSON(sampleYaml, 0)
test.AssertResult(t, expectedJSON, actualJSON)
}