Skip to content

Commit e59adcd

Browse files
ethantkoeniglafriks
authored andcommitted
Use httptest in integration tests (#3080)
1 parent 993b866 commit e59adcd

12 files changed

+77
-100
lines changed

integrations/api_branch_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) {
2020
req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s", branchName)
2121
resp := session.MakeRequest(t, req, NoExpectedStatus)
2222
if !exists {
23-
assert.EqualValues(t, http.StatusNotFound, resp.HeaderCode)
23+
assert.EqualValues(t, http.StatusNotFound, resp.Code)
2424
return
2525
}
26-
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
26+
assert.EqualValues(t, http.StatusOK, resp.Code)
2727
var branch api.Branch
2828
DecodeJSON(t, resp, &branch)
2929
assert.EqualValues(t, branchName, branch.Name)

integrations/api_gpg_keys_test.go

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,30 @@ package integrations
66

77
import (
88
"net/http"
9+
"net/http/httptest"
910
"strconv"
1011
"testing"
1112

12-
"github.com/stretchr/testify/assert"
13-
1413
api "code.gitea.io/sdk/gitea"
14+
15+
"github.com/stretchr/testify/assert"
1516
)
1617

18+
type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseRecorder
19+
1720
func TestGPGKeys(t *testing.T) {
1821
prepareTestEnv(t)
1922
session := loginUser(t, "user2")
2023

2124
tt := []struct {
22-
name string
23-
reqBuilder func(testing.TB, *http.Request, int) *TestResponse
24-
results []int
25+
name string
26+
makeRequest makeRequestFunc
27+
results []int
2528
}{
26-
{name: "NoLogin", reqBuilder: MakeRequest,
29+
{name: "NoLogin", makeRequest: MakeRequest,
2730
results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized},
2831
},
29-
{name: "LoggedAsUser2", reqBuilder: session.MakeRequest,
32+
{name: "LoggedAsUser2", makeRequest: session.MakeRequest,
3033
results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusInternalServerError, http.StatusInternalServerError, http.StatusCreated, http.StatusCreated}},
3134
}
3235

@@ -35,29 +38,29 @@ func TestGPGKeys(t *testing.T) {
3538
//Basic test on result code
3639
t.Run(tc.name, func(t *testing.T) {
3740
t.Run("ViewOwnGPGKeys", func(t *testing.T) {
38-
testViewOwnGPGKeys(t, tc.reqBuilder, tc.results[0])
41+
testViewOwnGPGKeys(t, tc.makeRequest, tc.results[0])
3942
})
4043
t.Run("ViewGPGKeys", func(t *testing.T) {
41-
testViewGPGKeys(t, tc.reqBuilder, tc.results[1])
44+
testViewGPGKeys(t, tc.makeRequest, tc.results[1])
4245
})
4346
t.Run("GetGPGKey", func(t *testing.T) {
44-
testGetGPGKey(t, tc.reqBuilder, tc.results[2])
47+
testGetGPGKey(t, tc.makeRequest, tc.results[2])
4548
})
4649
t.Run("DeleteGPGKey", func(t *testing.T) {
47-
testDeleteGPGKey(t, tc.reqBuilder, tc.results[3])
50+
testDeleteGPGKey(t, tc.makeRequest, tc.results[3])
4851
})
4952

5053
t.Run("CreateInvalidGPGKey", func(t *testing.T) {
51-
testCreateInvalidGPGKey(t, tc.reqBuilder, tc.results[4])
54+
testCreateInvalidGPGKey(t, tc.makeRequest, tc.results[4])
5255
})
5356
t.Run("CreateNoneRegistredEmailGPGKey", func(t *testing.T) {
54-
testCreateNoneRegistredEmailGPGKey(t, tc.reqBuilder, tc.results[5])
57+
testCreateNoneRegistredEmailGPGKey(t, tc.makeRequest, tc.results[5])
5558
})
5659
t.Run("CreateValidGPGKey", func(t *testing.T) {
57-
testCreateValidGPGKey(t, tc.reqBuilder, tc.results[6])
60+
testCreateValidGPGKey(t, tc.makeRequest, tc.results[6])
5861
})
5962
t.Run("CreateValidSecondaryEmailGPGKey", func(t *testing.T) {
60-
testCreateValidSecondaryEmailGPGKey(t, tc.reqBuilder, tc.results[7])
63+
testCreateValidSecondaryEmailGPGKey(t, tc.makeRequest, tc.results[7])
6164
})
6265
})
6366
}
@@ -140,39 +143,39 @@ func TestGPGKeys(t *testing.T) {
140143
})
141144
}
142145

