Skip to content

Commit

Permalink
Merge pull request #158 from Tibz-Dankan/switch/sqlite
Browse files Browse the repository at this point in the history
test: add tests for the post app endpoint
  • Loading branch information
Tibz-Dankan authored Aug 29, 2024
2 parents 01d9fe4 + b1ba0b5 commit 6acdf9d
Show file tree
Hide file tree
Showing 4 changed files with 278 additions and 9 deletions.
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"gorm",
"joho",
"mailjet",
"myapp",
"onrender",
"promhttp",
"psub",
"REQUESTINTERVAL",
Expand Down
3 changes: 1 addition & 2 deletions internal/models/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

var (
Expand Down Expand Up @@ -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)
Expand Down
23 changes: 16 additions & 7 deletions internal/routes/app/postApp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 {
Expand Down Expand Up @@ -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",
Expand All @@ -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")
}
259 changes: 259 additions & 0 deletions tests/app/postApp_test.go
Original file line number Diff line number Diff line change
@@ -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)

}

0 comments on commit 6acdf9d

Please sign in to comment.