2021-12-01 01:37:40 +00:00
|
|
|
package yqlib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"strings"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/mikefarah/yq/v4/test"
|
|
|
|
)
|
|
|
|
|
|
|
|
func yamlToCsv(sampleYaml string, separator rune) string {
|
|
|
|
var output bytes.Buffer
|
|
|
|
writer := bufio.NewWriter(&output)
|
|
|
|
|
2022-01-15 00:57:59 +00:00
|
|
|
var jsonEncoder = NewCsvEncoder(separator)
|
2021-12-21 04:02:07 +00:00
|
|
|
inputs, err := readDocuments(strings.NewReader(sampleYaml), "sample.yml", 0, NewYamlDecoder())
|
2021-12-01 01:37:40 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
node := inputs.Front().Value.(*CandidateNode).Node
|
2022-01-15 00:57:59 +00:00
|
|
|
err = jsonEncoder.Encode(writer, node)
|
2021-12-01 01:37:40 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
writer.Flush()
|
|
|
|
|
|
|
|
return strings.TrimSuffix(output.String(), "\n")
|
|
|
|
}
|
|
|
|
|
|
|
|
var sampleYaml = `["apple", apple2, "comma, in, value", "new
|
|
|
|
line", 3, 3.40, true, "tab here"]`
|
|
|
|
|
2021-12-02 01:11:15 +00:00
|
|
|
var sampleYamlArray = "[" + sampleYaml + ", [bob, cat, meow, puss]]"
|
|
|
|
|
|
|
|
func TestCsvEncoderEmptyArray(t *testing.T) {
|
|
|
|
var actualCsv = yamlToCsv(`[]`, ',')
|
|
|
|
test.AssertResult(t, "", actualCsv)
|
|
|
|
}
|
|
|
|
|
2021-12-01 01:37:40 +00:00
|
|
|
func TestCsvEncoder(t *testing.T) {
|
|
|
|
var expectedCsv = `apple,apple2,"comma, in, value",new line,3,3.40,true,tab here`
|
|
|
|
|
|
|
|
var actualCsv = yamlToCsv(sampleYaml, ',')
|
|
|
|
test.AssertResult(t, expectedCsv, actualCsv)
|
|
|
|
}
|
|
|
|
|
2021-12-02 01:11:15 +00:00
|
|
|
func TestCsvEncoderArrayOfArrays(t *testing.T) {
|
|
|
|
var actualCsv = yamlToCsv(sampleYamlArray, ',')
|
|
|
|
var expectedCsv = "apple,apple2,\"comma, in, value\",new line,3,3.40,true,tab here\nbob,cat,meow,puss"
|
|
|
|
test.AssertResult(t, expectedCsv, actualCsv)
|
|
|
|
}
|
|
|
|
|
2021-12-01 01:37:40 +00:00
|
|
|
func TestTsvEncoder(t *testing.T) {
|
|
|
|
|
|
|
|
var expectedCsv = `apple apple2 comma, in, value new line 3 3.40 true "tab here"`
|
|
|
|
|
|
|
|
var actualCsv = yamlToCsv(sampleYaml, '\t')
|
|
|
|
test.AssertResult(t, expectedCsv, actualCsv)
|
|
|
|
}
|