diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 1e17cbf..adb27ea 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -19,12 +19,21 @@ jobs: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: '1.21.5' + - name: Start MongoDB + uses: supercharge/mongodb-github-action@1.10.0 + with: + mongodb-version: 6.0 + - name: Build run: go build -v ./... - name: Test - run: go test -v ./... \ No newline at end of file + run: go test -v ./... + env: + GO_ENV: test + MONGODB_URI: mongodb://127.0.0.1:27017 + MONGO_DB: switcher-gitops-test \ No newline at end of file diff --git a/src/controller/account_test.go b/src/controller/account_test.go new file mode 100644 index 0000000..989e465 --- /dev/null +++ b/src/controller/account_test.go @@ -0,0 +1,88 @@ +package controller + +import ( + "bytes" + "context" + "encoding/json" + "io" + "log" + "net/http" + "net/http/httptest" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/switcherapi/switcher-gitops/src/config" + "github.com/switcherapi/switcher-gitops/src/db" + "github.com/switcherapi/switcher-gitops/src/model" + "github.com/switcherapi/switcher-gitops/src/repository" + "go.mongodb.org/mongo-driver/mongo" +) + +var mongoDb *mongo.Database + +func TestMain(m *testing.M) { + setup() + code := m.Run() + shutdown() + os.Exit(code) +} + +func setup() { + os.Setenv("GO_ENV", "test") + config.InitEnv() + mongoDb = db.InitDb() +} + +func shutdown() { + // Drop the database after all tests have run + mongoDb.Drop(context.Background()) + mongoDb.Client().Disconnect(context.Background()) +} + +func TestCreateAccountHandler(t *testing.T) { + controller := AccountController{ + AccountRepository: &repository.AccountRepositoryMongo{Db: mongoDb}, + } + + w := httptest.NewRecorder() + r := httptest.NewRequest("POST", "/api/account", nil) + + // Create a sample account request + accountRequest := model.Account{ + Repository: "switcherapi/switcher-gitops", + Branch: "master", + Domain: model.DomainDetails{ + ID: "123", + Name: "Switcher GitOps", + Version: "123", + LastCommit: "123", + Status: "active", + Message: "Synced successfully", + }, + Settings: model.Settings{ + Active: true, + Window: "10m", + ForcePrune: false, + }, + } + + // Encode the account request as JSON + body, _ := json.Marshal(accountRequest) + r.Body = io.NopCloser(bytes.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + + controller.CreateAccountHandler(w, r) + + // Assert the response status code + assert.Equal(t, http.StatusCreated, w.Code) + + // Assert the response body + var accountResponse model.Account + err := json.NewDecoder(w.Body).Decode(&accountResponse) + if err != nil { + log.Fatal(err) + } + + assert.Equal(t, accountRequest.Repository, accountResponse.Repository) +} diff --git a/src/controller/api_test.go b/src/controller/api_test.go new file mode 100644 index 0000000..5c00c3c --- /dev/null +++ b/src/controller/api_test.go @@ -0,0 +1,20 @@ +package controller + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCheckApiHandler(t *testing.T) { + controller := ApiController{} + w := httptest.NewRecorder() + r := httptest.NewRequest("GET", "/api/check", nil) + + controller.CheckApiHandler(w, r) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, `{"message":"API is working"}`, w.Body.String()) +} diff --git a/src/db/mongo.go b/src/db/mongo.go new file mode 100644 index 0000000..edd69a5 --- /dev/null +++ b/src/db/mongo.go @@ -0,0 +1,32 @@ +package db + +import ( + "context" + "log" + "time" + + "github.com/switcherapi/switcher-gitops/src/config" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +func InitDb() *mongo.Database { + var err error + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.GetEnv("MONGO_URI"))) + + if err != nil { + panic(err) + } + + err = client.Ping(context.Background(), nil) + if err != nil { + log.Fatal(err) + } + + log.Println("Connected to MongoDB!") + return client.Database(config.GetEnv("MONGO_DB")) +} diff --git a/src/server/app.go b/src/server/app.go index 8286fbf..b538baa 100644 --- a/src/server/app.go +++ b/src/server/app.go @@ -10,10 +10,10 @@ import ( "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/mongo" - "go.mongodb.org/mongo-driver/mongo/options" "github.com/switcherapi/switcher-gitops/src/config" "github.com/switcherapi/switcher-gitops/src/controller" + "github.com/switcherapi/switcher-gitops/src/db" "github.com/switcherapi/switcher-gitops/src/repository" ) @@ -23,7 +23,7 @@ type App struct { } func NewApp() *App { - db := initDb() + db := db.InitDb() routes := initRoutes(db) return &App{ @@ -57,27 +57,6 @@ func (app *App) Start() error { return app.httpServer.Shutdown(ctx) } -func initDb() *mongo.Database { - var err error - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - client, err := mongo.Connect(ctx, options.Client().ApplyURI(config.GetEnv("MONGO_URI"))) - - if err != nil { - panic(err) - } - - err = client.Ping(context.Background(), nil) - if err != nil { - log.Fatal(err) - } - - log.Println("Connected to MongoDB!") - return client.Database(config.GetEnv("MONGO_DB")) -} - func initRoutes(db *mongo.Database) *mux.Router { ApiController := controller.ApiController{} AccountController := controller.AccountController{AccountRepository: &repository.AccountRepositoryMongo{Db: db}} diff --git a/src/utils/http.go b/src/utils/http.go index 826db4d..f69a2f8 100644 --- a/src/utils/http.go +++ b/src/utils/http.go @@ -2,11 +2,20 @@ package utils import ( "encoding/json" + "fmt" "net/http" ) func ResponseJSON(w http.ResponseWriter, data interface{}, status int) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) - json.NewEncoder(w).Encode(data) + + encodedData, err := json.Marshal(data) + if err != nil { + fmt.Println("Error encoding JSON:", err) + return + } + + jsonString := string(encodedData) + w.Write([]byte(jsonString)) } diff --git a/src/utils/http_test.go b/src/utils/http_test.go new file mode 100644 index 0000000..1cbf167 --- /dev/null +++ b/src/utils/http_test.go @@ -0,0 +1,26 @@ +package utils + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestResponseJSON(t *testing.T) { + w := httptest.NewRecorder() + data := map[string]string{"message": "Some message"} + status := http.StatusOK + + ResponseJSON(w, data, status) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "application/json", w.Header().Get("Content-Type")) + + var response map[string]string + err := json.Unmarshal(w.Body.Bytes(), &response) + assert.NoError(t, err) + assert.Equal(t, "Some message", response["message"]) +}