test: added more tests

This commit is contained in:
Reinaldy Rafli 2021-11-08 19:39:29 +07:00
parent a308c0a7a2
commit 05120c23ab
No known key found for this signature in database
GPG Key ID: CFDB9400255D8CB6
12 changed files with 270 additions and 219 deletions

View File

@ -4,19 +4,23 @@ import (
"context" "context"
"jokes-bapak2-api/core/administrator" "jokes-bapak2-api/core/administrator"
"testing" "testing"
"time"
) )
func TestGetUserID_Success(t *testing.T) { func TestGetUserID_Success(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
c, err := db.Acquire(context.Background()) c, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer c.Release() defer c.Release()
_, err = c.Exec( _, err = c.Exec(
context.Background(), ctx,
`INSERT INTO administrators (id, key, token, last_used) VALUES ($1, $2, $3, $4)`, `INSERT INTO administrators (id, key, token, last_used) VALUES ($1, $2, $3, $4)`,
administratorsData..., administratorsData...,
) )
@ -24,7 +28,7 @@ func TestGetUserID_Success(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
id, err := administrator.GetUserID(db, context.Background(), "very secure") id, err := administrator.GetUserID(db, ctx, "very secure")
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
@ -35,15 +39,18 @@ func TestGetUserID_Success(t *testing.T) {
} }
func TestGetUserID_Failed(t *testing.T) { func TestGetUserID_Failed(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
c, err := db.Acquire(context.Background()) defer Flush()
c, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer c.Release() defer c.Release()
id, err := administrator.GetUserID(db, context.Background(), "very secure") id, err := administrator.GetUserID(db, ctx, "very secure")
if err == nil { if err == nil {
t.Error("an error was expected, got:", id) t.Error("an error was expected, got:", id)
} }

View File

@ -23,43 +23,32 @@ func TestMain(m *testing.M) {
} }
func Setup() { func Setup() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Minute))
defer cancel()
poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL")) poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil { if err != nil {
panic(err) panic(err)
} }
db, err = pgxpool.ConnectConfig(context.Background(), poolConfig) db, err = pgxpool.ConnectConfig(ctx, poolConfig)
if err != nil { if err != nil {
panic(err) panic(err)
} }
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer conn.Release() defer conn.Release()
tx, err := conn.Begin(ctx)
tx, err := conn.Begin(context.Background())
if err != nil {
panic(err)
}
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS submission")
if err != nil {
panic(err)
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS jokesbapak2")
if err != nil {
panic(err)
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS administrators")
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer tx.Rollback(ctx)
_, err = tx.Exec( _, err = tx.Exec(
context.Background(), ctx,
`CREATE TABLE IF NOT EXISTS administrators ( `CREATE TABLE IF NOT EXISTS administrators (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
key VARCHAR(255) NOT NULL UNIQUE, key VARCHAR(255) NOT NULL UNIQUE,
@ -71,49 +60,62 @@ func Setup() {
panic(err) panic(err)
} }
err = tx.Commit(context.Background()) err = tx.Commit(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
} }
} }
func Teardown() (err error) { func Teardown() (err error) {
tx, err := db.Begin(context.Background()) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Minute))
if err != nil { defer cancel()
return err
}
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS submission") defer db.Close()
c, err := db.Acquire(ctx)
if err != nil { if err != nil {
return err return err
} }
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS jokesbapak2") defer c.Release()
tx, err := c.Begin(ctx)
if err != nil { if err != nil {
return err return err
} }
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS administrators") defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, "TRUNCATE TABLE submission RESTART IDENTITY CASCADE")
if err != nil {
return err
}
_, err = tx.Exec(ctx, "TRUNCATE TABLE jokesbapak2 RESTART IDENTITY CASCADE")
if err != nil {
return err
}
_, err = tx.Exec(ctx, "TRUNCATE TABLE administrators RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }
err = tx.Commit(context.Background()) err = tx.Commit(ctx)
if err != nil { if err != nil {
return err return err
} }
db.Close()
return return
} }
func Flush() error { func Flush() error {
conn, err := db.Acquire(context.Background()) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
return err return err
} }
defer conn.Release() defer conn.Release()
_, err = conn.Exec(context.Background(), "TRUNCATE TABLE administrators") _, err = conn.Exec(ctx, "TRUNCATE TABLE administrators RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }

View File

@ -4,21 +4,23 @@ import (
"context" "context"
"jokes-bapak2-api/core/administrator" "jokes-bapak2-api/core/administrator"
"testing" "testing"
"time"
) )
func TestCheckKeyExists_Success(t *testing.T) { func TestCheckKeyExists_Success(t *testing.T) {
t.Cleanup(func() { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
Flush() defer cancel()
})
c, err := db.Acquire(context.Background()) defer Flush()
c, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer c.Release() defer c.Release()
_, err = c.Exec( _, err = c.Exec(
context.Background(), ctx,
"INSERT INTO administrators (id, key, token, last_used) VALUES ($1, $2, $3, $4)", "INSERT INTO administrators (id, key, token, last_used) VALUES ($1, $2, $3, $4)",
administratorsData..., administratorsData...,
) )
@ -26,7 +28,7 @@ func TestCheckKeyExists_Success(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
key, err := administrator.CheckKeyExists(db, context.Background(), "very secure") key, err := administrator.CheckKeyExists(db, ctx, "very secure")
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
@ -37,18 +39,19 @@ func TestCheckKeyExists_Success(t *testing.T) {
} }
func TestCheckKeyExists_Failing(t *testing.T) { func TestCheckKeyExists_Failing(t *testing.T) {
t.Cleanup(func() { ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
Flush() defer cancel()
})
defer Flush()
c, err := db.Acquire(context.Background()) c, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer c.Release() defer c.Release()
_, err = c.Exec( _, err = c.Exec(
context.Background(), ctx,
"INSERT INTO administrators (id, key, token, last_used) VALUES ($1, $2, $3, $4)", "INSERT INTO administrators (id, key, token, last_used) VALUES ($1, $2, $3, $4)",
administratorsData..., administratorsData...,
) )
@ -56,7 +59,7 @@ func TestCheckKeyExists_Failing(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
key, err := administrator.CheckKeyExists(db, context.Background(), "others") key, err := administrator.CheckKeyExists(db, ctx, "others")
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }

View File

@ -50,6 +50,7 @@ func GetRandomJokeFromDB(db *pgxpool.Pool, ctx context.Context) (string, error)
if err != nil { if err != nil {
return "", err return "", err
} }
defer conn.Release()
var link string var link string
err = conn.QueryRow(ctx, "SELECT link FROM jokesbapak2 ORDER BY random() LIMIT 1").Scan(&link) err = conn.QueryRow(ctx, "SELECT link FROM jokesbapak2 ORDER BY random() LIMIT 1").Scan(&link)

View File

@ -6,40 +6,44 @@ import (
"jokes-bapak2-api/core/joke" "jokes-bapak2-api/core/joke"
"jokes-bapak2-api/core/schema" "jokes-bapak2-api/core/schema"
"testing" "testing"
"time"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
func TestGetAllJSONJokes(t *testing.T) { func TestGetAllJSONJokes(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -52,7 +56,7 @@ func TestGetAllJSONJokes(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
j, err := joke.GetAllJSONJokes(db, context.Background()) j, err := joke.GetAllJSONJokes(db, ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
@ -63,35 +67,38 @@ func TestGetAllJSONJokes(t *testing.T) {
} }
func TestGetRandomJokeFromDB(t *testing.T) { func TestGetRandomJokeFromDB(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -104,7 +111,7 @@ func TestGetRandomJokeFromDB(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
j, err := joke.GetRandomJokeFromDB(db, context.Background()) j, err := joke.GetRandomJokeFromDB(db, ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
@ -114,8 +121,8 @@ func TestGetRandomJokeFromDB(t *testing.T) {
} }
} }
func TestGetRandomJokeFromCache(t *testing.T) { func TestGetRandomJokeFromCache(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
jokes := []schema.Joke{ jokes := []schema.Joke{
{ID: 1, Link: "link1", Creator: 1}, {ID: 1, Link: "link1", Creator: 1},
@ -143,7 +150,7 @@ func TestGetRandomJokeFromCache(t *testing.T) {
} }
func TestCheckJokesCache_True(t *testing.T) { func TestCheckJokesCache_True(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
jokes := []schema.Joke{ jokes := []schema.Joke{
{ID: 1, Link: "link1", Creator: 1}, {ID: 1, Link: "link1", Creator: 1},
@ -171,7 +178,7 @@ func TestCheckJokesCache_True(t *testing.T) {
} }
func TestCheckJokesCache_False(t *testing.T) { func TestCheckJokesCache_False(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
j, err := joke.CheckJokesCache(memory) j, err := joke.CheckJokesCache(memory)
if err != nil { if err != nil {
@ -184,7 +191,7 @@ func TestCheckJokesCache_False(t *testing.T) {
} }
func TestCheckTotalJokesCache_True(t *testing.T) { func TestCheckTotalJokesCache_True(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
err := memory.Set("total", []byte("10")) err := memory.Set("total", []byte("10"))
if err != nil { if err != nil {
@ -202,7 +209,7 @@ func TestCheckTotalJokesCache_True(t *testing.T) {
} }
func TestCheckTotalJokesCache_False(t *testing.T) { func TestCheckTotalJokesCache_False(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
j, err := joke.CheckTotalJokesCache(memory) j, err := joke.CheckTotalJokesCache(memory)
if err != nil { if err != nil {
@ -215,7 +222,7 @@ func TestCheckTotalJokesCache_False(t *testing.T) {
} }
func TestGetCachedJokeByID(t *testing.T) { func TestGetCachedJokeByID(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
jokes := []schema.Joke{ jokes := []schema.Joke{
{ID: 1, Link: "link1", Creator: 1}, {ID: 1, Link: "link1", Creator: 1},
@ -243,7 +250,7 @@ func TestGetCachedJokeByID(t *testing.T) {
k, err := joke.GetCachedJokeByID(memory, 4) k, err := joke.GetCachedJokeByID(memory, 4)
if err == nil { if err == nil {
t.Error("an error was not thrown") t.Error("an error was not thrown, k:", k)
} }
if k != "" { if k != "" {
@ -252,7 +259,7 @@ func TestGetCachedJokeByID(t *testing.T) {
} }
func TestGetCachedTotalJokes(t *testing.T) { func TestGetCachedTotalJokes(t *testing.T) {
t.Cleanup(func() { Flush() }) defer Flush()
err := memory.Set("total", []byte("10")) err := memory.Set("total", []byte("10"))
if err != nil { if err != nil {
@ -270,35 +277,38 @@ func TestGetCachedTotalJokes(t *testing.T) {
} }
func TestCheckJokeExists(t *testing.T) { func TestCheckJokeExists(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -311,7 +321,7 @@ func TestCheckJokeExists(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
j, err := joke.CheckJokeExists(db, context.Background(), "1") j, err := joke.CheckJokeExists(db, ctx, "1")
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
@ -320,7 +330,7 @@ func TestCheckJokeExists(t *testing.T) {
t.Error("j should not be false") t.Error("j should not be false")
} }
k, err := joke.CheckJokeExists(db, context.Background(), "4") k, err := joke.CheckJokeExists(db, ctx, "4")
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }

View File

@ -27,17 +27,21 @@ var administratorsData = []interface{}{
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
defer Teardown() defer Teardown()
Setup() Setup()
time.Sleep(3 * time.Second)
os.Exit(m.Run()) os.Exit(m.Run())
} }
func Setup() { func Setup() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Minute))
defer cancel()
poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL")) poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil { if err != nil {
panic(err) panic(err)
} }
db, err = pgxpool.ConnectConfig(context.Background(), poolConfig) db, err = pgxpool.ConnectConfig(ctx, poolConfig)
if err != nil { if err != nil {
panic(err) panic(err)
} }
@ -54,102 +58,98 @@ func Setup() {
panic(err) panic(err)
} }
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer conn.Release() defer conn.Release()
tx, err := conn.Begin(context.Background()) tx, err := conn.Begin(ctx)
if err != nil {
panic(err)
}
defer tx.Rollback(context.Background())
// Dropping all table first
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS submission")
if err != nil {
panic(err)
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS jokesbapak2")
if err != nil {
panic(err)
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS administrators")
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer tx.Rollback(ctx)
_, err = tx.Exec( _, err = tx.Exec(
context.Background(), ctx,
`CREATE TABLE IF NOT EXISTS administrators ( `CREATE TABLE IF NOT EXISTS administrators (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
key VARCHAR(255) NOT NULL UNIQUE, key VARCHAR(255) NOT NULL UNIQUE,
token TEXT, token TEXT,
last_used VARCHAR(255) last_used VARCHAR(255)
);`, )`,
) )
if err != nil { if err != nil {
panic(err) panic(err)
} }
_, err = tx.Exec( _, err = tx.Exec(
context.Background(), ctx,
`CREATE TABLE IF NOT EXISTS jokesbapak2 ( `CREATE TABLE IF NOT EXISTS jokesbapak2 (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
link TEXT UNIQUE, link TEXT UNIQUE,
creator INT NOT NULL REFERENCES "administrators" ("id") creator INT NOT NULL REFERENCES "administrators" ("id")
);`, )`,
) )
if err != nil { if err != nil {
panic(err) panic(err)
} }
_, err = tx.Exec( _, err = tx.Exec(
context.Background(), ctx,
`CREATE TABLE IF NOT EXISTS submission ( `CREATE TABLE IF NOT EXISTS submission (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
link VARCHAR(255) UNIQUE NOT NULL, link VARCHAR(255) UNIQUE NOT NULL,
created_at VARCHAR(255), created_at VARCHAR(255),
author VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL,
status SMALLINT DEFAULT 0 status SMALLINT DEFAULT 0
);`, )`,
) )
if err != nil { if err != nil {
panic(err) panic(err)
} }
err = tx.Commit(context.Background()) err = tx.Commit(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
} }
} }
func Teardown() (err error) { func Teardown() (err error) {
tx, err := db.Begin(context.Background()) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
if err != nil { defer cancel()
return err
} defer db.Close()
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS submission") conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
return err return err
} }
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS jokesbapak2") defer conn.Release()
tx, err := conn.Begin(ctx)
if err != nil { if err != nil {
return err return err
} }
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS administrators") defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, "TRUNCATE TABLE submission RESTART IDENTITY CASCADE")
if err != nil {
return err
}
_, err = tx.Exec(ctx, "TRUNCATE TABLE jokesbapak2 RESTART IDENTITY CASCADE")
if err != nil {
return err
}
_, err = tx.Exec(ctx, "TRUNCATE TABLE administrators RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }
err = tx.Commit(context.Background()) err = tx.Commit(ctx)
if err != nil { if err != nil {
return err return err
} }
db.Close()
err = cache.Close() err = cache.Close()
if err != nil { if err != nil {
return return
@ -159,26 +159,29 @@ func Teardown() (err error) {
} }
func Flush() error { func Flush() error {
conn, err := db.Acquire(context.Background()) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
return err return err
} }
defer conn.Release() defer conn.Release()
_, err = conn.Exec(context.Background(), "TRUNCATE TABLE submission") _, err = conn.Exec(ctx, "TRUNCATE TABLE submission RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }
_, err = conn.Exec(context.Background(), "TRUNCATE TABLE jokesbapak2") _, err = conn.Exec(ctx, "TRUNCATE TABLE jokesbapak2 RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }
_, err = conn.Exec(context.Background(), "TRUNCATE TABLE administrators") _, err = conn.Exec(ctx, "TRUNCATE TABLE administrators RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }
err = cache.FlushAll(context.Background()).Err() err = cache.FlushAll(ctx).Err()
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,40 +5,44 @@ import (
"jokes-bapak2-api/core/joke" "jokes-bapak2-api/core/joke"
"jokes-bapak2-api/core/schema" "jokes-bapak2-api/core/schema"
"testing" "testing"
"time"
"github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4"
) )
func TestSetAllJSONJoke(t *testing.T) { func TestSetAllJSONJoke(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
conn, err := db.Acquire(context.Background()) defer Flush()
conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -51,42 +55,45 @@ func TestSetAllJSONJoke(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
err = joke.SetAllJSONJoke(db, context.Background(), memory) err = joke.SetAllJSONJoke(db, ctx, memory)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
} }
func TestSetTotalJoke(t *testing.T) { func TestSetTotalJoke(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -99,56 +106,62 @@ func TestSetTotalJoke(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
err = joke.SetTotalJoke(db, context.Background(), memory) err = joke.SetTotalJoke(db, ctx, memory)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
} }
func TestInsertJokeIntoDB(t *testing.T) { func TestInsertJokeIntoDB(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
data := schema.Joke{ data := schema.Joke{
ID: 1, ID: 1,
Link: "link1", Link: "link1",
Creator: 1, Creator: 1,
} }
err := joke.InsertJokeIntoDB(db, context.Background(), data) err := joke.InsertJokeIntoDB(db, ctx, data)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
} }
func TestDeleteSingleJoke(t *testing.T) { func TestDeleteSingleJoke(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -161,42 +174,45 @@ func TestDeleteSingleJoke(t *testing.T) {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
err = joke.DeleteSingleJoke(db, context.Background(), 1) err = joke.DeleteSingleJoke(db, ctx, 1)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
} }
func TestUpdateJoke(t *testing.T) { func TestUpdateJoke(t *testing.T) {
t.Cleanup(func() { Flush() }) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush()
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer conn.Release() defer conn.Release()
err = conn.BeginFunc(context.Background(), func(t pgx.Tx) error { err = conn.BeginFunc(ctx, func(t pgx.Tx) error {
_, err := t.Exec( _, err := t.Exec(
context.Background(), ctx,
`INSERT INTO "administrators" `INSERT INTO "administrators"
(id, key, token, last_used) (id, key, token, last_used)
VALUES VALUES
($1, $2, $3, $4), ($1, $2, $3, $4),
($5, $6, $7, $8);`, ($5, $6, $7, $8)`,
administratorsData..., administratorsData...,
) )
if err != nil { if err != nil {
return err return err
} }
_, err = t.Exec( _, err = t.Exec(
context.Background(), ctx,
`INSERT INTO "jokesbapak2" `INSERT INTO "jokesbapak2"
(id, link, creator) (id, link, creator)
VALUES VALUES
($1, $2, $3), ($1, $2, $3),
($4, $5, $6), ($4, $5, $6),
($7, $8, $9);`, ($7, $8, $9)`,
jokesData..., jokesData...,
) )
if err != nil { if err != nil {
@ -215,7 +231,7 @@ func TestUpdateJoke(t *testing.T) {
Creator: 1, Creator: 1,
} }
err = joke.UpdateJoke(db, context.Background(), newJoke) err = joke.UpdateJoke(db, ctx, newJoke)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }

View File

@ -66,14 +66,12 @@ func GetSubmittedItems(db *pgxpool.Pool, ctx context.Context, queries schema.Sub
results, err := conn.Query(ctx, sql, args...) results, err := conn.Query(ctx, sql, args...)
if err != nil { if err != nil {
return []schema.Submission{}, err return []schema.Submission{}, err
} }
defer results.Close() defer results.Close()
err = pgxscan.ScanAll(&submissions, results) err = pgxscan.ScanAll(&submissions, results)
if err != nil { if err != nil {
return []schema.Submission{}, err return []schema.Submission{}, err
} }
return submissions, nil return submissions, nil

View File

@ -5,23 +5,27 @@ import (
"jokes-bapak2-api/core/schema" "jokes-bapak2-api/core/schema"
"jokes-bapak2-api/core/submit" "jokes-bapak2-api/core/submit"
"testing" "testing"
"time"
) )
func TestGetSubmittedItems(t *testing.T) { func TestGetSubmittedItems(t *testing.T) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush() defer Flush()
c, err := db.Acquire(context.Background()) c, err := db.Acquire(ctx)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
defer c.Release() defer c.Release()
_, err = c.Exec(context.Background(), "INSERT INTO submission (id, link, created_at, author, status) VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10)", submissionData...) _, err = c.Exec(ctx, "INSERT INTO submission (id, link, created_at, author, status) VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10)", submissionData...)
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
items, err := submit.GetSubmittedItems(db, context.Background(), schema.SubmissionQuery{}) items, err := submit.GetSubmittedItems(db, ctx, schema.SubmissionQuery{})
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }
@ -58,7 +62,7 @@ func TestGetterQueryBuilder(t *testing.T) {
t.Error("expected first arg to be Test <example@test.com>, got:", i[0].(string)) t.Error("expected first arg to be Test <example@test.com>, got:", i[0].(string))
} }
if i[1].(int) != 1 { if i[1].(int) != 2 {
t.Error("expected second arg to be 1, got:", i[1].(int)) t.Error("expected second arg to be 1, got:", i[1].(int))
} }
} }

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"os" "os"
"testing" "testing"
"time"
"github.com/jackc/pgx/v4/pgxpool" "github.com/jackc/pgx/v4/pgxpool"
) )
@ -18,103 +19,107 @@ var submissionData = []interface{}{
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
defer Teardown() defer Teardown()
Setup() Setup()
time.Sleep(3 * time.Second)
os.Exit(m.Run()) os.Exit(m.Run())
} }
func Setup() { func Setup() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Minute))
defer cancel()
poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL")) poolConfig, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil { if err != nil {
panic(err) panic(err)
} }
db, err = pgxpool.ConnectConfig(context.Background(), poolConfig) db, err = pgxpool.ConnectConfig(ctx, poolConfig)
if err != nil { if err != nil {
panic(err) panic(err)
} }
conn, err := db.Acquire(context.Background()) conn, err := db.Acquire(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer conn.Release() defer conn.Release()
tx, err := conn.Begin(context.Background()) tx, err := conn.Begin(ctx)
if err != nil {
panic(err)
}
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS submission")
if err != nil {
panic(err)
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS jokesbapak2")
if err != nil {
panic(err)
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS administrators")
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer tx.Rollback(ctx)
_, err = tx.Exec( _, err = tx.Exec(
context.Background(), ctx,
`CREATE TABLE IF NOT EXISTS submission ( `CREATE TABLE IF NOT EXISTS submission (
id SERIAL PRIMARY KEY, id SERIAL PRIMARY KEY,
link VARCHAR(255) UNIQUE NOT NULL, link VARCHAR(255) UNIQUE NOT NULL,
created_at VARCHAR(255), created_at VARCHAR(255),
author VARCHAR(255) NOT NULL, author VARCHAR(255) NOT NULL,
status SMALLINT DEFAULT 0 status SMALLINT DEFAULT 0
);`, )`,
) )
if err != nil { if err != nil {
panic(err) panic(err)
} }
err = tx.Commit(context.Background()) err = tx.Commit(ctx)
if err != nil { if err != nil {
panic(err) panic(err)
} }
} }
func Teardown() (err error) { func Teardown() (err error) {
tx, err := db.Begin(context.Background()) ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
if err != nil { defer cancel()
return err
}
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS submission") defer db.Close()
if err != nil {
return err
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS jokesbapak2")
if err != nil {
return err
}
_, err = tx.Exec(context.Background(), "DROP TABLE IF EXISTS administrators")
if err != nil {
return err
}
err = tx.Commit(context.Background()) conn, err := db.Acquire(ctx)
if err != nil {
return err
}
db.Close()
return
}
func Flush() error {
conn, err := db.Acquire(context.Background())
if err != nil { if err != nil {
return err return err
} }
defer conn.Release() defer conn.Release()
_, err = conn.Exec(context.Background(), "TRUNCATE TABLE submission") tx, err := conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, "DROP TABLE IF EXISTS submission CASCADE")
if err != nil {
return err
}
_, err = tx.Exec(ctx, "DROP TABLE IF EXISTS jokesbapak2 CASCADE")
if err != nil {
return err
}
_, err = tx.Exec(ctx, "DROP TABLE IF EXISTS administrators CASCADE")
if err != nil {
return err
}
err = tx.Commit(ctx)
if err != nil {
return err
}
return
}
func Flush() error {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
conn, err := db.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
_, err = conn.Exec(ctx, "TRUNCATE TABLE submission RESTART IDENTITY CASCADE")
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,12 +5,16 @@ import (
"jokes-bapak2-api/core/schema" "jokes-bapak2-api/core/schema"
"jokes-bapak2-api/core/submit" "jokes-bapak2-api/core/submit"
"testing" "testing"
"time"
) )
func TestSubmitJoke(t *testing.T) { func TestSubmitJoke(t *testing.T) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(30*time.Second))
defer cancel()
defer Flush() defer Flush()
s, err := submit.SubmitJoke(db, context.Background(), schema.Submission{Author: "Test <example@test.com>"}, "https://example.net/img.png") s, err := submit.SubmitJoke(db, ctx, schema.Submission{Author: "Test <example@test.com>"}, "https://example.net/img.png")
if err != nil { if err != nil {
t.Error("an error was thrown:", err) t.Error("an error was thrown:", err)
} }

View File

@ -3,8 +3,6 @@
-- key: test -- key: test
-- token: password -- token: password
INSERT INTO "administrators" ("id", "key", "token", "last_used") VALUES INSERT INTO "administrators" ("id", "key", "token", "last_used") VALUES
(1, 'test', '$argon2id$v=19$m=65536,t=16,p=4$3a08c79fbf2222467a623df9a9ebf75802c65a4f9be36eb1df2f5d2052d53cb7$ce434bd38f7ba1fc1f2eb773afb8a1f7f2dad49140803ac6cb9d7256ce9826fb3b4afa1e2488da511c852fc6c33a76d5657eba6298a8e49d617b9972645b7106', ''); (1, 'test', '$argon2id$v=19$m=65536,t=16,p=4$3a08c79fbf2222467a623df9a9ebf75802c65a4f9be36eb1df2f5d2052d53cb7$ce434bd38f7ba1fc1f2eb773afb8a1f7f2dad49140803ac6cb9d7256ce9826fb3b4afa1e2488da511c852fc6c33a76d5657eba6298a8e49d617b9972645b7106', '');