yq/pkg/yqlib/encoder_test.go

75 lines
1.7 KiB
Go
Raw 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)
var jsonEncoder = NewJsonEncoder(writer, indent)
2020-11-20 11:57:32 +00:00
inputs, err := readDocuments(strings.NewReader(sampleYaml), "sample.yml", 0)
if err != nil {
panic(err)
}
node := inputs.Front().Value.(*CandidateNode).Node
2020-11-19 11:11:26 +00:00
err = jsonEncoder.Encode(node)
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)
}
func TestJsonNull(t *testing.T) {
var sampleYaml = `null`
var actualJson = yamlToJson(sampleYaml, 0)
test.AssertResult(t, sampleYaml, actualJson)
}
func TestJsonNullInObject(t *testing.T) {
var sampleYaml = `{x: null}`
var actualJson = yamlToJson(sampleYaml, 0)
test.AssertResult(t, `{"x":null}`, actualJson)
}
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)
}