pgpass_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package pgpassfile
  2. import (
  3. "bytes"
  4. "strings"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/stretchr/testify/require"
  8. )
  9. func unescape(s string) string {
  10. s = strings.Replace(s, `\:`, `:`, -1)
  11. s = strings.Replace(s, `\\`, `\`, -1)
  12. return s
  13. }
  14. var passfile = [][]string{
  15. {"test1", "5432", "larrydb", "larry", "whatstheidea"},
  16. {"test1", "5432", "moedb", "moe", "imbecile"},
  17. {"test1", "5432", "curlydb", "curly", "nyuknyuknyuk"},
  18. {"test2", "5432", "*", "shemp", "heymoe"},
  19. {"test2", "5432", "*", "*", `test\\ing\:`},
  20. {"localhost", "*", "*", "*", "sesam"},
  21. {"test3", "*", "", "", "swordfish"}, // user will be filled later
  22. }
  23. func TestParsePassFile(t *testing.T) {
  24. buf := bytes.NewBufferString(`# A comment
  25. test1:5432:larrydb:larry:whatstheidea
  26. test1:5432:moedb:moe:imbecile
  27. test1:5432:curlydb:curly:nyuknyuknyuk
  28. test2:5432:*:shemp:heymoe
  29. test2:5432:*:*:test\\ing\:
  30. localhost:*:*:*:sesam
  31. `)
  32. passfile, err := ParsePassfile(buf)
  33. require.Nil(t, err)
  34. assert.Len(t, passfile.Entries, 6)
  35. assert.Equal(t, "whatstheidea", passfile.FindPassword("test1", "5432", "larrydb", "larry"))
  36. assert.Equal(t, "imbecile", passfile.FindPassword("test1", "5432", "moedb", "moe"))
  37. assert.Equal(t, `test\ing:`, passfile.FindPassword("test2", "5432", "something", "else"))
  38. assert.Equal(t, "sesam", passfile.FindPassword("localhost", "9999", "foo", "bare"))
  39. assert.Equal(t, "", passfile.FindPassword("wrong", "5432", "larrydb", "larry"))
  40. assert.Equal(t, "", passfile.FindPassword("test1", "wrong", "larrydb", "larry"))
  41. assert.Equal(t, "", passfile.FindPassword("test1", "5432", "wrong", "larry"))
  42. assert.Equal(t, "", passfile.FindPassword("test1", "5432", "larrydb", "wrong"))
  43. }