github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/pkg/parallel/future_test.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     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 parallel
    16  
    17  import (
    18  	"context"
    19  	"reflect"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  func TestGo(t *testing.T) {
    25  	type args struct {
    26  		ctx  context.Context
    27  		fn   func(ctx context.Context) (interface{}, error)
    28  		opts []RunOption
    29  	}
    30  	tests := []struct {
    31  		name    string
    32  		args    args
    33  		want    interface{}
    34  		wantErr interface{}
    35  	}{
    36  		{
    37  			args: args{
    38  				ctx: context.Background(),
    39  				fn: func(ctx context.Context) (interface{}, error) {
    40  					return 1, nil
    41  				},
    42  			},
    43  			want:    1,
    44  			wantErr: nil,
    45  		},
    46  		{
    47  			args: args{
    48  				ctx: context.Background(),
    49  				fn: func(ctx context.Context) (interface{}, error) {
    50  					return nil, context.Canceled
    51  				},
    52  			},
    53  			want:    nil,
    54  			wantErr: context.Canceled,
    55  		},
    56  		{
    57  			args: args{
    58  				ctx: context.Background(),
    59  				fn: func(ctx context.Context) (interface{}, error) {
    60  					select {
    61  					case <-ctx.Done():
    62  						return nil, ctx.Err()
    63  					}
    64  				},
    65  				opts: []RunOption{WithTimeout(1 * time.Second)},
    66  			},
    67  			want:    nil,
    68  			wantErr: context.DeadlineExceeded,
    69  		},
    70  	}
    71  	for _, tt := range tests {
    72  		t.Run(tt.name, func(t *testing.T) {
    73  			future := Go(tt.args.ctx, tt.args.fn, tt.args.opts...)
    74  
    75  			if data, err := future.Get(); !reflect.DeepEqual(data, tt.want) || !reflect.DeepEqual(err, tt.wantErr) {
    76  				t.Errorf("Go() And Get() = (%v, %v), want (%v, %v)", data, err, tt.want, tt.wantErr)
    77  			}
    78  		})
    79  	}
    80  }