2018-04-13 04:45:34 -04:00
|
|
|
package registry // import "github.com/docker/docker/internal/test/registry"
|
2015-09-16 13:42:17 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2018-04-18 11:16:55 -04:00
|
|
|
|
|
|
|
"github.com/docker/docker/internal/test"
|
2015-09-16 13:42:17 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type handlerFunc func(w http.ResponseWriter, r *http.Request)
|
|
|
|
|
2016-12-30 13:10:04 -05:00
|
|
|
// Mock represent a registry mock
|
|
|
|
type Mock struct {
|
2015-09-16 13:42:17 -04:00
|
|
|
server *httptest.Server
|
|
|
|
hostport string
|
|
|
|
handlers map[string]handlerFunc
|
|
|
|
mu sync.Mutex
|
|
|
|
}
|
|
|
|
|
2016-12-30 13:10:04 -05:00
|
|
|
// RegisterHandler register the specified handler for the registry mock
|
|
|
|
func (tr *Mock) RegisterHandler(path string, h handlerFunc) {
|
2015-09-16 13:42:17 -04:00
|
|
|
tr.mu.Lock()
|
|
|
|
defer tr.mu.Unlock()
|
|
|
|
tr.handlers[path] = h
|
|
|
|
}
|
|
|
|
|
2016-12-30 13:10:04 -05:00
|
|
|
// NewMock creates a registry mock
|
|
|
|
func NewMock(t testingT) (*Mock, error) {
|
2018-04-18 11:16:55 -04:00
|
|
|
if ht, ok := t.(test.HelperT); ok {
|
|
|
|
ht.Helper()
|
|
|
|
}
|
2016-12-30 13:10:04 -05:00
|
|
|
testReg := &Mock{handlers: make(map[string]handlerFunc)}
|
2015-09-16 13:42:17 -04: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 13:10:04 -05:00
|
|
|
t.Fatal("Error with handler regexp")
|
2015-09-16 13:42:17 -04:00
|
|
|
}
|
|
|
|
if matched {
|
|
|
|
function(w, r)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if !matched {
|
2016-12-30 13:10:04 -05:00
|
|
|
t.Fatalf("Unable to match %s with regexp", url)
|
2015-09-16 13:42:17 -04:00
|
|
|
}
|
|
|
|
}))
|
|
|
|
|
|
|
|
testReg.server = ts
|
|
|
|
testReg.hostport = strings.Replace(ts.URL, "http://", "", 1)
|
|
|
|
return testReg, nil
|
|
|
|
}
|
2016-12-30 13:10:04 -05:00
|
|
|
|
|
|
|
// URL returns the url of the registry
|
|
|
|
func (tr *Mock) URL() string {
|
|
|
|
return tr.hostport
|
|
|
|
}
|
2017-01-11 15:38:52 -05:00
|
|
|
|
|
|
|
// Close closes mock and releases resources
|
|
|
|
func (tr *Mock) Close() {
|
|
|
|
tr.server.Close()
|
|
|
|
}
|