github.com/matrixorigin/matrixone@v1.2.0/pkg/common/async/future_test.go (about)

     1  // Copyright 2021 - 2022 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package async
    16  
    17  import (
    18  	"fmt"
    19  	"testing"
    20  	"time"
    21  )
    22  
    23  func sleepMs(ms int) (int, error) {
    24  	d, _ := time.ParseDuration(fmt.Sprintf("%dms", ms))
    25  	time.Sleep(d)
    26  	return ms, nil
    27  }
    28  
    29  func sleepMany(args ...interface{}) (interface{}, error) {
    30  	var ret int
    31  	for _, ms := range args {
    32  		x, e := sleepMs(ms.(int))
    33  		if e != nil {
    34  			return ret, e
    35  		}
    36  		ret += x
    37  	}
    38  	return ret, nil
    39  }
    40  
    41  func TestFuture(t *testing.T) {
    42  	f1 := AsyncCall(sleepMany, 100)
    43  	r1 := f1.MustGet().(int)
    44  	if r1 != 100 {
    45  		t.Errorf("Should slept 100, get %d", r1)
    46  	}
    47  
    48  	f2 := AsyncCall(sleepMany, 100, 200, 300)
    49  	r2 := f2.MustGet().(int)
    50  	if r2 != 600 {
    51  		t.Errorf("Should slept 600, get %d", r2)
    52  	}
    53  
    54  	fs := make([]*Future, 100)
    55  	var totExp int
    56  	for i := 0; i < 100; i++ {
    57  		i2 := i % 2
    58  		i3 := i % 3
    59  		totExp += i2 + i3
    60  		fs[i] = AsyncCall(sleepMany, i2*100, i3*100)
    61  	}
    62  
    63  	var nReady int
    64  	var tot int
    65  	for i := 0; i < 100; i++ {
    66  		if fs[i].IsReady() {
    67  			nReady += 1
    68  		}
    69  	}
    70  	t.Logf("Num ready %d.\n", nReady)
    71  
    72  	ms, _ := time.ParseDuration("200ms")
    73  	time.Sleep(ms)
    74  	nReady = 0
    75  	for i := 0; i < 100; i++ {
    76  		if fs[i].IsReady() {
    77  			nReady += 1
    78  		}
    79  	}
    80  	t.Logf("Num ready %d.\n", nReady)
    81  
    82  	for i := 0; i < 100; i++ {
    83  		tot += fs[i].MustGet().(int)
    84  	}
    85  	if tot != totExp*100 {
    86  		t.Errorf("Should slept %d, get %d", totExp*100, tot)
    87  	}
    88  	t.Logf("Look, mo, I slept %d*100 ms in no time", totExp)
    89  }