aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2024-01-06 11:15:53 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2024-01-06 11:15:53 -0500
commit3d66d23b7f1f8d496711f01a164ac1d7717527ca (patch)
treeb4ce8a4deda41c57b1ab13ac4e89bfb9e6978cf0
parentAdd to changelog (diff)
downloadcli-3d66d23b7f1f8d496711f01a164ac1d7717527ca.zip
Add database integration tests
-rw-r--r--.env (renamed from .env.test)4
-rw-r--r--Dockerfile.test7
-rw-r--r--docker-compose.yml28
-rw-r--r--internal/commands/create.go12
-rw-r--r--internal/commands/list.go11
-rw-r--r--internal/commands/migrate.go11
-rw-r--r--internal/db/db.go48
-rw-r--r--internal/dbtest/dbtest.go24
-rw-r--r--internal/storage/storage.go40
-rw-r--r--internal/storage/storage_test.go76
-rwxr-xr-xtask70
11 files changed, 195 insertions, 136 deletions
diff --git a/.env.test b/.env
index d298ca7..22d4f3a 100644
--- a/.env.test
+++ b/.env
@@ -1,5 +1,5 @@
DB_NAME=test_db
-DB_HOST=test_db
-DB_PORT=5839
+DB_HOST=bolt_postgres_db
+DB_PORT=5432
DB_USERNAME=test_user
DB_PASSWORD=testpassword
diff --git a/Dockerfile.test b/Dockerfile.test
new file mode 100644
index 0000000..b08c4dc
--- /dev/null
+++ b/Dockerfile.test
@@ -0,0 +1,7 @@
+FROM golang:1.21.5-alpine3.19
+
+RUN apk update && apk add --no-cache bash
+
+WORKDIR /app
+COPY . .
+RUN go mod download
diff --git a/docker-compose.yml b/docker-compose.yml
index 3479b02..d6c4384 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,18 +1,38 @@
-version: '3.8'
+version: "3.8"
services:
+ app:
+ image: eugenetriguba/bolt
+ container_name: bolt
+ command: sleep infinity
+ env_file:
+ - .env
+ build:
+ dockerfile: Dockerfile.test
+ context: .
+ volumes:
+ - ./:/app
+ networks:
+ - app
+ depends_on:
+ - postgres_db
+
postgres_db:
image: postgres:16.1-alpine3.19
- container_name: postgres_db
- ports:
- - "${DB_PORT:?err}:5432"
+ container_name: bolt_postgres_db
environment:
- POSTGRES_DB=${DB_NAME:?err}
- POSTGRES_USER=${DB_USERNAME:?err}
- POSTGRES_PASSWORD=${DB_PASSWORD:?err}
volumes:
- postgres_db_volume:/var/lib/postgresql/data
+ networks:
+ - app
volumes:
postgres_db_volume:
name: postgres-db-volume
+
+networks:
+ app:
+ name: app
diff --git a/internal/commands/create.go b/internal/commands/create.go
index 169bc4d..de71fd7 100644
--- a/internal/commands/create.go
+++ b/internal/commands/create.go
@@ -7,9 +7,9 @@ import (
"os"
"github.com/eugenetriguba/bolt/internal/configloader"
- "github.com/eugenetriguba/bolt/internal/db"
"github.com/eugenetriguba/bolt/internal/models"
"github.com/eugenetriguba/bolt/internal/repositories"
+ "github.com/eugenetriguba/bolt/internal/storage"
"github.com/eugenetriguba/bolt/internal/util"
"github.com/google/subcommands"
)
@@ -42,19 +42,23 @@ func (cmd *CreateCmd) Execute(
f *flag.FlagSet,
_ ...interface{},
) subcommands.ExitStatus {
- conn, err := db.Connect()
+ cfg, err := configloader.NewConfig()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- cfg, err := configloader.NewConfig()
+ db, err := storage.DBConnect(
+ cfg.Connection.Driver,
+ storage.DBConnectionString(&cfg.Connection),
+ )
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
+ defer db.Close()
- migrationRepo, err := repositories.NewMigrationRepo(conn, cfg)
+ migrationRepo, err := repositories.NewMigrationRepo(db, cfg)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
diff --git a/internal/commands/list.go b/internal/commands/list.go
index 36600c9..0f03712 100644
--- a/internal/commands/list.go
+++ b/internal/commands/list.go
@@ -7,8 +7,8 @@ import (
"os"
"github.com/eugenetriguba/bolt/internal/configloader"
- "github.com/eugenetriguba/bolt/internal/db"
"github.com/eugenetriguba/bolt/internal/repositories"
+ "github.com/eugenetriguba/bolt/internal/storage"
"github.com/google/subcommands"
)
@@ -25,18 +25,21 @@ func (*ListCmd) Usage() string {
func (m *ListCmd) SetFlags(f *flag.FlagSet) {}
func (m *ListCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
- db, err := db.Connect()
+ cfg, err := configloader.NewConfig()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- defer db.Close()
- cfg, err := configloader.NewConfig()
+ db, err := storage.DBConnect(
+ cfg.Connection.Driver,
+ storage.DBConnectionString(&cfg.Connection),
+ )
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
+ defer db.Close()
migrationRepo, err := repositories.NewMigrationRepo(db, cfg)
if err != nil {
diff --git a/internal/commands/migrate.go b/internal/commands/migrate.go
index f3e4cbd..df1377a 100644
--- a/internal/commands/migrate.go
+++ b/internal/commands/migrate.go
@@ -7,8 +7,8 @@ import (
"os"
"github.com/eugenetriguba/bolt/internal/configloader"
- "github.com/eugenetriguba/bolt/internal/db"
"github.com/eugenetriguba/bolt/internal/repositories"
+ "github.com/eugenetriguba/bolt/internal/storage"
"github.com/google/subcommands"
)
@@ -25,18 +25,21 @@ func (*MigrateCmd) Usage() string {
func (m *MigrateCmd) SetFlags(f *flag.FlagSet) {}
func (m *MigrateCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
- db, err := db.Connect()
+ cfg, err := configloader.NewConfig()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
- defer db.Close()
- cfg, err := configloader.NewConfig()
+ db, err := storage.DBConnect(
+ cfg.Connection.Driver,
+ storage.DBConnectionString(&cfg.Connection),
+ )
if err != nil {
fmt.Fprintln(os.Stderr, err)
return subcommands.ExitFailure
}
+ defer db.Close()
migrationRepo, err := repositories.NewMigrationRepo(db, cfg)
if err != nil {
diff --git a/internal/db/db.go b/internal/db/db.go
deleted file mode 100644
index 3927681..0000000
--- a/internal/db/db.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package db
-
-import (
- "database/sql"
- "fmt"
-
- "github.com/eugenetriguba/bolt/internal/configloader"
- _ "github.com/lib/pq"
-)
-
-var db *sql.DB
-
-// Connect to the database using the driver and connection
-// parameter that are specified in the bolt configuration file.
-//
-// Note that subsequent calls to Connect return the same database
-// handle.
-func Connect() (*sql.DB, error) {
- if db == nil {
- config, err := configloader.NewConfig()
- if err != nil {
- return nil, err
- }
-
- connInfo := fmt.Sprintf(
- "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
- config.Connection.Host, config.Connection.Port, config.Connection.User,
- config.Connection.Password, config.Connection.DBName,
- )
- newDb, err := sql.Open(config.Connection.Driver, connInfo)
- if err != nil {
- return nil, err
- }
-
- // Note: `sql.Open` only validates the connection string we provided
- // it is sane. It doesn't actually open up a connection to the database.
- // For that, we ping the database to ensure the connection string is fully
- // valid.
- err = newDb.Ping()
- if err != nil {
- return nil, err
- }
-
- db = newDb
- }
-
- return db, nil
-}
diff --git a/internal/dbtest/dbtest.go b/internal/dbtest/dbtest.go
new file mode 100644
index 0000000..c53c04a
--- /dev/null
+++ b/internal/dbtest/dbtest.go
@@ -0,0 +1,24 @@
+package dbtest
+
+import (
+ "os"
+ "strconv"
+
+ "github.com/eugenetriguba/bolt/internal/configloader"
+)
+
+func NewTestConnectionConfig(driver string) (*configloader.ConnectionConfig, error) {
+ port, err := strconv.Atoi(os.Getenv("DB_PORT"))
+ if err != nil {
+ return nil, err
+ }
+
+ return &configloader.ConnectionConfig{
+ Driver: driver,
+ DBName: os.Getenv("DB_NAME"),
+ Host: os.Getenv("DB_HOST"),
+ Port: port,
+ User: os.Getenv("DB_USERNAME"),
+ Password: os.Getenv("DB_PASSWORD"),
+ }, nil
+}
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
new file mode 100644
index 0000000..cd6e514
--- /dev/null
+++ b/internal/storage/storage.go
@@ -0,0 +1,40 @@
+package storage
+
+import (
+ "database/sql"
+ "fmt"
+
+ "github.com/eugenetriguba/bolt/internal/configloader"
+ _ "github.com/lib/pq"
+)
+
+// DBConnect to the database using the driver and connection
+// information.
+func DBConnect(driver string, connectionInfo string) (*sql.DB, error) {
+ db, err := sql.Open(driver, connectionInfo)
+ if err != nil {
+ return nil, err
+ }
+
+ // Note: `sql.Open` only validates the connection string we provided
+ // it is sane. It doesn't actually open up a connection to the database.
+ // For that, we ping the database to ensure the connection string is fully
+ // valid.
+ err = db.Ping()
+ if err != nil {
+ return nil, err
+ }
+
+ return db, nil
+}
+
+// DBConnectionString generates a properly formatted connection
+// string to be passed to a database management system to initiate
+// a connection. It uses the passed in configuration values to create
+// the string. Note that sslmode is always disabled.
+func DBConnectionString(cfg *configloader.ConnectionConfig) string {
+ return fmt.Sprintf(
+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
+ cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName,
+ )
+}
diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go
new file mode 100644
index 0000000..53f7b49
--- /dev/null
+++ b/internal/storage/storage_test.go
@@ -0,0 +1,76 @@
+package storage_test
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/eugenetriguba/bolt/internal/configloader"
+ "github.com/eugenetriguba/bolt/internal/dbtest"
+ "github.com/eugenetriguba/bolt/internal/storage"
+)
+
+func TestDBConnectWithPostgres(t *testing.T) {
+ cfg, err := dbtest.NewTestConnectionConfig("postgres")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ conn, err := storage.DBConnect(cfg.Driver, storage.DBConnectionString(cfg))
+ if err != nil {
+ t.Fatalf("could not connect to postgres db using %s: %s",
+ storage.DBConnectionString(cfg),
+ err,
+ )
+ }
+ defer conn.Close()
+
+ _, err = conn.Exec("SELECT 1;")
+ if err != nil {
+ t.Fatalf("could not execute query against postgres db: %s", err)
+ }
+}
+
+func TestDBConnectMalformedConnectionString(t *testing.T) {
+ _, err := storage.DBConnect("postgres", "pizza=123")
+ if err == nil || (err != nil && !strings.Contains(err.Error(), "connection refused")) {
+ t.Fatalf("expected connection error, got %s", err)
+ }
+}
+
+func TestDBConnectUnsupportedDriver(t *testing.T) {
+ cfg, err := dbtest.NewTestConnectionConfig("redis")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ _, err = storage.DBConnect(cfg.Driver, storage.DBConnectionString(cfg))
+ if err == nil || (err != nil && !strings.Contains(err.Error(), `unknown driver "redis"`)) {
+ t.Fatalf("expected bad driver, got %s", err)
+ }
+}
+
+func TestDBConnectionString(t *testing.T) {
+ cfg := configloader.Config{
+ MigrationsDir: "",
+ Connection: configloader.ConnectionConfig{
+ Driver: "postgres",
+ Host: "db1",
+ Port: 5432,
+ User: "testuser",
+ Password: "supersecretpassword",
+ DBName: "testdb",
+ },
+ }
+ expectedConnectionString := fmt.Sprintf(
+ "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
+ cfg.Connection.Host, cfg.Connection.Port, cfg.Connection.User,
+ cfg.Connection.Password, cfg.Connection.DBName,
+ )
+
+ cs := storage.DBConnectionString(&cfg.Connection)
+
+ if cs != expectedConnectionString {
+ t.Fatalf("Expected %s, got %s", expectedConnectionString, cs)
+ }
+}
diff --git a/task b/task
deleted file mode 100755
index 18105b9..0000000
--- a/task
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/bin/sh
-set -e
-
-print_help() {
- echo "Usage: ./task <command>"
- echo ""
- echo "Commands:"
- echo " help Print this help message or help information for a specific command"
- echo " test Run the go test suite for the repo"
- echo ""
- echo "For more information on a specific command, use './task help <command>'"
-}
-
-run_tests() {
- docker compose --env-file .env.test up -d
-
- if [ "$1" = "-cov" ]; then
- go test -cover ./...
- else
- go test ./...
- fi
-
- docker compose --env-file .env.test down --volumes
-}
-
-print_help_command() {
- case "$1" in
- help)
- echo "Usage: ./task help <command>"
- echo ""
- echo "Commands:"
- echo " help Print this help message"
- echo " test Run the go test suite for the repo"
- ;;
- test)
- echo "Usage: ./task test [-cov]"
- echo ""
- echo "Options:"
- echo " -cov Generate a coverage report"
- ;;
- *)
- echo "Invalid command. Use 'help' to see available commands."
- ;;
- esac
-}
-
-main() {
- if [ $# -eq 0 ]; then
- print_help
- exit 1
- fi
-
- case "$1" in
- help)
- if [ $# -eq 1 ]; then
- print_help
- else
- print_help_command "$2"
- fi
- ;;
- test)
- run_tests "$2"
- ;;
- *)
- echo "Invalid command. Use 'help' to see available commands."
- ;;
- esac
-}
-
-main "$@"