143-
func testViewOwnGPGKeys(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
146+
func testViewOwnGPGKeys(t *testing.T, makeRequest makeRequestFunc, expected int) {
144147
req := NewRequest(t, "GET", "/api/v1/user/gpg_keys")
145-
reqBuilder(t, req, expected)
148+
makeRequest(t, req, expected)
146149
}
147150

148-
func testViewGPGKeys(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
151+
func testViewGPGKeys(t *testing.T, makeRequest makeRequestFunc, expected int) {
149152
req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys")
150-
reqBuilder(t, req, expected)
153+
makeRequest(t, req, expected)
151154
}
152155

153-
func testGetGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
156+
func testGetGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) {
154157
req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1")
155-
reqBuilder(t, req, expected)
158+
makeRequest(t, req, expected)
156159
}
157160

158-
func testDeleteGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
161+
func testDeleteGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) {
159162
req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1")
160-
reqBuilder(t, req, expected)
163+
makeRequest(t, req, expected)
161164
}
162165

163-
func testCreateGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int, publicKey string) {
166+
func testCreateGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int, publicKey string) {
164167
req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys", api.CreateGPGKeyOption{
165168
ArmoredKey: publicKey,
166169
})
167-
reqBuilder(t, req, expected)
170+
makeRequest(t, req, expected)
168171
}
169172

170-
func testCreateInvalidGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
171-
testCreateGPGKey(t, reqBuilder, expected, "invalid_key")
173+
func testCreateInvalidGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) {
174+
testCreateGPGKey(t, makeRequest, expected, "invalid_key")
172175
}
173176

174-
func testCreateNoneRegistredEmailGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
175-
testCreateGPGKey(t, reqBuilder, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
177+
func testCreateNoneRegistredEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) {
178+
testCreateGPGKey(t, makeRequest, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
176179
177180
mQENBFmGUygBCACjCNbKvMGgp0fd5vyFW9olE1CLCSyyF9gQN2hSuzmZLuAZF2Kh
178181
dCMCG2T1UwzUB/yWUFWJ2BtCwSjuaRv+cGohqEy6bhEBV90peGA33lHfjx7wP25O
@@ -191,9 +194,9 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz
191194
-----END PGP PUBLIC KEY BLOCK-----`)
192195
}
193196

194-
func testCreateValidGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
197+
func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) {
195198
//User2 <[email protected]> //primary & activated
196-
testCreateGPGKey(t, reqBuilder, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
199+
testCreateGPGKey(t, makeRequest, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
197200
198201
mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW
199202
VJhyBcnfNRDLKSQp5o/hhfDkCgdqBjLa1PnHlGS3PXJc0hP/FyYPD2BFvNMPpCYS
@@ -225,9 +228,9 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h
225228
-----END PGP PUBLIC KEY BLOCK-----`)
226229
}
227230

