github.com/cjdelisle/matterfoss@v5.11.1+incompatible/model/scheduled_task_test.go (about)

     1  // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package model
     5  
     6  import (
     7  	"sync/atomic"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestCreateTask(t *testing.T) {
    15  	TASK_NAME := "Test Task"
    16  	TASK_TIME := time.Second * 2
    17  
    18  	executionCount := new(int32)
    19  	testFunc := func() {
    20  		atomic.AddInt32(executionCount, 1)
    21  	}
    22  
    23  	task := CreateTask(TASK_NAME, testFunc, TASK_TIME)
    24  	assert.EqualValues(t, 0, atomic.LoadInt32(executionCount))
    25  
    26  	time.Sleep(TASK_TIME + time.Second)
    27  
    28  	assert.EqualValues(t, 1, atomic.LoadInt32(executionCount))
    29  	assert.Equal(t, TASK_NAME, task.Name)
    30  	assert.Equal(t, TASK_TIME, task.Interval)
    31  	assert.False(t, task.Recurring)
    32  }
    33  
    34  func TestCreateRecurringTask(t *testing.T) {
    35  	TASK_NAME := "Test Recurring Task"
    36  	TASK_TIME := time.Second * 2
    37  
    38  	executionCount := new(int32)
    39  	testFunc := func() {
    40  		atomic.AddInt32(executionCount, 1)
    41  	}
    42  
    43  	task := CreateRecurringTask(TASK_NAME, testFunc, TASK_TIME)
    44  	assert.EqualValues(t, 0, atomic.LoadInt32(executionCount))
    45  
    46  	time.Sleep(TASK_TIME + time.Second)
    47  
    48  	assert.EqualValues(t, 1, atomic.LoadInt32(executionCount))
    49  
    50  	time.Sleep(TASK_TIME)
    51  
    52  	assert.EqualValues(t, 2, atomic.LoadInt32(executionCount))
    53  	assert.Equal(t, TASK_NAME, task.Name)
    54  	assert.Equal(t, TASK_TIME, task.Interval)
    55  	assert.True(t, task.Recurring)
    56  
    57  	task.Cancel()
    58  }
    59  
    60  func TestCancelTask(t *testing.T) {
    61  	TASK_NAME := "Test Task"
    62  	TASK_TIME := time.Second
    63  
    64  	executionCount := new(int32)
    65  	testFunc := func() {
    66  		atomic.AddInt32(executionCount, 1)
    67  	}
    68  
    69  	task := CreateTask(TASK_NAME, testFunc, TASK_TIME)
    70  	assert.EqualValues(t, 0, atomic.LoadInt32(executionCount))
    71  	task.Cancel()
    72  
    73  	time.Sleep(TASK_TIME + time.Second)
    74  	assert.EqualValues(t, 0, atomic.LoadInt32(executionCount))
    75  }