package infrastructure import ( "database/sql" "fmt" "os" "testing" "code.osinet.fr/fgm/kurz/domain" "github.com/pressly/goose" "github.com/spf13/viper" ) func TestMySQLEmptyRepo(test *testing.T) { db := mySQLTestSetup(test) defer db.Close() test.Run("empty repo", func(subTest *testing.T) { _, err := domain.GetTargetURL("whatever", nil) if err == nil { subTest.Error("Empty repository should not find a target for any URL") } s1, isNew, err := domain.GetShortURL(exampleValidHTTPURL, nil) if err != nil { subTest.Error("Creating a short URL for a valid URL should not fail") } if !isNew { subTest.Error("The first short URL in an empty repository should be new") } s2, isNew, err := domain.GetShortURL(exampleValidHTTPURL, nil) if err != nil { subTest.Error("Creating a short URL for a valid URL should not fail") } if isNew { subTest.Error("The second short URL for an already shortened URL should not be new") } if s1 != s2 { subTest.Error("The second short URL for an already shortened URL should be the same as the first one") } t, err := domain.GetTargetURL(s1, nil) if err != nil { subTest.Error("Repository should find a target for an existing short URL") } if t != exampleValidHTTPURL { subTest.Error("Target URL for a short URL should match the target it was created for") } }) mySQLTestTeardown(test, db) } func TestMySQLSad(test *testing.T) { db := mySQLTestSetup(test) defer db.Close() test.Run("Sad", func(subTest *testing.T) { _, _, err := domain.GetShortURL("", nil) if err == nil { test.Error("Empty target URL has no valid short URL") } }) mySQLTestTeardown(test, db) } /** mySQLTestSetup opens the database and initialized it from the production database schema. */ func mySQLTestSetup(t *testing.T) *sql.DB { db, err := DbDial(ParseTestDbCred()) if err != nil { panic(err) } // Ensure current schema for test DB. cwd, _ := os.Getwd() current, err := goose.GetDBVersion(db) if err != nil { t.Errorf("setup failed to obtain the test DB version: %s", err) t.FailNow() } versions, err := goose.CollectMigrations(cwd, current, int64((1<<63)-1)) if err != nil { t.Errorf("setup failed to obtain the test DB migrations: %s", err) t.FailNow() } if versions != nil { err = goose.Up(db, cwd) if err != nil { t.Errorf("setup failed to upgrade the test DB schema: %s", err) t.FailNow() } } // Ensure empty test DB. _, err = db.Exec("DELETE FROM map") if err != nil { t.Error("setup failed to clean test database") } sr := MySQLShortURLRepository{db} tr := MySQLTargetURLRepository{db} domain.RegisterRepositories(sr, tr) return db } func mySQLTestTeardown(t *testing.T, db *sql.DB) { _, err := db.Exec("DELETE FROM map") if err != nil { t.Error("teardown failed to clean test database") } } func TestMain(m *testing.M) { viper.SetConfigName("config") viper.AddConfigPath(".") viper.AddConfigPath("$HOME/.kurz") err := viper.ReadInConfig() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } exitCode := m.Run() os.Exit(exitCode) }