From 31557117b25f456b0dda38453098fa92dba55200 Mon Sep 17 00:00:00 2001 From: krehermann <16602512+krehermann@users.noreply.github.com> Date: Mon, 15 Jul 2024 10:36:17 -0600 Subject: [PATCH] BCF-3322: automatically cleanup heavyweight test databases (#13843) --- .changeset/silver-peas-happen.md | 5 +++++ core/internal/cltest/heavyweight/orm.go | 4 ++-- internal/testdb/testdb.go | 25 +++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 .changeset/silver-peas-happen.md diff --git a/.changeset/silver-peas-happen.md b/.changeset/silver-peas-happen.md new file mode 100644 index 00000000000..2e7d062e265 --- /dev/null +++ b/.changeset/silver-peas-happen.md @@ -0,0 +1,5 @@ +--- +"chainlink": minor +--- + +#internal cleanup heavyweight test databases automatically diff --git a/core/internal/cltest/heavyweight/orm.go b/core/internal/cltest/heavyweight/orm.go index f49a94be05b..4e824b1ab0f 100644 --- a/core/internal/cltest/heavyweight/orm.go +++ b/core/internal/cltest/heavyweight/orm.go @@ -10,7 +10,6 @@ import ( "testing" "github.com/google/uuid" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/jmoiron/sqlx" @@ -68,7 +67,8 @@ func (c Kind) PrepareDB(t testing.TB, overrideFn func(c *chainlink.Config, s *ch db, err := pg.NewConnection(migrationTestDBURL, dialects.Postgres, gcfg.Database()) require.NoError(t, err) t.Cleanup(func() { - assert.NoError(t, db.Close()) + require.NoError(t, db.Close()) // must close before dropping + require.NoError(t, testdb.Drop(*testutils.MustParseURL(t, migrationTestDBURL))) os.RemoveAll(gcfg.RootDir()) }) diff --git a/internal/testdb/testdb.go b/internal/testdb/testdb.go index 9b531166113..88251ae2c6f 100644 --- a/internal/testdb/testdb.go +++ b/internal/testdb/testdb.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/url" + "strings" "github.com/smartcontractkit/chainlink/v2/core/store/dialects" ) @@ -54,3 +55,27 @@ func CreateOrReplace(parsed url.URL, suffix string, withTemplate bool) (string, parsed.Path = fmt.Sprintf("/%s", dbname) return parsed.String(), nil } + +// Drop drops the database at the given URL. +func Drop(dbURL url.URL) error { + if dbURL.Path == "" { + return errors.New("path missing from database URL") + } + dbname := strings.TrimPrefix(dbURL.Path, "/") + + // Cannot drop test database if we are connected to it, so we must connect + // to a different one. 'postgres' should be present on all postgres installations + dbURL.Path = "/postgres" + db, err := sql.Open(string(dialects.Postgres), dbURL.String()) + if err != nil { + return fmt.Errorf("in order to drop the test database, we need to connect to a separate database"+ + " called 'postgres'. But we are unable to open 'postgres' database: %+v\n", err) + } + defer db.Close() + + _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", dbname)) + if err != nil { + return fmt.Errorf("unable to drop postgres migrations test database: %v", err) + } + return nil +}