github.com/bcampbell/scrapeomat@v0.0.0-20220820232205-23e64141c89e/store/sqlstore/pg_test.go (about) 1 package sqlstore 2 3 import ( 4 "database/sql" 5 "os" 6 "testing" 7 8 _ "github.com/lib/pq" 9 ) 10 11 // TestPostgres runs the store tests against a postgresql database. 12 // It requires a test database to be set up in advance, with a 13 // schema loaded. 14 // The connection string should be in envvar SCRAPEOMAT_PGTEST. 15 // If it is not set, the postgres testing is skippped. 16 // 17 // Example setup: 18 // 19 // Add a line to `pg_hba.conf` to allow our test user to access the test 20 // database: 21 // 22 // local scrapetest timmytestfish peer map=scrapedev 23 // 24 // Map OS username to our test user, in `pg_ident.conf`: 25 // 26 // scrapedev ben timmytestfish 27 // 28 // Tell postgres to reload its config: 29 // $ sudo systemctl reload postgresql 30 // 31 // 32 // Create the test user and database and load the schema: 33 // 34 // $ sudo -u postgres createuser --no-superuser --no-createrole --no-createdb timmytestfish 35 // $ sudo -u postgres createdb -O timmytestfish -E utf8 scrapetest 36 // $ cat pg/schema.sql | psql -U timmytestfish scrapetest 37 // 38 // $ export SCRAPEOMAT_PGTEST="user=timmytestfish dbname=scrapetest host=/var/run/postgresql sslmode=disable" 39 // $ go test 40 // 41 42 func TestPostgres(t *testing.T) { 43 44 connStr := os.Getenv("SCRAPEOMAT_PGTEST") 45 if connStr == "" { 46 t.Skip("SCRAPEOMAT_PGTEST not set - skipping postgresql tests") 47 } 48 49 db, err := sql.Open("postgres", connStr) 50 if err != nil { 51 t.Fatal(err.Error()) 52 } 53 54 // Make sure we don't accidentally screw up real data! 55 var cnt int 56 err = db.QueryRow("SELECT COUNT(*) FROM article").Scan(&cnt) 57 if err != nil { 58 t.Fatal(err.Error()) 59 } 60 if cnt > 0 { 61 t.Fatal("Database already contains articles - refusing to clobber.") 62 } 63 64 ss, err := NewFromDB("postgres", db) 65 if err != nil { 66 t.Fatal(err.Error()) 67 } 68 69 // clear out db when we're done. 70 defer func() { 71 _, err = db.Exec("DELETE FROM article") 72 if err != nil { 73 t.Fatal(err.Error()) 74 } 75 ss.Close() 76 }() 77 78 // Now run the tests! 79 performDBTests(t, ss) 80 }