Skip to content

Commit

Permalink
add custom bool true type
Browse files Browse the repository at this point in the history
  • Loading branch information
bradrydzewski committed Jan 19, 2017
1 parent dbfaedd commit 67fbc8f
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
28 changes: 28 additions & 0 deletions yaml/types/bool.go
Original file line number Diff line number Diff line change
@@ -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
}
54 changes: 54 additions & 0 deletions yaml/types/bool_test.go
Original file line number Diff line number Diff line change
@@ -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")
})
})
})
}

0 comments on commit 67fbc8f

Please sign in to comment.