Skip to content

Commit

Permalink
use TRUNCATE TABLE tenants CASCADE to empty DB for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
briskt committed Dec 9, 2023
1 parent 506682f commit 624bcce
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 17 deletions.
7 changes: 1 addition & 6 deletions db/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (

"github.com/briskt/keygo/app"
"github.com/briskt/keygo/db"
"github.com/briskt/keygo/migrations"
)

// TestSuite contains common setup and configuration for tests
Expand All @@ -26,12 +25,8 @@ type TestSuite struct {

// SetupTest runs before every test function
func (ts *TestSuite) SetupTest() {
if sqlDB, err := ts.DB.DB(); err != nil {
panic(err.Error())
} else {
migrations.Fresh(sqlDB)
}
ts.Assertions = require.New(ts.T())
ts.NoError(ts.DB.Exec("TRUNCATE TABLE tenants CASCADE").Error)
}

func Test_RunSuite(t *testing.T) {
Expand Down
13 changes: 2 additions & 11 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ type Fixtures struct {
func (ts *TestSuite) SetupTest() {
ts.Assertions = require.New(ts.T())

deleteAll(ts.ctx, &db.Tenant{})
deleteAll(ts.ctx, &db.Token{})
deleteAll(ts.ctx, &db.User{})
ts.NoError(ts.tx.Exec("TRUNCATE TABLE tenants CASCADE").Error)
}

func Test_RunSuite(t *testing.T) {
Expand Down Expand Up @@ -89,13 +87,6 @@ func (ts *TestSuite) createTenantFixture() db.Tenant {
return createdTenant
}

func deleteAll(c echo.Context, i any) {
result := db.Tx(c).Where("TRUE").Delete(i)
if result.Error != nil {
panic(fmt.Sprintf("failed to delete all %T: %s", i, result.Error))
}
}

// RandStr generates a random string of length `n` containing uppercase, lowercase, and numbers
func RandStr(n int) string {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Expand Down Expand Up @@ -130,7 +121,7 @@ func (ts *TestSuite) createTokenFixture(plainText, userID string) db.Token {
PlainText: plainText,
ExpiresAt: time.Now().Add(time.Hour * 24),
}
err := db.Tx(ts.ctx).Omit("User").Create(&token).Error
err := ts.tx.Omit("User").Create(&token).Error
if err != nil {
panic("failed to create token fixture: " + err.Error())
}
Expand Down

0 comments on commit 624bcce

Please sign in to comment.