Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fuzzer: FuzzEncodeFromJSON #1028

Open
wants to merge 1 commit into
base: v3
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
74 changes: 74 additions & 0 deletions fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//go:build go1.18
// +build go1.18

package yaml_test

import (
"bytes"
"encoding/json"
"testing"

"gopkg.in/yaml.v3"
)

// FuzzEncodeFromJSON checks that any JSON encoded value can also be encoded as YAML... and decoded.
func FuzzEncodeFromJSON(f *testing.F) {
f.Add(`null`)
f.Add(`""`)
f.Add(`0`)
f.Add(`true`)
f.Add(`false`)
f.Add(`{}`)
f.Add(`[]`)
f.Add(`[[]]`)
f.Add(`{"a":[]}`)

f.Fuzz(func(t *testing.T, s string) {

var v interface{}
if err := json.Unmarshal([]byte(s), &v); err != nil {
t.Skip("not valid JSON")
}

t.Logf("JSON %q", s)
t.Logf("Go %q <%[1]x>", v)

// Encode as YAML
b, err := yaml.Marshal(v)
if err != nil {
t.Error(err)
}
t.Logf("YAML %q <%[1]x>", b)

// Decode as YAML
var v2 interface{}
if err := yaml.Unmarshal(b, &v2); err != nil {
t.Error(err)
}

t.Logf("Go %q <%[1]x>", v2)

/*
// Handling of number is different, so we can't have universal exact matching
if !reflect.DeepEqual(v2, v) {
t.Errorf("mismatch:\n- got: %#v\n- expected: %#v", v2, v)
}
*/

b2, err := yaml.Marshal(v2)
if err != nil {
t.Error(err)
}
t.Logf("YAML %q <%[1]x>", b2)

if !bytes.Equal(b, b2) {
t.Errorf("Marshal->Unmarshal->Marshal mismatch:\n- expected: %q\n- got: %q", b, b2)
}

})
}

func TestEncodeString(t *testing.T) {
b, _ := yaml.Marshal(`\n`)
t.Logf("%q <%[1]x>", string(b))
}