1
0
mirror of https://github.com/containous/traefik.git synced 2024-12-22 13:34:03 +03:00

Code cleaning.

This commit is contained in:
Ludovic Fernandez 2017-08-18 02:18:02 +02:00 committed by Traefiker
parent c360395afc
commit 759c269dee
19 changed files with 64 additions and 56 deletions

View File

@ -169,7 +169,7 @@ func (a *ACME) CreateClusterConfig(leadership *cluster.Leadership, tlsConfig *tl
leadership.AddListener(func(elected bool) error {
if elected {
object, err := a.store.Load()
_, err := a.store.Load()
if err != nil {
return err
}

View File

@ -123,10 +123,8 @@ func pemEncode(data interface{}) []byte {
pemBlock = &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}
case *rsa.PrivateKey:
pemBlock = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}
break
case *x509.CertificateRequest:
pemBlock = &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: key.Raw}
break
case []byte:
pemBlock = &pem.Block{Type: "CERTIFICATE", Bytes: []byte(data.([]byte))}
}

View File

@ -53,6 +53,7 @@ func (s *DynamoDBSuite) SetUpSuite(c *check.C) {
sess = session.New(config)
return nil
})
c.Assert(err, checker.IsNil)
svc := dynamodb.New(sess)
// create dynamodb table

View File

@ -176,6 +176,7 @@ func (s *EtcdSuite) TestNominalConfiguration(c *check.C) {
}
req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/test2", nil)
c.Assert(err, checker.IsNil)
req.Host = "test2.localhost"
resp, err := client.Do(req)
c.Assert(err, checker.IsNil)

View File

