github.com/mackerelio/mackerel-agent-plugins@v0.89.3/mackerel-plugin-postgres/lib/postgres_test.go (about) 1 package mppostgres 2 3 import ( 4 "testing" 5 6 "github.com/erikstmartin/go-testdb" 7 "github.com/jmoiron/sqlx" 8 ) 9 10 func TestFetchStatDatabase(t *testing.T) { 11 db, _ := sqlx.Connect("testdb", "") 12 13 columns := []string{"xact_commit", "xact_rollback", "blks_read", "blks_hit", "blk_read_time", "blk_write_time", 14 "tup_returned", "tup_fetched", "tup_inserted", "tup_updated", "tup_deleted", "deadlocks", "temp_bytes"} 15 16 testdb.StubQuery(`SELECT * FROM pg_stat_database`, testdb.RowsFromCSVString(columns, ` 17 1,2,3,4,5,6,7,8,9,10,11,12,13 18 10,20,30,40,50,60,70,80,90,100,110,120,130 19 `)) 20 21 stat, err := fetchStatDatabase(db) 22 23 expected := map[string]interface{}{ 24 "xact_commit": uint64(11), 25 "blks_hit": uint64(44), 26 "tup_returned": uint64(77), 27 } 28 29 if err != nil { 30 t.Errorf("Expected no error, but got %s instead", err) 31 } 32 if err = db.Close(); err != nil { 33 t.Errorf("Error '%s' was not expected while closing the database", err) 34 } 35 if stat["xact_commit"] != expected["xact_commit"] { 36 t.Error("should be 11") 37 } 38 if stat["blks_hit"] != expected["blks_hit"] { 39 t.Error("should be 44") 40 } 41 if stat["tup_returned"] != expected["tup_returned"] { 42 t.Error("should be 77") 43 } 44 } 45 46 var fetchVersionTests = []struct { 47 response string 48 expected version 49 }{ 50 { 51 ` 52 PostgreSQL 9.6.4 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-11), 64-bit 53 `, 54 version{uint(9), uint(6), uint(4)}, 55 }, 56 { 57 // Azure Database for PostgreSQL 58 ` 59 PostgreSQL 9.6.5, compiled by Visual C++ build 1800, 64-bit 60 `, 61 version{uint(9), uint(6), uint(5)}, 62 }, 63 { 64 ` 65 PostgreSQL 10.0 on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18) 6.3.0 20170516, 64-bit 66 `, 67 version{uint(10), uint(0), uint(0)}, 68 }, 69 } 70 71 func TestFetchVersion(t *testing.T) { 72 for _, tc := range fetchVersionTests { 73 db, _ := sqlx.Connect("testdb", "") 74 75 columns := []string{"version"} 76 77 testdb.StubQuery(`SELECT version()`, testdb.RowsFromCSVString(columns, tc.response, '|')) 78 79 v, err := fetchVersion(db) 80 81 if err != nil { 82 t.Errorf("Expected no error, but got %s instead", err) 83 } 84 if err = db.Close(); err != nil { 85 t.Errorf("Error '%s' was not expected while closing the database", err) 86 } 87 if v.first != tc.expected.first { 88 t.Errorf("should be %d", tc.expected.first) 89 } 90 if v.second != tc.expected.second { 91 t.Errorf("should be %d", tc.expected.second) 92 } 93 if v.third != tc.expected.third { 94 t.Errorf("should be %d", tc.expected.third) 95 } 96 } 97 }