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