File: registry_mock.go

package info (click to toggle)
docker.io 1.11.2~ds1-6
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 23,652 kB
  • ctags: 12,672
  • sloc: sh: 7,238; makefile: 340; ansic: 123; xml: 62
file content (55 lines) | stat: -rw-r--r-- 1,104 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
	"net/http"
	"net/http/httptest"
	"regexp"
	"strings"
	"sync"

	"gopkg.in/check.v1"
)

type handlerFunc func(w http.ResponseWriter, r *http.Request)

type testRegistry struct {
	server   *httptest.Server
	hostport string
	handlers map[string]handlerFunc
	mu       sync.Mutex
}

func (tr *testRegistry) registerHandler(path string, h handlerFunc) {
	tr.mu.Lock()
	defer tr.mu.Unlock()
	tr.handlers[path] = h
}

func newTestRegistry(c *check.C) (*testRegistry, error) {
	testReg := &testRegistry{handlers: make(map[string]handlerFunc)}

	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 {
				c.Fatal("Error with handler regexp")
			}
			if matched {
				function(w, r)
				break
			}
		}

		if !matched {
			c.Fatalf("Unable to match %s with regexp", url)
		}
	}))

	testReg.server = ts
	testReg.hostport = strings.Replace(ts.URL, "http://", "", 1)
	return testReg, nil
}