github.com/tunedmystic/hound@v0.0.0-20200829043919-3822fec61e65/app/database/database_integration_test.go (about) 1 package database 2 3 import ( 4 "log" 5 "os" 6 "testing" 7 8 "github.com/jmoiron/sqlx" 9 "github.com/matryer/is" 10 _ "github.com/mattn/go-sqlite3" // sqlite 11 12 "github.com/tunedmystic/hound/app/config" 13 ) 14 15 func createArticles(db *sqlx.DB) func() { 16 db.MustExec(` 17 insert into article (url, title, description, published_at, created_at) 18 values 19 ("cnn.com/article1", "Article 1 title", "Article 1 description", "2020-07-17 07:38:44", "2020-07-20 07:38:44"), 20 ("cnn.com/article2", "Article 2 title", "Article 2 description", "2020-07-01 01:06:31", "2020-07-01 04:00:21"), 21 ("msnbc.com/article2", "Article 2 title", "Article 2 description", "2020-06-12 13:21:00", "2020-06-13 21:00:00"); 22 `) 23 24 return func() { 25 // Truncate table and reset PK sequence. 26 db.MustExec(`delete from article; delete from sqlite_sequence where name='article';`) 27 } 28 } 29 30 func TestMain(m *testing.M) { 31 // Switch to project dir. 32 config := config.GetConfig() 33 os.Chdir(config.BaseDir) 34 35 // Create test db, and create tables. 36 db := NewDB() 37 CreateTables(db) 38 if err := db.Close(); err != nil { 39 log.Fatalf("Error when closing the database: %v\n", err) 40 } 41 42 // Run the test. 43 code := m.Run() 44 45 // Remove the test db. 46 if err := os.Remove(config.DatabaseName); err != nil { 47 log.Fatalf("Error when removing the database: %v\n", err) 48 } 49 os.Exit(code) 50 } 51 52 func Test_Database(t *testing.T) { 53 is := is.New(t) 54 55 db := NewDB() 56 defer db.Close() 57 58 cleanup := createArticles(db) 59 defer cleanup() 60 61 articles := GetArticles(db) 62 63 is.Equal(len(articles), 3) // 3 Articles exist 64 }