From 560e7b9d9a01ee470592922a80761b68cf850870 Mon Sep 17 00:00:00 2001 From: Tommaso Garuglieri Date: Mon, 1 Nov 2021 16:59:39 +0100 Subject: [PATCH] added tests for executor and gocron (#249) --- executor_test.go | 29 ++++++++++++++++ gocron_test.go | 90 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+) create mode 100644 executor_test.go diff --git a/executor_test.go b/executor_test.go new file mode 100644 index 00000000..7536c3a5 --- /dev/null +++ b/executor_test.go @@ -0,0 +1,29 @@ +package gocron + +import ( + "github.com/stretchr/testify/assert" + "sync" + "testing" +) + +func Test_ExecutorExecute(t *testing.T) { + e := newExecutor() + + wg := &sync.WaitGroup{} + wg.Add(1) + go e.start() + + var runState = int64(0) + e.jobFunctions <- jobFunction{ + name: "test_fn", + function: func(arg string) { + assert.Equal(t, arg, "test") + wg.Done() + }, + parameters: []interface{}{"test"}, + runState: &runState, + } + + e.stop() + wg.Wait() +} diff --git a/gocron_test.go b/gocron_test.go index b901d793..6815106b 100644 --- a/gocron_test.go +++ b/gocron_test.go @@ -1,6 +1,7 @@ package gocron import ( + "errors" "testing" "github.com/stretchr/testify/assert" @@ -105,3 +106,92 @@ func TestParseTime(t *testing.T) { }) } } + +func Test_callJobFuncWithParams(t *testing.T) { + type args struct { + jobFunc interface{} + params []interface{} + } + tests := []struct { + name string + args args + err bool + }{ + { + name: "test call func with no args", + args: args{ + jobFunc: func() {}, + params: nil, + }, + }, + { + name: "test call func with single arg", + args: args{ + jobFunc: func(arg string) {}, + params: []interface{}{"test"}, + }, + }, + { + name: "test call func with wrong arg type", + args: args{ + jobFunc: func(arg int) {}, + params: []interface{}{"test"}, + }, + err: true, + }, + { + name: "test call func with wrong arg count", + args: args{ + jobFunc: func(arg int) {}, + params: []interface{}{}, + }, + err: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := panicFnToErr(func() { + callJobFuncWithParams(tt.args.jobFunc, tt.args.params) + }) + + if err != nil && !tt.err { + t.Fatalf("unexpected panic: %s", err.Error()) + } + + }) + } +} + +func panicFnToErr(fn func()) (err error) { + defer func() { + if r := recover(); r != nil { + err = errors.New("func panic") + } + }() + fn() + return err +} + +func Test_getFunctionName(t *testing.T) { + type args struct { + fn interface{} + } + tests := []struct { + name string + args args + want string + }{ + { + name: "test get function name", + args: args{ + fn: Test_getFunctionName, + }, + want: "github.com/go-co-op/gocron.Test_getFunctionName", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equalf(t, tt.want, getFunctionName(tt.args.fn), "getFunctionName(%v)", tt.args.fn) + }) + } +}