Files
softplayer-backend/internal/controllers/accounts_test.go
Nikolai Rodionov 60297dfaf7
Some checks failed
ci/woodpecker/push/build Pipeline failed
Start adding tests
Signed-off-by: Nikolai Rodionov <allanger@badhouseplants.net>
2026-05-17 16:14:59 +02:00

92 lines
2.1 KiB
Go

package controllers_test
import (
"database/sql"
"fmt"
"os"
"testing"
"time"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/controllers"
"gitea.badhouseplants.net/softplayer/softplayer-backend/internal/helpers/postgres"
"github.com/google/uuid"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
)
func newTestDbConnection() *sql.DB {
connStr, ok := os.LookupEnv("SOFTPLAYER_DB_CONNECTION_STRING")
if !ok {
panic("set the db connection string env var")
}
db, err := postgres.Open(connStr)
if err != nil {
panic(err)
}
return db
}
func newTestRedisConnection() *redis.Client {
connStr, ok := os.LookupEnv("SOFTPLAYER_REDIS_HOST")
if !ok {
panic("set the redis connection string env var")
}
return redis.NewClient(&redis.Options{
Addr: connStr,
})
}
func newTestAccountController() *controllers.AccountController {
return &controllers.AccountController{
DB: newTestDbConnection(),
Redis: newTestRedisConnection(),
DevMode: true,
HashCost: 3,
AccessTokenTTL: time.Second * 10,
RefreshTokenTTL: time.Second * 15,
JWTSecret: []byte("test-secret"),
}
}
func newTestUniqueEmail(prefix string) string {
if prefix == "" {
prefix = "test"
}
return fmt.Sprintf(
"%s-%d-%s@example.com",
prefix,
time.Now().UnixMilli(),
uuid.NewString(),
)
}
func TestIntegrationAccountCreate_Success(t *testing.T) {
ctrl := newTestAccountController()
accountData := &controllers.AccountData{
Password: "qwertyu9",
Email: newTestUniqueEmail("accounts"),
}
id, err := ctrl.Create(t.Context(), accountData)
assert.NoError(t, err)
assert.NotEmpty(t, id)
}
func TestIntegrationAccountCreate_ExistingAccountErr(t *testing.T) {
ctrl := newTestAccountController()
email := newTestUniqueEmail("accounts")
accountData := &controllers.AccountData{
Password: "qwertyu9",
Email: email,
}
id, err := ctrl.Create(t.Context(), accountData)
assert.NoError(t, err)
assert.NotEmpty(t, id)
id, err = ctrl.Create(t.Context(), accountData)
assert.Empty(t, id)
assert.Error(t, err)
assert.ErrorIs(t, err, controllers.ErrEmailUsed)
}