I am trying to test the HttpServer code.I have mocked my proxy calls in the code Here's my server code:
func HttpServer(t *testing.T,version string,test ReqRes, basePath string, timeout int,transport metrics.HttpInstrumenter, corsConfig middleware.CorsConfig) (*http.Response,[]byte, bool){
proxyAuthServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(test.proxyAuthStatusCode)
_, err := w.Write([]byte(test.proxyAuthResp))
if err != nil {
return
}
}))
defer proxyAuthServer.Close()
configs :=config.Config{
Outbounds: struct {
APIAuthentication struct {
AuthPath string `yaml:"authPath"`
AuthTimeout int `yaml:"authTimeout"`
} `yaml:"apiauthentication"`
},
}
var mockProxy proxy.Proxies
newproxy:=proxy.NewProxies(zap.NewNop(),proxyInstrumenter,proxyTransport)
mockProxy,_=newproxy.Make(configs,proxyAuthServer.URL,"")
proxyAuthServer.URL=proxyAuthServer.URL+configs.Outbounds.APIAuthentication.AuthPath
service:=base.NewService(proxy.Proxies{ApiAuthenticationService:mockProxy.ApiAuthenticationService,OfferPrefixDataService:mockProxy.OfferPrefixDataService},true)
service=base.NewLoggingMiddleware(zap.NewNop())(service)
service = base.NewInstrumentingService(instrumenter)(service)
//Generating req
resp,_:=http.DefaultClient.Do(req)
body,_:=io.ReadAll(resp.Body)
return resp,body,false
}
Here's the line which is calling the proxy and giving error.s implements my AuthProxy:
endpointResp, err := s.ValidateEndpoint(ctx, req)
Whenever my code makes a proxy call,the proxyAuthServer is returning error like this in my debugger:
endpointResp: interface {} nil
error(*net/url.Error): *{Op: "Get", URL: "http://127.0.0.1:58807/auth", Err: error(context.deadlineExceededError) {}}
Why is my proxyAuthServer not returning the response when i have configured my endpoint to the proxyAuthServerURL and maxTimeout to be AuthTimeout.Can somebody explain
I guessed that the cause is related to timeout setting.
I think timeout/deadline can happen from two things at the view of client assuming its server has no problem.
Req with deadline context. (https://gist.github.com/orian/b54ce2b1cc3a4144b090eb5714725a43)
Client timeout (https://medium.com/@jac_ln/how-to-test-real-request-timeout-in-golang-with-httptest-dbc72ea23d1a)
Your problem is not about the deadline. So I guessed it is about 2.
We can test it easily by this code.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "This is only for test")
}))
req, _ := http.NewRequest("GET", server.URL, nil)
client := http.Client{Timeout: time.Nanosecond}
_, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
return
}