app/task/task_test.go

125 lines
2.4 KiB
Go
Raw Permalink Normal View History

2021-12-16 04:11:33 +00:00
package task
import (
"encoding/json"
"errors"
"fmt"
"os"
"testing"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func TestOverall(t *testing.T) {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006/01/02 15:04:05",
})
Init()
lg := l.With().Str("test", "TestOverall").Logger()
RunFunc("@every 1s", func() {
p := GetProfile()
d, _ := json.Marshal(p)
lg.Debug().Msg(string(d))
})
RunFunc("@every 2s", func() { l.Debug().Msg("@every 2s") })
test1 := &Task{
Name: "test1",
Description: "test1",
ID: "id1",
Group: "grp1",
Func: func(c *interface{}, args ...interface{}) error {
lg.Debug().Msgf("carry: %v, echo %v", c, args)
return nil
},
}
AddTask(test1)
test2 := &Task{
Name: "test2",
Description: "test2",
ID: "id2",
Func: func(c *interface{}, args ...interface{}) error {
carry, ok := (*c).(int)
if !ok {
carry = 1
}
lg.Debug().Msgf("carry: %d, echo %v", carry, args)
carry++
*c = carry
return nil
},
}
AddAndRunTask("@every 1s", test2, "1", 2, true)
RunTask("@every 3s", "id1", "arg1", 2)
RunTaskAfter(time.Second*10, "id2", "ONCE!!!")
RunTaskAt(time.Now().Add(time.Second*15), "id2", "ONCE!Again!!!")
test3 := &Task{
Name: "test3",
Description: "test3",
ID: "id3",
Func: func(c *interface{}, args ...interface{}) error {
carry, ok := (*c).(string)
if !ok {
carry = ""
}
lg.Debug().Msgf("carry: %s, echo %v", carry, args)
carry += "c"
*c = carry
return errors.New("test error")
},
}
AddAndRunTask("@every 5s", test3)
lg.Info().Msgf("%v", GetTasks())
Start()
<-time.After(time.Second * 20)
<-Stop().Done()
}
func TestReporter(t *testing.T) {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: "2006/01/02 15:04:05",
})
Init()
AddAndRunTask("@every 2s", &Task{
Name: "test",
Func: func(c *interface{}, args ...interface{}) error {
carry, ok := (*c).(int)
if !ok {
carry = 0
}
carry++
*c = carry
if carry%2 == 1 {
return fmt.Errorf("error with: %d", carry)
}
return nil
},
})
lg := l.With().Str("test", "TestReporter").Logger()
Start()
go func() {
for {
p := <-Reporter
lg.Debug().Msgf("%+v", p)
}
}()
<-time.After(time.Second * 20)
<-Stop().Done()
}