mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-02-16 02:08:26 -06:00
Add cron expression validation function and tests
This commit is contained in:
22
internal/validate/cron_expression.go
Normal file
22
internal/validate/cron_expression.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/adhocore/gronx"
|
||||
)
|
||||
|
||||
// CronExpression validates a cron expression.
|
||||
//
|
||||
// It only supports 5 fields (minute, hour, day of month, month, day of week).
|
||||
//
|
||||
// It returns a boolean indicating whether the expression is valid or not.
|
||||
func CronExpression(expression string) bool {
|
||||
fields := strings.Fields(expression)
|
||||
if len(fields) != 5 {
|
||||
return false
|
||||
}
|
||||
|
||||
gron := gronx.New()
|
||||
return gron.IsValid(expression)
|
||||
}
|
||||
58
internal/validate/cron_expression_test.go
Normal file
58
internal/validate/cron_expression_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCronExpression(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
expression string
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "Valid 5-field expression",
|
||||
expression: "0 12 * * 1-5",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid: too few fields",
|
||||
expression: "0 12 * *",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid: too many fields",
|
||||
expression: "0 12 * * 1-5 2023",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "Invalid: incorrect minute",
|
||||
expression: "60 12 * * 1-5",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "Valid: complex expression",
|
||||
expression: "*/15 2,8-17 * * 1-5",
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid: incorrect day of week",
|
||||
expression: "0 12 * * 8",
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "Valid: using names",
|
||||
expression: "0 12 * JAN-DEC MON-FRI",
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := CronExpression(tt.expression)
|
||||
assert.Equal(t, tt.want, got, "CronExpression(%v)", tt.expression)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user