registry_mock.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package registry
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "regexp"
  6. "strings"
  7. "sync"
  8. )
  9. type handlerFunc func(w http.ResponseWriter, r *http.Request)
  10. // Mock represent a registry mock
  11. type Mock struct {
  12. server *httptest.Server
  13. hostport string
  14. handlers map[string]handlerFunc
  15. mu sync.Mutex
  16. }
  17. // RegisterHandler register the specified handler for the registry mock
  18. func (tr *Mock) RegisterHandler(path string, h handlerFunc) {
  19. tr.mu.Lock()
  20. defer tr.mu.Unlock()
  21. tr.handlers[path] = h
  22. }
  23. // NewMock creates a registry mock
  24. func NewMock(t testingT) (*Mock, error) {
  25. testReg := &Mock{handlers: make(map[string]handlerFunc)}
  26. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  27. url := r.URL.String()
  28. var matched bool
  29. var err error
  30. for re, function := range testReg.handlers {
  31. matched, err = regexp.MatchString(re, url)
  32. if err != nil {
  33. t.Fatal("Error with handler regexp")
  34. }
  35. if matched {
  36. function(w, r)
  37. break
  38. }
  39. }
  40. if !matched {
  41. t.Fatalf("Unable to match %s with regexp", url)
  42. }
  43. }))
  44. testReg.server = ts
  45. testReg.hostport = strings.Replace(ts.URL, "http://", "", 1)
  46. return testReg, nil
  47. }
  48. // URL returns the url of the registry
  49. func (tr *Mock) URL() string {
  50. return tr.hostport
  51. }
  52. // Close closes mock and releases resources
  53. func (tr *Mock) Close() {
  54. tr.server.Close()
  55. }