-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest.go
70 lines (53 loc) · 1.79 KB
/
request.go
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
package grpcsteps
import (
"context"
"fmt"
"time"
"github.com/cucumber/godog"
)
// ErrNoRequestPlannerInContext indicates that there is no request planner in context.
const ErrNoRequestPlannerInContext err = "no request planner in context"
type requestPlanner interface {
WithHeader(header string, value interface{}) error
WithTimeout(d time.Duration) error
}
func registerRequestPlanner(sc *godog.ScenarioContext) {
sc.Step(`^[tT]he (?:gRPC|GRPC|grpc) request has(?: a)? header "([^"]*): ([^"]*)"$`, planRequestWithHeader)
sc.Step(`^[tT]he (?:gRPC|GRPC|grpc) request timeout is "([^"]*)"$`, planRequestWithTimeout)
}
func planRequestWithHeader(ctx context.Context, header, value string) error {
return requestPlannerFromContext(ctx).WithHeader(header, value)
}
func planRequestWithTimeout(ctx context.Context, t string) error {
timeout, err := time.ParseDuration(t)
if err != nil {
return err
}
return requestPlannerFromContext(ctx).WithTimeout(timeout)
}
type requestCtxKey struct{}
type requestPlannerCtxKey struct{}
func requestPlannerFromContext(ctx context.Context) requestPlanner {
p, ok := ctx.Value(requestPlannerCtxKey{}).(requestPlanner)
if !ok {
return missingRequestPlanner{}
}
return p
}
func requestPlannerToContext(ctx context.Context, r requestPlanner) context.Context {
return context.WithValue(ctx, requestPlannerCtxKey{}, r)
}
type missingRequestPlanner struct{}
func (missingRequestPlanner) WithHeader(string, interface{}) error {
return missingRequestPlannerErr()
}
func (missingRequestPlanner) WithTimeout(time.Duration) error {
return missingRequestPlannerErr()
}
func missingRequestPlannerErr() error {
//goland:noinspection GoErrorStringFormat
return fmt.Errorf(
"%w, did you forget to setup a gprc request in the scenario?",
ErrNoRequestPlannerInContext,
)
}