Commit aa15b3a4 authored by Janoš Guljaš's avatar Janoš Guljaš Committed by GitHub

cleanup jsonhttptest package (#577)

parent 24d5b25a
...@@ -41,9 +41,12 @@ func TestBytes(t *testing.T) { ...@@ -41,9 +41,12 @@ func TestBytes(t *testing.T) {
} }
t.Run("upload", func(t *testing.T) { t.Run("upload", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, client, http.MethodPost, resource, bytes.NewReader(content), http.StatusOK, api.BytesPostResponse{ jsonhttptest.Request(t, client, http.MethodPost, resource, http.StatusOK,
Reference: swarm.MustParseHexAddress(expHash), jsonhttptest.WithRequestBody(bytes.NewReader(content)),
}) jsonhttptest.WithExpectedJSONResponse(api.BytesPostResponse{
Reference: swarm.MustParseHexAddress(expHash),
}),
)
}) })
t.Run("download", func(t *testing.T) { t.Run("download", func(t *testing.T) {
...@@ -67,9 +70,11 @@ func TestBytes(t *testing.T) { ...@@ -67,9 +70,11 @@ func TestBytes(t *testing.T) {
}) })
t.Run("not found", func(t *testing.T) { t.Run("not found", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, client, http.MethodGet, resource+"/abcd", nil, http.StatusNotFound, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodGet, resource+"/abcd", http.StatusNotFound,
Message: "not found", jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusNotFound, Message: "not found",
}) Code: http.StatusNotFound,
}),
)
}) })
} }
...@@ -132,7 +132,9 @@ func TestBzz(t *testing.T) { ...@@ -132,7 +132,9 @@ func TestBzz(t *testing.T) {
// read file from manifest path // read file from manifest path
rcvdHeader := jsonhttptest.ResponseDirectCheckBinaryResponse(t, client, http.MethodGet, bzzDownloadResource(manifestFileReference.String(), filePath), nil, http.StatusOK, []byte(sampleHtml), nil) rcvdHeader := jsonhttptest.Request(t, client, http.MethodGet, bzzDownloadResource(manifestFileReference.String(), filePath), http.StatusOK,
jsonhttptest.WithExpectedResponse([]byte(sampleHtml)),
)
cd := rcvdHeader.Get("Content-Disposition") cd := rcvdHeader.Get("Content-Disposition")
_, params, err := mime.ParseMediaType(cd) _, params, err := mime.ParseMediaType(cd)
if err != nil { if err != nil {
...@@ -150,11 +152,12 @@ func TestBzz(t *testing.T) { ...@@ -150,11 +152,12 @@ func TestBzz(t *testing.T) {
// check on invalid path // check on invalid path
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodGet, bzzDownloadResource(manifestFileReference.String(), missingFilePath), nil, http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodGet, bzzDownloadResource(manifestFileReference.String(), missingFilePath), http.StatusBadRequest,
Message: "invalid path address", jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusBadRequest, Message: "invalid path address",
}, nil) Code: http.StatusBadRequest,
}),
)
}) })
} }
...@@ -44,30 +44,39 @@ func TestChunkUploadDownload(t *testing.T) { ...@@ -44,30 +44,39 @@ func TestChunkUploadDownload(t *testing.T) {
) )
t.Run("invalid hash", func(t *testing.T) { t.Run("invalid hash", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, client, http.MethodPost, resource(invalidHash), bytes.NewReader(validContent), http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodPost, resource(invalidHash), http.StatusBadRequest,
Message: "chunk write error", jsonhttptest.WithRequestBody(bytes.NewReader(validContent)),
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
}) Message: "chunk write error",
Code: http.StatusBadRequest,
}),
)
// make sure chunk is not retrievable // make sure chunk is not retrievable
_ = request(t, client, http.MethodGet, resource(invalidHash), nil, http.StatusNotFound) _ = request(t, client, http.MethodGet, resource(invalidHash), nil, http.StatusNotFound)
}) })
t.Run("invalid content", func(t *testing.T) { t.Run("invalid content", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, client, http.MethodPost, resource(validHash), bytes.NewReader(invalidContent), http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodPost, resource(invalidHash), http.StatusBadRequest,
Message: "chunk write error", jsonhttptest.WithRequestBody(bytes.NewReader(invalidContent)),
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
}) Message: "chunk write error",
Code: http.StatusBadRequest,
}),
)
// make sure not retrievable // make sure not retrievable
_ = request(t, client, http.MethodGet, resource(validHash), nil, http.StatusNotFound) _ = request(t, client, http.MethodGet, resource(validHash), nil, http.StatusNotFound)
}) })
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, client, http.MethodPost, resource(validHash), bytes.NewReader(validContent), http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodPost, resource(validHash), http.StatusOK,
Message: http.StatusText(http.StatusOK), jsonhttptest.WithRequestBody(bytes.NewReader(validContent)),
Code: http.StatusOK, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
}) Message: http.StatusText(http.StatusOK),
Code: http.StatusOK,
}),
)
// try to fetch the same chunk // try to fetch the same chunk
resp := request(t, client, http.MethodGet, resource(validHash), nil, http.StatusOK) resp := request(t, client, http.MethodGet, resource(validHash), nil, http.StatusOK)
...@@ -82,12 +91,14 @@ func TestChunkUploadDownload(t *testing.T) { ...@@ -82,12 +91,14 @@ func TestChunkUploadDownload(t *testing.T) {
}) })
t.Run("pin-invalid-value", func(t *testing.T) { t.Run("pin-invalid-value", func(t *testing.T) {
headers := make(map[string][]string) jsonhttptest.Request(t, client, http.MethodPost, resource(validHash), http.StatusOK,
headers[api.SwarmPinHeader] = []string{"hdgdh"} jsonhttptest.WithRequestBody(bytes.NewReader(validContent)),
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, resource(validHash), bytes.NewReader(validContent), http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusOK), Message: http.StatusText(http.StatusOK),
Code: http.StatusOK, Code: http.StatusOK,
}, headers) }),
jsonhttptest.WithRequestHeader(api.SwarmPinHeader, "invalid-pin"),
)
// Also check if the chunk is NOT pinned // Also check if the chunk is NOT pinned
if mockValidatingStorer.GetModeSet(validHash) == storage.ModeSetPin { if mockValidatingStorer.GetModeSet(validHash) == storage.ModeSetPin {
...@@ -95,11 +106,13 @@ func TestChunkUploadDownload(t *testing.T) { ...@@ -95,11 +106,13 @@ func TestChunkUploadDownload(t *testing.T) {
} }
}) })
t.Run("pin-header-missing", func(t *testing.T) { t.Run("pin-header-missing", func(t *testing.T) {
headers := make(map[string][]string) jsonhttptest.Request(t, client, http.MethodPost, resource(validHash), http.StatusOK,
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, resource(validHash), bytes.NewReader(validContent), http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.WithRequestBody(bytes.NewReader(validContent)),
Message: http.StatusText(http.StatusOK), jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusOK, Message: http.StatusText(http.StatusOK),
}, headers) Code: http.StatusOK,
}),
)
// Also check if the chunk is NOT pinned // Also check if the chunk is NOT pinned
if mockValidatingStorer.GetModeSet(validHash) == storage.ModeSetPin { if mockValidatingStorer.GetModeSet(validHash) == storage.ModeSetPin {
...@@ -107,12 +120,14 @@ func TestChunkUploadDownload(t *testing.T) { ...@@ -107,12 +120,14 @@ func TestChunkUploadDownload(t *testing.T) {
} }
}) })
t.Run("pin-ok", func(t *testing.T) { t.Run("pin-ok", func(t *testing.T) {
headers := make(map[string][]string) jsonhttptest.Request(t, client, http.MethodPost, resource(validHash), http.StatusOK,
headers[api.SwarmPinHeader] = []string{"True"} jsonhttptest.WithRequestBody(bytes.NewReader(validContent)),
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, resource(validHash), bytes.NewReader(validContent), http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusOK), Message: http.StatusText(http.StatusOK),
Code: http.StatusOK, Code: http.StatusOK,
}, headers) }),
jsonhttptest.WithRequestHeader(api.SwarmPinHeader, "True"),
)
// Also check if the chunk is pinned // Also check if the chunk is pinned
if mockValidatingStorer.GetModePut(validHash) != storage.ModePutUploadPin { if mockValidatingStorer.GetModePut(validHash) != storage.ModePutUploadPin {
......
...@@ -34,23 +34,27 @@ func TestDirs(t *testing.T) { ...@@ -34,23 +34,27 @@ func TestDirs(t *testing.T) {
) )
t.Run("empty request body", func(t *testing.T) { t.Run("empty request body", func(t *testing.T) {
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, dirUploadResource, bytes.NewReader(nil), http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodPost, dirUploadResource, http.StatusBadRequest,
Message: "could not validate request", jsonhttptest.WithRequestBody(bytes.NewReader(nil)),
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
}, http.Header{ Message: "could not validate request",
"Content-Type": {api.ContentTypeTar}, Code: http.StatusBadRequest,
}) }),
jsonhttptest.WithRequestHeader("Content-Type", api.ContentTypeTar),
)
}) })
t.Run("non tar file", func(t *testing.T) { t.Run("non tar file", func(t *testing.T) {
file := bytes.NewReader([]byte("some data")) file := bytes.NewReader([]byte("some data"))
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, dirUploadResource, file, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodPost, dirUploadResource, http.StatusInternalServerError,
Message: "could not store dir", jsonhttptest.WithRequestBody(file),
Code: http.StatusInternalServerError, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
}, http.Header{ Message: "could not store dir",
"Content-Type": {api.ContentTypeTar}, Code: http.StatusInternalServerError,
}) }),
jsonhttptest.WithRequestHeader("Content-Type", api.ContentTypeTar),
)
}) })
t.Run("wrong content type", func(t *testing.T) { t.Run("wrong content type", func(t *testing.T) {
...@@ -60,12 +64,14 @@ func TestDirs(t *testing.T) { ...@@ -60,12 +64,14 @@ func TestDirs(t *testing.T) {
}}) }})
// submit valid tar, but with wrong content-type // submit valid tar, but with wrong content-type
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, dirUploadResource, tarReader, http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, client, http.MethodPost, dirUploadResource, http.StatusBadRequest,
Message: "could not validate request", jsonhttptest.WithRequestBody(tarReader),
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
}, http.Header{ Message: "could not validate request",
"Content-Type": {"other"}, Code: http.StatusBadRequest,
}) }),
jsonhttptest.WithRequestHeader("Content-Type", "other"),
)
}) })
// valid tars // valid tars
...@@ -137,11 +143,13 @@ func TestDirs(t *testing.T) { ...@@ -137,11 +143,13 @@ func TestDirs(t *testing.T) {
tarReader := tarFiles(t, tc.files) tarReader := tarFiles(t, tc.files)
// verify directory tar upload response // verify directory tar upload response
jsonhttptest.ResponseDirectSendHeadersAndReceiveHeaders(t, client, http.MethodPost, dirUploadResource, tarReader, http.StatusOK, api.FileUploadResponse{ jsonhttptest.Request(t, client, http.MethodPost, dirUploadResource, http.StatusOK,
Reference: swarm.MustParseHexAddress(tc.expectedHash), jsonhttptest.WithRequestBody(tarReader),
}, http.Header{ jsonhttptest.WithExpectedJSONResponse(api.FileUploadResponse{
"Content-Type": {api.ContentTypeTar}, Reference: swarm.MustParseHexAddress(tc.expectedHash),
}) }),
jsonhttptest.WithRequestHeader("Content-Type", api.ContentTypeTar),
)
// create expected manifest // create expected manifest
expectedManifest := jsonmanifest.NewManifest() expectedManifest := jsonmanifest.NewManifest()
...@@ -156,7 +164,9 @@ func TestDirs(t *testing.T) { ...@@ -156,7 +164,9 @@ func TestDirs(t *testing.T) {
} }
// verify directory upload manifest through files api // verify directory upload manifest through files api
jsonhttptest.ResponseDirectCheckBinaryResponse(t, client, http.MethodGet, fileDownloadResource(tc.expectedHash), nil, http.StatusOK, b, nil) jsonhttptest.Request(t, client, http.MethodGet, fileDownloadResource(tc.expectedHash), http.StatusOK,
jsonhttptest.WithExpectedResponse(b),
)
}) })
} }
} }
......
This diff is collapsed.
This diff is collapsed.
...@@ -48,7 +48,9 @@ func TestBalances(t *testing.T) { ...@@ -48,7 +48,9 @@ func TestBalances(t *testing.T) {
// We expect a list of items unordered by peer: // We expect a list of items unordered by peer:
var got *debugapi.BalancesResponse var got *debugapi.BalancesResponse
jsonhttptest.ResponseUnmarshal(t, testServer.Client, http.MethodGet, "/balances", nil, http.StatusOK, &got) jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/balances", http.StatusOK,
jsonhttptest.WithUnmarshalJSONResponse(&got),
)
if !equalBalances(got, expected) { if !equalBalances(got, expected) {
t.Errorf("got balances: %v, expected: %v", got, expected) t.Errorf("got balances: %v, expected: %v", got, expected)
...@@ -65,10 +67,12 @@ func TestBalancesError(t *testing.T) { ...@@ -65,10 +67,12 @@ func TestBalancesError(t *testing.T) {
AccountingOpts: []mock.Option{mock.WithBalancesFunc(balancesFunc)}, AccountingOpts: []mock.Option{mock.WithBalancesFunc(balancesFunc)},
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/balances", nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/balances", http.StatusInternalServerError,
Message: debugapi.ErrCantBalances, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusInternalServerError, Message: debugapi.ErrCantBalances,
}) Code: http.StatusInternalServerError,
}),
)
} }
func TestBalancesPeers(t *testing.T) { func TestBalancesPeers(t *testing.T) {
...@@ -80,10 +84,12 @@ func TestBalancesPeers(t *testing.T) { ...@@ -80,10 +84,12 @@ func TestBalancesPeers(t *testing.T) {
AccountingOpts: []mock.Option{mock.WithBalanceFunc(balanceFunc)}, AccountingOpts: []mock.Option{mock.WithBalanceFunc(balanceFunc)},
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/balances/"+peer, nil, http.StatusOK, debugapi.BalanceResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/balances/"+peer, http.StatusOK,
Peer: peer, jsonhttptest.WithExpectedJSONResponse(debugapi.BalanceResponse{
Balance: 1000000000000000000, Peer: peer,
}) Balance: 1000000000000000000,
}),
)
} }
func TestBalancesPeersError(t *testing.T) { func TestBalancesPeersError(t *testing.T) {
...@@ -96,10 +102,12 @@ func TestBalancesPeersError(t *testing.T) { ...@@ -96,10 +102,12 @@ func TestBalancesPeersError(t *testing.T) {
AccountingOpts: []mock.Option{mock.WithBalanceFunc(balanceFunc)}, AccountingOpts: []mock.Option{mock.WithBalanceFunc(balanceFunc)},
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/balances/"+peer, nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/balances/"+peer, http.StatusInternalServerError,
Message: debugapi.ErrCantBalance, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusInternalServerError, Message: debugapi.ErrCantBalance,
}) Code: http.StatusInternalServerError,
}),
)
} }
func TestBalancesInvalidAddress(t *testing.T) { func TestBalancesInvalidAddress(t *testing.T) {
...@@ -107,10 +115,12 @@ func TestBalancesInvalidAddress(t *testing.T) { ...@@ -107,10 +115,12 @@ func TestBalancesInvalidAddress(t *testing.T) {
testServer := newTestServer(t, testServerOptions{}) testServer := newTestServer(t, testServerOptions{})
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/balances/"+peer, nil, http.StatusNotFound, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/balances/"+peer, http.StatusNotFound,
Message: debugapi.ErrInvaliAddress, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusNotFound, Message: debugapi.ErrInvaliAddress,
}) Code: http.StatusNotFound,
}),
)
} }
func equalBalances(a, b *debugapi.BalancesResponse) bool { func equalBalances(a, b *debugapi.BalancesResponse) bool {
......
...@@ -31,31 +31,39 @@ func TestHasChunkHandler(t *testing.T) { ...@@ -31,31 +31,39 @@ func TestHasChunkHandler(t *testing.T) {
} }
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/chunks/"+key.String(), nil, http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/chunks/"+key.String(), http.StatusOK,
Message: http.StatusText(http.StatusOK), jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusOK, Message: http.StatusText(http.StatusOK),
}) Code: http.StatusOK,
}),
)
}) })
t.Run("not found", func(t *testing.T) { t.Run("not found", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/chunks/abbbbb", nil, http.StatusNotFound, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/chunks/abbbbb", http.StatusNotFound,
Message: http.StatusText(http.StatusNotFound), jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusNotFound, Message: http.StatusText(http.StatusNotFound),
}) Code: http.StatusNotFound,
}),
)
}) })
t.Run("bad address", func(t *testing.T) { t.Run("bad address", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/chunks/abcd1100zz", nil, http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/chunks/abcd1100zz", http.StatusBadRequest,
Message: "bad address", jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusBadRequest, Message: "bad address",
}) Code: http.StatusBadRequest,
}),
)
}) })
t.Run("remove-chunk", func(t *testing.T) { t.Run("remove-chunk", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodDelete, "/chunks/"+key.String(), nil, http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodDelete, "/chunks/"+key.String(), http.StatusOK,
Message: http.StatusText(http.StatusOK), jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusOK, Message: http.StatusText(http.StatusOK),
}) Code: http.StatusOK,
}),
)
yes, err := mockStorer.Has(context.Background(), key) yes, err := mockStorer.Has(context.Background(), key)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
...@@ -67,10 +75,12 @@ func TestHasChunkHandler(t *testing.T) { ...@@ -67,10 +75,12 @@ func TestHasChunkHandler(t *testing.T) {
t.Run("remove-not-present-chunk", func(t *testing.T) { t.Run("remove-not-present-chunk", func(t *testing.T) {
notPresentChunkAddress := "deadbeef" notPresentChunkAddress := "deadbeef"
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodDelete, "/chunks/"+notPresentChunkAddress, nil, http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodDelete, "/chunks/"+notPresentChunkAddress, http.StatusOK,
Message: http.StatusText(http.StatusOK), jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusOK, Message: http.StatusText(http.StatusOK),
}) Code: http.StatusOK,
}),
)
yes, err := mockStorer.Has(context.Background(), swarm.NewAddress([]byte(notPresentChunkAddress))) yes, err := mockStorer.Has(context.Background(), swarm.NewAddress([]byte(notPresentChunkAddress)))
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
......
...@@ -33,17 +33,21 @@ func TestAddresses(t *testing.T) { ...@@ -33,17 +33,21 @@ func TestAddresses(t *testing.T) {
}) })
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/addresses", nil, http.StatusOK, debugapi.AddressesResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/addresses", http.StatusOK,
Overlay: overlay, jsonhttptest.WithExpectedJSONResponse(debugapi.AddressesResponse{
Underlay: addresses, Overlay: overlay,
}) Underlay: addresses,
}),
)
}) })
t.Run("post method not allowed", func(t *testing.T) { t.Run("post method not allowed", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodPost, "/addresses", nil, http.StatusMethodNotAllowed, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodPost, "/addresses", http.StatusMethodNotAllowed,
Code: http.StatusMethodNotAllowed, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusMethodNotAllowed), Code: http.StatusMethodNotAllowed,
}) Message: http.StatusText(http.StatusMethodNotAllowed),
}),
)
}) })
} }
...@@ -56,8 +60,10 @@ func TestAddresses_error(t *testing.T) { ...@@ -56,8 +60,10 @@ func TestAddresses_error(t *testing.T) {
})), })),
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/addresses", nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/addresses", http.StatusInternalServerError,
Code: http.StatusInternalServerError, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: testErr.Error(), Code: http.StatusInternalServerError,
}) Message: testErr.Error(),
}),
)
} }
...@@ -55,26 +55,32 @@ func TestConnect(t *testing.T) { ...@@ -55,26 +55,32 @@ func TestConnect(t *testing.T) {
}) })
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodPost, "/connect"+underlay, nil, http.StatusOK, debugapi.PeerConnectResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodPost, "/connect"+underlay, http.StatusOK,
Address: overlay.String(), jsonhttptest.WithExpectedJSONResponse(debugapi.PeerConnectResponse{
}) Address: overlay.String(),
}),
)
if testServer.P2PMock.ConnectNotifyCalls() != 1 { if testServer.P2PMock.ConnectNotifyCalls() != 1 {
t.Fatal("connect notify not called") t.Fatal("connect notify not called")
} }
}) })
t.Run("error", func(t *testing.T) { t.Run("error", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodPost, "/connect"+errorUnderlay, nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodPost, "/connect"+errorUnderlay, http.StatusInternalServerError,
Code: http.StatusInternalServerError, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: testErr.Error(), Code: http.StatusInternalServerError,
}) Message: testErr.Error(),
}),
)
}) })
t.Run("get method not allowed", func(t *testing.T) { t.Run("get method not allowed", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/connect"+underlay, nil, http.StatusMethodNotAllowed, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/connect"+underlay, http.StatusMethodNotAllowed,
Code: http.StatusMethodNotAllowed, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusMethodNotAllowed), Code: http.StatusMethodNotAllowed,
}) Message: http.StatusText(http.StatusMethodNotAllowed),
}),
)
}) })
t.Run("error - add peer", func(t *testing.T) { t.Run("error - add peer", func(t *testing.T) {
...@@ -87,10 +93,12 @@ func TestConnect(t *testing.T) { ...@@ -87,10 +93,12 @@ func TestConnect(t *testing.T) {
})), })),
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodPost, "/connect"+errorUnderlay, nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodPost, "/connect"+errorUnderlay, http.StatusInternalServerError,
Code: http.StatusInternalServerError, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: testErr.Error(), Code: http.StatusInternalServerError,
}) Message: testErr.Error(),
}),
)
}) })
} }
...@@ -115,31 +123,39 @@ func TestDisconnect(t *testing.T) { ...@@ -115,31 +123,39 @@ func TestDisconnect(t *testing.T) {
}) })
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodDelete, "/peers/"+address.String(), nil, http.StatusOK, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodDelete, "/peers/"+address.String(), http.StatusOK,
Code: http.StatusOK, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusOK), Code: http.StatusOK,
}) Message: http.StatusText(http.StatusOK),
}),
)
}) })
t.Run("unknown", func(t *testing.T) { t.Run("unknown", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodDelete, "/peers/"+unknownAdddress.String(), nil, http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodDelete, "/peers/"+unknownAdddress.String(), http.StatusBadRequest,
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: "peer not found", Code: http.StatusBadRequest,
}) Message: "peer not found",
}),
)
}) })
t.Run("invalid peer address", func(t *testing.T) { t.Run("invalid peer address", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodDelete, "/peers/invalid-address", nil, http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodDelete, "/peers/invalid-address", http.StatusBadRequest,
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: "invalid peer address", Code: http.StatusBadRequest,
}) Message: "invalid peer address",
}),
)
}) })
t.Run("error", func(t *testing.T) { t.Run("error", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodDelete, "/peers/"+errorAddress.String(), nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodDelete, "/peers/"+errorAddress.String(), http.StatusInternalServerError,
Code: http.StatusInternalServerError, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: testErr.Error(), Code: http.StatusInternalServerError,
}) Message: testErr.Error(),
}),
)
}) })
} }
...@@ -152,15 +168,19 @@ func TestPeer(t *testing.T) { ...@@ -152,15 +168,19 @@ func TestPeer(t *testing.T) {
}) })
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/peers", nil, http.StatusOK, debugapi.PeersResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/peers", http.StatusOK,
Peers: []p2p.Peer{{Address: overlay}}, jsonhttptest.WithExpectedJSONResponse(debugapi.PeersResponse{
}) Peers: []p2p.Peer{{Address: overlay}},
}),
)
}) })
t.Run("get method not allowed", func(t *testing.T) { t.Run("get method not allowed", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodPost, "/peers", nil, http.StatusMethodNotAllowed, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodPost, "/peers", http.StatusMethodNotAllowed,
Code: http.StatusMethodNotAllowed, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusMethodNotAllowed), Code: http.StatusMethodNotAllowed,
}) Message: http.StatusText(http.StatusMethodNotAllowed),
}),
)
}) })
} }
This diff is collapsed.
...@@ -41,36 +41,46 @@ func TestPingpong(t *testing.T) { ...@@ -41,36 +41,46 @@ func TestPingpong(t *testing.T) {
}) })
t.Run("ok", func(t *testing.T) { t.Run("ok", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, ts.Client, http.MethodPost, "/pingpong/"+peerID.String(), nil, http.StatusOK, debugapi.PingpongResponse{ jsonhttptest.Request(t, ts.Client, http.MethodPost, "/pingpong/"+peerID.String(), http.StatusOK,
RTT: rtt.String(), jsonhttptest.WithExpectedJSONResponse(debugapi.PingpongResponse{
}) RTT: rtt.String(),
}),
)
}) })
t.Run("peer not found", func(t *testing.T) { t.Run("peer not found", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, ts.Client, http.MethodPost, "/pingpong/"+unknownPeerID.String(), nil, http.StatusNotFound, jsonhttp.StatusResponse{ jsonhttptest.Request(t, ts.Client, http.MethodPost, "/pingpong/"+unknownPeerID.String(), http.StatusNotFound,
Code: http.StatusNotFound, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: "peer not found", Code: http.StatusNotFound,
}) Message: "peer not found",
}),
)
}) })
t.Run("invalid peer address", func(t *testing.T) { t.Run("invalid peer address", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, ts.Client, http.MethodPost, "/pingpong/invalid-address", nil, http.StatusBadRequest, jsonhttp.StatusResponse{ jsonhttptest.Request(t, ts.Client, http.MethodPost, "/pingpong/invalid-address", http.StatusBadRequest,
Code: http.StatusBadRequest, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: "invalid peer address", Code: http.StatusBadRequest,
}) Message: "invalid peer address",
}),
)
}) })
t.Run("error", func(t *testing.T) { t.Run("error", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, ts.Client, http.MethodPost, "/pingpong/"+errorPeerID.String(), nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, ts.Client, http.MethodPost, "/pingpong/"+errorPeerID.String(), http.StatusInternalServerError,
Code: http.StatusInternalServerError, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusInternalServerError), // do not leak internal error Code: http.StatusInternalServerError,
}) Message: http.StatusText(http.StatusInternalServerError), // do not leak internal error
}),
)
}) })
t.Run("get method not allowed", func(t *testing.T) { t.Run("get method not allowed", func(t *testing.T) {
jsonhttptest.ResponseDirect(t, ts.Client, http.MethodGet, "/pingpong/"+peerID.String(), nil, http.StatusMethodNotAllowed, jsonhttp.StatusResponse{ jsonhttptest.Request(t, ts.Client, http.MethodGet, "/pingpong/"+peerID.String(), http.StatusMethodNotAllowed,
Code: http.StatusMethodNotAllowed, jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Message: http.StatusText(http.StatusMethodNotAllowed), Code: http.StatusMethodNotAllowed,
}) Message: http.StatusText(http.StatusMethodNotAllowed),
}),
)
}) })
} }
...@@ -15,15 +15,19 @@ import ( ...@@ -15,15 +15,19 @@ import (
func TestHealth(t *testing.T) { func TestHealth(t *testing.T) {
testServer := newTestServer(t, testServerOptions{}) testServer := newTestServer(t, testServerOptions{})
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/health", nil, http.StatusOK, debugapi.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/health", http.StatusOK,
Status: "ok", jsonhttptest.WithExpectedJSONResponse(debugapi.StatusResponse{
}) Status: "ok",
}),
)
} }
func TestReadiness(t *testing.T) { func TestReadiness(t *testing.T) {
testServer := newTestServer(t, testServerOptions{}) testServer := newTestServer(t, testServerOptions{})
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/readiness", nil, http.StatusOK, debugapi.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/readiness", http.StatusOK,
Status: "ok", jsonhttptest.WithExpectedJSONResponse(debugapi.StatusResponse{
}) Status: "ok",
}),
)
} }
...@@ -27,9 +27,11 @@ func TestTopologyOK(t *testing.T) { ...@@ -27,9 +27,11 @@ func TestTopologyOK(t *testing.T) {
TopologyOpts: []topmock.Option{topmock.WithMarshalJSONFunc(marshalFunc)}, TopologyOpts: []topmock.Option{topmock.WithMarshalJSONFunc(marshalFunc)},
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/topology", nil, http.StatusOK, topologyResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/topology", http.StatusOK,
Topology: "abcd", jsonhttptest.WithExpectedJSONResponse(topologyResponse{
}) Topology: "abcd",
}),
)
} }
func TestTopologyError(t *testing.T) { func TestTopologyError(t *testing.T) {
...@@ -40,8 +42,10 @@ func TestTopologyError(t *testing.T) { ...@@ -40,8 +42,10 @@ func TestTopologyError(t *testing.T) {
TopologyOpts: []topmock.Option{topmock.WithMarshalJSONFunc(marshalFunc)}, TopologyOpts: []topmock.Option{topmock.WithMarshalJSONFunc(marshalFunc)},
}) })
jsonhttptest.ResponseDirect(t, testServer.Client, http.MethodGet, "/topology", nil, http.StatusInternalServerError, jsonhttp.StatusResponse{ jsonhttptest.Request(t, testServer.Client, http.MethodGet, "/topology", http.StatusInternalServerError,
Message: "error", jsonhttptest.WithExpectedJSONResponse(jsonhttp.StatusResponse{
Code: http.StatusInternalServerError, Message: "error",
}) Code: http.StatusInternalServerError,
}),
)
} }
...@@ -25,9 +25,11 @@ func TestGetWelcomeMessage(t *testing.T) { ...@@ -25,9 +25,11 @@ func TestGetWelcomeMessage(t *testing.T) {
return DefaultTestWelcomeMessage return DefaultTestWelcomeMessage
}))}) }))})
jsonhttptest.ResponseDirect(t, srv.Client, http.MethodGet, "/welcome-message", nil, http.StatusOK, debugapi.WelcomeMessageResponse{ jsonhttptest.Request(t, srv.Client, http.MethodGet, "/welcome-message", http.StatusOK,
WelcomeMesssage: DefaultTestWelcomeMessage, jsonhttptest.WithExpectedJSONResponse(debugapi.WelcomeMessageResponse{
}) WelcomeMesssage: DefaultTestWelcomeMessage,
}),
)
} }
func TestSetWelcomeMessage(t *testing.T) { func TestSetWelcomeMessage(t *testing.T) {
...@@ -81,7 +83,10 @@ func TestSetWelcomeMessage(t *testing.T) { ...@@ -81,7 +83,10 @@ func TestSetWelcomeMessage(t *testing.T) {
Message: tC.wantMessage, Message: tC.wantMessage,
Code: tC.wantStatus, Code: tC.wantStatus,
} }
jsonhttptest.ResponseDirect(t, srv.Client, http.MethodPost, testURL, body, tC.wantStatus, wantResponse) jsonhttptest.Request(t, srv.Client, http.MethodPost, testURL, tC.wantStatus,
jsonhttptest.WithRequestBody(body),
jsonhttptest.WithExpectedJSONResponse(wantResponse),
)
if !tC.wantFail { if !tC.wantFail {
got := srv.P2PMock.GetWelcomeMessage() got := srv.P2PMock.GetWelcomeMessage()
if got != tC.message { if got != tC.message {
...@@ -113,7 +118,10 @@ func TestSetWelcomeMessageInternalServerError(t *testing.T) { ...@@ -113,7 +118,10 @@ func TestSetWelcomeMessageInternalServerError(t *testing.T) {
Message: testError.Error(), Message: testError.Error(),
Code: wantCode, Code: wantCode,
} }
jsonhttptest.ResponseDirect(t, srv.Client, http.MethodPost, testURL, body, wantCode, wantResp) jsonhttptest.Request(t, srv.Client, http.MethodPost, testURL, wantCode,
jsonhttptest.WithRequestBody(body),
jsonhttptest.WithExpectedJSONResponse(wantResp),
)
}) })
} }
This diff is collapsed.
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonhttptest_test
import (
"errors"
"fmt"
"testing"
)
// assert is a test helper that validates a functionality of another helper
// function by mocking Errorf, Fatal and Helper methods on testing.TB.
func assert(t *testing.T, wantError, wantFatal string, f func(m *mock)) {
t.Helper()
defer func() {
if v := recover(); v != nil {
if err, ok := v.(error); ok && errors.Is(err, errFailed) {
return // execution of the goroutine is stopped by a mock Fatal function
}
t.Fatalf("panic: %v", v)
}
}()
m := &mock{
wantError: wantError,
wantFatal: wantFatal,
}
f(m)
if !m.isHelper { // Request function is tested and it must be always a helper
t.Error("not a helper function")
}
if m.gotError != m.wantError {
t.Errorf("got error %q, want %q", m.gotError, m.wantError)
}
if m.gotFatal != m.wantFatal {
t.Errorf("got error %v, want %v", m.gotFatal, m.wantFatal)
}
}
// mock provides the same interface as testing.TB with overridden Errorf, Fatal
// and Heleper methods.
type mock struct {
testing.TB
isHelper bool
gotError string
wantError string
gotFatal string
wantFatal string
}
func (m *mock) Helper() {
m.isHelper = true
}
func (m *mock) Errorf(format string, args ...interface{}) {
m.gotError = fmt.Sprintf(format, args...)
}
func (m *mock) Fatal(args ...interface{}) {
m.gotFatal = fmt.Sprint(args...)
panic(errFailed) // terminate the goroutine to detect it in the assert function
}
var errFailed = errors.New("failed")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment