-
Notifications
You must be signed in to change notification settings - Fork 0
/
service_test.go
77 lines (60 loc) · 2 KB
/
service_test.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
71
72
73
74
75
76
77
package service
import (
"context"
"errors"
"reflect"
"testing"
"time"
)
// Test case for the happy path. The service served the request in time without errors.
func TestService_Serve_Success(t *testing.T) {
srv := NewService(func() (Response, error) {
time.Sleep(500 * time.Millisecond)
return Response{Data: "success"}, nil
})
ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Millisecond)
defer cancel()
response, err := srv.Serve(ctx, Request{})
if err != nil {
t.Errorf("Serve() should not return an error, go %v", err)
}
wantResp := Response{"success"}
if !reflect.DeepEqual(response, wantResp) {
t.Errorf("Serve() got response %v, wanted %v", response, wantResp)
}
}
// Test case for service failure. Service failed to serve the request before reaching the context timeout.
func TestService_Serve_Error(t *testing.T) {
wantErr := errors.New("error")
srv := NewService(func() (Response, error) {
time.Sleep(500 * time.Millisecond)
return Response{}, wantErr
})
ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Millisecond)
defer cancel()
response, err := srv.Serve(ctx, Request{})
if err == nil {
t.Errorf("Serve() got err %v, wanted %v", err, wantErr)
}
wantResp := Response{}
if !reflect.DeepEqual(response, wantResp) {
t.Errorf("Serve() got response %v, wanted %v", response, wantResp)
}
}
// Test case for service timeout. Context timed out before the service finished serving the request.
func TestService_Serve_Timeout(t *testing.T) {
srv := NewService(func() (Response, error) {
time.Sleep(2000 * time.Millisecond)
return Response{Data: "success"}, nil
})
ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Millisecond)
defer cancel()
response, err := srv.Serve(ctx, Request{})
if err == nil {
t.Errorf("Serve() got err %v, wanted %v", err, context.DeadlineExceeded)
}
wantResp := Response{}
if !reflect.DeepEqual(response, wantResp) {
t.Errorf("Serve() got response %v, wanted %v", response, wantResp)
}
}