From b1ba0b59ee124b95907c800bd4b05bb9b6448021 Mon Sep 17 00:00:00 2001 From: Tibz-Dankan Date: Wed, 28 Aug 2024 23:39:21 +0300 Subject: [PATCH] test: add tests for the post app endpoint --- .vscode/settings.json | 2 + internal/models/db.go | 3 +- internal/routes/app/postApp.go | 23 ++- tests/app/postApp_test.go | 259 +++++++++++++++++++++++++++++++++ 4 files changed, 278 insertions(+), 9 deletions(-) create mode 100644 tests/app/postApp_test.go diff --git a/.vscode/settings.json b/.vscode/settings.json index 437937a..18f4664 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,6 +10,8 @@ "gorm", "joho", "mailjet", + "myapp", + "onrender", "promhttp", "psub", "REQUESTINTERVAL", diff --git a/internal/models/db.go b/internal/models/db.go index e169a21..e7ae286 100644 --- a/internal/models/db.go +++ b/internal/models/db.go @@ -9,7 +9,6 @@ import ( "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm" - "gorm.io/gorm/logger" ) var ( @@ -44,7 +43,7 @@ func Db() *gorm.DB { if isTestingOrStagingEnv { gormDB, err = gorm.Open(sqlite.Open("./../../appcrons_test.db"), &gorm.Config{ SkipDefaultTransaction: true, PrepareStmt: true, - Logger: logger.Default.LogMode(logger.Info), + // Logger: logger.Default.LogMode(logger.Info), }) if err != nil { log.Fatal("Failed to connect to sqlite db:", err) diff --git a/internal/routes/app/postApp.go b/internal/routes/app/postApp.go index a474444..d52f41b 100644 --- a/internal/routes/app/postApp.go +++ b/internal/routes/app/postApp.go @@ -2,7 +2,9 @@ package app import ( "encoding/json" + "log" "net/http" + "os" "github.com/Tibz-Dankan/keep-active/internal/events" "github.com/Tibz-Dankan/keep-active/internal/middlewares" @@ -11,14 +13,14 @@ import ( "github.com/gorilla/mux" ) -func PostAdd(w http.ResponseWriter, r *http.Request) { - userID, ok := r.Context().Value(middlewares.UserIDKey).(string) +func PostApp(w http.ResponseWriter, r *http.Request) { + userId, ok := r.Context().Value(middlewares.UserIDKey).(string) if !ok { services.AppError("UserID not found in context", 500, w) return } - app := models.App{UserID: userID} + app := models.App{UserID: userId} err := json.NewDecoder(r.Body).Decode(&app) if err != nil { @@ -59,6 +61,16 @@ func PostAdd(w http.ResponseWriter, r *http.Request) { return } + user := models.User{ID: userId} + if os.Getenv("GO_ENV") == "testing" || os.Getenv("GO_ENV") == "staging" { + permission := models.Permissions{} + if err := permission.Set(user.ID); err != nil { + log.Println("Error setting permissions:", err) + } + } else { + events.EB.Publish("permissions", user) + } + response := map[string]interface{}{ "status": "success", "message": "Created successfully", @@ -68,11 +80,8 @@ func PostAdd(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(response) - - user := models.User{ID: userID} - events.EB.Publish("permissions", user) } func PostAppRoute(router *mux.Router) { - router.HandleFunc("/post", PostAdd).Methods("POST") + router.HandleFunc("/post", PostApp).Methods("POST") } diff --git a/tests/app/postApp_test.go b/tests/app/postApp_test.go new file mode 100644 index 0000000..d72b4c5 --- /dev/null +++ b/tests/app/postApp_test.go @@ -0,0 +1,259 @@ +package tests + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Tibz-Dankan/keep-active/internal/models" + "github.com/Tibz-Dankan/keep-active/tests/data" + "github.com/Tibz-Dankan/keep-active/tests/setup" +) + +func TestMissingPostAppFields(t *testing.T) { + setup.ClearAllTables() + + var label string = "Expects 400 with postApp fields" + var payload []byte + var req *http.Request + var response *httptest.ResponseRecorder + var body map[string]interface{} + + genData := data.NewGenTestData() + name := genData.RandomUniqueName() + email := genData.RandomUniqueEmail() + password := genData.RandomUniquePassword(8) + + user := models.User{Name: name, Email: email, Password: password} + + userId, err := user.Create(user) + if err != nil { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects new user. Got %v\n", err) + return + } + user.ID = userId + + signInPayload, _ := json.Marshal(user) + req, _ = http.NewRequest("POST", "/api/v1/auth/signin", bytes.NewBuffer(signInPayload)) + response = setup.ExecuteRequest(req) + + json.Unmarshal(response.Body.Bytes(), &body) + + token, ok := body["accessToken"] + if !ok { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects accessToken. Got %v\n", token) + } + accessToken, _ := token.(string) + bearerToken := fmt.Sprintf("Bearer %s", accessToken) + + label = "Expects 400 with missing app name" + payload = []byte(`{"name":"","url":"myapp.onrender.com/active","requestInterval":"5"}`) + req, _ = http.NewRequest("POST", "/api/v1/apps/post", bytes.NewBuffer(payload)) + req.Header.Set("Authorization", bearerToken) + response = setup.ExecuteRequest(req) + setup.CheckResponseCode(t, label, http.StatusBadRequest, response.Code) + + label = "Expects 400 with missing app url" + payload = []byte(`{"name":"myApp","url":"","requestInterval":"5"}`) + req, _ = http.NewRequest("POST", "/api/v1/apps/post", bytes.NewBuffer(payload)) + req.Header.Set("Authorization", bearerToken) + response = setup.ExecuteRequest(req) + setup.CheckResponseCode(t, label, http.StatusBadRequest, response.Code) + + label = "Expects 400 with missing app request interval" + payload = []byte(`{"name":"myApp","url":"myapp.onrender.com/active","requestInterval":""}`) + req, _ = http.NewRequest("POST", "/api/v1/apps/post", bytes.NewBuffer(payload)) + req.Header.Set("Authorization", bearerToken) + response = setup.ExecuteRequest(req) + setup.CheckResponseCode(t, label, http.StatusBadRequest, response.Code) +} + +func TestAlreadyExistingApplicationName(t *testing.T) { + setup.ClearAllTables() + + var label string = "Expects 400 with already existing application name" + var payload []byte + var req *http.Request + var response *httptest.ResponseRecorder + var body map[string]interface{} + + genData := data.NewGenTestData() + name := genData.RandomUniqueName() + email := genData.RandomUniqueEmail() + password := genData.RandomUniquePassword(8) + appURL := genData.RandomUniqueURL() + appName := genData.RandomUniqueAppName() + + user := models.User{Name: name, Email: email, Password: password} + + userId, err := user.Create(user) + if err != nil { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects new user. Got %v\n", err) + return + } + + app := models.App{UserID: userId, Name: appName, URL: appURL, RequestInterval: "5"} + + if _, err := app.Create(app); err != nil { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects accessToken. Got %v\n", err) + } + + signInPayload, _ := json.Marshal(user) + req, _ = http.NewRequest("POST", "/api/v1/auth/signin", bytes.NewBuffer(signInPayload)) + response = setup.ExecuteRequest(req) + + json.Unmarshal(response.Body.Bytes(), &body) + + token, ok := body["accessToken"] + if !ok { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects accessToken. Got %v\n", token) + } + accessToken, _ := token.(string) + bearerToken := fmt.Sprintf("Bearer %s", accessToken) + + newApp := struct { + Name string `json:"name"` + URL string `json:"url"` + RequestInterval string `json:"requestInterval"` + }{ + Name: appName, + URL: genData.RandomUniqueURL(), + RequestInterval: "5", + } + + payload, _ = json.Marshal(newApp) + req, _ = http.NewRequest("POST", "/api/v1/apps/post", bytes.NewBuffer(payload)) + req.Header.Set("Authorization", bearerToken) + response = setup.ExecuteRequest(req) + setup.CheckResponseCode(t, label, http.StatusBadRequest, response.Code) + +} + +func TestAlreadyExistingApplicationURL(t *testing.T) { + setup.ClearAllTables() + + var label string = "Expects 400 with already existing application URL" + var payload []byte + var req *http.Request + var response *httptest.ResponseRecorder + var body map[string]interface{} + + genData := data.NewGenTestData() + name := genData.RandomUniqueName() + email := genData.RandomUniqueEmail() + password := genData.RandomUniquePassword(8) + appURL := genData.RandomUniqueURL() + appName := genData.RandomUniqueAppName() + + user := models.User{Name: name, Email: email, Password: password} + + userId, err := user.Create(user) + if err != nil { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects new user. Got %v\n", err) + return + } + + app := models.App{UserID: userId, Name: appName, URL: appURL, RequestInterval: "5"} + + if _, err := app.Create(app); err != nil { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects accessToken. Got %v\n", err) + } + + signInPayload, _ := json.Marshal(user) + req, _ = http.NewRequest("POST", "/api/v1/auth/signin", bytes.NewBuffer(signInPayload)) + response = setup.ExecuteRequest(req) + + json.Unmarshal(response.Body.Bytes(), &body) + + token, ok := body["accessToken"] + if !ok { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects accessToken. Got %v\n", token) + } + accessToken, _ := token.(string) + bearerToken := fmt.Sprintf("Bearer %s", accessToken) + + newApp := struct { + Name string `json:"name"` + URL string `json:"url"` + RequestInterval string `json:"requestInterval"` + }{ + Name: genData.RandomUniqueAppName(), + URL: appURL, + RequestInterval: "5", + } + + payload, _ = json.Marshal(newApp) + req, _ = http.NewRequest("POST", "/api/v1/apps/post", bytes.NewBuffer(payload)) + req.Header.Set("Authorization", bearerToken) + response = setup.ExecuteRequest(req) + setup.CheckResponseCode(t, label, http.StatusBadRequest, response.Code) + +} + +func TestSuccessfulApplicationPost(t *testing.T) { + setup.ClearAllTables() + + var label string = "Expects 201 on successful post" + var payload []byte + var req *http.Request + var response *httptest.ResponseRecorder + var body map[string]interface{} + + genData := data.NewGenTestData() + name := genData.RandomUniqueName() + email := genData.RandomUniqueEmail() + password := genData.RandomUniquePassword(8) + appURL := genData.RandomUniqueURL() + appName := genData.RandomUniqueAppName() + + user := models.User{Name: name, Email: email, Password: password} + + _, err := user.Create(user) + if err != nil { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects new user. Got %v\n", err) + return + } + + signInPayload, _ := json.Marshal(user) + req, _ = http.NewRequest("POST", "/api/v1/auth/signin", bytes.NewBuffer(signInPayload)) + response = setup.ExecuteRequest(req) + + json.Unmarshal(response.Body.Bytes(), &body) + + token, ok := body["accessToken"] + if !ok { + fmt.Printf("=== FAIL: %s\n", label) + t.Errorf("Expects accessToken. Got %v\n", token) + } + accessToken, _ := token.(string) + bearerToken := fmt.Sprintf("Bearer %s", accessToken) + + newApp := struct { + Name string `json:"name"` + URL string `json:"url"` + RequestInterval string `json:"requestInterval"` + }{ + Name: appName, + URL: appURL, + RequestInterval: "5", + } + + payload, _ = json.Marshal(newApp) + req, _ = http.NewRequest("POST", "/api/v1/apps/post", bytes.NewBuffer(payload)) + req.Header.Set("Authorization", bearerToken) + response = setup.ExecuteRequest(req) + setup.CheckResponseCode(t, label, http.StatusCreated, response.Code) + +}