Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions .github/workflows/master.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 ./...
run: go test -v ./...
env:
GO_ENV: test
MONGODB_URI: mongodb://127.0.0.1:27017
MONGO_DB: switcher-gitops-test
88 changes: 88 additions & 0 deletions src/controller/account_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
20 changes: 20 additions & 0 deletions src/controller/api_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
32 changes: 32 additions & 0 deletions src/db/mongo.go
Original file line number Diff line number Diff line change
@@ -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"))
}
25 changes: 2 additions & 23 deletions src/server/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -23,7 +23,7 @@ type App struct {
}

func NewApp() *App {
db := initDb()
db := db.InitDb()
routes := initRoutes(db)

return &App{
Expand Down Expand Up @@ -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}}
Expand Down
11 changes: 10 additions & 1 deletion src/utils/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
26 changes: 26 additions & 0 deletions src/utils/http_test.go
Original file line number Diff line number Diff line change
@@ -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"])
}