diff --git a/yaml/types/bool.go b/yaml/types/bool.go new file mode 100644 index 000000000..ac7d295c7 --- /dev/null +++ b/yaml/types/bool.go @@ -0,0 +1,28 @@ +package types + +import "strconv" + +// BoolTrue is a custom Yaml boolean type that defaults to true. +type BoolTrue struct { + value bool +} + +// UnmarshalYAML implements custom Yaml unmarshaling. +func (b *BoolTrue) UnmarshalYAML(unmarshal func(interface{}) error) error { + var s string + err := unmarshal(&s) + if err != nil { + return err + } + + b.value, err = strconv.ParseBool(s) + if err != nil { + b.value = true + } + return nil +} + +// Bool returns the bool value. +func (b BoolTrue) Bool() bool { + return b.value +} diff --git a/yaml/types/bool_test.go b/yaml/types/bool_test.go new file mode 100644 index 000000000..641b74c0f --- /dev/null +++ b/yaml/types/bool_test.go @@ -0,0 +1,54 @@ +package types + +import ( + "testing" + + "github.com/franela/goblin" + "gopkg.in/yaml.v2" +) + +func TestBoolTrue(t *testing.T) { + g := goblin.Goblin(t) + + g.Describe("Yaml bool type", func() { + g.Describe("given a yaml file", func() { + + g.It("should unmarshal true", func() { + in := []byte("true") + out := BoolTrue{} + err := yaml.Unmarshal(in, &out) + if err != nil { + g.Fail(err) + } + g.Assert(out.Bool()).Equal(true) + }) + + g.It("should unmarshal false", func() { + in := []byte("false") + out := BoolTrue{} + err := yaml.Unmarshal(in, &out) + if err != nil { + g.Fail(err) + } + g.Assert(out.Bool()).Equal(false) + }) + + g.It("should unmarshal true when empty", func() { + in := []byte("") + out := BoolTrue{} + err := yaml.Unmarshal(in, &out) + if err != nil { + g.Fail(err) + } + g.Assert(out.Bool()).Equal(false) + }) + + g.It("should throw error when invalid", func() { + in := []byte("{ }") // string value should fail parse + out := BoolTrue{} + err := yaml.Unmarshal(in, &out) + g.Assert(err != nil).IsTrue("expects error") + }) + }) + }) +}