github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/registry/endpoint_test.go (about)

     1  package registry // import "github.com/demonoid81/moby/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", "http://0.0.0.0:5000/v1/"},
    18  		{"0.0.0.0:5000", "https://0.0.0.0:5000/v1/"},
    19  		{"http://0.0.0.0:5000/nonversion/", "http://0.0.0.0:5000/nonversion/v1/"},
    20  		{"http://0.0.0.0:5000/v0/", "http://0.0.0.0:5000/v0/v1/"},
    21  	}
    22  	for _, td := range testData {
    23  		e, err := newV1EndpointFromStr(td.str, nil, "", nil)
    24  		if err != nil {
    25  			t.Errorf("%q: %s", td.str, err)
    26  		}
    27  		if e == nil {
    28  			t.Logf("something's fishy, endpoint for %q is nil", td.str)
    29  			continue
    30  		}
    31  		if e.String() != td.expected {
    32  			t.Errorf("expected %q, got %q", td.expected, e.String())
    33  		}
    34  	}
    35  }
    36  
    37  func TestEndpointParseInvalid(t *testing.T) {
    38  	testData := []string{
    39  		"http://0.0.0.0:5000/v2/",
    40  	}
    41  	for _, td := range testData {
    42  		e, err := newV1EndpointFromStr(td, nil, "", nil)
    43  		if err == nil {
    44  			t.Errorf("expected error parsing %q: parsed as %q", td, e)
    45  		}
    46  	}
    47  }
    48  
    49  // Ensure that a registry endpoint that responds with a 401 only is determined
    50  // to be a valid v1 registry endpoint
    51  func TestValidateEndpoint(t *testing.T) {
    52  	requireBasicAuthHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    53  		w.Header().Add("WWW-Authenticate", `Basic realm="localhost"`)
    54  		w.WriteHeader(http.StatusUnauthorized)
    55  	})
    56  
    57  	// Make a test server which should validate as a v1 server.
    58  	testServer := httptest.NewServer(requireBasicAuthHandler)
    59  	defer testServer.Close()
    60  
    61  	testServerURL, err := url.Parse(testServer.URL)
    62  	if err != nil {
    63  		t.Fatal(err)
    64  	}
    65  
    66  	testEndpoint := V1Endpoint{
    67  		URL:    testServerURL,
    68  		client: HTTPClient(NewTransport(nil)),
    69  	}
    70  
    71  	if err = validateEndpoint(&testEndpoint); err != nil {
    72  		t.Fatal(err)
    73  	}
    74  
    75  	if testEndpoint.URL.Scheme != "http" {
    76  		t.Fatalf("expecting to validate endpoint as http, got url %s", testEndpoint.String())
    77  	}
    78  }