github.com/gunjan5/docker@v1.8.2/registry/endpoint_test.go (about) 1 package registry 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "net/url" 7 "testing" 8 ) 9 10 func TestEndpointParse(t *testing.T) { 11 testData := []struct { 12 str string 13 expected string 14 }{ 15 {IndexServer, IndexServer}, 16 {"http://0.0.0.0:5000/v1/", "http://0.0.0.0:5000/v1/"}, 17 {"http://0.0.0.0:5000/v2/", "http://0.0.0.0:5000/v2/"}, 18 {"http://0.0.0.0:5000", "http://0.0.0.0:5000/v0/"}, 19 {"0.0.0.0:5000", "https://0.0.0.0:5000/v0/"}, 20 } 21 for _, td := range testData { 22 e, err := newEndpoint(td.str, nil, nil) 23 if err != nil { 24 t.Errorf("%q: %s", td.str, err) 25 } 26 if e == nil { 27 t.Logf("something's fishy, endpoint for %q is nil", td.str) 28 continue 29 } 30 if e.String() != td.expected { 31 t.Errorf("expected %q, got %q", td.expected, e.String()) 32 } 33 } 34 } 35 36 // Ensure that a registry endpoint that responds with a 401 only is determined 37 // to be a v1 registry unless it includes a valid v2 API header. 38 func TestValidateEndpointAmbiguousAPIVersion(t *testing.T) { 39 requireBasicAuthHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 40 w.Header().Add("WWW-Authenticate", `Basic realm="localhost"`) 41 w.WriteHeader(http.StatusUnauthorized) 42 }) 43 44 requireBasicAuthHandlerV2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 45 // This mock server supports v2.0, v2.1, v42.0, and v100.0 46 w.Header().Add("Docker-Distribution-API-Version", "registry/100.0 registry/42.0") 47 w.Header().Add("Docker-Distribution-API-Version", "registry/2.0 registry/2.1") 48 requireBasicAuthHandler.ServeHTTP(w, r) 49 }) 50 51 // Make a test server which should validate as a v1 server. 52 testServer := httptest.NewServer(requireBasicAuthHandler) 53 defer testServer.Close() 54 55 testServerURL, err := url.Parse(testServer.URL) 56 if err != nil { 57 t.Fatal(err) 58 } 59 60 testEndpoint := Endpoint{ 61 URL: testServerURL, 62 Version: APIVersionUnknown, 63 client: HTTPClient(NewTransport(nil)), 64 } 65 66 if err = validateEndpoint(&testEndpoint); err != nil { 67 t.Fatal(err) 68 } 69 70 if testEndpoint.Version != APIVersion1 { 71 t.Fatalf("expected endpoint to validate to %d, got %d", APIVersion1, testEndpoint.Version) 72 } 73 74 // Make a test server which should validate as a v2 server. 75 testServer = httptest.NewServer(requireBasicAuthHandlerV2) 76 defer testServer.Close() 77 78 testServerURL, err = url.Parse(testServer.URL) 79 if err != nil { 80 t.Fatal(err) 81 } 82 83 testEndpoint.URL = testServerURL 84 testEndpoint.Version = APIVersionUnknown 85 86 if err = validateEndpoint(&testEndpoint); err != nil { 87 t.Fatal(err) 88 } 89 90 if testEndpoint.Version != APIVersion2 { 91 t.Fatalf("expected endpoint to validate to %d, got %d", APIVersion2, testEndpoint.Version) 92 } 93 }