From fe1f2f0806f8ff3134d09141ee28f17093ad85ce Mon Sep 17 00:00:00 2001 From: Graham Christensen Date: Mon, 22 Feb 2021 13:47:41 -0500 Subject: [PATCH] Create an ephemeral PostgreSQL database per test --- src/libhydra/db.hh | 14 ++++++++++---- tests/evaluation.t | 9 ++++++--- tests/lib/Setup.pm | 21 ++++++++++++++++++--- 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/libhydra/db.hh b/src/libhydra/db.hh index 35d78edf..ec9a024b 100644 --- a/src/libhydra/db.hh +++ b/src/libhydra/db.hh @@ -13,10 +13,16 @@ struct Connection : pqxx::connection { using namespace nix; auto s = getEnv("HYDRA_DBI").value_or("dbi:Pg:dbname=hydra;"); - std::string prefix = "dbi:Pg:"; - if (std::string(s, 0, prefix.size()) != prefix) - throw Error("$HYDRA_DBI does not denote a PostgreSQL database"); - return concatStringsSep(" ", tokenizeString(string(s, prefix.size()), ";")); + + std::string lower_prefix = "dbi:Pg:"; + std::string upper_prefix = "DBI:Pg:"; + + if ((std::string(s, 0, lower_prefix.size()) == lower_prefix) || + (std::string(s, 0, upper_prefix.size()) == upper_prefix)) { + return concatStringsSep(" ", tokenizeString(string(s, lower_prefix.size()), ";")); + } + + throw Error("$HYDRA_DBI does not denote a PostgreSQL database"); } }; diff --git a/tests/evaluation.t b/tests/evaluation.t index 1d4c37a5..04dc144e 100644 --- a/tests/evaluation.t +++ b/tests/evaluation.t @@ -1,13 +1,16 @@ use strict; -use Hydra::Schema; -use Hydra::Model::DB; use Cwd; use Setup; -my $db = Hydra::Model::DB->new; +my $pgsql = dbinit(); +my $dsn = $pgsql->dsn; + +require Hydra::Schema; +require Hydra::Model::DB; use Test::Simple tests => 76; +my $db = Hydra::Model::DB->new; hydra_setup($db); my $res; diff --git a/tests/lib/Setup.pm b/tests/lib/Setup.pm index 6ddd0162..2989120b 100644 --- a/tests/lib/Setup.pm +++ b/tests/lib/Setup.pm @@ -2,12 +2,27 @@ package Setup; use strict; use Exporter; -use Hydra::Helper::Nix; -use Hydra::Model::DB; +use Test::PostgreSQL; use Cwd; our @ISA = qw(Exporter); -our @EXPORT = qw(hydra_setup nrBuildsForJobset queuedBuildsForJobset nrQueuedBuildsForJobset createBaseJobset createJobsetWithOneInput evalSucceeds runBuild updateRepository); +our @EXPORT = qw(dbinit hydra_setup nrBuildsForJobset queuedBuildsForJobset nrQueuedBuildsForJobset createBaseJobset createJobsetWithOneInput evalSucceeds runBuild updateRepository); + +sub dbinit() { + my $pgsql = Test::PostgreSQL->new(); + $ENV{'HYDRA_DBI'} = $pgsql->dsn; + system("hydra-init") == 0 or die; + return $pgsql; +} + +sub captureStdoutStderr { + # "Lazy"-load Hydra::Helper::Nix to avoid the compile-time + # import of Hydra::Model::DB. Early loading of the DB class + # causes fixation of the DSN, and we need to fixate it after + # the temporary DB is setup. + require Hydra::Helper::Nix; + return Hydra::Helper::Nix::captureStdoutStderr(@_) +} sub hydra_setup { my ($db) = @_;