-
Notifications
You must be signed in to change notification settings - Fork 946
feat(coderd/database/dbtestutil): add ability to dump database on failure #9704
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e711c7c
feat(coderd/database/dbtestutil): add ability to dump database on fai…
johnstcn 1c4bf16
column inserts only
johnstcn d9353a5
lint
johnstcn e44e8d2
make gen
johnstcn fad8705
Merge remote-tracking branch 'origin/main' into cj/dbtestutil-dump-on…
johnstcn ea7fe2e
address PR comments
johnstcn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -64,3 +64,6 @@ scaletest/terraform/secrets.tfvars | |
|
||
# Nix | ||
result | ||
|
||
# Data dumps from unit tests | ||
**/*.test.sql |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,21 @@ | ||
package dbtestutil | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"database/sql" | ||
"fmt" | ||
"net/url" | ||
"os" | ||
"os/exec" | ||
"path/filepath" | ||
"regexp" | ||
"strings" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/require" | ||
"golang.org/x/xerrors" | ||
|
||
"github.com/coder/coder/v2/coderd/database" | ||
"github.com/coder/coder/v2/coderd/database/dbfake" | ||
|
@@ -24,6 +30,7 @@ func WillUsePostgres() bool { | |
|
||
type options struct { | ||
fixedTimezone string | ||
dumpOnFailure bool | ||
} | ||
|
||
type Option func(*options) | ||
|
@@ -35,6 +42,13 @@ func WithTimezone(tz string) Option { | |
} | ||
} | ||
|
||
// WithDumpOnFailure will dump the entire database on test failure. | ||
func WithDumpOnFailure() Option { | ||
return func(o *options) { | ||
o.dumpOnFailure = true | ||
} | ||
} | ||
|
||
func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) { | ||
t.Helper() | ||
|
||
|
@@ -74,6 +88,9 @@ func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) { | |
t.Cleanup(func() { | ||
_ = sqlDB.Close() | ||
}) | ||
if o.dumpOnFailure { | ||
t.Cleanup(func() { DumpOnFailure(t, connectionURL) }) | ||
} | ||
db = database.New(sqlDB) | ||
|
||
ps, err = pubsub.New(context.Background(), sqlDB, connectionURL) | ||
|
@@ -110,3 +127,87 @@ func dbNameFromConnectionURL(t testing.TB, connectionURL string) string { | |
require.NoError(t, err) | ||
return strings.TrimPrefix(u.Path, "/") | ||
} | ||
|
||
// 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/migrate-ci/main.go and note the database name it outputs | ||
// - Import the file into the above database: | ||
// psql 'postgres://postgres:[email protected]:5432/<dbname>?sslmode=disable' -f <path to file.test.sql> | ||
// - Run a dev server against that database: | ||
// ./scripts/coder-dev.sh server --postgres-url='postgres://postgres:[email protected]:5432/<dbname>?sslmode=disable' | ||
func DumpOnFailure(t testing.TB, connectionURL string) { | ||
if !t.Failed() { | ||
return | ||
} | ||
cwd, err := filepath.Abs(".") | ||
if err != nil { | ||
t.Errorf("dump on failure: cannot determine current working directory") | ||
return | ||
} | ||
snakeCaseName := regexp.MustCompile("[^a-zA-Z0-9-_]+").ReplaceAllString(t.Name(), "_") | ||
now := time.Now() | ||
timeSuffix := fmt.Sprintf("%d%d%d%d%d%d", now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) | ||
outPath := filepath.Join(cwd, snakeCaseName+"."+timeSuffix+".test.sql") | ||
dump, err := pgDump(connectionURL) | ||
if err != nil { | ||
t.Errorf("dump on failure: failed to run pg_dump") | ||
return | ||
} | ||
if err := os.WriteFile(outPath, filterDump(dump), 0o600); err != nil { | ||
t.Errorf("dump on failure: failed to write: %s", err.Error()) | ||
return | ||
} | ||
t.Logf("Dumped database to %q due to failed test. I hope you find what you're looking for!", outPath) | ||
} | ||
|
||
// pgDump runs pg_dump against dbURL and returns the output. | ||
func pgDump(dbURL string) ([]byte, error) { | ||
if _, err := exec.LookPath("pg_dump"); err != nil { | ||
return nil, xerrors.Errorf("could not find pg_dump in path: %w", err) | ||
} | ||
cmdArgs := []string{ | ||
"pg_dump", | ||
dbURL, | ||
"--data-only", | ||
"--column-inserts", | ||
"--no-comments", | ||
"--no-privileges", | ||
"--no-publication", | ||
"--no-security-labels", | ||
"--no-subscriptions", | ||
"--no-tablespaces", | ||
// "--no-unlogged-table-data", // some tables are unlogged and may contain data of interest | ||
"--no-owner", | ||
"--exclude-table=schema_migrations", | ||
} | ||
cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) // nolint:gosec | ||
cmd.Env = []string{ | ||
// "PGTZ=UTC", // This is probably not going to be useful if tz has been changed. | ||
"PGCLIENTENCODINDG=UTF8", | ||
"PGDATABASE=", // we should always specify the database name in the connection string | ||
} | ||
var stdout bytes.Buffer | ||
cmd.Stdout = &stdout | ||
if err := cmd.Run(); err != nil { | ||
return nil, xerrors.Errorf("exec pg_dump: %w", err) | ||
} | ||
return stdout.Bytes(), nil | ||
} | ||
|
||
func filterDump(dump []byte) []byte { | ||
lines := bytes.Split(dump, []byte{'\n'}) | ||
var buf bytes.Buffer | ||
for _, line := range lines { | ||
// We dump in column-insert format, so these are the only lines | ||
// we care about | ||
if !bytes.HasPrefix(line, []byte("INSERT")) { | ||
continue | ||
} | ||
_, _ = buf.Write(line) | ||
_, _ = buf.WriteRune('\n') | ||
} | ||
return buf.Bytes() | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.