1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Merge pull request #34790 from dnephin/add-ineffassign-linter

Add ineffassign linter
This commit is contained in:
Yong Tang 2017-09-09 15:41:55 -07:00 committed by GitHub
commit 13fec06073
18 changed files with 122 additions and 209 deletions

View file

@ -9,6 +9,7 @@ import (
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/builder/dockerfile/parser"
"github.com/docker/docker/builder/remotecontext"
"github.com/docker/docker/internal/testutil"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/reexec"
)
@ -197,14 +198,6 @@ func executeTestCase(t *testing.T, testCase dispatchTestCase) {
shlex: shlex,
source: context,
}
state, err = b.dispatch(opts)
if err == nil {
t.Fatalf("No error when executing test %s", testCase.name)
}
if !strings.Contains(err.Error(), testCase.expectedError) {
t.Fatalf("Wrong error message. Should be \"%s\". Got \"%s\"", testCase.expectedError, err.Error())
}
_, err = b.dispatch(opts)
testutil.ErrorContains(t, err, testCase.expectedError)
}

View file

@ -149,15 +149,12 @@ func (cs *CachableSource) normalize(path string) (cleanpath, fullpath string, er
// Hash returns a hash for a single file in the source
func (cs *CachableSource) Hash(path string) (string, error) {
n := cs.getRoot()
sum := ""
// TODO: check this for symlinks
v, ok := n.Get([]byte(path))
if !ok {
sum = path
} else {
sum = v.(*fileInfo).sum
return path, nil
}
return sum, nil
return v.(*fileInfo).sum, nil
}
// Root returns a root directory for the source

View file

@ -88,13 +88,12 @@ func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec,
func imageDigestAndPlatforms(ctx context.Context, cli DistributionAPIClient, image, encodedAuth string) (string, []swarm.Platform, error) {
distributionInspect, err := cli.DistributionInspect(ctx, image, encodedAuth)
imageWithDigest := image
var platforms []swarm.Platform
if err != nil {
return "", nil, err
}
imageWithDigest = imageWithDigestString(image, distributionInspect.Descriptor.Digest)
imageWithDigest := imageWithDigestString(image, distributionInspect.Descriptor.Digest)
if len(distributionInspect.Platforms) > 0 {
platforms = make([]swarm.Platform, 0, len(distributionInspect.Platforms))
@ -105,12 +104,12 @@ func imageDigestAndPlatforms(ctx context.Context, cli DistributionAPIClient, ima
// something like "armv7l" (includes the variant), which causes arm images
// to stop working with swarm mode. This patch removes the architecture
// constraint for arm images to ensure tasks get scheduled.
arch := strings.ToLower(p.Architecture)
if arch == "arm" {
arch := p.Architecture
if strings.ToLower(arch) == "arm" {
arch = ""
}
platforms = append(platforms, swarm.Platform{
Architecture: p.Architecture,
Architecture: arch,
OS: p.OS,
})
}

View file

@ -17,6 +17,7 @@ import (
"github.com/docker/docker/volume/drivers"
"github.com/docker/docker/volume/local"
"github.com/docker/docker/volume/store"
"github.com/stretchr/testify/require"
)
type fakeContainerGetter struct {
@ -289,13 +290,12 @@ func TestMigratePre17Volumes(t *testing.T) {
containerRoot := filepath.Join(rootDir, "containers")
cid := "1234"
err = os.MkdirAll(filepath.Join(containerRoot, cid), 0755)
require.NoError(t, err)
vid := "5678"
vfsPath := filepath.Join(rootDir, "vfs", "dir", vid)
err = os.MkdirAll(vfsPath, 0755)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
config := []byte(`
{

View file

@ -4,92 +4,77 @@ import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDiscoveryOptsErrors(t *testing.T) {
var testcases = []struct {
doc string
opts map[string]string
}{
{
doc: "discovery.ttl < discovery.heartbeat",
opts: map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "5"},
},
{
doc: "discovery.ttl == discovery.heartbeat",
opts: map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "10"},
},
{
doc: "negative discovery.heartbeat",
opts: map[string]string{"discovery.heartbeat": "-10", "discovery.ttl": "10"},
},
{
doc: "negative discovery.ttl",
opts: map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "-10"},
},
{
doc: "invalid discovery.heartbeat",
opts: map[string]string{"discovery.heartbeat": "invalid"},
},
{
doc: "invalid discovery.ttl",
opts: map[string]string{"discovery.ttl": "invalid"},
},
}
for _, testcase := range testcases {
_, _, err := discoveryOpts(testcase.opts)
assert.Error(t, err, testcase.doc)
}
}
func TestDiscoveryOpts(t *testing.T) {
clusterOpts := map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "5"}
clusterOpts := map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "20"}
heartbeat, ttl, err := discoveryOpts(clusterOpts)
if err == nil {
t.Fatal("discovery.ttl < discovery.heartbeat must fail")
}
clusterOpts = map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "10"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err == nil {
t.Fatal("discovery.ttl == discovery.heartbeat must fail")
}
clusterOpts = map[string]string{"discovery.heartbeat": "-10", "discovery.ttl": "10"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err == nil {
t.Fatal("negative discovery.heartbeat must fail")
}
clusterOpts = map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "-10"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err == nil {
t.Fatal("negative discovery.ttl must fail")
}
clusterOpts = map[string]string{"discovery.heartbeat": "invalid"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err == nil {
t.Fatal("invalid discovery.heartbeat must fail")
}
clusterOpts = map[string]string{"discovery.ttl": "invalid"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err == nil {
t.Fatal("invalid discovery.ttl must fail")
}
clusterOpts = map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "20"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err != nil {
t.Fatal(err)
}
if heartbeat != 10*time.Second {
t.Fatalf("Heartbeat - Expected : %v, Actual : %v", 10*time.Second, heartbeat)
}
if ttl != 20*time.Second {
t.Fatalf("TTL - Expected : %v, Actual : %v", 20*time.Second, ttl)
}
require.NoError(t, err)
assert.Equal(t, 10*time.Second, heartbeat)
assert.Equal(t, 20*time.Second, ttl)
clusterOpts = map[string]string{"discovery.heartbeat": "10"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err != nil {
t.Fatal(err)
}
if heartbeat != 10*time.Second {
t.Fatalf("Heartbeat - Expected : %v, Actual : %v", 10*time.Second, heartbeat)
}
expected := 10 * defaultDiscoveryTTLFactor * time.Second
if ttl != expected {
t.Fatalf("TTL - Expected : %v, Actual : %v", expected, ttl)
}
require.NoError(t, err)
assert.Equal(t, 10*time.Second, heartbeat)
assert.Equal(t, 10*defaultDiscoveryTTLFactor*time.Second, ttl)
clusterOpts = map[string]string{"discovery.ttl": "30"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if ttl != 30*time.Second {
t.Fatalf("TTL - Expected : %v, Actual : %v", 30*time.Second, ttl)
}
expected = 30 * time.Second / defaultDiscoveryTTLFactor
expected := 30 * time.Second / defaultDiscoveryTTLFactor
if heartbeat != expected {
t.Fatalf("Heartbeat - Expected : %v, Actual : %v", expected, heartbeat)
}
discoveryTTL := fmt.Sprintf("%d", defaultDiscoveryTTLFactor-1)
clusterOpts = map[string]string{"discovery.ttl": discoveryTTL}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
heartbeat, _, err = discoveryOpts(clusterOpts)
if err == nil && heartbeat == 0 {
t.Fatal("discovery.heartbeat must be positive")
}

View file

@ -1,21 +1,15 @@
package distribution
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"runtime"
"strings"
"testing"
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types"
registrytypes "github.com/docker/docker/api/types/registry"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/registry"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
@ -42,12 +36,6 @@ func (h *tokenPassThruHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
}
func testTokenPassThru(t *testing.T, ts *httptest.Server) {
tmp, err := testDirectory("")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
uri, err := url.Parse(ts.URL)
if err != nil {
t.Fatalf("could not parse url from test server: %v", err)
@ -137,36 +125,3 @@ func TestTokenPassThruDifferentHost(t *testing.T) {
t.Fatal("Redirect should not forward Authorization header to another host")
}
}
// testDirectory creates a new temporary directory and returns its path.
// The contents of directory at path `templateDir` is copied into the
// new directory.
func testDirectory(templateDir string) (dir string, err error) {
testID := stringid.GenerateNonCryptoID()[:4]
prefix := fmt.Sprintf("docker-test%s-%s-", testID, getCallerName(2))
if prefix == "" {
prefix = "docker-test-"
}
dir, err = ioutil.TempDir("", prefix)
if err = os.Remove(dir); err != nil {
return
}
if templateDir != "" {
if err = archive.NewDefaultArchiver().CopyWithTar(templateDir, dir); err != nil {
return
}
}
return
}
// getCallerName introspects the call stack and returns the name of the
// function `depth` levels down in the stack.
func getCallerName(depth int) string {
// Use the caller function name as a prefix.
// This helps trace temp directories back to their test.
pc, _, _, _ := runtime.Caller(depth + 1)
callerLongName := runtime.FuncForPC(pc).Name()
parts := strings.Split(callerLongName, ".")
callerShortName := parts[len(parts)-1]
return callerShortName
}

View file

@ -10,4 +10,4 @@ LIBNETWORK_COMMIT=7b2b1feb1de4817d522cc372af149ff48d25028e
VNDR_COMMIT=9909bb2b8a0b7ea464527b376dc50389c90df587
# Linting
GOMETALINTER_COMMIT=f7b6e55301c9c67035003b7ba7f8a1cde532d338
GOMETALINTER_COMMIT=5507b26af3204e949ffe50ec08ee73e5847938e1

View file

@ -1,6 +1,7 @@
{
"Vendor": true,
"Deadline": "2m",
"EnableGC": true,
"Sort": ["linter", "severity", "path"],
"Exclude": [
".*\\.pb\\.go",
@ -17,6 +18,7 @@
"gofmt",
"goimports",
"golint",
"ineffassign",
"interfacer",
"unconvert",
"vet"

View file

@ -41,10 +41,10 @@ func TestRestore(t *testing.T) {
assert.Equal(t, "abc", img1.Comment)
assert.Equal(t, "def", img2.Comment)
p, err := is.GetParent(ID(id1))
_, err = is.GetParent(ID(id1))
testutil.ErrorContains(t, err, "failed to read metadata")
p, err = is.GetParent(ID(id2))
p, err := is.GetParent(ID(id2))
assert.NoError(t, err)
assert.Equal(t, ID(id1), p)

View file

@ -1183,8 +1183,10 @@ func TestUntarInvalidSymlink(t *testing.T) {
func TestTempArchiveCloseMultipleTimes(t *testing.T) {
reader := ioutil.NopCloser(strings.NewReader("hello"))
tempArchive, err := NewTempArchive(reader, "")
require.NoError(t, err)
buf := make([]byte, 10)
n, err := tempArchive.Read(buf)
require.NoError(t, err)
if n != 5 {
t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
}

View file

@ -188,6 +188,7 @@ func TestChangesWithChangesGH13590(t *testing.T) {
t.Skip("symlinks on Windows")
}
baseLayer, err := ioutil.TempDir("", "docker-changes-test.")
require.NoError(t, err)
defer os.RemoveAll(baseLayer)
dir3 := path.Join(baseLayer, "dir1/dir2/dir3")
@ -197,6 +198,7 @@ func TestChangesWithChangesGH13590(t *testing.T) {
ioutil.WriteFile(file, []byte("hello"), 0666)
layer, err := ioutil.TempDir("", "docker-changes-test2.")
require.NoError(t, err)
defer os.RemoveAll(layer)
// Test creating a new file
@ -219,6 +221,7 @@ func TestChangesWithChangesGH13590(t *testing.T) {
// Now test changing a file
layer, err = ioutil.TempDir("", "docker-changes-test3.")
require.NoError(t, err)
defer os.RemoveAll(layer)
if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil {
@ -465,6 +468,7 @@ func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) {
func TestChangesSize(t *testing.T) {
parentPath, err := ioutil.TempDir("", "docker-changes-test")
require.NoError(t, err)
defer os.RemoveAll(parentPath)
addition := path.Join(parentPath, "addition")
err = ioutil.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744)

View file

@ -10,6 +10,8 @@ import (
"path/filepath"
"reflect"
"testing"
"github.com/stretchr/testify/require"
)
func TestLocalSocket(t *testing.T) {
@ -89,6 +91,7 @@ func TestScan(t *testing.T) {
r := newLocalRegistry()
p, err := r.Plugin(name)
require.NoError(t, err)
pluginNamesNotEmpty, err := Scan()
if err != nil {

View file

@ -7,12 +7,13 @@ import "testing"
// TestCheckSystemDriveAndRemoveDriveLetter tests CheckSystemDriveAndRemoveDriveLetter
func TestCheckSystemDriveAndRemoveDriveLetter(t *testing.T) {
// Fails if not C drive.
path, err := CheckSystemDriveAndRemoveDriveLetter(`d:\`)
_, err := CheckSystemDriveAndRemoveDriveLetter(`d:\`)
if err == nil || (err != nil && err.Error() != "The specified path is not on the system drive (C:)") {
t.Fatalf("Expected error for d:")
}
// Single character is unchanged
var path string
if path, err = CheckSystemDriveAndRemoveDriveLetter("z"); err != nil {
t.Fatalf("Single character should pass")
}

View file

@ -6,6 +6,8 @@ import (
"os"
"syscall"
"testing"
"github.com/stretchr/testify/require"
)
// TestFromStatT tests fromStatT for a tempfile
@ -15,11 +17,10 @@ func TestFromStatT(t *testing.T) {
stat := &syscall.Stat_t{}
err := syscall.Lstat(file, stat)
require.NoError(t, err)
s, err := fromStatT(stat)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if stat.Mode != s.Mode() {
t.Fatal("got invalid mode")

View file

@ -16,6 +16,9 @@ import (
"os"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type testLayer struct {
@ -222,17 +225,13 @@ func TestNewTarSumForLabel(t *testing.T) {
func TestEmptyTar(t *testing.T) {
// Test without gzip.
ts, err := emptyTarSum(false)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
zeroBlock := make([]byte, 1024)
buf := new(bytes.Buffer)
n, err := io.Copy(buf, ts)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
if n != int64(len(zeroBlock)) || !bytes.Equal(buf.Bytes(), zeroBlock) {
t.Fatalf("tarSum did not write the correct number of zeroed bytes: %d", n)
@ -247,19 +246,16 @@ func TestEmptyTar(t *testing.T) {
// Test with gzip.
ts, err = emptyTarSum(true)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
buf.Reset()
n, err = io.Copy(buf, ts)
if err != nil {
t.Fatal(err)
}
_, err = io.Copy(buf, ts)
require.NoError(t, err)
bufgz := new(bytes.Buffer)
gz := gzip.NewWriter(bufgz)
n, err = io.Copy(gz, bytes.NewBuffer(zeroBlock))
require.NoError(t, err)
gz.Close()
gzBytes := bufgz.Bytes()
@ -279,10 +275,7 @@ func TestEmptyTar(t *testing.T) {
}
resultSum = ts.Sum(nil)
if resultSum != expectedSum {
t.Fatalf("expected [%s] but got [%s]", expectedSum, resultSum)
}
assert.Equal(t, expectedSum, resultSum)
}
var (

View file

@ -1,43 +1,25 @@
package term
import "testing"
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestToBytes(t *testing.T) {
codes, err := ToBytes("ctrl-a,a")
if err != nil {
t.Fatal(err)
}
if len(codes) != 2 {
t.Fatalf("Expected 2 codes, got %d", len(codes))
}
if codes[0] != 1 || codes[1] != 97 {
t.Fatalf("Expected '1' '97', got '%d' '%d'", codes[0], codes[1])
}
require.NoError(t, err)
assert.Equal(t, []byte{1, 97}, codes)
codes, err = ToBytes("shift-z")
if err == nil {
t.Fatalf("Expected error, got none")
}
_, err = ToBytes("shift-z")
assert.Error(t, err)
codes, err = ToBytes("ctrl-@,ctrl-[,~,ctrl-o")
if err != nil {
t.Fatal(err)
}
if len(codes) != 4 {
t.Fatalf("Expected 4 codes, got %d", len(codes))
}
if codes[0] != 0 || codes[1] != 27 || codes[2] != 126 || codes[3] != 15 {
t.Fatalf("Expected '0' '27' '126', '15', got '%d' '%d' '%d' '%d'", codes[0], codes[1], codes[2], codes[3])
}
require.NoError(t, err)
assert.Equal(t, []byte{0, 27, 126, 15}, codes)
codes, err = ToBytes("DEL,+")
if err != nil {
t.Fatal(err)
}
if len(codes) != 2 {
t.Fatalf("Expected 2 codes, got %d", len(codes))
}
if codes[0] != 127 || codes[1] != 43 {
t.Fatalf("Expected '127 '43'', got '%d' '%d'", codes[0], codes[1])
}
require.NoError(t, err)
assert.Equal(t, []byte{127, 43}, codes)
}

View file

@ -68,6 +68,7 @@ func TestGetFdInfo(t *testing.T) {
require.Equal(t, inFd, tty.Fd())
require.Equal(t, isTerminal, true)
tmpFile, err := newTempFile()
require.NoError(t, err)
defer tmpFile.Close()
inFd, isTerminal = GetFdInfo(tmpFile)
require.Equal(t, inFd, tmpFile.Fd())
@ -81,6 +82,7 @@ func TestIsTerminal(t *testing.T) {
isTerminal := IsTerminal(tty.Fd())
require.Equal(t, isTerminal, true)
tmpFile, err := newTempFile()
require.NoError(t, err)
defer tmpFile.Close()
isTerminal = IsTerminal(tmpFile.Fd())
require.Equal(t, isTerminal, false)
@ -94,6 +96,7 @@ func TestSaveState(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, state)
tty, err = newTtyForTest(t)
require.NoError(t, err)
defer tty.Close()
err = RestoreTerminal(tty.Fd(), state)
require.NoError(t, err)

View file

@ -9,7 +9,9 @@ import (
"testing"
"github.com/docker/distribution/reference"
"github.com/opencontainers/go-digest"
digest "github.com/opencontainers/go-digest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
@ -62,10 +64,10 @@ func TestLoad(t *testing.T) {
func TestSave(t *testing.T) {
jsonFile, err := ioutil.TempFile("", "tag-store-test")
if err != nil {
t.Fatalf("error creating temp file: %v", err)
}
require.NoError(t, err)
_, err = jsonFile.Write([]byte(`{}`))
require.NoError(t, err)
jsonFile.Close()
defer os.RemoveAll(jsonFile.Name())
@ -326,32 +328,23 @@ func TestAddDeleteGet(t *testing.T) {
func TestInvalidTags(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "tag-store-test")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
store, err := NewReferenceStore(filepath.Join(tmpDir, "repositories.json"))
if err != nil {
t.Fatalf("error creating tag store: %v", err)
}
require.NoError(t, err)
id := digest.Digest("sha256:470022b8af682154f57a2163d030eb369549549cba00edc69e1b99b46bb924d6")
// sha256 as repo name
ref, err := reference.ParseNormalizedNamed("sha256:abc")
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
err = store.AddTag(ref, id, true)
if err == nil {
t.Fatalf("expected setting tag %q to fail", ref)
}
assert.Error(t, err)
// setting digest as a tag
ref, err = reference.ParseNormalizedNamed("registry@sha256:367eb40fd0330a7e464777121e39d2f5b3e8e23a1e159342e53ab05c9e4d94e6")
if err != nil {
t.Fatal(err)
}
err = store.AddTag(ref, id, true)
if err == nil {
t.Fatalf("expected setting tag %q to fail", ref)
}
require.NoError(t, err)
err = store.AddTag(ref, id, true)
assert.Error(t, err)
}