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

bug: MarshalYAML not called on embedded type #1058

Open
gabyx opened this issue Dec 5, 2024 · 0 comments
Open

bug: MarshalYAML not called on embedded type #1058

gabyx opened this issue Dec 5, 2024 · 0 comments

Comments

@gabyx
Copy link

gabyx commented Dec 5, 2024

The following test seems not to pass:

Serializing a struct C which has Wrapper struct as field which implements MarshalYAML does not get called.
Is that a bug?

package ci

import (
	"errors"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"
	"gopkg.in/yaml.v3"
)

type Interface interface {
	DoUnmarshal(v *yaml.Node) error
}

type Impl struct {
	A string `yaml:"aa"`
}

func (s *Impl) DoUnmarshal(v *yaml.Node) error {
	return v.Decode(&s)
}

type MyType struct {
	Value  bool    `yaml:"v"`
	Custom Wrapper `yaml:"custom"`
}

type Wrapper struct {
	inst Interface
}

var called bool

func (w *Wrapper) MarshalYAML() (interface{}, error) {
	fmt.Printf("Marshal wrapper.")
	called = true
	return w.inst, nil
}

func (w *Wrapper) UnmarshalYAML(v *yaml.Node) error {
	fmt.Printf("Unmarshal wrapper.")
	return w.inst.DoUnmarshal(v)
}

func TestUnmarshal(t *testing.T) {

	c := MyType{
		Value:  true,
		Custom: Wrapper{inst: &Impl{A: "asdf"}}}

	b, e := yaml.Marshal(&c)

	require.NoError(t, e)
	t.Logf("\n%v", string(b))
	require.True(t, called, "MarshalYAML is not called.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant