如何从上游测试上下文取消

时间:2019-12-19 03:41:48

标签: http go testing

假设我正在使用这样的函数:

func Handle(req *http.Request) {

   // do some stuff

   timeout, _ := time.ParseDuration(req.FormValue("timeout"))
   ctx, cancel := context.WithTimeout(req.Context(), timeout)
   req = req.WithContext(ctx)
   defer cancel()

   // do some other stuff

}

我想写一个这样的测试:

func TestContextIsCancelled(t *testing.T) {

   req := httptest.NewRequest("GET", "http://example.com", nil)
   q := req.URL.Query()
   q.Set("timeout", "1s")  // short timeout
   req.URL.RawQuery = q.Encode()
   go Handle(req)
   time.Sleep(2 * time.Second)  // request should be timed out after this

   // verify request was cancelled
   err := req.Context().Err()
   if err != context.Canceled {
      t.Error("Request hasn't been cancelled")
   }

}

这不起作用,因为下游一个超时时,上游请求/上下文不会被取消。有没有一种方法可以使此测试按我想要的方式进行而无需更改Handle的签名?

0 个答案:

没有答案