package main import ( "io/ioutil" "os" "testing" ) var db *DB func initTestCase(t *testing.T) { os.Setenv("PGDATABASE", "levyraati_test") os.Setenv("PGUSER", "levyraati_test") os.Setenv("PGPASSWORD", "levyraati_test") db = InitDatabase() execSQLFile(t, "sql/clear-schema.sql") execSQLFile(t, "sql/database.sql") execSQLFile(t, "sql/database-test.sql") } func execSQLFile(t *testing.T, filename string) { data, err := ioutil.ReadFile(filename) if err != nil { t.Fatal("Unable to read setup file", filename) } _, err = db.database.Exec(string(data)) if err != nil { t.Fatal("Unable to setup database", err) } } func TestDbConnWorks(t *testing.T) { initTestCase(t) if db == nil { t.Error("Database not initialized") } } func TestFindAllEntries(t *testing.T) { initTestCase(t) songs, err := db.FindAllEntries("Lamperi") if err != nil { t.Error("Error while searching for entries") } if len(songs) != 52 { t.Error("Should have found 52 entries, got", len(songs)) } } func TestFindAllPanels(t *testing.T) { initTestCase(t) panels, err := db.FindAllPanels() if err != nil { t.Error("Error while searching for panels") } if len(panels) != 1 { t.Error("Should have found 1 panel, got", len(panels)) } } func TestFindPlaylistBySection(t *testing.T) { initTestCase(t) playlistEntries, err := db.FindPlaylistBySection("Viikko 07") if err != nil { t.Error("Error while searching for playlist") } if len(playlistEntries) != 0 { t.Error("Should have found 0 playlistEntries, got", len(playlistEntries)) } } func TestUpdatePlaylistBySection(t *testing.T) { initTestCase(t) updated, err := db.UpdatePlaylistBySection("Viikko 07", []string{"ID1", "ID2", "ID3", "ID4"}) if err != nil { t.Error("Error while updating for panels", err) } if !updated { t.Error("Could not update section") } playlistEntries, err := db.FindPlaylistBySection("Viikko 07") if err != nil { t.Error("Error while searching for playlist", err) } if len(playlistEntries) != 4 { t.Error("Should have found 4 playlistEntries, got", len(playlistEntries)) } } func TestUpdatePlaylistBySectionUnknownSection(t *testing.T) { initTestCase(t) updated, err := db.UpdatePlaylistBySection("Viikko joskus", []string{"ID1", "ID2", "ID3", "ID4"}) if err != nil { t.Error("Error while updating for panels", err) } if updated { t.Error("Should not update unknown section") } _, err = db.FindPlaylistBySection("Viikko joskus") if err == nil { t.Error("Should be error with unknown section", err) } }