1 package embeddedpostgres
2
3 import (
4 "errors"
5 "fmt"
6 "io/ioutil"
7 "os"
8 "path/filepath"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 )
13
14 func Test_defaultInitDatabase_ErrorWhenCannotCreatePasswordFile(t *testing.T) {
15 err := defaultInitDatabase("path_not_exists", "path_not_exists", "path_not_exists", "Tom", "Beer", "", os.Stderr)
16
17 assert.EqualError(t, err, "unable to write password file to path_not_exists/pwfile")
18 }
19
20 func Test_defaultInitDatabase_ErrorWhenCannotStartInitDBProcess(t *testing.T) {
21 binTempDir, err := os.MkdirTemp("", "prepare_database_test_bin")
22 if err != nil {
23 panic(err)
24 }
25
26 runtimeTempDir, err := os.MkdirTemp("", "prepare_database_test_runtime")
27 if err != nil {
28 panic(err)
29 }
30
31 logFile, err := ioutil.TempFile("", "prepare_database_test_log")
32 if err != nil {
33 panic(err)
34 }
35
36 defer func() {
37 if err := os.RemoveAll(binTempDir); err != nil {
38 panic(err)
39 }
40
41 if err := os.RemoveAll(runtimeTempDir); err != nil {
42 panic(err)
43 }
44
45 if err := os.Remove(logFile.Name()); err != nil {
46 panic(err)
47 }
48 }()
49
50 _, _ = logFile.Write([]byte("and here are the logs!"))
51
52 err = defaultInitDatabase(binTempDir, runtimeTempDir, filepath.Join(runtimeTempDir, "data"), "Tom", "Beer", "", logFile)
53
54 assert.NotNil(t, err)
55 assert.Contains(t, err.Error(), fmt.Sprintf("unable to init database using '%s/bin/initdb -A password -U Tom -D %s/data --pwfile=%s/pwfile'",
56 binTempDir,
57 runtimeTempDir,
58 runtimeTempDir))
59 assert.Contains(t, err.Error(), "and here are the logs!")
60 assert.FileExists(t, filepath.Join(runtimeTempDir, "pwfile"))
61 }
62
63 func Test_defaultInitDatabase_ErrorInvalidLocaleSetting(t *testing.T) {
64 tempDir, err := os.MkdirTemp("", "prepare_database_test")
65 if err != nil {
66 panic(err)
67 }
68
69 defer func() {
70 if err := os.RemoveAll(tempDir); err != nil {
71 panic(err)
72 }
73 }()
74
75 err = defaultInitDatabase(tempDir, tempDir, filepath.Join(tempDir, "data"), "postgres", "postgres", "en_XY", os.Stderr)
76
77 assert.NotNil(t, err)
78 assert.Contains(t, err.Error(), fmt.Sprintf("unable to init database using '%s/bin/initdb -A password -U postgres -D %s/data --pwfile=%s/pwfile --locale=en_XY'",
79 tempDir,
80 tempDir,
81 tempDir))
82 }
83
84 func Test_defaultInitDatabase_PwFileRemoved(t *testing.T) {
85 tempDir, err := os.MkdirTemp("", "prepare_database_test")
86 if err != nil {
87 panic(err)
88 }
89
90 defer func() {
91 if err := os.RemoveAll(tempDir); err != nil {
92 panic(err)
93 }
94 }()
95
96 database := NewDatabase(DefaultConfig().RuntimePath(tempDir))
97 if err := database.Start(); err != nil {
98 t.Fatal(err)
99 }
100
101 defer func() {
102 if err := database.Stop(); err != nil {
103 t.Fatal(err)
104 }
105 }()
106
107 pwFile := filepath.Join(tempDir, "pwfile")
108 _, err = os.Stat(pwFile)
109
110 assert.True(t, os.IsNotExist(err), "pwfile (%v) still exists after starting the db", pwFile)
111 }
112
113 func Test_defaultCreateDatabase_ErrorWhenSQLOpenError(t *testing.T) {
114 err := defaultCreateDatabase(1234, "user client_encoding=lol", "password", "database")
115
116 assert.EqualError(t, err, "unable to connect to create database with custom name database with the following error: client_encoding must be absent or 'UTF8'")
117 }
118
119 func Test_defaultCreateDatabase_DashesInName(t *testing.T) {
120 database := NewDatabase(DefaultConfig().
121 Port(9832).
122 Database("my-cool-database"))
123
124 if err := database.Start(); err != nil {
125 t.Fatal(err)
126 }
127
128 if err := database.Stop(); err != nil {
129 t.Fatal(err)
130 }
131 }
132
133 func Test_defaultCreateDatabase_ErrorWhenQueryError(t *testing.T) {
134 database := NewDatabase(DefaultConfig().
135 Port(9831).
136 Database("b33r"))
137 if err := database.Start(); err != nil {
138 t.Fatal(err)
139 }
140
141 defer func() {
142 if err := database.Stop(); err != nil {
143 t.Fatal(err)
144 }
145 }()
146
147 err := defaultCreateDatabase(9831, "postgres", "postgres", "b33r")
148
149 assert.EqualError(t, err, `unable to connect to create database with custom name b33r with the following error: pq: database "b33r" already exists`)
150 }
151
152 func Test_healthCheckDatabase_ErrorWhenSQLConnectingError(t *testing.T) {
153 err := healthCheckDatabase(1234, "tom client_encoding=lol", "more", "b33r")
154
155 assert.EqualError(t, err, "client_encoding must be absent or 'UTF8'")
156 }
157
158 type CloserWithoutErr struct{}
159
160 func (c *CloserWithoutErr) Close() error {
161 return nil
162 }
163
164 func TestConnCloserWithoutErr(t *testing.T) {
165 originalErr := errors.New("OriginalError")
166
167 tests := []struct {
168 name string
169 err error
170 expectedErrTxt string
171 }{
172 {
173 "No original error, no error from closer",
174 nil,
175 "",
176 },
177 {
178 "original error, no error from closer",
179 originalErr,
180 originalErr.Error(),
181 },
182 }
183
184 for _, tt := range tests {
185 t.Run(tt.name, func(t *testing.T) {
186 resultErr := connectionClose(&CloserWithoutErr{}, tt.err)
187
188 if len(tt.expectedErrTxt) == 0 {
189 if resultErr != nil {
190 t.Fatalf("Expected nil error, got error: %v", resultErr)
191 }
192
193 return
194 }
195
196 if resultErr.Error() != tt.expectedErrTxt {
197 t.Fatalf("Expected error: %v, got error: %v", tt.expectedErrTxt, resultErr)
198 }
199 })
200 }
201 }
202
203 type CloserWithErr struct{}
204
205 const testError = "TestError"
206
207 func (c *CloserWithErr) Close() error {
208 return errors.New(testError)
209 }
210
211 func TestConnCloserWithErr(t *testing.T) {
212 originalErr := errors.New("OriginalError")
213
214 closeDBConnErr := fmt.Errorf(fmtCloseDBConn, errors.New(testError))
215
216 tests := []struct {
217 name string
218 err error
219 expectedErrTxt string
220 }{
221 {
222 "No original error, error from closer",
223 nil,
224 closeDBConnErr.Error(),
225 },
226 {
227 "original error, error from closer",
228 originalErr,
229 fmt.Errorf(fmtAfterError, closeDBConnErr, originalErr).Error(),
230 },
231 }
232
233 for _, tt := range tests {
234 t.Run(tt.name, func(t *testing.T) {
235 resultErr := connectionClose(&CloserWithErr{}, tt.err)
236
237 if len(tt.expectedErrTxt) == 0 {
238 if resultErr != nil {
239 t.Fatalf("Expected nil error, got error: %v", resultErr)
240 }
241
242 return
243 }
244
245 if resultErr.Error() != tt.expectedErrTxt {
246 t.Fatalf("Expected error: %v, got error: %v", tt.expectedErrTxt, resultErr)
247 }
248 })
249 }
250 }
251
View as plain text