Skip to content

Commit

Permalink
model refactor and user relation complete
Browse files Browse the repository at this point in the history
  • Loading branch information
piyush7833 committed Jun 24, 2024
1 parent 01d6d50 commit cbb0540
Show file tree
Hide file tree
Showing 7 changed files with 563 additions and 53 deletions.
55 changes: 45 additions & 10 deletions test/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestCreateUser(t *testing.T) {
"phone": "+1234567890",
"image": "https://example.com/avatar.png"
}`
TestPostRequest(t, userData, "/api/signup", 201, "User created successfully")
TestPostRequest(t, userData, "/api/signup", 201, "User created successfully", true)
}

func TestDuplicateUserError(t *testing.T) {
Expand All @@ -26,8 +26,7 @@ func TestDuplicateUserError(t *testing.T) {
"phone": "+1234567890",
"image": "https://example.com/avatar.png"
}`
TestPostRequest(t, userData, "/api/signup", http.StatusForbidden, "User with given user name or email or phone already exist")

TestPostRequest(t, userData, "/api/signup", http.StatusForbidden, "User with given user name or email or phone already exist", true)
}
func TestMissingFieldErrorSignup(t *testing.T) {
userData := `{
Expand All @@ -37,39 +36,75 @@ func TestMissingFieldErrorSignup(t *testing.T) {
"phone": "+1234567892",
"image": "https://example.com/avatar.png"
}`
TestPostRequest(t, userData, "/api/signup", 500, "Missing field")
TestPostRequest(t, userData, "/api/signup", 500, "Missing field", true)
}

//signin

func TestLoginUser(t *testing.T) {
userData := `{
"username": "test_user",
"password": "password"
"password": "password"
}`
TestPostRequest(t, userData, "/api/signin", 200, "Login successfull")

TestPostRequest(t, userData, "/api/signin", 200, "Login successfull", true)
}

func TestIncorrectPasswordError(t *testing.T) {
userData := `{
"username": "test_user",
"password": "incorrect"
}`
TestPostRequest(t, userData, "/api/signin", 403, "Incorrect Password")
TestPostRequest(t, userData, "/api/signin", 403, "Incorrect Password", true)

}
func TestNoUserErrorSignin(t *testing.T) {
userData := `{
"username": "test_user_not_found",
"password": "password"
}`
TestPostRequest(t, userData, "/api/signin", 404, "User not found")
TestPostRequest(t, userData, "/api/signin", 404, "User not found", true)
}

func TestMissingFieldErrorSignin(t *testing.T) {
userData := `{
"username": "test_user"
}`
TestPostRequest(t, userData, "/api/signin", 500, "Field not found")
TestPostRequest(t, userData, "/api/signin", 500, "Field not found", true)
}

func TestCreateOtherUsers(t *testing.T) {
userData := `{
"username": "related_user",
"name": "related_user",
"email": "[email protected]",
"password": "password",
"phone": "+1234557890",
"image": "https://example.com/avatar.png"
}`
TestPostRequest(t, userData, "/api/signup", 201, "User created successfully", true)
userData2 := `{
"username": "not_allowed_user",
"name": "not_allowed_user",
"email": "[email protected]",
"password": "password",
"phone": "+1234457890",
"image": "https://example.com/avatar.png"
}`
TestPostRequest(t, userData2, "/api/signup", 201, "User created successfully", true)
}

// logged in related user
func TestLoginRelatedUserUsingEmail(t *testing.T) {
userData := `{
"email": "[email protected]",
"password": "password"
}`
TestPostRequest(t, userData, "/api/signin", 200, "Login successfull", true)
}
func TestLoginNotAllowedUserUsingPhone(t *testing.T) {
userData := `{
"phone": "+1234457890",
"password": "password"
}`
TestPostRequest(t, userData, "/api/signin", 200, "Login successfull", true)
}
34 changes: 0 additions & 34 deletions test/friend_request_test.go

