Commit 9a4a1d48 authored by Nick Thomas's avatar Nick Thomas

Merge branch 'jv-more-require-3' into 'master'

Make more use of testify/require

See merge request gitlab-org/gitlab-workhorse!573
parents d427c150 2460bbbb
......@@ -14,6 +14,8 @@ import (
"gitlab.com/gitlab-org/gitlab-workhorse/internal/secret"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/upstream/roundtripper"
"github.com/stretchr/testify/require"
)
func okHandler(w http.ResponseWriter, _ *http.Request, _ *api.Response) {
......@@ -38,7 +40,7 @@ func runPreAuthorizeHandler(t *testing.T, ts *httptest.Server, suffix string, ur
response := httptest.NewRecorder()
a.PreAuthorizeHandler(okHandler, suffix).ServeHTTP(response, httpRequest)
testhelper.RequireResponseCode(t, response, expectedCode)
require.Equal(t, expectedCode, response.Code)
return response
}
......
......@@ -4,13 +4,16 @@ package main
import (
"archive/tar"
"bufio"
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path"
"regexp"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
......@@ -317,7 +320,7 @@ func TestAllowedGetGitFormatPatch(t *testing.T) {
assert.Equal(t, 200, resp.StatusCode, "GET %q: status code", resp.Request.URL)
assertNginxResponseBuffering(t, "no", resp, "GET %q: nginx response buffering", resp.Request.URL)
testhelper.RequirePatchSeries(
requirePatchSeries(
t,
body,
"372ab6950519549b14d220271ee2322caa44d4eb",
......@@ -327,3 +330,29 @@ func TestAllowedGetGitFormatPatch(t *testing.T) {
rightCommit,
)
}
var extractPatchSeriesMatcher = regexp.MustCompile(`^From (\w+)`)
// RequirePatchSeries takes a `git format-patch` blob, extracts the From xxxxx
// lines and compares the SHAs to expected list.
func requirePatchSeries(t *testing.T, blob []byte, expected ...string) {
t.Helper()
var actual []string
footer := make([]string, 3)
scanner := bufio.NewScanner(bytes.NewReader(blob))
for scanner.Scan() {
line := scanner.Text()
if matches := extractPatchSeriesMatcher.FindStringSubmatch(line); len(matches) == 2 {
actual = append(actual, matches[1])
}
footer = []string{footer[1], footer[2], line}
}
require.Equal(t, strings.Join(expected, "\n"), strings.Join(actual, "\n"), "patch series")
// Check the last returned patch is complete
// Don't assert on the final line, it is a git version
require.Equal(t, "-- ", footer[0], "end of patch marker")
}
......@@ -136,7 +136,7 @@ func TestUploadHandlerSendingToExternalStorage(t *testing.T) {
contentBuffer, contentType := createTestMultipartForm(t, archiveData)
response := testUploadArtifacts(t, contentType, ts.URL+Path, &contentBuffer)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseHeader(t, response, MetadataHeaderKey, MetadataHeaderPresent)
assert.Equal(t, 1, storeServerCalled, "store should be called only once")
assert.Equal(t, 1, responseProcessorCalled, "response processor should be called only once")
......@@ -167,7 +167,7 @@ func TestUploadHandlerSendingToExternalStorageAndStorageServerUnreachable(t *tes
defer ts.Close()
response := testUploadArtifactsFromTestZip(t, ts)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
}
func TestUploadHandlerSendingToExternalStorageAndInvalidURLIsUsed(t *testing.T) {
......@@ -193,7 +193,7 @@ func TestUploadHandlerSendingToExternalStorageAndInvalidURLIsUsed(t *testing.T)
defer ts.Close()
response := testUploadArtifactsFromTestZip(t, ts)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
}
func TestUploadHandlerSendingToExternalStorageAndItReturnsAnError(t *testing.T) {
......@@ -231,7 +231,7 @@ func TestUploadHandlerSendingToExternalStorageAndItReturnsAnError(t *testing.T)
defer ts.Close()
response := testUploadArtifactsFromTestZip(t, ts)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
assert.Equal(t, 1, putCalledTimes, "upload should be called only once")
}
......@@ -272,7 +272,7 @@ func TestUploadHandlerSendingToExternalStorageAndSupportRequestTimeout(t *testin
defer ts.Close()
response := testUploadArtifactsFromTestZip(t, ts)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
assert.Equal(t, 1, putCalledTimes, "upload should be called only once")
}
......@@ -308,7 +308,7 @@ func TestUploadHandlerMultipartUploadSizeLimit(t *testing.T) {
contentBuffer, contentType := createTestMultipartForm(t, make([]byte, uploadSize))
response := testUploadArtifacts(t, contentType, ts.URL+Path, &contentBuffer)
testhelper.RequireResponseCode(t, response, http.StatusRequestEntityTooLarge)
require.Equal(t, http.StatusRequestEntityTooLarge, response.Code)
// Poll because AbortMultipartUpload is async
for i := 0; os.IsMultipartUpload(test.ObjectPath) && i < 100; i++ {
......
......@@ -184,7 +184,7 @@ func TestUploadHandlerAddingMetadata(t *testing.T) {
require.NoError(t, s.writer.Close())
response := testUploadArtifacts(t, s.writer.FormDataContentType(), s.url, s.buffer)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseHeader(t, response, MetadataHeaderKey, MetadataHeaderPresent)
}
......@@ -194,7 +194,7 @@ func TestUploadHandlerForUnsupportedArchive(t *testing.T) {
require.NoError(t, s.writer.Close())
response := testUploadArtifacts(t, s.writer.FormDataContentType(), s.url, s.buffer)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseHeader(t, response, MetadataHeaderKey, MetadataHeaderMissing)
}
......@@ -208,7 +208,7 @@ func TestUploadHandlerForMultipleFiles(t *testing.T) {
require.NoError(t, s.writer.Close())
response := testUploadArtifacts(t, s.writer.FormDataContentType(), s.url, s.buffer)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
}
func TestUploadFormProcessing(t *testing.T) {
......@@ -217,7 +217,7 @@ func TestUploadFormProcessing(t *testing.T) {
require.NoError(t, s.writer.Close())
response := testUploadArtifacts(t, s.writer.FormDataContentType(), s.url, s.buffer)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
}
func TestLsifFileProcessing(t *testing.T) {
......@@ -236,7 +236,7 @@ func TestLsifFileProcessing(t *testing.T) {
require.NoError(t, s.writer.Close())
response := testUploadArtifacts(t, s.writer.FormDataContentType(), s.url, s.buffer)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseHeader(t, response, MetadataHeaderKey, MetadataHeaderPresent)
}
......@@ -256,5 +256,5 @@ func TestInvalidLsifFileProcessing(t *testing.T) {
require.NoError(t, s.writer.Close())
response := testUploadArtifacts(t, s.writer.FormDataContentType(), s.url, s.buffer)
testhelper.RequireResponseCode(t, response, http.StatusInternalServerError)
require.Equal(t, http.StatusInternalServerError, response.Code)
}
......@@ -50,12 +50,12 @@ func TestDownloadingFromValidArchive(t *testing.T) {
response := testEntryServer(t, tempFile.Name(), "test.txt")
testhelper.RequireResponseCode(t, response, 200)
require.Equal(t, 200, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Type",
"text/plain; charset=utf-8")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Disposition",
"attachment; filename=\"test.txt\"")
......@@ -84,12 +84,12 @@ func TestDownloadingFromValidHTTPArchive(t *testing.T) {
response := testEntryServer(t, fileServer.URL+"/archive.zip", "test.txt")
testhelper.RequireResponseCode(t, response, 200)
require.Equal(t, 200, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Type",
"text/plain; charset=utf-8")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Disposition",
"attachment; filename=\"test.txt\"")
......@@ -107,17 +107,17 @@ func TestDownloadingNonExistingFile(t *testing.T) {
archive.Close()
response := testEntryServer(t, tempFile.Name(), "test")
testhelper.RequireResponseCode(t, response, 404)
require.Equal(t, 404, response.Code)
}
func TestDownloadingFromInvalidArchive(t *testing.T) {
response := testEntryServer(t, "path/to/non/existing/file", "test")
testhelper.RequireResponseCode(t, response, 404)
require.Equal(t, 404, response.Code)
}
func TestIncompleteApiResponse(t *testing.T) {
response := testEntryServer(t, "", "")
testhelper.RequireResponseCode(t, response, 500)
require.Equal(t, 500, response.Code)
}
func TestDownloadingFromNonExistingHTTPArchive(t *testing.T) {
......@@ -130,5 +130,5 @@ func TestDownloadingFromNonExistingHTTPArchive(t *testing.T) {
response := testEntryServer(t, fileServer.URL+"/not-existing-archive-file.zip", "test.txt")
testhelper.RequireResponseCode(t, response, 404)
require.Equal(t, 404, response.Code)
}
......@@ -8,6 +8,8 @@ import (
"gitlab.com/gitlab-org/gitaly/proto/go/gitalypb"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"github.com/stretchr/testify/require"
)
func TestParseBasename(t *testing.T) {
......@@ -76,10 +78,10 @@ func TestSetArchiveHeaders(t *testing.T) {
setArchiveHeaders(w, testCase.in, "filename")
testhelper.RequireResponseWriterHeader(t, w, "Content-Type", testCase.out)
testhelper.RequireResponseWriterHeader(t, w, "Content-Length")
testhelper.RequireResponseWriterHeader(t, w, "Content-Disposition", `attachment; filename="filename"`)
testhelper.RequireResponseWriterHeader(t, w, "Cache-Control", "public, max-age=3600")
testhelper.RequireAbsentResponseWriterHeader(t, w, "Set-Cookie")
testhelper.RequireResponseHeader(t, w, "Content-Type", testCase.out)
testhelper.RequireResponseHeader(t, w, "Content-Length")
testhelper.RequireResponseHeader(t, w, "Content-Disposition", `attachment; filename="filename"`)
testhelper.RequireResponseHeader(t, w, "Cache-Control", "public, max-age=3600")
require.Empty(t, w.Header().Get("Set-Cookie"), "remove Set-Cookie")
}
}
......@@ -4,7 +4,7 @@ import (
"net/http/httptest"
"testing"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"github.com/stretchr/testify/require"
)
func TestSetBlobHeaders(t *testing.T) {
......@@ -13,5 +13,5 @@ func TestSetBlobHeaders(t *testing.T) {
setBlobHeaders(w)
testhelper.RequireAbsentResponseWriterHeader(t, w, "Set-Cookie")
require.Empty(t, w.Header().Get("Set-Cookie"), "remove Set-Cookie")
}
......@@ -84,12 +84,12 @@ func testEntryServer(t *testing.T, requestURL string, httpHeaders http.Header, a
func TestDownloadingUsingSendURL(t *testing.T) {
response := testEntryServer(t, "/get/request", nil, false)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Type",
"text/plain; charset=utf-8")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Disposition",
"attachment; filename=\"archive.txt\"")
......@@ -104,15 +104,15 @@ func TestDownloadingAChunkOfDataWithSendURL(t *testing.T) {
}
response := testEntryServer(t, "/get/request", httpHeaders, false)
testhelper.RequireResponseCode(t, response, http.StatusPartialContent)
require.Equal(t, http.StatusPartialContent, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Type",
"text/plain; charset=utf-8")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Disposition",
"attachment; filename=\"archive.txt\"")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Range",
"bytes 1-2/30")
......@@ -125,22 +125,22 @@ func TestAccessingAlreadyDownloadedFileWithSendURL(t *testing.T) {
}
response := testEntryServer(t, "/get/request", httpHeaders, false)
testhelper.RequireResponseCode(t, response, http.StatusNotModified)
require.Equal(t, http.StatusNotModified, response.Code)
}
func TestAccessingRedirectWithSendURL(t *testing.T) {
response := testEntryServer(t, "/get/redirect", nil, false)
testhelper.RequireResponseCode(t, response, http.StatusTemporaryRedirect)
require.Equal(t, http.StatusTemporaryRedirect, response.Code)
}
func TestAccessingAllowedRedirectWithSendURL(t *testing.T) {
response := testEntryServer(t, "/get/redirect", nil, true)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Type",
"text/plain; charset=utf-8")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Disposition",
"attachment; filename=\"archive.txt\"")
}
......@@ -153,15 +153,15 @@ func TestAccessingAllowedRedirectWithChunkOfDataWithSendURL(t *testing.T) {
}
response := testEntryServer(t, "/get/redirect", httpHeaders, true)
testhelper.RequireResponseCode(t, response, http.StatusPartialContent)
require.Equal(t, http.StatusPartialContent, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Type",
"text/plain; charset=utf-8")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Disposition",
"attachment; filename=\"archive.txt\"")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Content-Range",
"bytes 1-2/30")
......@@ -170,28 +170,28 @@ func TestAccessingAllowedRedirectWithChunkOfDataWithSendURL(t *testing.T) {
func TestOriginalCacheHeadersPreservedWithSendURL(t *testing.T) {
response := testEntryServer(t, "/get/redirect", nil, true)
testhelper.RequireResponseCode(t, response, http.StatusOK)
require.Equal(t, http.StatusOK, response.Code)
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Cache-Control",
"no-cache")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Expires",
"")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Date",
"Wed, 21 Oct 2015 05:28:00 GMT")
testhelper.RequireResponseWriterHeader(t, response,
testhelper.RequireResponseHeader(t, response,
"Pragma",
"no-cache")
}
func TestDownloadingNonExistingFileUsingSendURL(t *testing.T) {
response := testEntryServer(t, "/invalid/path", nil, false)
testhelper.RequireResponseCode(t, response, http.StatusNotFound)
require.Equal(t, http.StatusNotFound, response.Code)
}
func TestDownloadingNonExistingRemoteFileWithSendURL(t *testing.T) {
response := testEntryServer(t, "/get/file-not-existing", nil, false)
testhelper.RequireResponseCode(t, response, http.StatusNotFound)
require.Equal(t, http.StatusNotFound, response.Code)
}
......@@ -9,6 +9,8 @@ import (
"testing"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"github.com/stretchr/testify/require"
)
func TestIfNoDeployPageExist(t *testing.T) {
......@@ -52,6 +54,6 @@ func TestIfDeployPageExist(t *testing.T) {
}
w.Flush()
testhelper.RequireResponseCode(t, w, 200)
require.Equal(t, 200, w.Code)
testhelper.RequireResponseBody(t, w, deployPage)
}
......@@ -36,7 +36,7 @@ func TestIfErrorPageIsPresented(t *testing.T) {
st.ErrorPagesUnless(false, ErrorFormatHTML, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
testhelper.RequireResponseBody(t, w, errorPage)
testhelper.RequireResponseHeader(t, w, "Content-Type", "text/html; charset=utf-8")
}
......@@ -58,7 +58,7 @@ func TestIfErrorPassedIfNoErrorPageIsFound(t *testing.T) {
st.ErrorPagesUnless(false, ErrorFormatHTML, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
testhelper.RequireResponseBody(t, w, errorResponse)
}
......@@ -81,7 +81,7 @@ func TestIfErrorPageIsIgnoredInDevelopment(t *testing.T) {
st := &Static{dir}
st.ErrorPagesUnless(true, ErrorFormatHTML, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 500)
require.Equal(t, 500, w.Code)
testhelper.RequireResponseBody(t, w, serverError)
}
......@@ -105,7 +105,7 @@ func TestIfErrorPageIsIgnoredIfCustomError(t *testing.T) {
st := &Static{dir}
st.ErrorPagesUnless(false, ErrorFormatHTML, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 500)
require.Equal(t, 500, w.Code)
testhelper.RequireResponseBody(t, w, serverError)
}
......@@ -140,7 +140,7 @@ func TestErrorPageInterceptedByContentType(t *testing.T) {
st := &Static{dir}
st.ErrorPagesUnless(false, ErrorFormatHTML, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 500)
require.Equal(t, 500, w.Code)
if tc.intercepted {
testhelper.RequireResponseBody(t, w, errorPage)
......@@ -165,7 +165,7 @@ func TestIfErrorPageIsPresentedJSON(t *testing.T) {
st.ErrorPagesUnless(false, ErrorFormatJSON, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
testhelper.RequireResponseBody(t, w, errorPage)
testhelper.RequireResponseHeader(t, w, "Content-Type", "application/json; charset=utf-8")
}
......@@ -185,7 +185,7 @@ func TestIfErrorPageIsPresentedText(t *testing.T) {
st.ErrorPagesUnless(false, ErrorFormatText, h).ServeHTTP(w, nil)
w.Flush()
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
testhelper.RequireResponseBody(t, w, errorPage)
testhelper.RequireResponseHeader(t, w, "Content-Type", "text/plain; charset=utf-8")
}
......@@ -11,6 +11,8 @@ import (
"testing"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"github.com/stretchr/testify/require"
)
func TestServingNonExistingFile(t *testing.T) {
......@@ -20,7 +22,7 @@ func TestServingNonExistingFile(t *testing.T) {
w := httptest.NewRecorder()
st := &Static{dir}
st.ServeExisting("/", CacheDisabled, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
}
func TestServingDirectory(t *testing.T) {
......@@ -34,7 +36,7 @@ func TestServingDirectory(t *testing.T) {
w := httptest.NewRecorder()
st := &Static{dir}
st.ServeExisting("/", CacheDisabled, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
}
func TestServingMalformedUri(t *testing.T) {
......@@ -44,7 +46,7 @@ func TestServingMalformedUri(t *testing.T) {
w := httptest.NewRecorder()
st := &Static{dir}
st.ServeExisting("/", CacheDisabled, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
}
func TestExecutingHandlerWhenNoFileFound(t *testing.T) {
......@@ -76,7 +78,7 @@ func TestServingTheActualFile(t *testing.T) {
w := httptest.NewRecorder()
st := &Static{dir}
st.ServeExisting("/", CacheDisabled, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 200)
require.Equal(t, 200, w.Code)
if w.Body.String() != fileContent {
t.Error("We should serve the file: ", w.Body.String())
}
......@@ -108,15 +110,15 @@ func testServingThePregzippedFile(t *testing.T, enableGzip bool) {
w := httptest.NewRecorder()
st := &Static{dir}
st.ServeExisting("/", CacheDisabled, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 200)
require.Equal(t, 200, w.Code)
if enableGzip {
testhelper.RequireResponseWriterHeader(t, w, "Content-Encoding", "gzip")
testhelper.RequireResponseHeader(t, w, "Content-Encoding", "gzip")
if !bytes.Equal(w.Body.Bytes(), fileGzipContent.Bytes()) {
t.Error("We should serve the pregzipped file")
}
} else {
testhelper.RequireResponseCode(t, w, 200)
testhelper.RequireResponseWriterHeader(t, w, "Content-Encoding")
require.Equal(t, 200, w.Code)
testhelper.RequireResponseHeader(t, w, "Content-Encoding")
if w.Body.String() != fileContent {
t.Error("We should serve the file: ", w.Body.String())
}
......
package testhelper
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
......@@ -13,7 +11,6 @@ import (
"path"
"regexp"
"runtime"
"strings"
"testing"
"time"
......@@ -31,71 +28,9 @@ func ConfigureSecret() {
secret.SetPath(path.Join(RootDir(), "testdata/test-secret"))
}
var extractPatchSeriesMatcher = regexp.MustCompile(`^From (\w+)`)
// RequirePatchSeries takes a `git format-patch` blob, extracts the From xxxxx
// lines and compares the SHAs to expected list.
func RequirePatchSeries(t *testing.T, blob []byte, expected ...string) {
t.Helper()
var actual []string
footer := make([]string, 3)
scanner := bufio.NewScanner(bytes.NewReader(blob))
for scanner.Scan() {
line := scanner.Text()
if matches := extractPatchSeriesMatcher.FindStringSubmatch(line); len(matches) == 2 {
actual = append(actual, matches[1])
}
footer = []string{footer[1], footer[2], line}
}
if strings.Join(actual, "\n") != strings.Join(expected, "\n") {
t.Fatalf("Patch series differs. Expected: %v. Got: %v", expected, actual)
}
// Check the last returned patch is complete
// Don't assert on the final line, it is a git version
if footer[0] != "-- " {
t.Fatalf("Expected end of patch, found: \n\t%q", strings.Join(footer, "\n\t"))
}
}
func RequireResponseCode(t *testing.T, response *httptest.ResponseRecorder, expectedCode int) {
t.Helper()
if response.Code != expectedCode {
t.Fatalf("for HTTP request expected to get %d, got %d instead", expectedCode, response.Code)
}
}
func RequireResponseBody(t *testing.T, response *httptest.ResponseRecorder, expectedBody string) {
t.Helper()
if response.Body.String() != expectedBody {
t.Fatalf("for HTTP request expected to receive %q, got %q instead as body", expectedBody, response.Body.String())
}
}
func RequireResponseBodyRegexp(t *testing.T, response *httptest.ResponseRecorder, expectedBody *regexp.Regexp) {
t.Helper()
if !expectedBody.MatchString(response.Body.String()) {
t.Fatalf("for HTTP request expected to receive body matching %q, got %q instead", expectedBody.String(), response.Body.String())
}
}
func RequireResponseWriterHeader(t *testing.T, w http.ResponseWriter, header string, expected ...string) {
t.Helper()
actual := w.Header()[http.CanonicalHeaderKey(header)]
requireHeaderExists(t, header, actual, expected)
}
func RequireAbsentResponseWriterHeader(t *testing.T, w http.ResponseWriter, header string) {
t.Helper()
actual := w.Header()[http.CanonicalHeaderKey(header)]
if len(actual) != 0 {
t.Fatalf("for HTTP request expected not to receive the header %q, got %+v", header, actual)
}
require.Equal(t, expectedBody, response.Body.String(), "response body")
}
func RequireResponseHeader(t *testing.T, w interface{}, header string, expected ...string) {
......@@ -103,31 +38,18 @@ func RequireResponseHeader(t *testing.T, w interface{}, header string, expected
var actual []string
header = http.CanonicalHeaderKey(header)
type headerer interface{ Header() http.Header }
if resp, ok := w.(*http.Response); ok {
switch resp := w.(type) {
case *http.Response:
actual = resp.Header[header]
} else if resp, ok := w.(http.ResponseWriter); ok {
case headerer:
actual = resp.Header()[header]
} else if resp, ok := w.(*httptest.ResponseRecorder); ok {
actual = resp.Header()[header]
} else {
t.Fatalf("invalid type of w passed RequireResponseHeader")
default:
t.Fatal("invalid type of w passed RequireResponseHeader")
}
requireHeaderExists(t, header, actual, expected)
}
func requireHeaderExists(t *testing.T, header string, actual, expected []string) {
t.Helper()
if len(expected) != len(actual) {
t.Fatalf("for HTTP request expected to receive the header %q with %+v, got %+v", header, expected, actual)
}
for i, value := range expected {
if value != actual[i] {
t.Fatalf("for HTTP request expected to receive the header %q with %+v, got %+v", header, expected, actual)
}
}
require.Equal(t, expected, actual, "values for HTTP header %s", header)
}
func TestServerWithHandler(url *regexp.Regexp, handler http.HandlerFunc) *httptest.Server {
......@@ -183,10 +105,9 @@ func RootDir() string {
}
func LoadFile(t *testing.T, filePath string) string {
t.Helper()
content, err := ioutil.ReadFile(path.Join(RootDir(), filePath))
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
return string(content)
}
......
......@@ -59,7 +59,7 @@ func TestUploadTempPathRequirement(t *testing.T) {
require.NoError(t, err)
HandleFileUploads(response, request, nilHandler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, 500)
require.Equal(t, 500, response.Code)
}
func TestUploadHandlerForwardingRawData(t *testing.T) {
......@@ -92,7 +92,7 @@ func TestUploadHandlerForwardingRawData(t *testing.T) {
HandleFileUploads(response, httpRequest, handler, apiResponse, nil, opts)
testhelper.RequireResponseCode(t, response, 202)
require.Equal(t, 202, response.Code)
require.Equal(t, "RESPONSE", response.Body.String(), "response body")
}
......@@ -162,7 +162,7 @@ func TestUploadHandlerRewritingMultiPartData(t *testing.T) {
require.NoError(t, err)
HandleFileUploads(response, httpRequest, handler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, 202)
require.Equal(t, 202, response.Code)
cancel() // this will trigger an async cleanup
waitUntilDeleted(t, filePath)
......@@ -231,7 +231,7 @@ func TestUploadHandlerDetectingInjectedMultiPartData(t *testing.T) {
require.NoError(t, err)
HandleFileUploads(response, httpRequest, handler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, test.response)
require.Equal(t, test.response, response.Code)
cancel() // this will trigger an async cleanup
waitUntilDeleted(t, filePath)
......@@ -262,7 +262,7 @@ func TestUploadProcessingField(t *testing.T) {
HandleFileUploads(response, httpRequest, nilHandler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, 500)
require.Equal(t, 500, response.Code)
}
func TestUploadProcessingFile(t *testing.T) {
......@@ -317,7 +317,7 @@ func TestUploadProcessingFile(t *testing.T) {
HandleFileUploads(response, httpRequest, nilHandler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, 200)
require.Equal(t, 200, response.Code)
})
}
......@@ -359,7 +359,7 @@ func TestInvalidFileNames(t *testing.T) {
require.NoError(t, err)
HandleFileUploads(response, httpRequest, nilHandler, apiResponse, &SavedFileTracker{Request: httpRequest}, opts)
testhelper.RequireResponseCode(t, response, testCase.code)
require.Equal(t, testCase.code, response.Code)
}
}
......@@ -415,7 +415,7 @@ func TestUploadHandlerRemovingExif(t *testing.T) {
require.NoError(t, err)
HandleFileUploads(response, httpRequest, handler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, 200)
require.Equal(t, 200, response.Code)
}
func TestUploadHandlerRemovingInvalidExif(t *testing.T) {
......@@ -457,7 +457,7 @@ func TestUploadHandlerRemovingInvalidExif(t *testing.T) {
require.NoError(t, err)
HandleFileUploads(response, httpRequest, handler, apiResponse, &testFormProcessor{}, opts)
testhelper.RequireResponseCode(t, response, 422)
require.Equal(t, 422, response.Code)
}
func newProxy(url string) *proxy.Proxy {
......
......@@ -5,8 +5,6 @@ import (
"net/http/httptest"
"testing"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"github.com/stretchr/testify/require"
)
......@@ -37,5 +35,5 @@ func TestDevelopmentModeDisabled(t *testing.T) {
require.False(t, executed, "The handler should not get executed")
testhelper.RequireResponseCode(t, w, 404)
require.Equal(t, 404, w.Code)
}
......@@ -9,8 +9,6 @@ import (
"net/http/httptest"
"testing"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"github.com/stretchr/testify/require"
)
......@@ -33,7 +31,7 @@ func TestGzipEncoding(t *testing.T) {
require.Empty(t, r.Header.Get("Content-Encoding"), "Content-Encoding should be deleted")
})).ServeHTTP(resp, req)
testhelper.RequireResponseCode(t, resp, 200)
require.Equal(t, 200, resp.Code)
}
func TestNoEncoding(t *testing.T) {
......@@ -51,7 +49,7 @@ func TestNoEncoding(t *testing.T) {
require.Empty(t, r.Header.Get("Content-Encoding"), "Content-Encoding should be deleted")
})).ServeHTTP(resp, req)
testhelper.RequireResponseCode(t, resp, 200)
require.Equal(t, 200, resp.Code)
}
func TestInvalidEncoding(t *testing.T) {
......@@ -65,5 +63,5 @@ func TestInvalidEncoding(t *testing.T) {
t.Fatal("it shouldn't be executed")
})).ServeHTTP(resp, req)
testhelper.RequireResponseCode(t, resp, 500)
require.Equal(t, 500, resp.Code)
}
......@@ -17,6 +17,8 @@ import (
"gitlab.com/gitlab-org/gitlab-workhorse/internal/proxy"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/testhelper"
"gitlab.com/gitlab-org/gitlab-workhorse/internal/upstream/roundtripper"
"github.com/stretchr/testify/require"
)
const testVersion = "123"
......@@ -66,7 +68,7 @@ func TestProxyRequest(t *testing.T) {
w := httptest.NewRecorder()
newProxy(ts.URL, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 202)
require.Equal(t, 202, w.Code)
testhelper.RequireResponseBody(t, w, "RESPONSE")
if w.Header().Get("Custom-Response-Header") != "test" {
......@@ -83,8 +85,8 @@ func TestProxyError(t *testing.T) {
w := httptest.NewRecorder()
newProxy("http://localhost:655575/", nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 502)
testhelper.RequireResponseBodyRegexp(t, w, regexp.MustCompile("dial tcp:.*invalid port.*"))
require.Equal(t, 502, w.Code)
require.Regexp(t, regexp.MustCompile("dial tcp:.*invalid port.*"), w.Body.String(), "response body")
}
func TestProxyReadTimeout(t *testing.T) {
......@@ -110,7 +112,7 @@ func TestProxyReadTimeout(t *testing.T) {
p := newProxy(ts.URL, rt)
w := httptest.NewRecorder()
p.ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 502)
require.Equal(t, 502, w.Code)
testhelper.RequireResponseBody(t, w, "GitLab is not responding")
}
......@@ -128,6 +130,6 @@ func TestProxyHandlerTimeout(t *testing.T) {
w := httptest.NewRecorder()
newProxy(ts.URL, nil).ServeHTTP(w, httpRequest)
testhelper.RequireResponseCode(t, w, 503)
require.Equal(t, 503, w.Code)
testhelper.RequireResponseBody(t, w, "Request took too long")
}
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