DumpOnFailure exports the database referenced by connectionURL to a file corresponding to the current test, with a suffix indicating the time the test was run. To import this into a new database (assuming you have already run make test-postgres-docker): - Create a new test database: go run ./scripts
(t testing.TB, connectionURL string)
| 181 | // - Run a dev server against that database: |
| 182 | // ./scripts/coder-dev.sh server --postgres-url='postgres://postgres:postgres@127.0.0.1:5432/<dbname>?sslmode=disable' |
| 183 | func DumpOnFailure(t testing.TB, connectionURL string) { |
| 184 | if !t.Failed() { |
| 185 | return |
| 186 | } |
| 187 | cwd, err := filepath.Abs(".") |
| 188 | if err != nil { |
| 189 | t.Errorf("dump on failure: cannot determine current working directory") |
| 190 | return |
| 191 | } |
| 192 | snakeCaseName := regexp.MustCompile("[^a-zA-Z0-9-_]+").ReplaceAllString(t.Name(), "_") |
| 193 | now := time.Now() |
| 194 | timeSuffix := fmt.Sprintf("%d%d%d%d%d%d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) |
| 195 | outPath := filepath.Join(cwd, snakeCaseName+"."+timeSuffix+".test.sql") |
| 196 | dump, err := PGDump(connectionURL) |
| 197 | if err != nil { |
| 198 | t.Errorf("dump on failure: failed to run pg_dump: %s", err.Error()) |
| 199 | return |
| 200 | } |
| 201 | if err := os.WriteFile(outPath, normalizeDump(dump), 0o600); err != nil { |
| 202 | t.Errorf("dump on failure: failed to write: %s", err.Error()) |
| 203 | return |
| 204 | } |
| 205 | t.Logf("Dumped database to %q due to failed test. I hope you find what you're looking for!", outPath) |
| 206 | } |
| 207 | |
| 208 | // PGDump runs pg_dump against dbURL and returns the output. |
| 209 | // It is used by DumpOnFailure(). |