github.com/sams1990/dockerrepo@v17.12.1-ce-rc2+incompatible/pkg/authorization/middleware_unix_test.go (about)

     1  // +build !windows
     2  
     3  package authorization
     4  
     5  import (
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"testing"
     9  
    10  	"github.com/docker/docker/pkg/plugingetter"
    11  	"github.com/stretchr/testify/require"
    12  	"golang.org/x/net/context"
    13  )
    14  
    15  func TestMiddlewareWrapHandler(t *testing.T) {
    16  	server := authZPluginTestServer{t: t}
    17  	server.start()
    18  	defer server.stop()
    19  
    20  	authZPlugin := createTestPlugin(t)
    21  	pluginNames := []string{authZPlugin.name}
    22  
    23  	var pluginGetter plugingetter.PluginGetter
    24  	middleWare := NewMiddleware(pluginNames, pluginGetter)
    25  	handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    26  		return nil
    27  	}
    28  
    29  	authList := []Plugin{authZPlugin}
    30  	middleWare.SetPlugins([]string{"My Test Plugin"})
    31  	setAuthzPlugins(middleWare, authList)
    32  	mdHandler := middleWare.WrapHandler(handler)
    33  	require.NotNil(t, mdHandler)
    34  
    35  	addr := "www.example.com/auth"
    36  	req, _ := http.NewRequest("GET", addr, nil)
    37  	req.RequestURI = addr
    38  	req.Header.Add("header", "value")
    39  
    40  	resp := httptest.NewRecorder()
    41  	ctx := context.Background()
    42  
    43  	t.Run("Error Test Case :", func(t *testing.T) {
    44  		server.replayResponse = Response{
    45  			Allow: false,
    46  			Msg:   "Server Auth Not Allowed",
    47  		}
    48  		if err := mdHandler(ctx, resp, req, map[string]string{}); err == nil {
    49  			require.Error(t, err)
    50  		}
    51  
    52  	})
    53  
    54  	t.Run("Positive Test Case :", func(t *testing.T) {
    55  		server.replayResponse = Response{
    56  			Allow: true,
    57  			Msg:   "Server Auth Allowed",
    58  		}
    59  		if err := mdHandler(ctx, resp, req, map[string]string{}); err != nil {
    60  			require.NoError(t, err)
    61  		}
    62  
    63  	})
    64  
    65  }