1package pgx 2 3import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "strings" 8 "testing" 9) 10 11func unescape(s string) string { 12 s = strings.Replace(s, `\:`, `:`, -1) 13 s = strings.Replace(s, `\\`, `\`, -1) 14 return s 15} 16 17var passfile = [][]string{ 18 {"test1", "5432", "larrydb", "larry", "whatstheidea"}, 19 {"test1", "5432", "moedb", "moe", "imbecile"}, 20 {"test1", "5432", "curlydb", "curly", "nyuknyuknyuk"}, 21 {"test2", "5432", "*", "shemp", "heymoe"}, 22 {"test2", "5432", "*", "*", `test\\ing\:`}, 23} 24 25func TestPGPass(t *testing.T) { 26 tf, err := ioutil.TempFile("", "") 27 if err != nil { 28 t.Fatal(err) 29 } 30 defer tf.Close() 31 defer os.Remove(tf.Name()) 32 os.Setenv("PGPASSFILE", tf.Name()) 33 for _, l := range passfile { 34 _, err := fmt.Fprintln(tf, strings.Join(l, `:`)) 35 if err != nil { 36 t.Fatal(err) 37 } 38 } 39 if err = tf.Close(); err != nil { 40 t.Fatal(err) 41 } 42 for i, l := range passfile { 43 cfg := ConnConfig{Host: l[0], Database: l[2], User: l[3]} 44 found := pgpass(&cfg) 45 if !found { 46 t.Fatalf("Entry %v not found", i) 47 } 48 if cfg.Password != unescape(l[4]) { 49 t.Fatalf(`Password mismatch entry %v want %s got %s`, i, unescape(l[4]), cfg.Password) 50 } 51 } 52 cfg := ConnConfig{Host: "derp", Database: "herp", User: "joe"} 53 found := pgpass(&cfg) 54 if found { 55 t.Fatal("bad found") 56 } 57} 58