Skip to content

Commit

Permalink
simplifying test for context deadline priority
Browse files Browse the repository at this point in the history
  • Loading branch information
actatum committed Oct 10, 2022
1 parent be6d0af commit 755fa27
Showing 1 changed file with 25 additions and 30 deletions.
55 changes: 25 additions & 30 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,25 +345,25 @@ func TestServer_handler(t *testing.T) {

subject := strconv.Itoa(rand.Int())
srv.Handle(subject, func(ctx context.Context, r Request) Response {
start := time.Now()
defer func(start time.Time) {
if time.Since(start).Round(1*time.Second) < timeout.Round(1*time.Second) {
t.Errorf("time.Since(start) got = %v, want %v", time.Since(start), timeout)
}
}(start)
ticker := time.NewTicker(timeout + 1*time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return NewErrorResponse(r.Reply, Error{
Code: ErrorCodeDeadlineExceeded,
Message: ctx.Err().Error(),
})
case <-ticker.C:
return NewErrorResponse(r.Reply, fmt.Errorf("somethings wrong"))
}
dl, ok := ctx.Deadline()
if !ok {
t.Error("context should have deadline")
}

var req map[string]time.Time
_ = r.Decode(&req)

if req["default"].After(dl) {
t.Errorf("req[default] got = %v, want before %v", req["default"], dl)
}

var resp Response
resp, err = NewResponse(r.Reply, map[string]string{"success": "ok"})
if err != nil {
return NewErrorResponse(r.Reply, err)
}

return resp
})

runCh := make(chan error)
Expand All @@ -381,21 +381,16 @@ func TestServer_handler(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

req, err := NewRequest(subject, map[string]string{"x": "D"})
ctxWithDefaultServerTimeout, cancel2 := context.WithTimeout(ctx, srv.timeout)
defer cancel2()

defaultDeadline, _ := ctxWithDefaultServerTimeout.Deadline()

req, err := NewRequest(subject, map[string]time.Time{"default": defaultDeadline})
if err != nil {
t.Fatal(err)
}
resp := client.Do(ctx, req)
var e *Error
ok := errors.As(resp.Err, &e)
if !ok {
t.Fatalf("expected error to be of type Error, got %T", resp.Err)
}
if e.Code != ErrorCodeDeadlineExceeded {
t.Fatalf("e.Code got = %v, want %v", e.Code, ErrorCodeDeadlineExceeded)
} else if e.Message != context.DeadlineExceeded.Error() {
t.Fatalf("e.Message got = %v, want %v", e.Message, context.DeadlineExceeded.Error())
}
_ = client.Do(ctx, req)

if err = srv.Shutdown(ctx); err != nil {
t.Fatal(err)
Expand Down

0 comments on commit 755fa27

Please sign in to comment.