aboutsummaryrefslogtreecommitdiffstats
path: root/internal/storage/storage_test.go
blob: 3b36a34439fbc6c81455fc998301037d44ff01f9 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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.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.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName,
	)

	cs := storage.DBConnectionString(&cfg)

	if cs != expectedConnectionString {
		t.Fatalf("Expected %s, got %s", expectedConnectionString, cs)
	}
}