Skip to content

Commit

Permalink
Merge pull request #6 from basemind-ai/BM-0001-tests
Browse files Browse the repository at this point in the history
feat(infrastructure): setup mock db env
  • Loading branch information
Goldziher authored Aug 28, 2023
2 parents bd75ba6 + 5f574f7 commit 2ef49dd
Show file tree
Hide file tree
Showing 14 changed files with 512 additions and 221 deletions.
5 changes: 3 additions & 2 deletions .github/workflows/ci-tests-go.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ jobs:
id-token: write
steps:
- uses: actions/checkout@v3

- name: Setup Golang
uses: actions/setup-go@v4
with:
Expand All @@ -41,7 +40,9 @@ jobs:
if: steps.cached-go-dependencies.outputs.cache-hit != 'true'
shell: bash
run: go get -v -t ./...

- name: Install Atlas
shell: bash
run: curl -sSf https://atlasgo.sh | sh
- name: Authenticate with GCP
id: auth
uses: google-github-actions/[email protected]
Expand Down
2 changes: 0 additions & 2 deletions .github/workflows/ci-tests-ts.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3

- name: Setup Node
uses: actions/setup-node@v3
with:
Expand All @@ -46,7 +45,6 @@ jobs:
restore-keys: ${{ runner.os }}-pnpm-store-
- name: Install Node dependencies
run: pnpm install -r

- name: Test
run: pnpm run test:coverage
- name: Coverage
Expand Down
16 changes: 9 additions & 7 deletions .idea/runConfigurations/All_Tests.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 7 additions & 9 deletions .idea/runConfigurations/All_Tests2.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ repos:
- id: prettier
exclude: 'go.mod'
- repo: https://github.com/pre-commit/mirrors-eslint
rev: 'v8.47.0'
rev: 'v8.48.0'
hooks:
- id: eslint
files: \.ts$
Expand Down
4 changes: 2 additions & 2 deletions Taskfile.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ tasks:
migrations:apply:
desc: Apply the migrations to the local database
cmds:
- task: db-up
- task: db:up
- sleep 2
- atlas migrate apply --dir "file://sql/migrations" --url "postgresql://basemind:basemind@localhost:5432/basemind?search_path=public&sslmode=disable"
migrations:create:
desc: Create a new migration
cmds:
- task: db-up
- task: db:up
- sleep 2
- atlas migrate diff {{.CLI_ARGS}} --dir "file://sql/migrations" --to "file://sql/schema.sql" --dev-url "postgresql://basemind:basemind@localhost:5432/basemind?search_path=public&sslmode=disable"
114 changes: 65 additions & 49 deletions go-services/dashboard-backend/api/api.go
Original file line number Diff line number Diff line change
@@ -1,79 +1,95 @@
package api

import (
"context"
"net/http"

"github.com/basemind-ai/monorepo/go-services/dashboard-backend/config"
"github.com/basemind-ai/monorepo/go-services/dashboard-backend/constants"
"github.com/basemind-ai/monorepo/go-shared/apierror"
"github.com/basemind-ai/monorepo/go-shared/db"
"github.com/basemind-ai/monorepo/go-shared/serialization"
"github.com/rs/zerolog/log"
"net/http"

"github.com/go-chi/chi/v5"
)