228-
func testCreateValidSecondaryEmailGPGKey(t *testing.T, reqBuilder func(testing.TB, *http.Request, int) *TestResponse, expected int) {
231+
func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) {
229232
//User2 <[email protected]> //secondary and not activated
230-
testCreateGPGKey(t, reqBuilder, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
233+
testCreateGPGKey(t, makeRequest, expected, `-----BEGIN PGP PUBLIC KEY BLOCK-----
231234
232235
mQENBFmGWN4BCAC18V4tVGO65VLCV7p14FuXJlUtZ5CuYMvgEkcOqrvRaBSW9ao4
233236
PGESOhJpfWpnW3QgJniYndLzPpsmdHEclEER6aZjiNgReWPOjHD5tykWocZAJqXD

integrations/branches_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,8 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
5959
link, exists := htmlDoc.doc.Find(button).Attr("data-url")
6060
assert.True(t, exists, "The template has changed")
6161

62-
htmlDoc = NewHTMLParser(t, resp.Body)
6362
req = NewRequestWithValues(t, "POST", link, map[string]string{
64-
"_csrf": getCsrf(htmlDoc.doc),
63+
"_csrf": getCsrf(t, htmlDoc.doc),
6564
})
6665
resp = session.MakeRequest(t, req, http.StatusOK)
6766

@@ -73,7 +72,8 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
7372
return NewHTMLParser(t, resp.Body), url.Query()["name"][0]
7473
}
7574

76-
func getCsrf(doc *goquery.Document) string {
77-
csrf, _ := doc.Find("meta[name=\"_csrf\"]").Attr("content")
75+
func getCsrf(t *testing.T, doc *goquery.Document) string {
76+
csrf, exists := doc.Find("meta[name=\"_csrf\"]").Attr("content")
77+
assert.True(t, exists)
7878
return csrf
7979
}

integrations/editor_test.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package integrations
66

77
import (
88
"net/http"
9+
"net/http/httptest"
910
"path"
1011
"testing"
1112

@@ -72,7 +73,7 @@ func TestCreateFileOnProtectedBranch(t *testing.T) {
7273

7374
resp = session.MakeRequest(t, req, http.StatusOK)
7475
// Check body for error message
75-
assert.Contains(t, string(resp.Body), "Can not commit to protected branch &#39;master&#39;.")
76+
assert.Contains(t, resp.Body.String(), "Can not commit to protected branch &#39;master&#39;.")
7677

7778
// remove the protected branch
7879
csrf = GetCSRF(t, session, "/user2/repo1/settings/branches")
@@ -89,7 +90,7 @@ func TestCreateFileOnProtectedBranch(t *testing.T) {
8990

9091
}
9192

92-
func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePath, newContent string) *TestResponse {
93+
func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePath, newContent string) *httptest.ResponseRecorder {
9394
// Get to the 'edit this file' page
9495
req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath))
9596
resp := session.MakeRequest(t, req, http.StatusOK)
@@ -113,12 +114,12 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
113114
// Verify the change
114115
req = NewRequest(t, "GET", path.Join(user, repo, "raw/branch", branch, filePath))
115116
resp = session.MakeRequest(t, req, http.StatusOK)
116-
assert.EqualValues(t, newContent, string(resp.Body))
117+
assert.EqualValues(t, newContent, resp.Body.String())
117118

118119
return resp
119120
}
120121

121-
func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *TestResponse {
122+
func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, branch, targetBranch, filePath, newContent string) *httptest.ResponseRecorder {
122123

123124
// Get to the 'edit this file' page
124125
req := NewRequest(t, "GET", path.Join(user, repo, "_edit", branch, filePath))
@@ -144,7 +145,7 @@ func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, bra
144145
// Verify the change
145146
req = NewRequest(t, "GET", path.Join(user, repo, "raw/branch", targetBranch, filePath))
146147
resp = session.MakeRequest(t, req, http.StatusOK)
147-
assert.EqualValues(t, newContent, string(resp.Body))
148+
assert.EqualValues(t, newContent, resp.Body.String())
148149

149150
return resp
150151
}

integrations/html_helper.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ type HTMLDoc struct {
1818
}
1919

2020
// NewHTMLParser parse html file
21-
func NewHTMLParser(t testing.TB, content []byte) *HTMLDoc {
22-
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(content))
21+
func NewHTMLParser(t testing.TB, body *bytes.Buffer) *HTMLDoc {
22+
doc, err := goquery.NewDocumentFromReader(body)
2323
assert.NoError(t, err)
2424
return &HTMLDoc{doc: doc}
2525
}

integrations/integration_test.go

Lines changed: 13 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"log"
1414
"net/http"
1515
"net/http/cookiejar"
16+
"net/http/httptest"
1617
"net/url"
1718
"os"
1819
"path"
@@ -158,7 +159,7 @@ func (s *TestSession) GetCookie(name string) *http.Cookie {
158159
return nil
159160
}
160161

161-
func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *TestResponse {
162+
func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
162163
baseURL, err := url.Parse(setting.AppURL)
163164
assert.NoError(t, err)
164165
for _, c := range s.jar.Cookies(baseURL) {
@@ -167,7 +168,7 @@ func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatu
167168
resp := MakeRequest(t, req, expectedStatus)
168169

169170
ch := http.Header{}
170-
ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
171+
ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
171172
cr := http.Request{Header: ch}
172173
s.jar.SetCookies(baseURL, cr.Cookies())
173174

@@ -207,7 +208,7 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
207208
resp = MakeRequest(t, req, http.StatusFound)
208209

209210
ch := http.Header{}
210-
ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
211+
ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
211212
cr := http.Request{Header: ch}
212213

213214
session := emptyTestSession(t)
@@ -219,30 +220,6 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
219220
return session
220221
}
221222

222-
type TestResponseWriter struct {
223-
HeaderCode int
224-
Writer io.Writer
225-
Headers http.Header
226-
}
227-
228-
func (w *TestResponseWriter) Header() http.Header {
229-
return w.Headers
230-
}
231-
232-
func (w *TestResponseWriter) Write(b []byte) (int, error) {
233-
return w.Writer.Write(b)
234-
}
235-
236-
func (w *TestResponseWriter) WriteHeader(n int) {
237-
w.HeaderCode = n
238-
}
239-
240-
type TestResponse struct {
241-
HeaderCode int
242-
Body []byte
243-
Headers http.Header
244-
}
245-
246223
func NewRequest(t testing.TB, method, urlStr string) *http.Request {
247224
return NewRequestWithBody(t, method, urlStr, nil)
248225
}
@@ -278,26 +255,18 @@ func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *ht
278255

279256
const NoExpectedStatus = -1
280257

281-
func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *TestResponse {
282-
buffer := bytes.NewBuffer(nil)
283-
respWriter := &TestResponseWriter{
284-
Writer: buffer,
285-
Headers: make(map[string][]string),
286-
}
287-
mac.ServeHTTP(respWriter, req)
258+
func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
259+
recorder := httptest.NewRecorder()
260+
mac.ServeHTTP(recorder, req)
288261
if expectedStatus != NoExpectedStatus {
289-
assert.EqualValues(t, expectedStatus, respWriter.HeaderCode,
262+
assert.EqualValues(t, expectedStatus, recorder.Code,
290263
"Request: %s %s", req.Method, req.URL.String())
291264
}
292-
return &TestResponse{
293-
HeaderCode: respWriter.HeaderCode,
294-
Body: buffer.Bytes(),
295-
Headers: respWriter.Headers,
296-
}
265+
return recorder
297266
}
298267

299-
func DecodeJSON(t testing.TB, resp *TestResponse, v interface{}) {
300-
decoder := json.NewDecoder(bytes.NewBuffer(resp.Body))
268+
func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
269+
decoder := json.NewDecoder(resp.Body)
301270
assert.NoError(t, decoder.Decode(v))
302271
}
303272

@@ -308,8 +277,8 @@ func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
308277
return doc.GetCSRF()
309278
}
310279

311-
func RedirectURL(t testing.TB, resp *TestResponse) string {
312-
urlSlice := resp.Headers["Location"]
280+
func RedirectURL(t testing.TB, resp *httptest.ResponseRecorder) string {
281+
urlSlice := resp.HeaderMap["Location"]
313282
assert.NotEmpty(t, urlSlice, "No redirect URL founds")
314283
return urlSlice[0]
315284
}

integrations/internal_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ func assertProtectedBranch(t *testing.T, repoID int64, branchName string, isErr,
2525

2626
resp := MakeRequest(t, req, NoExpectedStatus)
2727
if isErr {
28-
assert.EqualValues(t, http.StatusInternalServerError, resp.HeaderCode)
28+
assert.EqualValues(t, http.StatusInternalServerError, resp.Code)
2929
} else {
30-
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
30+
assert.EqualValues(t, http.StatusOK, resp.Code)
3131
var branch models.ProtectedBranch
32-
t.Log(string(resp.Body))
33-
assert.NoError(t, json.Unmarshal(resp.Body, &branch))
32+
t.Log(resp.Body.String())
33+
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &branch))
3434
assert.Equal(t, canPush, !branch.IsProtected())
3535
}
3636
}

integrations/pull_compare_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,5 @@ func TestPullCompare(t *testing.T) {
2323

2424
req = NewRequest(t, "GET", link)
2525
resp = session.MakeRequest(t, req, http.StatusOK)
26-
assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
26+
assert.EqualValues(t, http.StatusOK, resp.Code)
2727
}

0 commit comments

Comments
 (0)