github.com/lusis/distribution@v2.0.1+incompatible/registry/auth/silly/access_test.go (about) 1 package silly 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "testing" 7 8 "github.com/docker/distribution/registry/auth" 9 "golang.org/x/net/context" 10 ) 11 12 func TestSillyAccessController(t *testing.T) { 13 ac := &accessController{ 14 realm: "test-realm", 15 service: "test-service", 16 } 17 18 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 19 ctx := context.WithValue(nil, "http.request", r) 20 authCtx, err := ac.Authorized(ctx) 21 if err != nil { 22 switch err := err.(type) { 23 case auth.Challenge: 24 err.ServeHTTP(w, r) 25 return 26 default: 27 t.Fatalf("unexpected error authorizing request: %v", err) 28 } 29 } 30 31 userInfo, ok := authCtx.Value("auth.user").(auth.UserInfo) 32 if !ok { 33 t.Fatal("silly accessController did not set auth.user context") 34 } 35 36 if userInfo.Name != "silly" { 37 t.Fatalf("expected user name %q, got %q", "silly", userInfo.Name) 38 } 39 40 w.WriteHeader(http.StatusNoContent) 41 })) 42 43 resp, err := http.Get(server.URL) 44 if err != nil { 45 t.Fatalf("unexpected error during GET: %v", err) 46 } 47 defer resp.Body.Close() 48 49 // Request should not be authorized 50 if resp.StatusCode != http.StatusUnauthorized { 51 t.Fatalf("unexpected response status: %v != %v", resp.StatusCode, http.StatusUnauthorized) 52 } 53 54 req, err := http.NewRequest("GET", server.URL, nil) 55 if err != nil { 56 t.Fatalf("unexpected error creating new request: %v", err) 57 } 58 req.Header.Set("Authorization", "seriously, anything") 59 60 resp, err = http.DefaultClient.Do(req) 61 if err != nil { 62 t.Fatalf("unexpected error during GET: %v", err) 63 } 64 defer resp.Body.Close() 65 66 // Request should not be authorized 67 if resp.StatusCode != http.StatusNoContent { 68 t.Fatalf("unexpected response status: %v != %v", resp.StatusCode, http.StatusNoContent) 69 } 70 }