1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-24 19:40:54 +00:00
Beego/toolbox/task_test.go

86 lines
2.0 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2013-11-20 15:53:54 +00:00
package toolbox
import (
2020-07-19 14:34:57 +00:00
"errors"
2013-11-20 15:53:54 +00:00
"fmt"
"sync"
"testing"
"time"
2020-07-19 14:34:57 +00:00
"github.com/stretchr/testify/assert"
2013-11-20 15:53:54 +00:00
)
func TestParse(t *testing.T) {
tk := NewTask("taska", "0/30 * * * * *", func() error { fmt.Println("hello world"); return nil })
err := tk.Run()
if err != nil {
t.Fatal(err)
}
AddTask("taska", tk)
StartTask()
time.Sleep(6 * time.Second)
StopTask()
}
func TestSpec(t *testing.T) {
wg := &sync.WaitGroup{}
wg.Add(2)
tk1 := NewTask("tk1", "0 12 * * * *", func() error { fmt.Println("tk1"); return nil })
tk2 := NewTask("tk2", "0,10,20 * * * * *", func() error { fmt.Println("tk2"); wg.Done(); return nil })
tk3 := NewTask("tk3", "0 10 * * * *", func() error { fmt.Println("tk3"); wg.Done(); return nil })
AddTask("tk1", tk1)
AddTask("tk2", tk2)
AddTask("tk3", tk3)
StartTask()
defer StopTask()
select {
case <-time.After(200 * time.Second):
t.FailNow()
case <-wait(wg):
}
}
2020-07-19 14:34:57 +00:00
func TestTask_Run(t *testing.T) {
cnt := -1
task := func() error {
2020-07-22 15:00:06 +00:00
cnt++
2020-07-19 14:34:57 +00:00
fmt.Printf("Hello, world! %d \n", cnt)
return errors.New(fmt.Sprintf("Hello, world! %d", cnt))
}
tk := NewTask("taska", "0/30 * * * * *", task)
2020-07-22 15:00:06 +00:00
for i := 0; i < 200; i++ {
2020-07-19 14:34:57 +00:00
e := tk.Run()
assert.NotNil(t, e)
}
l := tk.Errlist
assert.Equal(t, 100, len(l))
assert.Equal(t, "Hello, world! 100", l[0].errinfo)
assert.Equal(t, "Hello, world! 101", l[1].errinfo)
}
2013-11-20 15:53:54 +00:00
func wait(wg *sync.WaitGroup) chan bool {
ch := make(chan bool)
go func() {
wg.Wait()
ch <- true
}()
return ch
}