github.com/turingchain2020/turingchain@v1.1.21/blockchain/task_test.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package blockchain
     6  
     7  import (
     8  	"fmt"
     9  	"math/rand"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/stretchr/testify/assert"
    14  )
    15  
    16  func TestTask(t *testing.T) {
    17  	task := newTask(time.Millisecond * 10)
    18  	if task.InProgress() {
    19  		task.Cancel()
    20  		t.Log("task not start")
    21  		return
    22  	}
    23  	task.Start(1, 10, nil, nil)
    24  	perm := rand.Perm(10)
    25  	for i := 0; i < len(perm); i++ {
    26  		time.Sleep(time.Millisecond * 5)
    27  		task.Done(int64(perm[i]) + 1)
    28  		if i < len(perm)-1 && !task.InProgress() {
    29  			task.Cancel()
    30  			t.Log("task not done, but InProgress is false")
    31  			return
    32  		}
    33  		if i == len(perm)-1 && task.InProgress() {
    34  			task.Cancel()
    35  			t.Log("task is done, but InProgress is true")
    36  			return
    37  		}
    38  	}
    39  }
    40  
    41  func TestTasks(t *testing.T) {
    42  	for n := 0; n < 10; n++ {
    43  		task := newTask(time.Millisecond * 10)
    44  		if task.InProgress() {
    45  			task.Cancel()
    46  			t.Log("task not start")
    47  			return
    48  		}
    49  		task.Start(1, 10, nil, nil)
    50  		perm := rand.Perm(10)
    51  		for i := 0; i < len(perm); i++ {
    52  			time.Sleep(time.Millisecond / 10)
    53  			task.Done(int64(perm[i]) + 1)
    54  			if i < len(perm)-1 && !task.InProgress() {
    55  				task.Cancel()
    56  				t.Log("task not done, but InProgress is false")
    57  				return
    58  			}
    59  			if i == len(perm)-1 && task.InProgress() {
    60  				task.Cancel()
    61  				t.Log("task is done, but InProgress is true")
    62  				return
    63  			}
    64  		}
    65  	}
    66  }
    67  
    68  func TestTaskTimeOut(t *testing.T) {
    69  	task := newTask(time.Millisecond * 10)
    70  	if task.InProgress() {
    71  		task.Cancel()
    72  		t.Log("task not start")
    73  		return
    74  	}
    75  	defer task.Cancel()
    76  	timeoutHeight := make(chan int64, 1)
    77  
    78  	timeoutcb := func(height int64) {
    79  		fmt.Println("timeout:height", height)
    80  		timeoutHeight <- height
    81  	}
    82  	task.Start(1, 11, nil, timeoutcb)
    83  	perm := rand.Perm(10)
    84  	for i := 0; i < len(perm); i++ {
    85  		task.Done(int64(perm[i]) + 1)
    86  	}
    87  	h := <-timeoutHeight
    88  	assert.Equal(t, h, int64(11))
    89  }