github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/cmd/generates/processes/process_test.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package processes_test 19 20 import ( 21 "context" 22 "fmt" 23 "github.com/aacfactory/errors" 24 processes2 "github.com/aacfactory/fns/cmd/generates/processes" 25 "testing" 26 "time" 27 ) 28 29 type WorkUnit struct { 30 name string 31 no int 32 value int 33 } 34 35 func (unit *WorkUnit) Handle(ctx context.Context) (message interface{}, err error) { 36 if ctx.Err() != nil { 37 err = ctx.Err() 38 return 39 } 40 if unit.no%2 == 1 { 41 err = errors.ServiceError("failed") 42 } else { 43 unit.value = unit.no 44 message = unit.name 45 } 46 time.Sleep(1 * time.Second) 47 return 48 } 49 50 func TestNew(t *testing.T) { 51 units := make([]*WorkUnit, 0, 1) 52 process := processes2.New() 53 for i := 0; i < 10; i++ { 54 name := fmt.Sprintf("s%d", i) 55 unit := &WorkUnit{ 56 name: name, 57 no: i, 58 } 59 units = append(units, unit) 60 process.Add(name, unit) 61 } 62 63 results := process.Start(context.TODO()) 64 go func(process *processes2.Process) { 65 time.Sleep(3100 * time.Millisecond) 66 fmt.Println("abort:", process.Abort(2*time.Second)) 67 }(process) 68 for { 69 result, ok := <-results 70 if !ok { 71 break 72 } 73 fmt.Println("result:", result.String()) 74 } 75 } 76 77 func TestParallelUnits(t *testing.T) { 78 process := processes2.New() 79 for i := 0; i < 2; i++ { 80 subs := make([]processes2.Unit, 0, 1) 81 for j := 0; j < 10; j++ { 82 unit := &WorkUnit{ 83 name: fmt.Sprintf("s:%d:%d", i, j), 84 no: i, 85 } 86 subs = append(subs, unit) 87 } 88 process.Add(fmt.Sprintf("s:%d", i), subs...) 89 } 90 results := process.Start(context.TODO()) 91 go func(process *processes2.Process) { 92 time.Sleep(1100 * time.Millisecond) 93 fmt.Println("abort:", process.Abort(2*time.Second)) 94 }(process) 95 for { 96 result, ok := <-results 97 if !ok { 98 break 99 } 100 fmt.Println("result:", result.String()) 101 } 102 }