github.com/mika/distribution@v2.2.2-0.20160108133430-a75790e3d8e0+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/context" 9 "github.com/docker/distribution/registry/auth" 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.SetHeaders(w) 25 w.WriteHeader(http.StatusUnauthorized) 26 return 27 default: 28 t.Fatalf("unexpected error authorizing request: %v", err) 29 } 30 } 31 32 userInfo, ok := authCtx.Value("auth.user").(auth.UserInfo) 33 if !ok { 34 t.Fatal("silly accessController did not set auth.user context") 35 } 36 37 if userInfo.Name != "silly" { 38 t.Fatalf("expected user name %q, got %q", "silly", userInfo.Name) 39 } 40 41 w.WriteHeader(http.StatusNoContent) 42 })) 43 44 resp, err := http.Get(server.URL) 45 if err != nil { 46 t.Fatalf("unexpected error during GET: %v", err) 47 } 48 defer resp.Body.Close() 49 50 // Request should not be authorized 51 if resp.StatusCode != http.StatusUnauthorized { 52 t.Fatalf("unexpected response status: %v != %v", resp.StatusCode, http.StatusUnauthorized) 53 } 54 55 req, err := http.NewRequest("GET", server.URL, nil) 56 if err != nil { 57 t.Fatalf("unexpected error creating new request: %v", err) 58 } 59 req.Header.Set("Authorization", "seriously, anything") 60 61 resp, err = http.DefaultClient.Do(req) 62 if err != nil { 63 t.Fatalf("unexpected error during GET: %v", err) 64 } 65 defer resp.Body.Close() 66 67 // Request should not be authorized 68 if resp.StatusCode != http.StatusNoContent { 69 t.Fatalf("unexpected response status: %v != %v", resp.StatusCode, http.StatusNoContent) 70 } 71 }