This file was deleted.

92 changes: 88 additions & 4 deletions test/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,36 @@ import (
"github.com/piyush7833/Chat-Api/helpers"
)

func TestPostRequest(t *testing.T, data string, url string, expectedStatusCode int, expectedMessage string) {
r, _ := InitRoutes()
func TestPostRequest(t *testing.T, data string, url string, expectedStatusCode int, expectedMessage string, isAuthorized bool) {
r := InitRoutes()
ts := httptest.NewServer(r)
defer ts.Close()

// fmt.Println(strings.NewReader(data), "post")

req, err := http.NewRequest("POST", ts.URL+url, strings.NewReader(data))
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
if isAuthorized {
req.Header.Set("Cookie", "token="+*token)
} else {
req.Header.Set("Cookie", "token=unauthorized token")
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer res.Body.Close()
if url == "/api/signin" {
for _, cookie := range res.Cookies() {
if cookie.Name == "token" {
token = &cookie.Value
break
}
}
}
if res.StatusCode != expectedStatusCode {
t.Errorf("expected status %d; got %d", expectedStatusCode, res.StatusCode)
var errorResponse helpers.ErrorResponse
Expand All @@ -35,15 +51,83 @@ func TestPostRequest(t *testing.T, data string, url string, expectedStatusCode i
}
}

func TestGetRequest(t *testing.T, url string, expectedStatusCode int, expectedMessage string) {
r, _ := InitRoutes()
func TestPatchRequest(t *testing.T, data string, url string, expectedStatusCode int, expectedMessage string, isAuthorized bool) {
r := InitRoutes()
ts := httptest.NewServer(r)
defer ts.Close()

req, err := http.NewRequest("PATCH", ts.URL+url, strings.NewReader(data))

if err != nil {
t.Fatalf("failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
if isAuthorized {
req.Header.Set("Cookie", "token="+*token)
} else {
req.Header.Set("Cookie", "token=unauthorized token")
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer res.Body.Close()

if res.StatusCode != expectedStatusCode {
t.Errorf("expected status %d; got %d", expectedStatusCode, res.StatusCode)
var errorResponse helpers.ErrorResponse
err = json.NewDecoder(res.Body).Decode(&errorResponse)
if err != nil {
t.Fatalf("failed to decode error response: %v", err)
}
t.Logf("Error message: %s", errorResponse.Message)
}
}

func TestGetRequest(t *testing.T, url string, expectedStatusCode int, expectedMessage string, isAuthorized bool) {
r := InitRoutes()
ts := httptest.NewServer(r)
defer ts.Close()
req, err := http.NewRequest("GET", ts.URL+url, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
if isAuthorized {
req.Header.Set("Cookie", "token="+*token)
} else {
req.Header.Set("Cookie", "token=unauthorized token")
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer res.Body.Close()
if res.StatusCode != expectedStatusCode {
t.Errorf("expected status %d; got %d", expectedStatusCode, res.StatusCode)
var errorResponse helpers.ErrorResponse
err = json.NewDecoder(res.Body).Decode(&errorResponse)
if err != nil {
t.Fatalf("failed to decode error response: %v", err)
}
t.Logf("Error message: %s", errorResponse.Message)
}
}

func TestDeleteRequest(t *testing.T, url string, expectedStatusCode int, expectedMessage string, isAuthorized bool) {
r := InitRoutes()
ts := httptest.NewServer(r)
defer ts.Close()
req, err := http.NewRequest("DELETE", ts.URL+url, nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
if isAuthorized {
req.Header.Set("Cookie", "token="+*token)
} else {
req.Header.Set("Cookie", "token=unauthorized token")
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
Expand Down
10 changes: 7 additions & 3 deletions test/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,29 @@ import (
"github.com/piyush7833/Chat-Api/services"
)

var token *string

func Init() error {
if os.Getenv("ENVIRONMENT") == "" || os.Getenv("ENVIRONMENT") == "test" {
if err := godotenv.Load(".env.test"); err != nil {
return err
}
}
mytoken := "token"
token = &mytoken
services.ConnectDb()
scripts.CreateTables()
return nil
}

func InitRoutes() (*mux.Router, *mux.Router) {
func InitRoutes() *mux.Router {
router := mux.NewRouter()
protectedRouter := router.PathPrefix("/api/protected").Subrouter()
protectedRouter.Use(middlewares.AuthMiddleware)
routes.AuthRoutes(router.PathPrefix("/api").Subrouter())
routes.UserRoutes(router.PathPrefix("/api/user").Subrouter(), protectedRouter.PathPrefix("/user").Subrouter())
routes.FriendRequestRoutes(router.PathPrefix("/api/fr").Subrouter(), protectedRouter.PathPrefix("/fr").Subrouter())
return router, protectedRouter
routes.UserRelationRoutes(router.PathPrefix("/api/ur").Subrouter(), protectedRouter.PathPrefix("/ur").Subrouter())

Check failure on line 35 in test/init.go

View workflow job for this annotation

GitHub Actions / lint

undefined: routes.UserRelationRoutes
return router
}

func Close() {
Expand Down
78 changes: 78 additions & 0 deletions test/order_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package test

import (
"fmt"
"log"
"os"
"testing"
Expand All @@ -18,11 +19,88 @@ func TestMain(m *testing.M) {

func TestOrder(t *testing.T) {

//tests for main user logged in
t.Run("TestCreateUser", TestCreateUser)
t.Run("TestDuplicateUserError", TestDuplicateUserError)
t.Run("TestMissingFieldErrorSignup", TestMissingFieldErrorSignup)
t.Run("TestLoginUser", TestLoginUser)

t.Run("TestIncorrectPasswordError", TestIncorrectPasswordError)
t.Run("TestNoUserErrorSignin", TestNoUserErrorSignin)
t.Run("TestMissingFieldErrorSignin", TestMissingFieldErrorSignin)

t.Run("TestGetAllUser", TestGetAllUser)
t.Run("TestGetAllUserErrorUnAuthorized", TestGetAllUserErrorUnAuthorized)
t.Run("TestGetAllUserErrorInvalidColumns", TestGetAllUserErrorInvalidColumns)

t.Run("TestGetUserById", TestGetUserById)
t.Run("TestGetUserByIdErrorInvalidColumns", TestGetUserByIdErrorInvalidColumns)
t.Run("TestGetUserByIdErrorUnauthorized", TestGetUserByIdErrorUnauthorized)
t.Run("TestGetUserByIdErrorUserNotFound", TestGetUserByIdErrorUserNotFound)

t.Run("TestGetUserByUsername", TestGetUserByUsername)
t.Run("TestGetUserByUsernameErrorInvalidColumns", TestGetUserByUsernameErrorInvalidColumns)
t.Run("TestGetUserByUsernameErrorUnauthorized", TestGetUserByUsernameErrorUnauthorized)
t.Run("TestGetUserByUsernameErrorUserNotFound", TestGetUserByUsernameErrorUserNotFound)

t.Run("TestGetAuthenticatedUser", TestGetAuthenticatedUser)
t.Run("TestGetAuthenticatedUserErrorUnAuthorized", TestGetAuthenticatedUserErrorUnauthorized)
t.Run("TestGetAuthenticatedUserErrorInvalidColumns", TestGetAuthenticatedUserErrorInvalidColumns)

t.Run("TestUpdateUserErrorInvalidColumns", TestUpdateUserErrorInvalidColumns)
t.Run("TestUpdateUserErrorUnauthorized", TestUpdateUserErrorUnauthorized)

// // create other users after testing user routes
t.Run("TestCreateOtherUsers", TestCreateOtherUsers)

t.Run("TestCreateUserRelation", TestCreateUserRelation)
t.Run("TestCreateUserRelationErrorDuplicateRelation", TestCreateUserRelationErrorDuplicateRelation)
// t.Run("TestCreateUserRelationErrorRelationAlreadyExist",TestCreateUserRelationErrorRelationAlreadyExist) //need to handle
t.Run("TestCreateUserRelationErrorUnauthorized", TestCreateUserRelationErrorUnauthorized)
t.Run("TestCreateUserRelationErrorInvalidRelatedUserId", TestCreateUserRelationErrorInvalidRelatedUserId)

t.Run("TestGetAllUserRelation", TestGetAllUserRelation)
t.Run("TestGetAllUserRelationParticularStatus", TestGetAllUserRelationParticularStatus)
t.Run("TestGetAllUserRelationParticularType", TestGetAllUserRelationParticularType)
t.Run("TestGetAllUserRelationParticularTypeParticularStatus", TestGetAllUserRelationParticularTypeParticularStatus)
t.Run("TestGetAllUserRelationErrorUnauthorized", TestGetAllUserRelationErrorUnauthorized)
t.Run("TestGetAllUserRelationErrorInvalidColumns", TestGetAllUserRelationErrorInvalidColumns)
t.Run("TestGetAllUserRelationErrorInvalidStatus", TestGetAllUserRelationErrorInvalidStatus)
t.Run("TestGetAllUserRelationErrorInvalidType", TestGetAllUserRelationErrorInvalidType)

t.Run("TestGetParticularUserRelation", TestGetParticularUserRelation)
t.Run("TestGetParticularUserRelationErrorUserRelationNotFound", TestGetParticularUserRelationErrorUserRelationNotFound)
t.Run("TestGetParticularUserRelationErrorInvalidColumn", TestGetParticularUserRelationErrorInvalidColumn)
t.Run("TestGetParticularUserRelationErrorUnauthorized", TestGetParticularUserRelationErrorUnauthorized)

t.Run("TestUpdateUserRelationErrorNotAllowed", TestUpdateUserRelationErrorNotAllowed)
t.Run("TestUpdateUserRelationErrorStatusNotProvided", TestUpdateUserRelationErrorStatusNotProvided)
t.Run("TestUpdateUserRelationErrorNotFound", TestUpdateUserRelationErrorNotFound)
t.Run("TestUpdateUserRelationErrorUnauthorized", TestUpdateUserRelationErrorUnauthorized)

t.Run("TestDeleteUserRelationErrorNotFound", TestDeleteUserRelationErrorNotFound)
t.Run("TestDeleteUserRelationErrorUnauthorised", TestDeleteUserRelationErrorUnauthorised)

// //tests for related user logged in
t.Run("Test login related user", TestLoginRelatedUserUsingEmail)

t.Run("TestUpdateUserRelation", TestUpdateUserRelation)
t.Run("TestUpdateUserRelationErrorNotAllowedToRevertToPendingStatus", TestUpdateUserRelationErrorNotAllowedToRevertToPendingStatus)

//tests for third user who is not allowed for things
t.Run("Test login not allowed user", TestLoginNotAllowedUserUsingPhone)

t.Run("TestUpdateUserRelationErrorNotAllowed", TestUpdateUserRelationErrorNotAllowed)
t.Run("TestGetParticularUserRelationErrorNotAllowed", TestGetParticularUserRelationErrorNotAllowed)
t.Run("TestDeleteUserRelationErrorNotAllowed", TestDeleteUserRelationErrorNotAllowed)

// //delete/update tests for main user logged in user
t.Run("Test login main user", TestLoginUser)
t.Run("TestUpdateUser", TestUpdateUser)
t.Run("TestDeleteUserRelation", TestDeleteUserRelation)

t.Run("TestDeleteUserErrorUnauthorized", TestDeleteUserErrorUnauthorized)
t.Run("TestDeleteUser", TestDeleteUser)

fmt.Println("All tests passed successfully")
}
Loading

0 comments on commit cbb0540

Please sign in to comment.