2019-08-29 20:52:40 +00:00
|
|
|
package registry // import "github.com/docker/docker/testutil/registry"
|
2015-09-16 17:42:17 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2019-09-23 11:54:51 +00:00
|
|
|
"testing"
|
2015-09-16 17:42:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type handlerFunc func(w http.ResponseWriter, r *http.Request)
|
|
|
|
|
2016-12-30 18:10:04 +00:00
|
|
|
// Mock represent a registry mock
|
|
|
|
type Mock struct {
|
2015-09-16 17:42:17 +00:00
|
|
|
server *httptest.Server
|
|
|
|
hostport string
|
|
|
|
handlers map[string]handlerFunc
|
|
|
|
mu sync.Mutex
|
|
|
|
}
|
|
|
|
|
2016-12-30 18:10:04 +00:00
|
|
|
// RegisterHandler register the specified handler for the registry mock
|
|
|
|
func (tr *Mock) RegisterHandler(path string, h handlerFunc) {
|
2015-09-16 17:42:17 +00:00
|
|
|
tr.mu.Lock()
|
|
|
|
defer tr.mu.Unlock()
|
|
|
|
tr.handlers[path] = h
|
|
|
|
}
|
|
|
|
|
2016-12-30 18:10:04 +00:00
|
|
|
// NewMock creates a registry mock
|
2019-09-23 11:54:51 +00:00
|
|
|
func NewMock(t testing.TB) (*Mock, error) {
|
2019-09-23 12:06:27 +00:00
|
|
|
t.Helper()
|
2016-12-30 18:10:04 +00:00
|
|
|
testReg := &Mock{handlers: make(map[string]handlerFunc)}
|
2015-09-16 17:42:17 +00:00
|
|
|
|
|
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
url := r.URL.String()
|
|
|
|
|
|
|
|
var matched bool
|
|
|
|
var err error
|
|
|
|
for re, function := range testReg.handlers {
|
|
|
|
matched, err = regexp.MatchString(re, url)
|
|
|
|
if err != nil {
|
2016-12-30 18:10:04 +00:00
|
|
|
t.Fatal("Error with handler regexp")
|
2015-09-16 17:42:17 +00:00
|
|
|
}
|
|
|
|
if matched {
|
|
|
|
function(w, r)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !matched {
|
2016-12-30 18:10:04 +00:00
|
|
|
t.Fatalf("Unable to match %s with regexp", url)
|
2015-09-16 17:42:17 +00:00
|
|
|
}
|
|
|
|
}))
|
|
|
|
|
|
|
|
testReg.server = ts
|
|
|
|
testReg.hostport = strings.Replace(ts.URL, "http://", "", 1)
|
|
|
|
return testReg, nil
|
|
|
|
}
|
2016-12-30 18:10:04 +00:00
|
|
|
|
|
|
|
// URL returns the url of the registry
|
|
|
|
func (tr *Mock) URL() string {
|
|
|
|
return tr.hostport
|
|
|
|
}
|
2017-01-11 20:38:52 +00:00
|
|
|
|
|
|
|
// Close closes mock and releases resources
|
|
|
|
func (tr *Mock) Close() {
|
|
|
|
tr.server.Close()
|
|
|
|
}
|