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