aboutsummaryrefslogtreecommitdiffstats
path: root/internal/storage/db_test.go
blob: d9e22d09e805a696ba7cd4aa00b0a6a34e676b5d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package storage_test

import (
	"fmt"
	"testing"

	"github.com/eugenetriguba/bolt/internal/bolttest"
	"github.com/eugenetriguba/bolt/internal/configloader"
	"github.com/eugenetriguba/bolt/internal/storage"
	"gotest.tools/v3/assert"
)

func TestDBConnectWithPostgres(t *testing.T) {
	cfg := bolttest.NewTestConnectionConfig(t, "postgres")

	conn, err := storage.DBConnect(cfg.Driver, storage.DBConnectionString(cfg))
	assert.NilError(t, err)
	defer conn.Close()

	_, err = conn.Exec("SELECT 1;")
	assert.NilError(t, err)
}

func TestDBConnectMalformedConnectionString(t *testing.T) {
	_, err := storage.DBConnect("postgres", "pizza=123")
	assert.ErrorContains(t, err, "connection refused")
}

func TestDBConnectUnsupportedDriver(t *testing.T) {
	cfg := bolttest.NewTestConnectionConfig(t, "redis")

	_, err := storage.DBConnect(cfg.Driver, storage.DBConnectionString(cfg))
	assert.ErrorContains(t, err, `unknown driver "redis"`)
}

func TestDBConnectionString(t *testing.T) {
	cfg := configloader.ConnectionConfig{
		Driver:   "postgres",
		Host:     "db1",
		Port:     5432,
		User:     "testuser",
		Password: "supersecretpassword",
		DBName:   "testdb",
	}

	cs := storage.DBConnectionString(&cfg)

	expectedConnectionString := fmt.Sprintf(
		"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
		cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName,
	)
	assert.Equal(t, cs, expectedConnectionString)
}