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 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 // 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 field = 0
var err error var err error
expr.expression = cronLine
// second field (optional) // second field (optional)
if fieldCount == 7 { if fieldCount == 7 {
err = expr.secondFieldHandler(cron[indices[field][0]:indices[field][1]]) err = expr.secondFieldHandler(cron[indices[field][0]:indices[field][1]])
@ -144,6 +149,20 @@ func Parse(cronLine string) (*Expression, error) {
return &expr, nil 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 // Next returns the closest time instant immediately following `fromTime` which

View File

@ -17,6 +17,8 @@ package cronexpr
import ( import (
"testing" "testing"
"time" "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) { func TestNextN(t *testing.T) {
expected := []string{ expected := []string{
"Sat, 30 Nov 2013 00:00:00", "Sat, 30 Nov 2013 00:00:00",