Skip to content

Commit

Permalink
chore: use http constants instead of string (argoproj#12334)
Browse files Browse the repository at this point in the history
Signed-off-by: Fish-pro <[email protected]>
  • Loading branch information
Fish-pro authored Feb 17, 2023
1 parent cbb8d21 commit c85902c
Show file tree
Hide file tree
Showing 29 changed files with 80 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func TestListPullRequestBasicAuth(t *testing.T) {

func TestListResponseError(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}))
defer ts.Close()
svc, _ := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO")
Expand Down
2 changes: 1 addition & 1 deletion applicationset/services/scm_provider/bitbucket_cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (c *ExtendedClient) GetContents(repo *Repository, path string) (bool, error
urlStr += fmt.Sprintf("/repositories/%s/%s/src/%s/%s?format=meta", c.owner, repo.Repository, repo.SHA, path)
body := strings.NewReader("")

req, err := http.NewRequest("GET", urlStr, body)
req, err := http.NewRequest(http.MethodGet, urlStr, body)
if err != nil {
return false, err
}
Expand Down
16 changes: 8 additions & 8 deletions applicationset/services/scm_provider/bitbucket_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ func TestGetBranchesMissingDefault(t *testing.T) {
assert.Empty(t, r.Header.Get("Authorization"))
switch r.RequestURI {
case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Not found", 404)
http.Error(w, "Not found", http.StatusNotFound)
}
defaultHandler(t)(w, r)
}))
Expand All @@ -370,7 +370,7 @@ func TestGetBranchesErrorDefaultBranch(t *testing.T) {
assert.Empty(t, r.Header.Get("Authorization"))
switch r.RequestURI {
case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Internal server error", 500)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
defaultHandler(t)(w, r)
}))
Expand Down Expand Up @@ -442,7 +442,7 @@ func TestListReposMissingDefaultBranch(t *testing.T) {
assert.Empty(t, r.Header.Get("Authorization"))
switch r.RequestURI {
case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Not found", 404)
http.Error(w, "Not found", http.StatusNotFound)
}
defaultHandler(t)(w, r)
}))
Expand All @@ -459,7 +459,7 @@ func TestListReposErrorDefaultBranch(t *testing.T) {
assert.Empty(t, r.Header.Get("Authorization"))
switch r.RequestURI {
case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Internal server error", 500)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
defaultHandler(t)(w, r)
}))
Expand Down Expand Up @@ -516,17 +516,17 @@ func TestBitbucketServerHasPath(t *testing.T) {
_, err = io.WriteString(w, `{"type":"FILE"}`)

case "/rest/api/1.0/projects/PROJECT/repos/REPO/browse/anotherpkg/missing.txt?at=main&limit=100&type=true":
http.Error(w, "The path \"anotherpkg/missing.txt\" does not exist at revision \"main\"", 404)
http.Error(w, "The path \"anotherpkg/missing.txt\" does not exist at revision \"main\"", http.StatusNotFound)
case "/rest/api/1.0/projects/PROJECT/repos/REPO/browse/notathing?at=main&limit=100&type=true":
http.Error(w, "The path \"notathing\" does not exist at revision \"main\"", 404)
http.Error(w, "The path \"notathing\" does not exist at revision \"main\"", http.StatusNotFound)

case "/rest/api/1.0/projects/PROJECT/repos/REPO/browse/return-redirect?at=main&limit=100&type=true":
http.Redirect(w, r, "http://"+r.Host+"/rest/api/1.0/projects/PROJECT/repos/REPO/browse/redirected?at=main&limit=100&type=true", 301)
http.Redirect(w, r, "http://"+r.Host+"/rest/api/1.0/projects/PROJECT/repos/REPO/browse/redirected?at=main&limit=100&type=true", http.StatusMovedPermanently)
case "/rest/api/1.0/projects/PROJECT/repos/REPO/browse/redirected?at=main&limit=100&type=true":
_, err = io.WriteString(w, `{"type":"DIRECTORY"}`)

case "/rest/api/1.0/projects/PROJECT/repos/REPO/browse/unauthorized-response?at=main&limit=100&type=true":
http.Error(w, "Authentication failed", 401)
http.Error(w, "Authentication failed", http.StatusUnauthorized)

default:
t.Fail()
Expand Down
2 changes: 1 addition & 1 deletion applicationset/services/scm_provider/gitea.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func NewGiteaProvider(ctx context.Context, owner, token, url string, allBranches
func (g *GiteaProvider) GetBranches(ctx context.Context, repo *Repository) ([]*Repository, error) {
if !g.allBranches {
branch, status, err := g.client.GetRepoBranch(g.owner, repo.Repository, repo.Branch)
if status.StatusCode == 404 {
if status.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("got 404 while getting default branch %q for repo %q - check your repo config: %w", repo.Branch, repo.Repository, err)
}
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion applicationset/services/scm_provider/gitea_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ func giteaMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
_, err := io.WriteString(w, testdata.ReposGiteaGoSdkContentsGiteaResponse)
require.NoError(t, err)
case "/api/v1/repos/gitea/go-sdk/contents/notathing?ref=master":
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
_, err := io.WriteString(w, `{"errors":["object does not exist [id: , rel_path: notathing]"],"message":"GetContentsOrList","url":"https://gitea.com/api/swagger"}`)
require.NoError(t, err)
default:
Expand Down
3 changes: 2 additions & 1 deletion applicationset/services/scm_provider/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net/http"
"os"

"github.com/google/go-github/v35/github"
Expand Down Expand Up @@ -123,7 +124,7 @@ func (g *GithubProvider) listBranches(ctx context.Context, repo *Repository) ([]
if err != nil {
var githubErrorResponse *github.ErrorResponse
if errors.As(err, &githubErrorResponse) {
if githubErrorResponse.Response.StatusCode == 404 {
if githubErrorResponse.Response.StatusCode == http.StatusNotFound {
// Default branch doesn't exist, so the repo is empty.
return []github.Branch{}, nil
}
Expand Down
2 changes: 1 addition & 1 deletion applicationset/services/scm_provider/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func githubMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
t.Fail()
}
default:
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion applicationset/webhook/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Infof("Webhook processing failed: %s", err)
status := http.StatusBadRequest
if r.Method != "POST" {
if r.Method != http.MethodPost {
status = http.StatusMethodNotAllowed
}
http.Error(w, fmt.Sprintf("Webhook processing failed: %s", html.EscapeString(err.Error())), status)
Expand Down
2 changes: 1 addition & 1 deletion applicationset/webhook/webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func TestWebhookHandler(t *testing.T) {
h, err := NewWebhookHandler(namespace, set, fc, mockGenerators())
assert.Nil(t, err)

req := httptest.NewRequest("POST", "/api/webhook", nil)
req := httptest.NewRequest(http.MethodPost, "/api/webhook", nil)
req.Header.Set(test.headerKey, test.headerValue)
eventJSON, err := os.ReadFile(filepath.Join("testdata", test.payloadFile))
assert.NoError(t, err)
Expand Down
10 changes: 5 additions & 5 deletions controller/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ func runTest(t *testing.T, cfg TestMetricServerConfig) {
metricsServ.registry.MustRegister(collector)
}

req, err := http.NewRequest("GET", "/metrics", nil)
req, err := http.NewRequest(http.MethodGet, "/metrics", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
metricsServ.Handler.ServeHTTP(rr, req)
Expand Down Expand Up @@ -337,7 +337,7 @@ argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespa
metricsServ.IncSync(fakeApp, &argoappv1.OperationState{Phase: common.OperationSucceeded})
metricsServ.IncSync(fakeApp, &argoappv1.OperationState{Phase: common.OperationSucceeded})

req, err := http.NewRequest("GET", "/metrics", nil)
req, err := http.NewRequest(http.MethodGet, "/metrics", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
metricsServ.Handler.ServeHTTP(rr, req)
Expand Down Expand Up @@ -391,7 +391,7 @@ argocd_app_reconcile_count{dest_server="https://localhost:6443",namespace="argoc
fakeApp := newFakeApp(fakeApp)
metricsServ.IncReconcile(fakeApp, 5*time.Second)

req, err := http.NewRequest("GET", "/metrics", nil)
req, err := http.NewRequest(http.MethodGet, "/metrics", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
metricsServ.Handler.ServeHTTP(rr, req)
Expand All @@ -415,7 +415,7 @@ argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespa
argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Succeeded",project="important-project"} 2
`

req, err := http.NewRequest("GET", "/metrics", nil)
req, err := http.NewRequest(http.MethodGet, "/metrics", nil)
assert.NoError(t, err)
rr := httptest.NewRecorder()
metricsServ.Handler.ServeHTTP(rr, req)
Expand All @@ -426,7 +426,7 @@ argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespa
err = metricsServ.SetExpiration(time.Second)
assert.NoError(t, err)
time.Sleep(2 * time.Second)
req, err = http.NewRequest("GET", "/metrics", nil)
req, err = http.NewRequest(http.MethodGet, "/metrics", nil)
assert.NoError(t, err)
rr = httptest.NewRecorder()
metricsServ.Handler.ServeHTTP(rr, req)
Expand Down
2 changes: 1 addition & 1 deletion hack/gen-resources/generators/repo_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func NewRepoGenerator(clientSet *kubernetes.Clientset) Generator {

func fetchRepos(token string, page int) ([]Repo, error) {
client := &http.Client{}
req, _ := http.NewRequest("GET", fmt.Sprintf("https://api.github.com/repos/argoproj/argocd-example-apps/forks?per_page=100&page=%v", page), nil)
req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("https://api.github.com/repos/argoproj/argocd-example-apps/forks?per_page=100&page=%v", page), nil)
req.Header.Set("Authorization", token)
resp, err := client.Do(req)
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions server/application/terminal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func TestTerminalHandler_ServeHTTP_empty_params(t *testing.T) {
paramsArray = append(paramsArray, key+"="+value)
}
paramsString := strings.Join(paramsArray, "&")
request := httptest.NewRequest("GET", "https://argocd.example.com/api/v1/terminal?"+paramsString, nil)
request := httptest.NewRequest(http.MethodGet, "https://argocd.example.com/api/v1/terminal?"+paramsString, nil)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
response := recorder.Result()
Expand All @@ -226,7 +226,7 @@ func TestTerminalHandler_ServeHTTP_empty_params(t *testing.T) {

func TestTerminalHandler_ServeHTTP_disallowed_namespace(t *testing.T) {
handler := terminalHandler{namespace: "argocd", enabledNamespaces: []string{"allowed"}}
request := httptest.NewRequest("GET", "https://argocd.example.com/api/v1/terminal?pod=valid&container=valid&appName=valid&projectName=valid&namespace=test&appNamespace=disallowed", nil)
request := httptest.NewRequest(http.MethodGet, "https://argocd.example.com/api/v1/terminal?pod=valid&container=valid&appName=valid&projectName=valid&namespace=test&appNamespace=disallowed", nil)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
response := recorder.Result()
Expand Down
12 changes: 6 additions & 6 deletions server/badge/badge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ var (
func TestHandlerFeatureIsEnabled(t *testing.T) {
settingsMgr := settings.NewSettingsManager(context.Background(), fake.NewSimpleClientset(&argoCDCm, &argoCDSecret), "default")
handler := NewHandler(appclientset.NewSimpleClientset(&testApp), settingsMgr, "default")
req, err := http.NewRequest("GET", "/api/badge?name=testApp", nil)
req, err := http.NewRequest(http.MethodGet, "/api/badge?name=testApp", nil)
assert.NoError(t, err)

rr := httptest.NewRecorder()
Expand Down Expand Up @@ -113,7 +113,7 @@ func TestHandlerFeatureProjectIsEnabled(t *testing.T) {
settingsMgr := settings.NewSettingsManager(context.Background(), fake.NewSimpleClientset(&argoCDCm, &argoCDSecret), tt.namespace)
handler := NewHandler(appclientset.NewSimpleClientset(&testProject, tt.testApp[0], tt.testApp[1]), settingsMgr, tt.namespace)
rr := httptest.NewRecorder()
req, err := http.NewRequest("GET", tt.apiEndPoint, nil)
req, err := http.NewRequest(http.MethodGet, tt.apiEndPoint, nil)
assert.NoError(t, err)
handler.ServeHTTP(rr, req)
assert.Equal(t, "private, no-store", rr.Header().Get("Cache-Control"))
Expand Down Expand Up @@ -177,7 +177,7 @@ func createApplications(appCombo, projectName []string, namespace string) []*v1a
func TestHandlerFeatureIsEnabledRevisionIsEnabled(t *testing.T) {
settingsMgr := settings.NewSettingsManager(context.Background(), fake.NewSimpleClientset(&argoCDCm, &argoCDSecret), "default")
handler := NewHandler(appclientset.NewSimpleClientset(&testApp), settingsMgr, "default")
req, err := http.NewRequest("GET", "/api/badge?name=testApp&revision=true", nil)
req, err := http.NewRequest(http.MethodGet, "/api/badge?name=testApp&revision=true", nil)
assert.NoError(t, err)

rr := httptest.NewRecorder()
Expand All @@ -200,7 +200,7 @@ func TestHandlerRevisionIsEnabledNoOperationState(t *testing.T) {

settingsMgr := settings.NewSettingsManager(context.Background(), fake.NewSimpleClientset(&argoCDCm, &argoCDSecret), "default")
handler := NewHandler(appclientset.NewSimpleClientset(app), settingsMgr, "default")
req, err := http.NewRequest("GET", "/api/badge?name=testApp&revision=true", nil)
req, err := http.NewRequest(http.MethodGet, "/api/badge?name=testApp&revision=true", nil)
assert.NoError(t, err)

rr := httptest.NewRecorder()
Expand All @@ -223,7 +223,7 @@ func TestHandlerRevisionIsEnabledShortCommitSHA(t *testing.T) {

settingsMgr := settings.NewSettingsManager(context.Background(), fake.NewSimpleClientset(&argoCDCm, &argoCDSecret), "default")
handler := NewHandler(appclientset.NewSimpleClientset(app), settingsMgr, "default")
req, err := http.NewRequest("GET", "/api/badge?name=testApp&revision=true", nil)
req, err := http.NewRequest(http.MethodGet, "/api/badge?name=testApp&revision=true", nil)
assert.NoError(t, err)

rr := httptest.NewRecorder()
Expand All @@ -240,7 +240,7 @@ func TestHandlerFeatureIsDisabled(t *testing.T) {

settingsMgr := settings.NewSettingsManager(context.Background(), fake.NewSimpleClientset(argoCDCmDisabled, &argoCDSecret), "default")
handler := NewHandler(appclientset.NewSimpleClientset(&testApp), settingsMgr, "default")
req, err := http.NewRequest("GET", "/api/badge?name=testApp", nil)
req, err := http.NewRequest(http.MethodGet, "/api/badge?name=testApp", nil)
assert.NoError(t, err)

rr := httptest.NewRecorder()
Expand Down
8 changes: 4 additions & 4 deletions server/logout/logout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,17 +251,17 @@ func TestHandlerConstructLogoutURL(t *testing.T) {
invalidHeader := make(map[string][]string)
invalidHeader["Cookie"] = []string{"argocd.token=" + invalidToken}

oidcRequest, err := http.NewRequest("GET", "http://localhost:4000/api/logout", nil)
oidcRequest, err := http.NewRequest(http.MethodGet, "http://localhost:4000/api/logout", nil)
assert.NoError(t, err)
oidcRequest.Header = oidcTokenHeader
nonoidcRequest, err := http.NewRequest("GET", "http://localhost:4000/api/logout", nil)
nonoidcRequest, err := http.NewRequest(http.MethodGet, "http://localhost:4000/api/logout", nil)
assert.NoError(t, err)
nonoidcRequest.Header = nonOidcTokenHeader
assert.NoError(t, err)
requestWithInvalidToken, err := http.NewRequest("GET", "http://localhost:4000/api/logout", nil)
requestWithInvalidToken, err := http.NewRequest(http.MethodGet, "http://localhost:4000/api/logout", nil)
assert.NoError(t, err)
requestWithInvalidToken.Header = invalidHeader
invalidRequest, err := http.NewRequest("GET", "http://localhost:4000/api/logout", nil)
invalidRequest, err := http.NewRequest(http.MethodGet, "http://localhost:4000/api/logout", nil)
assert.NoError(t, err)

tests := []struct {
Expand Down
6 changes: 3 additions & 3 deletions server/server_norace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func Test_StaticHeaders(t *testing.T) {

client := http.Client{}
url := fmt.Sprintf("http://127.0.0.1:%d/test.html", s.ListenPort)
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
assert.NoError(t, err)
resp, err := client.Do(req)
assert.NoError(t, err)
Expand Down Expand Up @@ -140,7 +140,7 @@ func Test_StaticHeaders(t *testing.T) {

client := http.Client{}
url := fmt.Sprintf("http://127.0.0.1:%d/test.html", s.ListenPort)
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
assert.NoError(t, err)
resp, err := client.Do(req)
assert.NoError(t, err)
Expand Down Expand Up @@ -172,7 +172,7 @@ func Test_StaticHeaders(t *testing.T) {

client := http.Client{}
url := fmt.Sprintf("http://127.0.0.1:%d/test.html", s.ListenPort)
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
assert.NoError(t, err)
resp, err := client.Do(req)
assert.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ func dexMockHandler(t *testing.T, url string) func(http.ResponseWriter, *http.Re
t.Fail()
}
default:
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/applicationset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,7 @@ func githubSCMMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request)
t.Fail()
}
default:
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
}
}
}
Expand Down Expand Up @@ -1279,7 +1279,7 @@ func githubPullMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request
t.Fail()
}
default:
w.WriteHeader(404)
w.WriteHeader(http.StatusNotFound)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion util/dex/dex.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func NewDexHTTPReverseProxy(serverAddr string, baseHRef string, tlsConfig *DexTL
}

proxy.ModifyResponse = func(resp *http.Response) error {
if resp.StatusCode == 500 {
if resp.StatusCode == http.StatusInternalServerError {
b, err := io.ReadAll(resp.Body)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion util/dex/dex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ func Test_DexReverseProxy(t *testing.T) {
defer server.Close()
rt := NewDexRewriteURLRoundTripper(server.URL, http.DefaultTransport)
assert.NotNil(t, rt)
req, err := http.NewRequest("GET", "/", bytes.NewBuffer([]byte("")))
req, err := http.NewRequest(http.MethodGet, "/", bytes.NewBuffer([]byte("")))
assert.NoError(t, err)
_, err = rt.RoundTrip(req)
assert.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion util/git/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func TestCustomHTTPClient(t *testing.T) {
assert.Nil(t, cert.PrivateKey)
}
}
req, err := http.NewRequest("GET", "http://proxy-from-env:7878", nil)
req, err := http.NewRequest(http.MethodGet, "http://proxy-from-env:7878", nil)
assert.Nil(t, err)
proxy, err := transport.Proxy(req)
assert.Nil(t, err)
Expand Down
4 changes: 2 additions & 2 deletions util/healthz/healthz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ func TestHealthCheck(t *testing.T) {
t.Fatal(err)
}

if resp.StatusCode != 200 {
if resp.StatusCode != http.StatusOK {
t.Fatalf("Was expecting status code 200 from health check, but got %d instead", resp.StatusCode)
}

sentinel = true

resp, _ = http.Get(server + "/healthz")
if resp.StatusCode != 503 {
if resp.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("Was expecting status code 503 from health check, but got %d instead", resp.StatusCode)
}

Expand Down
Loading

0 comments on commit c85902c

Please sign in to comment.