From 47a81e4d44f9a4b198fe646ef9376ced4e9fff48 Mon Sep 17 00:00:00 2001 From: "Giau. Tran Minh" <12751435+giautm@users.noreply.github.com> Date: Sun, 5 Jan 2025 14:22:51 +0700 Subject: [PATCH] atlasaction: update test for lint with GitHub context (#296) Added test for this : https://github.com/ariga/atlas-action/pull/294 Also replace `gorilla/mux` with `http.ServeMux` --- atlasaction/circleci_action_test.go | 32 ++++- atlasaction/gitlab_ci_test.go | 118 ++++++++---------- .../testdata/circleci/migrate-lint.txtar | 5 +- go.mod | 3 +- go.sum | 4 +- 5 files changed, 92 insertions(+), 70 deletions(-) diff --git a/atlasaction/circleci_action_test.go b/atlasaction/circleci_action_test.go index 33b19caa..3e9ba080 100644 --- a/atlasaction/circleci_action_test.go +++ b/atlasaction/circleci_action_test.go @@ -6,6 +6,8 @@ package atlasaction_test import ( "context" + "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -72,10 +74,36 @@ func TestCircleCI(t *testing.T) { if err := os.Mkdir(dir, 0700); err != nil { return err } + m := http.NewServeMux() + m.Handle("GET /repos/{owner}/{repo}/pulls", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.NoError(t, json.NewEncoder(w).Encode([]struct { + URL string `json:"url"` + Number int `json:"number"` + }{ + { + Number: 1, + URL: fmt.Sprintf("https://github.com/%s/%s/pull/1", + r.PathValue("owner"), r.PathValue("repo")), + }, + })) + })) + m.Handle("GET /repos/{owner}/{repo}/issues/{num}/comments", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // No comments + w.Write([]byte(`[]`)) + })) + m.Handle("POST /repos/{owner}/{repo}/issues/{num}/comments", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Created comment + w.WriteHeader(http.StatusCreated) + })) + m.Handle("GET /repos/{owner}/{repo}/pulls/{num}/files", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // No files + w.Write([]byte(`[]`)) + })) + srv := httptest.NewServer(m) + e.Defer(srv.Close) e.Setenv("MOCK_ATLAS", filepath.Join(wd, "mock-atlas.sh")) e.Setenv("CIRCLECI", "true") - e.Setenv("CIRCLE_PROJECT_REPONAME", "atlas-orb") - e.Setenv("CIRCLE_SHA1", "1234567890") + e.Setenv("GITHUB_API_URL", srv.URL) e.Setenv("BASH_ENV", filepath.Join(dir, "output.sh")) return nil }, diff --git a/atlasaction/gitlab_ci_test.go b/atlasaction/gitlab_ci_test.go index 578556af..baf277ec 100644 --- a/atlasaction/gitlab_ci_test.go +++ b/atlasaction/gitlab_ci_test.go @@ -10,7 +10,6 @@ import ( "testing" "ariga.io/atlas-action/internal/gitlab" - "github.com/gorilla/mux" "github.com/rogpeppe/go-internal/testscript" "github.com/stretchr/testify/require" ) @@ -58,71 +57,64 @@ func TestGitlabCI(t *testing.T) { func mockClientHandler(dir, token string) http.Handler { counter := 1 - r := mux.NewRouter() - r.Use(func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if t := r.Header.Get("PRIVATE-TOKEN"); t != token { - http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - return - } - next.ServeHTTP(w, r) - }) - }) - r.Methods(http.MethodGet).Path("/projects/{project}/merge_requests/{mr}/notes"). - HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - entries, err := os.ReadDir(dir) + m := http.NewServeMux() + m.HandleFunc("GET /projects/{project}/merge_requests/{mr}/notes", func(w http.ResponseWriter, r *http.Request) { + entries, err := os.ReadDir(dir) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + comments := make([]*gitlab.Note, len(entries)) + for i, e := range entries { + b, err := os.ReadFile(filepath.Join(dir, e.Name())) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - comments := make([]*gitlab.Note, len(entries)) - for i, e := range entries { - b, err := os.ReadFile(filepath.Join(dir, e.Name())) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - id, err := strconv.Atoi(e.Name()) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - comments[i] = &gitlab.Note{ID: id, Body: string(b)} - } - if err = json.NewEncoder(w).Encode(comments); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - }) - r.Methods(http.MethodPost).Path("/projects/{project}/merge_requests/{mr}/notes"). - HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - var body struct { - Body string `json:"body"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - if err := os.WriteFile(filepath.Join(dir, strconv.Itoa(counter)), []byte(body.Body+"\n"), 0666); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - counter++ - w.WriteHeader(http.StatusCreated) - }) - r.Methods(http.MethodPut).Path("/projects/{project}/merge_requests/{mr}/notes/{note}"). - HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - if _, err := os.Stat(filepath.Join(dir, vars["note"])); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } - var body struct { - Body string `json:"body"` - } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return } - if err := os.WriteFile(filepath.Join(dir, vars["note"]), []byte(body.Body+"\n"), 0666); err != nil { + id, err := strconv.Atoi(e.Name()) + if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } - }) - return r + comments[i] = &gitlab.Note{ID: id, Body: string(b)} + } + if err = json.NewEncoder(w).Encode(comments); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + m.HandleFunc("POST /projects/{project}/merge_requests/{mr}/notes", func(w http.ResponseWriter, r *http.Request) { + var body struct { + Body string `json:"body"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := os.WriteFile(filepath.Join(dir, strconv.Itoa(counter)), []byte(body.Body+"\n"), 0666); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + counter++ + w.WriteHeader(http.StatusCreated) + }) + m.HandleFunc("PUT /projects/{project}/merge_requests/{mr}/notes/{note}", func(w http.ResponseWriter, r *http.Request) { + if _, err := os.Stat(filepath.Join(dir, r.PathValue("note"))); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + var body struct { + Body string `json:"body"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err := os.WriteFile(filepath.Join(dir, r.PathValue("note")), []byte(body.Body+"\n"), 0666); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if t := r.Header.Get("PRIVATE-TOKEN"); t != token { + http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) + return + } + m.ServeHTTP(w, r) + }) } diff --git a/atlasaction/testdata/circleci/migrate-lint.txtar b/atlasaction/testdata/circleci/migrate-lint.txtar index 11abcb39..c3568a37 100644 --- a/atlasaction/testdata/circleci/migrate-lint.txtar +++ b/atlasaction/testdata/circleci/migrate-lint.txtar @@ -1,5 +1,8 @@ # Mock the atlas command outputs env ATLAS_PATH=$MOCK_ATLAS TEST_BATCH=./migrate-lint +# Run context +env CIRCLE_PROJECT_REPONAME=atlas-orb CIRCLE_SHA1=1234567890 CIRCLE_BRANCH=master +env GITHUB_TOKEN=foo GITHUB_REPOSITORY=foo/bar # Setup the action input variables env ATLAS_INPUT_CONFIG=file://testdata/config/atlas.hcl env ATLAS_INPUT_ENV=test @@ -16,7 +19,7 @@ atlas-action --action=migrate/lint output output.sh -- migrate-lint/1/args -- -migrate lint -w --context {"repo":"atlas-orb","path":"file://testdata/migrations","commit":"1234567890"} --env test --config file://testdata/config/atlas.hcl --dev-url sqlite://file?mode=memory --dir file://testdata/migrations --base atlas://pupisu?tag=staging --var var1=value1 --var var2=value2 --format {{ json . }} +migrate lint -w --context {"repo":"foo/bar","path":"file://testdata/migrations","branch":"master","commit":"1234567890","url":"https://github.com/foo/bar/pull/1","scmType":"GITHUB"} --env test --config file://testdata/config/atlas.hcl --dev-url sqlite://file?mode=memory --dir file://testdata/migrations --base atlas://pupisu?tag=staging --var var1=value1 --var var2=value2 --format {{ json . }} -- migrate-lint/1/stdout -- {"URL":"https://migration-lint-report-url"} -- output-pre.sh -- diff --git a/go.mod b/go.mod index 6057a86c..c086e3d0 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( ariga.io/atlas-go-sdk v0.6.5 github.com/alecthomas/kong v0.8.0 github.com/fatih/color v1.17.0 - github.com/gorilla/mux v1.8.1 + github.com/hashicorp/go-retryablehttp v0.7.7 github.com/mattn/go-sqlite3 v1.14.17 github.com/mitchellh/mapstructure v1.1.2 github.com/rogpeppe/go-internal v1.12.1-0.20240709150035-ccf4b4329d21 @@ -24,7 +24,6 @@ require ( github.com/go-openapi/inflect v0.19.0 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect - github.com/hashicorp/go-retryablehttp v0.7.7 // indirect github.com/hashicorp/hcl/v2 v2.18.1 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect diff --git a/go.sum b/go.sum index 399cef3a..e425ce59 100644 --- a/go.sum +++ b/go.sum @@ -28,10 +28,10 @@ github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-retryablehttp v0.7.7 h1:C8hUCYzor8PIfXHa4UrZkU4VvK8o9ISHxT2Q8+VepXU= github.com/hashicorp/go-retryablehttp v0.7.7/go.mod h1:pkQpWZeYWskR+D1tR2O5OcBFOxfA7DoAO6xtkuQnHTk= github.com/hashicorp/hcl/v2 v2.18.1 h1:6nxnOJFku1EuSawSD81fuviYUV8DxFr3fp2dUi3ZYSo=