registry_mock.go 1.4 KB

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