func HandleCreateNewUser(ctx context.Context, dbQueries *db.Queries, firebaseId string) (*HandleDashboardUserPostLoginDTO, error) {
user, createUserErr := dbQueries.CreateUser(ctx, firebaseId)
if createUserErr != nil {
log.Error().Err(createUserErr).Msg("failed to create user row")
return nil, createUserErr
}

project, createProjectErr := dbQueries.CreateProject(ctx, db.CreateProjectParams{Name: "Default Project", Description: "Default Project"})
if createProjectErr != nil {
log.Error().Err(createProjectErr).Msg("failed to create project row")
return nil, createProjectErr
}

userProject, createUserProjectErr := dbQueries.CreateUserProject(ctx, db.CreateUserProjectParams{
UserID: user.ID,
ProjectID: project.ID,
Permission: db.AccessPermissionTypeADMIN,
IsUserDefaultProject: true,
})
if createUserProjectErr != nil {
log.Error().Err(createUserProjectErr).Msg("failed to create user project row")
return nil, createUserProjectErr
}

var userProjects = []db.FindProjectsByUserIdRow{{
ID: project.ID,
CreatedAt: project.CreatedAt,
Name: project.Name,
Description: project.Description,
Permission: userProject.Permission,
IsUserDefaultProject: userProject.IsUserDefaultProject,
}}

return &HandleDashboardUserPostLoginDTO{User: user, Projects: userProjects}, nil
}

func HandleRetrieveUserProjects(ctx context.Context, dbQueries *db.Queries, firebaseId string) (*HandleDashboardUserPostLoginDTO, error) {
user, findUserErr := dbQueries.FindUserByFirebaseId(ctx, firebaseId)
if findUserErr != nil {
log.Error().Err(findUserErr).Msg("failed to find user")
return nil, findUserErr
}

userProjects, findProjectsErr := dbQueries.FindProjectsByUserId(ctx, user.ID)
if findProjectsErr != nil {
log.Error().Err(findProjectsErr).Msg("failed to find user projects")
return nil, findProjectsErr
}

return &HandleDashboardUserPostLoginDTO{User: user, Projects: userProjects}, nil
}

