mirror of
https://github.com/woodpecker-ci/woodpecker.git
synced 2024-12-28 11:20:30 +00:00
add custom bool true type
This commit is contained in:
parent
dbfaedd54b
commit
67fbc8f14d
2 changed files with 82 additions and 0 deletions
28
yaml/types/bool.go
Normal file
28
yaml/types/bool.go
Normal file
|
@ -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
yaml/types/bool_test.go
Normal file
54
yaml/types/bool_test.go
Normal file
|
@ -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")
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
Loading…
Reference in a new issue