-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathstep_function.go
More file actions
111 lines (92 loc) · 2.29 KB
/
step_function.go
File metadata and controls
111 lines (92 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package hrp
import (
"fmt"
"os"
"time"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
"github.com/httprunner/httprunner/v5/uixt"
"github.com/httprunner/httprunner/v5/uixt/option"
)
// StepFunction implements IStep interface.
type StepFunction struct {
StepConfig
Fn func()
}
func (s *StepFunction) Name() string {
return s.StepName
}
func (s *StepFunction) Type() StepType {
return StepTypeFunction
}
func (s *StepFunction) Config() *StepConfig {
return &s.StepConfig
}
func (s *StepFunction) Run(r *SessionRunner) (*StepResult, error) {
return runStepFunction(r, s)
}
func runStepFunction(r *SessionRunner, step IStep) (stepResult *StepResult, err error) {
var fn func()
switch stepFn := step.(type) {
case *StepFunction:
fn = stepFn.Fn
default:
return nil, errors.New("unexpected function step type")
}
log.Info().
Str("name", step.Name()).
Str("type", string(StepTypeFunction)).
Msg("run function")
start := time.Now()
stepResult = &StepResult{
Name: step.Name(),
StepType: step.Type(),
Success: false,
ContentSize: 0,
StartTime: start.UnixMilli(),
}
defer func() {
attachments := uixt.Attachments{}
if err != nil {
attachments["error"] = err.Error()
}
stepResult.Attachments = attachments
stepResult.Elapsed = time.Since(start).Milliseconds()
}()
vars := r.caseRunner.Config.Get().Variables
for key, value := range vars {
os.Setenv(key, fmt.Sprintf("%v", value))
}
// exec function
fn()
stepResult.Success = true
return stepResult, nil
}
// Call custom function, used for pre/post action hook
func Call(desc string, fn func(), opts ...option.ActionOption) error {
actionOptions := option.NewActionOptions(opts...)
startTime := time.Now()
defer func() {
log.Info().Str("desc", desc).
Int64("duration(ms)", time.Since(startTime).Milliseconds()).
Msg("function called")
}()
if actionOptions.Timeout == 0 {
// wait for function to finish
fn()
return nil
}
// set timeout for function execution
done := make(chan struct{})
go func() {
defer close(done)
fn()
}()
select {
case <-done:
// function completed within timeout
return nil
case <-time.After(time.Duration(actionOptions.Timeout) * time.Second):
return fmt.Errorf("function execution exceeded timeout of %d seconds", actionOptions.Timeout)
}
}