'Golang Test EOF after client.Do(req)
I am using an application using the Gin framework. I am writing a test for one of my handlers:
package controllers
import (
"bytes"
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
".x.x.x./driver/database/elastic"
".x.x.x./driver/database/mysql"
".x.x.x./driver/locale"
".x.x.x./driver/server/request/client"
".x.x.x./presenter/api/config"
"testing"
)
func init() {
config.Read()
config.SetSentry()
config.SetStructsDefaultTag("json")
mysql.Setup()
elastic.Setup()
locale.Setup()
}
func TestClientBasketCtrl_AddItem(t *testing.T) {
deviceId := "20b15b3f-8d8c-4a24-87c5-461a5d2bf0c8"
userId := "0153783d-9971-4e4f-8cc3-3a3bc55d2268"
serviceName := "payment"
productId := "49f94d8f-5cdc-4325-9468-18b78e242130"
count := uint(1)
extra := "qqq"
reqBody := client.BasketAddReq{
DeviceId: deviceId,
UserId: userId,
ServiceName: serviceName,
ProductId: productId,
Count: count,
Extra: extra,
}
jsn, err := json.Marshal(reqBody)
if err != nil {
t.Fatalf("Error: %v", err)
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, _ := gin.CreateTestContext(w)
jsnTest, _ := json.Marshal(reqBody)
r.Body = ioutil.NopCloser(bytes.NewReader(jsnTest))
r.Header.Set("Content-Type", "application/json")
c.Request = r
new(ClientBasketCtrl).AddItem(c)
}))
defer ts.Close()
clnt := &http.Client{}
req, err := http.NewRequest(http.MethodPost, ts.URL, bytes.NewBuffer(jsn))
req.Header.Set("Content-Type", "application/json")
req.Close = true
resp, err := clnt.Do(req)
if err != nil { //HERE err HAPPENS
t.Fatalf("Error: %v", err)
}
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
The error seems to happen when you are not closing the request and I have added req.Close = true to the code but the error still remains. What's wrong with my code?
I have mentioned by comments (//HERE err HAPPENS) that where the error happens. The err is like this (on the debugger).
err = {error | *url.Error}
OP = {string} "POST"
URL = {string} "http://127.0.0.1:41687"
Err = {error | *errors.errorString} EOF
s = {string} "EOF"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
