Implement UnmarshalYAML

This commit is contained in:
Jian Li 2018-08-15 18:50:16 -07:00
parent 88b0669f7d
commit cc9f59582a
2 changed files with 43 additions and 0 deletions

View File

@ -44,6 +44,10 @@ type Expression struct {
yearList []int
}
func (expr Expression) String() string {
return fmt.Sprintf("(%s)", expr.expression)
}
/******************************************************************************/
// MustParse returns a new Expression pointer. It expects a well-formed cron
@ -85,6 +89,7 @@ func Parse(cronLine string) (*Expression, error) {
var field = 0
var err error
expr.expression = cronLine
// second field (optional)
if fieldCount == 7 {
err = expr.secondFieldHandler(cron[indices[field][0]:indices[field][1]])
@ -144,6 +149,20 @@ func Parse(cronLine string) (*Expression, error) {
return &expr, nil
}
func (expr *Expression) UnmarshalYAML(unmarshal func(interface{}) error) error {
var cronLine string
if err := unmarshal(&cronLine); err != nil {
return err
}
var err error
expression, err := Parse(cronLine)
if err != nil {
return err
}
*expr = *expression
return nil
}
/******************************************************************************/
// Next returns the closest time instant immediately following `fromTime` which

View File

@ -17,6 +17,8 @@ package cronexpr
import (
"testing"
"time"
yaml "gopkg.in/yaml.v2"
)
/******************************************************************************/
@ -236,6 +238,28 @@ func TestZero(t *testing.T) {
/******************************************************************************/
type Config struct {
Expression Expression `yaml:"Expression"`
}
func TestUnmarshaler(t *testing.T) {
var config Config
err := yaml.Unmarshal([]byte(`Expression: "* * * * *"`), &config)
if err != nil {
t.Errorf("Unexpected error while unmarshaling")
}
if config.Expression.String() != "(* * * * *)" {
t.Errorf("Unexpected value when unmarshaled")
}
err = yaml.Unmarshal([]byte(`Expression: * * * * *`), &config)
if err == nil {
t.Errorf("Expected an error")
}
}
/******************************************************************************/
func TestNextN(t *testing.T) {
expected := []string{
"Sat, 30 Nov 2013 00:00:00",