@ -126,7 +126,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthentication(c *check.C) {
Certificates: []tls.Certificate{},
}
// Connection without client certificate should fail
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
_, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
// Connect with client certificate signed by ca1
@ -134,7 +134,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthentication(c *check.C) {
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
conn.Close()
@ -149,7 +149,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthentication(c *check.C) {
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
_, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}
@ -172,7 +172,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAs(c *check.
Certificates: []tls.Certificate{},
}
// Connection without client certificate should fail
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
_, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
// Connect with client signed by ca1
@ -180,7 +180,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAs(c *check.
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
conn.Close()
@ -197,6 +197,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAs(c *check.
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
conn.Close()
// Connect with client signed by ca3 should fail
@ -209,7 +210,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAs(c *check.
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
_, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}
@ -231,7 +232,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFi
Certificates: []tls.Certificate{},
}
// Connection without client certificate should fail
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
_, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
// Connect with client signed by ca1
@ -239,7 +240,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFi
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
conn.Close()
@ -268,7 +269,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFi
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
_, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}

View File

@ -48,7 +48,6 @@ func (suite *WebsocketSuite) TestBase(c *check.C) {
cmd, _ := suite.cmdTraefik(withConfigFile(file), "--debug")
err := cmd.Start()
c.Assert(err, check.IsNil)
defer cmd.Process.Kill()
@ -57,15 +56,14 @@ func (suite *WebsocketSuite) TestBase(c *check.C) {
c.Assert(err, checker.IsNil)
conn, _, err := gorillawebsocket.DefaultDialer.Dial("ws://127.0.0.1:8000/ws", nil)
c.Assert(err, checker.IsNil)
conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK"))
err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK"))
c.Assert(err, checker.IsNil)
_, msg, err := conn.ReadMessage()
c.Assert(err, checker.IsNil)
c.Assert(string(msg), checker.Equals, "OK")
}
func (suite *WebsocketSuite) TestWrongOrigin(c *check.C) {
@ -99,7 +97,6 @@ func (suite *WebsocketSuite) TestWrongOrigin(c *check.C) {
cmd, _ := suite.cmdTraefik(withConfigFile(file), "--debug")
err := cmd.Start()
c.Assert(err, check.IsNil)
defer cmd.Process.Kill()
@ -111,14 +108,15 @@ func (suite *WebsocketSuite) TestWrongOrigin(c *check.C) {
c.Assert(err, check.IsNil)
conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second)
c.Assert(err, checker.IsNil)
_, err = websocket.NewClient(config, conn)
c.Assert(err, checker.NotNil)
c.Assert(err, checker.ErrorMatches, "bad status")
}
func (suite *WebsocketSuite) TestOrigin(c *check.C) {
var upgrader = gorillawebsocket.Upgrader{} // use default options
// use default options
var upgrader = gorillawebsocket.Upgrader{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
@ -148,7 +146,6 @@ func (suite *WebsocketSuite) TestOrigin(c *check.C) {
cmd, _ := suite.cmdTraefik(withConfigFile(file), "--debug")
err := cmd.Start()
c.Assert(err, check.IsNil)
defer cmd.Process.Kill()
@ -160,6 +157,7 @@ func (suite *WebsocketSuite) TestOrigin(c *check.C) {
c.Assert(err, check.IsNil)
conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second)
c.Assert(err, check.IsNil)
client, err := websocket.NewClient(config, conn)
c.Assert(err, checker.IsNil)
@ -208,7 +206,6 @@ func (suite *WebsocketSuite) TestWrongOriginIgnoredByServer(c *check.C) {
cmd, _ := suite.cmdTraefik(withConfigFile(file), "--debug")
err := cmd.Start()
c.Assert(err, check.IsNil)
defer cmd.Process.Kill()
@ -220,6 +217,7 @@ func (suite *WebsocketSuite) TestWrongOriginIgnoredByServer(c *check.C) {
c.Assert(err, check.IsNil)
conn, err := net.DialTimeout("tcp", "127.0.0.1:8000", time.Second)
c.Assert(err, checker.IsNil)
client, err := websocket.NewClient(config, conn)
c.Assert(err, checker.IsNil)

View File

@ -218,8 +218,8 @@ func createTempDir(t *testing.T, prefix string) string {
func doLogging(t *testing.T, config *types.AccessLog) {
logger, err := NewLogHandler(config)
defer logger.Close()
require.NoError(t, err)
defer logger.Close()
if config.FilePath != "" {
_, err = os.Stat(config.FilePath)

View File

@ -66,14 +66,14 @@ func TestAuthUsersFromFile(t *testing.T) {
}
func TestBasicAuthFail(t *testing.T) {
authMiddleware, err := NewAuthenticator(&types.Auth{
_, err := NewAuthenticator(&types.Auth{
Basic: &types.Basic{
Users: []string{"test"},
},
})
assert.Contains(t, err.Error(), "Error parsing Authenticator user", "should contains")
authMiddleware, err = NewAuthenticator(&types.Auth{
authMiddleware, err := NewAuthenticator(&types.Auth{
Basic: &types.Basic{
Users: []string{"test:test"},
},
@ -125,14 +125,14 @@ func TestBasicAuthSuccess(t *testing.T) {
}
func TestDigestAuthFail(t *testing.T) {
authMiddleware, err := NewAuthenticator(&types.Auth{
_, err := NewAuthenticator(&types.Auth{
Digest: &types.Digest{
Users: []string{"test"},
},
})
assert.Contains(t, err.Error(), "Error parsing Authenticator user", "should contains")
authMiddleware, err = NewAuthenticator(&types.Auth{
authMiddleware, err := NewAuthenticator(&types.Auth{
Digest: &types.Digest{
Users: []string{"test:traefik:test"},
},
@ -161,12 +161,12 @@ func TestBasicAuthUserHeader(t *testing.T) {
Basic: &types.Basic{
Users: []string{"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/"},
},
HeaderField: "X-WebAuth-User",
HeaderField: "X-Webauth-User",
})
assert.NoError(t, err, "there should be no error")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "test", r.Header["X-WebAuth-User"][0], "auth user should be set")
assert.Equal(t, "test", r.Header["X-Webauth-User"][0], "auth user should be set")
fmt.Fprintln(w, "traefik")
})
n := negroni.New(authMiddleware)

View File

@ -9,6 +9,7 @@ import (
"github.com/containous/traefik/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/urfave/negroni"
)
@ -19,13 +20,15 @@ func TestErrorPage(t *testing.T) {
defer ts.Close()
testErrorPage := &types.ErrorPage{Backend: "error", Query: "/test", Status: []string{"500-501", "503-599"}}
testHandler, err := NewErrorPagesHandler(*testErrorPage, ts.URL)
assert.Equal(t, nil, err, "Should be no error")
testHandler, err := NewErrorPagesHandler(*testErrorPage, ts.URL)
require.NoError(t, err)
assert.Equal(t, testHandler.BackendURL, ts.URL+"/test", "Should be equal")
recorder := httptest.NewRecorder()
req, err := http.NewRequest("GET", ts.URL+"/test", nil)
require.NoError(t, err)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "traefik")
@ -68,7 +71,6 @@ func TestErrorPage(t *testing.T) {
assert.Equal(t, http.StatusBadGateway, recorder502.Code, "HTTP status Bad Gateway")
assert.Contains(t, recorder502.Body.String(), "oops")
assert.NotContains(t, recorder502.Body.String(), "Test Server", "Should return the oops page since we have not configured the 502 code")
}
func TestErrorPageQuery(t *testing.T) {
@ -83,16 +85,22 @@ func TestErrorPageQuery(t *testing.T) {
defer ts.Close()
testErrorPage := &types.ErrorPage{Backend: "error", Query: "/{status}", Status: []string{"503-503"}}
testHandler, err := NewErrorPagesHandler(*testErrorPage, ts.URL)
assert.Equal(t, nil, err, "Should be no error")
require.NoError(t, err)
assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(503)
fmt.Fprintln(w, "oops")
})
recorder := httptest.NewRecorder()
req, err := http.NewRequest("GET", ts.URL+"/test", nil)
require.NoError(t, err)
n := negroni.New()
n.Use(testHandler)
n.UseHandler(handler)
@ -102,7 +110,6 @@ func TestErrorPageQuery(t *testing.T) {
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code, "HTTP status Service Unavailable")
assert.Contains(t, recorder.Body.String(), "503 Test Server")
assert.NotContains(t, recorder.Body.String(), "oops", "Should not return the oops page")
}
func TestErrorPageSingleCode(t *testing.T) {
@ -117,16 +124,22 @@ func TestErrorPageSingleCode(t *testing.T) {
defer ts.Close()
testErrorPage := &types.ErrorPage{Backend: "error", Query: "/{status}", Status: []string{"503"}}
testHandler, err := NewErrorPagesHandler(*testErrorPage, ts.URL)
assert.Equal(t, nil, err, "Should be no error")
require.NoError(t, err)
assert.Equal(t, testHandler.BackendURL, ts.URL+"/{status}", "Should be equal")
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(503)
fmt.Fprintln(w, "oops")
})
recorder := httptest.NewRecorder()
req, err := http.NewRequest("GET", ts.URL+"/test", nil)
require.NoError(t, err)
n := negroni.New()
n.Use(testHandler)
n.UseHandler(handler)
@ -136,5 +149,4 @@ func TestErrorPageSingleCode(t *testing.T) {
assert.Equal(t, http.StatusServiceUnavailable, recorder.Code, "HTTP status Service Unavailable")
assert.Contains(t, recorder.Body.String(), "503 Test Server")
assert.NotContains(t, recorder.Body.String(), "oops", "Should not return the oops page")
}

View File

@ -57,7 +57,6 @@ func (whitelister *IPWhitelister) handle(w http.ResponseWriter, r *http.Request,
log.Debugf("source-IP %s matched none of the whitelists - rejecting", remoteIP)
reject(w)
return
}
func reject(w http.ResponseWriter) {

View File

@ -41,8 +41,7 @@ func TestRetry(t *testing.T) {
t.Run(tcName, func(t *testing.T) {
t.Parallel()
var httpHandler http.Handler
httpHandler = &networkFailingHTTPHandler{failAtCalls: tc.failAtCalls, netErrorRecorder: &DefaultNetErrorRecorder{}}
var httpHandler http.Handler = &networkFailingHTTPHandler{failAtCalls: tc.failAtCalls, netErrorRecorder: &DefaultNetErrorRecorder{}}
httpHandler = NewRetry(tc.attempts, httpHandler, tc.listener)
recorder := httptest.NewRecorder()

View File

@ -132,6 +132,10 @@ func (p *Provider) Provide(configurationChan chan<- types.ConfigMessage, pool *s
ctx := context.Background()
version, err := dockerClient.ServerVersion(ctx)
if err != nil {
log.Errorf("Failed to retrieve information of the docker client and server host: %s", err)
return err
}
log.Debugf("Provider connection established with docker %s (API %s)", version.Version, version.APIVersion)
var dockerDataList []dockerData
if p.SwarmMode {
@ -908,7 +912,7 @@ func parseTasks(task swarmtypes.Task, serviceDockerData dockerData, networkMap m
NetworkSettings: networkSettings{},
}
if isGlobalSvc == true {
if isGlobalSvc {
dockerData.Name = serviceDockerData.Name + "." + task.ID
}

View File

@ -38,7 +38,7 @@ func TestProvideSingleFileAndWatch(t *testing.T) {
expectedNumFrontends = 1
expectedNumBackends = 1
tempFile = createFile(t,
createFile(t,
tempDir, "simple.toml",
createFrontendConfiguration(expectedNumFrontends),
createBackendConfiguration(expectedNumBackends))
@ -72,7 +72,7 @@ func TestProvideSingleFileAndNotWatch(t *testing.T) {
expectedNumFrontends = 1
expectedNumBackends = 1
tempFile = createFile(t,
createFile(t,
tempDir, "simple.toml",
createFrontendConfiguration(expectedNumFrontends),
createBackendConfiguration(expectedNumBackends))

View File

@ -427,10 +427,7 @@ func shouldProcessIngress(ingressClass string) bool {
}
func (p *Provider) getPassHostHeader() bool {
if p.DisablePassHostHeaders {
return false
}
return true
return !p.DisablePassHostHeaders
}
func (p *Provider) loadConfig(templateObjects types.Configuration) *types.Configuration {

View File

@ -152,7 +152,7 @@ func (p *Provider) loadConfig() *types.Configuration {
}
for key, frontend := range configuration.Frontends {
if _, ok := configuration.Backends[frontend.Backend]; ok == false {
if _, ok := configuration.Backends[frontend.Backend]; !ok {
delete(configuration.Frontends, key)
}
}
@ -231,7 +231,7 @@ func (p *Provider) checkConstraints(keys ...string) bool {
constraintTags := strings.Split(value, ",")
ok, failingConstraint := p.MatchConstraints(constraintTags)
if ok == false {
if !ok {
if failingConstraint != nil {
log.Debugf("Constraint %v not matching with following tags: %v", failingConstraint.String(), value)
}

View File

@ -282,7 +282,7 @@ func TestKvWatchTree(t *testing.T) {
}
select {
case _ = <-configChan:
case <-configChan:
t.Fatalf("configChan should be empty")
default:
}
@ -371,9 +371,7 @@ func (s *Mock) AtomicDelete(key string, previous *store.KVPair) (bool, error) {
}
// Close mock
func (s *Mock) Close() {
return
}
func (s *Mock) Close() {}
func TestKVLoadConfig(t *testing.T) {
provider := &Provider{

View File

@ -189,7 +189,7 @@ func (ep *EntryPoints) String() string {
// Set's argument is a string to be parsed to set the flag.
// It's a comma-separated list, so we split it.
func (ep *EntryPoints) Set(value string) error {
regex := regexp.MustCompile("(?:Name:(?P<Name>\\S*))\\s*(?:Address:(?P<Address>\\S*))?\\s*(?:TLS:(?P<TLS>\\S*))?\\s*((?P<TLSACME>TLS))?\\s*(?:CA:(?P<CA>\\S*))?\\s*(?:Redirect.EntryPoint:(?P<RedirectEntryPoint>\\S*))?\\s*(?:Redirect.Regex:(?P<RedirectRegex>\\S*))?\\s*(?:Redirect.Replacement:(?P<RedirectReplacement>\\S*))?\\s*(?:Compress:(?P<Compress>\\S*))?\\s*(?:WhiteListSourceRange:(?P<WhiteListSourceRange>\\S*))?")
regex := regexp.MustCompile(`(?:Name:(?P<Name>\S*))\s*(?:Address:(?P<Address>\S*))?\s*(?:TLS:(?P<TLS>\S*))?\s*((?P<TLSACME>TLS))?\s*(?:CA:(?P<CA>\S*))?\s*(?:Redirect.EntryPoint:(?P<RedirectEntryPoint>\S*))?\s*(?:Redirect.Regex:(?P<RedirectRegex>\\S*))?\s*(?:Redirect.Replacement:(?P<RedirectReplacement>\S*))?\s*(?:Compress:(?P<Compress>\S*))?\s*(?:WhiteListSourceRange:(?P<WhiteListSourceRange>\S*))?`)
match := regex.FindAllStringSubmatch(value, -1)
if match == nil {
return fmt.Errorf("bad EntryPoints format: %s", value)

View File

@ -947,7 +947,7 @@ func (server *Server) loadEntryPointConfig(entryPointName string, entryPoint *En
regex := entryPoint.Redirect.Regex
replacement := entryPoint.Redirect.Replacement
if len(entryPoint.Redirect.EntryPoint) > 0 {
regex = "^(?:https?:\\/\\/)?([\\w\\._-]+)(?::\\d+)?(.*)$"
regex = `^(?:https?:\/\/)?([\w\._-]+)(?::\d+)?(.*)$`
if server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint] == nil {
return nil, errors.New("Unknown entrypoint " + entryPoint.Redirect.EntryPoint)
}
@ -955,7 +955,7 @@ func (server *Server) loadEntryPointConfig(entryPointName string, entryPoint *En
if server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint].TLS != nil {
protocol = "https"
}
r, _ := regexp.Compile("(:\\d+)")
r, _ := regexp.Compile(`(:\d+)`)
match := r.FindStringSubmatch(server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint].Address)
if len(match) == 0 {
return nil, errors.New("Bad Address format: " + server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint].Address)

View File

@ -277,7 +277,7 @@ func (cs *Constraints) SetValue(val interface{}) {
// Type exports the Constraints type as a string
func (cs *Constraints) Type() string {
return fmt.Sprint("constraint")
return "constraint"
}
// Store holds KV store cluster config