package main import ( "database/sql" "fmt" "io/ioutil" "log" "os" "testing" ) func assert_string(t *testing.T, expected string, actual string) { if actual != expected { t.Fatalf("(%s, %s)", expected, actual) } } func assert_int(t *testing.T, expected int, actual int) { if actual != expected { t.Fatalf("(%d, %d)", expected, actual) } } func TestInitBasic(t *testing.T) { var db_location = ":memory:" ctx, err := Init(db_location) if err != nil { t.Fatalf(err.Error()) } // check that the tables exist var table_name string ctx.db.QueryRow( "SELECT name FROM sqlite_master WHERE type='table' AND name='eng_log_version';", ).Scan(&table_name) assert_string(t, "eng_log_version", table_name) ctx.db.QueryRow( "SELECT name FROM sqlite_master WHERE type='table' AND name='log';", ).Scan(&table_name) assert_string(t, "log", table_name) // Check that the version stored is correct var version int ctx.db.QueryRow("SELECT id FROM eng_log_version").Scan(&version) assert_int(t, __version, ctx.version) assert_int(t, __version, version) } func TestInitLogVersionTableExists(t *testing.T) { var db_location = ":memory:" db, err := sql.Open("sqlite3", db_location) db.Exec(` CREATE TABLE eng_log_version (id INTEGER NOT NULL); INSERT INTO eng_log_version (id) VALUES (1); `) _, err = Init(db_location) if err != nil { t.Fatalf(err.Error()) } } func TestInitWrongLogVersionExists(t *testing.T) { file, err := ioutil.TempFile("", "log_test_init_wrong.*.db") defer os.Remove(file.Name()) // clean up db, err := sql.Open("sqlite3", file.Name()) if err != nil { log.Fatal(err.Error()) } db.Exec(` CREATE TABLE eng_log_version (id INTEGER NOT NULL); `) db.Exec(` INSERT INTO eng_log_version (id) VALUES (?); `, __version+1) var version int db.QueryRow("SELECT id FROM eng_log_version LIMIT 1").Scan(&version) _, err = Init(file.Name()) if err == nil { t.Fatal("No error when error expected") } assert_string( t, fmt.Sprintf("Wrong version. Expected %d got %d", __version, __version+1), err.Error(), ) }