func HandleDashboardUserPostLogin(w http.ResponseWriter, r *http.Request) {
firebaseId := r.Context().Value(constants.FireBaseIdContextKey).(string)

if userExists, queryErr := db.GetQueries().CheckUserExists(r.Context(), firebaseId); queryErr != nil {
log.Error().Err(queryErr).Msg("failed to retrieve user")
dbQueries := db.GetQueries()

if userExists, userExistsErr := dbQueries.CheckUserExists(r.Context(), firebaseId); userExistsErr != nil {
log.Error().Err(userExistsErr).Msg("failed to check user exists")
_ = apierror.InternalServerError().Render(w, r)
return
} else if !userExists {
user, queryErr := db.GetQueries().CreateUser(r.Context(), firebaseId)
if queryErr != nil {
log.Error().Err(queryErr).Msg("failed to create user")
_ = apierror.InternalServerError().Render(w, r)
return
}

project, queryErr := db.GetQueries().CreateProject(r.Context(), db.CreateProjectParams{Name: "Default Project", Description: "Default Project"})
if queryErr != nil {
log.Error().Err(queryErr).Msg("failed to create project")
_ = apierror.InternalServerError().Render(w, r)
return
}

userProject, queryErr := db.GetQueries().CreateUserProject(r.Context(), db.CreateUserProjectParams{
UserID: user.ID,
ProjectID: project.ID,
Permission: db.AccessPermissionTypeADMIN,
IsUserDefaultProject: true,
})
if queryErr != nil {
log.Error().Err(queryErr).Msg("failed to create user project mapping")
responseDTO, err := HandleCreateNewUser(r.Context(), dbQueries, firebaseId)
if err != nil {
_ = apierror.InternalServerError().Render(w, r)
return
}

var userProjects = []db.FindProjectsByUserIdRow{{
ID: project.ID,
CreatedAt: project.CreatedAt,
Name: project.Name,
Description: project.Description,
Permission: userProject.Permission,
IsUserDefaultProject: userProject.IsUserDefaultProject,
}}

responseDTO := HandleDashboardUserPostLoginDTO{User: user, Projects: userProjects}

_ = serialization.RenderJsonResponse(w, http.StatusCreated, responseDTO)
return
} else {
user, queryErr := db.GetQueries().FindUserByFirebaseId(r.Context(), firebaseId)
if queryErr != nil {
log.Error().Err(queryErr).Msg("failed to find user")
_ = apierror.InternalServerError().Render(w, r)
return
}
responseDTO, err := HandleRetrieveUserProjects(r.Context(), dbQueries, firebaseId)

userProjects, queryErr := db.GetQueries().FindProjectsByUserId(r.Context(), user.ID)
if queryErr != nil {
log.Error().Err(queryErr).Msg("failed to find user projects")
if err != nil {
_ = apierror.InternalServerError().Render(w, r)
return
}

responseDTO := HandleDashboardUserPostLoginDTO{User: user, Projects: userProjects}

_ = serialization.RenderJsonResponse(w, http.StatusOK, responseDTO)
}
}
Expand Down
75 changes: 75 additions & 0 deletions go-services/dashboard-backend/api/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package api_test

import (
"net/http"
"net/http/httptest"
"testing"

dbTestUtils "github.com/basemind-ai/monorepo/go-shared/db/testutils"

"github.com/basemind-ai/monorepo/go-services/dashboard-backend/api"

"github.com/basemind-ai/monorepo/go-shared/serialization"

"github.com/basemind-ai/monorepo/go-services/dashboard-backend/constants"
firebaseTestUtils "github.com/basemind-ai/monorepo/go-shared/firebaseutils/testutils"
"github.com/stretchr/testify/assert"
)

func TestHandleDashboardUserPostLogin(t *testing.T) {
dbTestUtils.CreateTestDB(t)

t.Run("Create New User tests", func(t *testing.T) {
t.Run("success case", func(t *testing.T) {
rr := httptest.NewRecorder()

req, err := http.NewRequestWithContext(firebaseTestUtils.MockFirebaseContext(), http.MethodGet, constants.DashboardLoginEndpoint, nil)
assert.Nil(t, err)

api.HandleDashboardUserPostLogin(rr, req)
res := rr.Result()

assert.Equal(t, http.StatusCreated, res.StatusCode)

var responseUser api.HandleDashboardUserPostLoginDTO
err = serialization.DeserializeJson(res, &responseUser)

assert.Nil(t, err)
assert.Equal(t, "1", responseUser.User.FirebaseID)
assert.Equal(t, "Default Project", responseUser.Projects[0].Name)
assert.Equal(t, "Default Project", responseUser.Projects[0].Description)
})

t.Run("failure case - failed to create user", func(t *testing.T) {})
t.Run("failure case - failed to create project", func(t *testing.T) {})
t.Run("failure case - failed to create user-project", func(t *testing.T) {})
})

t.Run("Retrieves a existing user tests", func(t *testing.T) {
t.Run("success case", func(t *testing.T) {
req, err := http.NewRequestWithContext(firebaseTestUtils.MockFirebaseContext(), http.MethodGet, constants.DashboardLoginEndpoint, nil)
assert.Nil(t, err)
api.HandleDashboardUserPostLogin(httptest.NewRecorder(), req)

req, err = http.NewRequestWithContext(firebaseTestUtils.MockFirebaseContext(), http.MethodGet, constants.DashboardLoginEndpoint, nil)
assert.Nil(t, err)

rr := httptest.NewRecorder()
api.HandleDashboardUserPostLogin(rr, req)

res := rr.Result()
assert.Equal(t, http.StatusOK, res.StatusCode)

var responseUser api.HandleDashboardUserPostLoginDTO
err = serialization.DeserializeJson(res, &responseUser)

assert.Nil(t, err)
assert.Equal(t, "1", responseUser.User.FirebaseID)
assert.Equal(t, "Default Project", responseUser.Projects[0].Name)
assert.Equal(t, "Default Project", responseUser.Projects[0].Description)
})

t.Run("failure case - failed to retrieve user", func(t *testing.T) {})
t.Run("failure case - failed to retrieve user projects", func(t *testing.T) {})
})
}
4 changes: 4 additions & 0 deletions go-shared/db/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ func GetQueries() *Queries {
})
return queries
}

func SetConnection(conn *pgx.Conn) {
connection = conn
}
Loading

0 comments on commit 2ef49dd

Please sign in to comment.