Automated migration using

gty-migrate-from-testify --ignore-build-tags

Signed-off-by: Daniel Nephin <dnephin@docker.com>
This commit is contained in:
Daniel Nephin
2018-03-13 15:28:34 -04:00
parent ef01dea893
commit 6be0f70983
183 changed files with 2253 additions and 2199 deletions

View File

@@ -3,7 +3,8 @@ package middleware // import "github.com/docker/docker/api/server/middleware"
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestMaskSecretKeys(t *testing.T) { func TestMaskSecretKeys(t *testing.T) {
@@ -53,6 +54,6 @@ func TestMaskSecretKeys(t *testing.T) {
for _, testcase := range tests { for _, testcase := range tests {
maskSecretKeys(testcase.input, testcase.path) maskSecretKeys(testcase.input, testcase.path)
assert.Equal(t, testcase.expected, testcase.input) assert.Check(t, is.DeepEqual(testcase.expected, testcase.input))
} }
} }

View File

@@ -7,7 +7,8 @@ import (
"testing" "testing"
"github.com/docker/docker/api/server/httputils" "github.com/docker/docker/api/server/httputils"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -17,7 +18,7 @@ func TestVersionMiddlewareVersion(t *testing.T) {
expectedVersion := defaultVersion expectedVersion := defaultVersion
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
v := httputils.VersionFromContext(ctx) v := httputils.VersionFromContext(ctx)
assert.Equal(t, expectedVersion, v) assert.Check(t, is.Equal(expectedVersion, v))
return nil return nil
} }
@@ -56,9 +57,9 @@ func TestVersionMiddlewareVersion(t *testing.T) {
err := h(ctx, resp, req, map[string]string{"version": test.reqVersion}) err := h(ctx, resp, req, map[string]string{"version": test.reqVersion})
if test.errString != "" { if test.errString != "" {
assert.EqualError(t, err, test.errString) assert.Check(t, is.Error(err, test.errString))
} else { } else {
assert.NoError(t, err) assert.Check(t, err)
} }
} }
} }
@@ -66,7 +67,7 @@ func TestVersionMiddlewareVersion(t *testing.T) {
func TestVersionMiddlewareWithErrorsReturnsHeaders(t *testing.T) { func TestVersionMiddlewareWithErrorsReturnsHeaders(t *testing.T) {
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
v := httputils.VersionFromContext(ctx) v := httputils.VersionFromContext(ctx)
assert.NotEmpty(t, v) assert.Check(t, len(v) != 0)
return nil return nil
} }
@@ -81,11 +82,11 @@ func TestVersionMiddlewareWithErrorsReturnsHeaders(t *testing.T) {
vars := map[string]string{"version": "0.1"} vars := map[string]string{"version": "0.1"}
err := h(ctx, resp, req, vars) err := h(ctx, resp, req, vars)
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
hdr := resp.Result().Header hdr := resp.Result().Header
assert.Contains(t, hdr.Get("Server"), "Docker/"+defaultVersion) assert.Check(t, is.Contains(hdr.Get("Server"), "Docker/"+defaultVersion))
assert.Contains(t, hdr.Get("Server"), runtime.GOOS) assert.Check(t, is.Contains(hdr.Get("Server"), runtime.GOOS))
assert.Equal(t, hdr.Get("API-Version"), defaultVersion) assert.Check(t, is.Equal(hdr.Get("API-Version"), defaultVersion))
assert.Equal(t, hdr.Get("OSType"), runtime.GOOS) assert.Check(t, is.Equal(hdr.Get("OSType"), runtime.GOOS))
} }

View File

@@ -4,8 +4,8 @@ import (
"errors" "errors"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestParseArgs(t *testing.T) { func TestParseArgs(t *testing.T) {
@@ -22,10 +22,10 @@ func TestParseArgs(t *testing.T) {
for i := range flagArgs { for i := range flagArgs {
args, err = ParseFlag(flagArgs[i], args) args, err = ParseFlag(flagArgs[i], args)
require.NoError(t, err) assert.NilError(t, err)
} }
assert.Len(t, args.Get("created"), 1) assert.Check(t, is.Len(args.Get("created"), 1))
assert.Len(t, args.Get("image.name"), 2) assert.Check(t, is.Len(args.Get("image.name"), 2))
} }
func TestParseArgsEdgeCase(t *testing.T) { func TestParseArgsEdgeCase(t *testing.T) {
@@ -231,7 +231,7 @@ func TestArgsMatch(t *testing.T) {
} }
for args, field := range matches { for args, field := range matches {
assert.True(t, args.Match(field, source), assert.Check(t, args.Match(field, source),
"Expected field %s to match %s", field, source) "Expected field %s to match %s", field, source)
} }
@@ -255,8 +255,7 @@ func TestArgsMatch(t *testing.T) {
} }
for args, field := range differs { for args, field := range differs {
assert.False(t, args.Match(field, source), assert.Check(t, !args.Match(field, source), "Expected field %s to not match %s", field, source)
"Expected field %s to not match %s", field, source)
} }
} }

View File

@@ -4,7 +4,8 @@ import (
"bytes" "bytes"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func strPtr(source string) *string { func strPtr(source string) *string {
@@ -39,7 +40,7 @@ func TestGetAllAllowed(t *testing.T) {
"ArgFromMeta": "frommeta1", "ArgFromMeta": "frommeta1",
"ArgFromMetaOverridden": "fromdockerfile3", "ArgFromMetaOverridden": "fromdockerfile3",
} }
assert.Equal(t, expected, all) assert.Check(t, is.DeepEqual(expected, all))
} }
func TestGetAllMeta(t *testing.T) { func TestGetAllMeta(t *testing.T) {
@@ -61,7 +62,7 @@ func TestGetAllMeta(t *testing.T) {
"ArgOverriddenByOptions": "fromopt2", "ArgOverriddenByOptions": "fromopt2",
"ArgNoDefaultInMetaFromOptions": "fromopt3", "ArgNoDefaultInMetaFromOptions": "fromopt3",
} }
assert.Equal(t, expected, all) assert.Check(t, is.DeepEqual(expected, all))
} }
func TestWarnOnUnusedBuildArgs(t *testing.T) { func TestWarnOnUnusedBuildArgs(t *testing.T) {
@@ -80,7 +81,7 @@ func TestWarnOnUnusedBuildArgs(t *testing.T) {
assert.NotContains(t, out, "ThisArgIsUsed") assert.NotContains(t, out, "ThisArgIsUsed")
assert.NotContains(t, out, "HTTPS_PROXY") assert.NotContains(t, out, "HTTPS_PROXY")
assert.NotContains(t, out, "HTTP_PROXY") assert.NotContains(t, out, "HTTP_PROXY")
assert.Contains(t, out, "ThisArgIsNotUsed") assert.Check(t, is.Contains(out, "ThisArgIsNotUsed"))
} }
func TestIsUnreferencedBuiltin(t *testing.T) { func TestIsUnreferencedBuiltin(t *testing.T) {
@@ -93,8 +94,8 @@ func TestIsUnreferencedBuiltin(t *testing.T) {
buildArgs.AddArg("ThisArgIsUsed", nil) buildArgs.AddArg("ThisArgIsUsed", nil)
buildArgs.AddArg("HTTPS_PROXY", nil) buildArgs.AddArg("HTTPS_PROXY", nil)
assert.True(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsUsed")) assert.Check(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsUsed"))
assert.True(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsNotUsed")) assert.Check(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsNotUsed"))
assert.True(t, buildArgs.IsReferencedOrNotBuiltin("HTTPS_PROXY")) assert.Check(t, buildArgs.IsReferencedOrNotBuiltin("HTTPS_PROXY"))
assert.False(t, buildArgs.IsReferencedOrNotBuiltin("HTTP_PROXY")) assert.Check(t, !buildArgs.IsReferencedOrNotBuiltin("HTTP_PROXY"))
} }

View File

@@ -5,13 +5,14 @@ import (
"testing" "testing"
"github.com/docker/docker/builder/dockerfile/parser" "github.com/docker/docker/builder/dockerfile/parser"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestAddNodesForLabelOption(t *testing.T) { func TestAddNodesForLabelOption(t *testing.T) {
dockerfile := "FROM scratch" dockerfile := "FROM scratch"
result, err := parser.Parse(strings.NewReader(dockerfile)) result, err := parser.Parse(strings.NewReader(dockerfile))
assert.NoError(t, err) assert.Check(t, err)
labels := map[string]string{ labels := map[string]string{
"org.e": "cli-e", "org.e": "cli-e",
@@ -27,8 +28,8 @@ func TestAddNodesForLabelOption(t *testing.T) {
"FROM scratch", "FROM scratch",
`LABEL "org.a"='cli-a' "org.b"='cli-b' "org.c"='cli-c' "org.d"='cli-d' "org.e"='cli-e'`, `LABEL "org.a"='cli-a' "org.b"='cli-b' "org.c"='cli-c' "org.d"='cli-d' "org.e"='cli-e'`,
} }
assert.Len(t, nodes.Children, 2) assert.Check(t, is.Len(nodes.Children, 2))
for i, v := range nodes.Children { for i, v := range nodes.Children {
assert.Equal(t, expected[i], v.Original) assert.Check(t, is.Equal(expected[i], v.Original))
} }
} }

View File

@@ -5,8 +5,9 @@ import (
"testing" "testing"
"github.com/docker/docker/pkg/containerfs" "github.com/docker/docker/pkg/containerfs"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
) )
func TestIsExistingDirectory(t *testing.T) { func TestIsExistingDirectory(t *testing.T) {
@@ -39,10 +40,10 @@ func TestIsExistingDirectory(t *testing.T) {
for _, testcase := range testcases { for _, testcase := range testcases {
result, err := isExistingDirectory(&copyEndpoint{driver: containerfs.NewLocalDriver(), path: testcase.path}) result, err := isExistingDirectory(&copyEndpoint{driver: containerfs.NewLocalDriver(), path: testcase.path})
if !assert.NoError(t, err) { if !assert.Check(t, err) {
continue continue
} }
assert.Equal(t, testcase.expected, result, testcase.doc) assert.Check(t, is.Equal(testcase.expected, result), testcase.doc)
} }
} }
@@ -142,6 +143,6 @@ func TestGetFilenameForDownload(t *testing.T) {
resp.Header.Add("Content-Disposition", testcase.disposition) resp.Header.Add("Content-Disposition", testcase.disposition)
} }
filename := getFilenameForDownload(testcase.path, &resp) filename := getFilenameForDownload(testcase.path, &resp)
assert.Equal(t, testcase.expected, filename) assert.Check(t, is.Equal(testcase.expected, filename))
} }
} }

View File

@@ -16,8 +16,8 @@ import (
"github.com/docker/docker/image" "github.com/docker/docker/image"
"github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/system"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func newBuilderWithMockBackend() *Builder { func newBuilderWithMockBackend() *Builder {
@@ -49,13 +49,13 @@ func TestEnv2Variables(t *testing.T) {
}, },
} }
err := dispatch(sb, envCommand) err := dispatch(sb, envCommand)
require.NoError(t, err) assert.NilError(t, err)
expected := []string{ expected := []string{
"var1=val1", "var1=val1",
"var2=val2", "var2=val2",
} }
assert.Equal(t, expected, sb.state.runConfig.Env) assert.Check(t, is.DeepEqual(expected, sb.state.runConfig.Env))
} }
func TestEnvValueWithExistingRunConfigEnv(t *testing.T) { func TestEnvValueWithExistingRunConfigEnv(t *testing.T) {
@@ -68,12 +68,12 @@ func TestEnvValueWithExistingRunConfigEnv(t *testing.T) {
}, },
} }
err := dispatch(sb, envCommand) err := dispatch(sb, envCommand)
require.NoError(t, err) assert.NilError(t, err)
expected := []string{ expected := []string{
"var1=val1", "var1=val1",
"var2=fromenv", "var2=fromenv",
} }
assert.Equal(t, expected, sb.state.runConfig.Env) assert.Check(t, is.DeepEqual(expected, sb.state.runConfig.Env))
} }
func TestMaintainer(t *testing.T) { func TestMaintainer(t *testing.T) {
@@ -82,8 +82,8 @@ func TestMaintainer(t *testing.T) {
sb := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults()) sb := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults())
cmd := &instructions.MaintainerCommand{Maintainer: maintainerEntry} cmd := &instructions.MaintainerCommand{Maintainer: maintainerEntry}
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, maintainerEntry, sb.state.maintainer) assert.Check(t, is.Equal(maintainerEntry, sb.state.maintainer))
} }
func TestLabel(t *testing.T) { func TestLabel(t *testing.T) {
@@ -98,10 +98,10 @@ func TestLabel(t *testing.T) {
}, },
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
require.Contains(t, sb.state.runConfig.Labels, labelName) assert.Assert(t, is.Contains(sb.state.runConfig.Labels, labelName))
assert.Equal(t, sb.state.runConfig.Labels[labelName], labelValue) assert.Check(t, is.Equal(sb.state.runConfig.Labels[labelName], labelValue))
} }
func TestFromScratch(t *testing.T) { func TestFromScratch(t *testing.T) {
@@ -113,22 +113,22 @@ func TestFromScratch(t *testing.T) {
err := initializeStage(sb, cmd) err := initializeStage(sb, cmd)
if runtime.GOOS == "windows" && !system.LCOWSupported() { if runtime.GOOS == "windows" && !system.LCOWSupported() {
assert.EqualError(t, err, "Windows does not support FROM scratch") assert.Check(t, is.Error(err, "Windows does not support FROM scratch"))
return return
} }
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, sb.state.hasFromImage()) assert.Check(t, sb.state.hasFromImage())
assert.Equal(t, "", sb.state.imageID) assert.Check(t, is.Equal("", sb.state.imageID))
expected := "PATH=" + system.DefaultPathEnv(runtime.GOOS) expected := "PATH=" + system.DefaultPathEnv(runtime.GOOS)
assert.Equal(t, []string{expected}, sb.state.runConfig.Env) assert.Check(t, is.DeepEqual([]string{expected}, sb.state.runConfig.Env))
} }
func TestFromWithArg(t *testing.T) { func TestFromWithArg(t *testing.T) {
tag, expected := ":sometag", "expectedthisid" tag, expected := ":sometag", "expectedthisid"
getImage := func(name string) (builder.Image, builder.ROLayer, error) { getImage := func(name string) (builder.Image, builder.ROLayer, error) {
assert.Equal(t, "alpine"+tag, name) assert.Check(t, is.Equal("alpine"+tag, name))
return &mockImage{id: "expectedthisid"}, nil, nil return &mockImage{id: "expectedthisid"}, nil, nil
} }
b := newBuilderWithMockBackend() b := newBuilderWithMockBackend()
@@ -146,21 +146,21 @@ func TestFromWithArg(t *testing.T) {
err := processMetaArg(metaArg, shell.NewLex('\\'), args) err := processMetaArg(metaArg, shell.NewLex('\\'), args)
sb := newDispatchRequest(b, '\\', nil, args, newStagesBuildResults()) sb := newDispatchRequest(b, '\\', nil, args, newStagesBuildResults())
require.NoError(t, err) assert.NilError(t, err)
err = initializeStage(sb, cmd) err = initializeStage(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, expected, sb.state.imageID) assert.Check(t, is.Equal(expected, sb.state.imageID))
assert.Equal(t, expected, sb.state.baseImage.ImageID()) assert.Check(t, is.Equal(expected, sb.state.baseImage.ImageID()))
assert.Len(t, sb.state.buildArgs.GetAllAllowed(), 0) assert.Check(t, is.Len(sb.state.buildArgs.GetAllAllowed(), 0))
assert.Len(t, sb.state.buildArgs.GetAllMeta(), 1) assert.Check(t, is.Len(sb.state.buildArgs.GetAllMeta(), 1))
} }
func TestFromWithUndefinedArg(t *testing.T) { func TestFromWithUndefinedArg(t *testing.T) {
tag, expected := "sometag", "expectedthisid" tag, expected := "sometag", "expectedthisid"
getImage := func(name string) (builder.Image, builder.ROLayer, error) { getImage := func(name string) (builder.Image, builder.ROLayer, error) {
assert.Equal(t, "alpine", name) assert.Check(t, is.Equal("alpine", name))
return &mockImage{id: "expectedthisid"}, nil, nil return &mockImage{id: "expectedthisid"}, nil, nil
} }
b := newBuilderWithMockBackend() b := newBuilderWithMockBackend()
@@ -173,8 +173,8 @@ func TestFromWithUndefinedArg(t *testing.T) {
BaseName: "alpine${THETAG}", BaseName: "alpine${THETAG}",
} }
err := initializeStage(sb, cmd) err := initializeStage(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, expected, sb.state.imageID) assert.Check(t, is.Equal(expected, sb.state.imageID))
} }
func TestFromMultiStageWithNamedStage(t *testing.T) { func TestFromMultiStageWithNamedStage(t *testing.T) {
@@ -185,13 +185,13 @@ func TestFromMultiStageWithNamedStage(t *testing.T) {
firstSB := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), previousResults) firstSB := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), previousResults)
secondSB := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), previousResults) secondSB := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), previousResults)
err := initializeStage(firstSB, firstFrom) err := initializeStage(firstSB, firstFrom)
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, firstSB.state.hasFromImage()) assert.Check(t, firstSB.state.hasFromImage())
previousResults.indexed["base"] = firstSB.state.runConfig previousResults.indexed["base"] = firstSB.state.runConfig
previousResults.flat = append(previousResults.flat, firstSB.state.runConfig) previousResults.flat = append(previousResults.flat, firstSB.state.runConfig)
err = initializeStage(secondSB, secondFrom) err = initializeStage(secondSB, secondFrom)
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, secondSB.state.hasFromImage()) assert.Check(t, secondSB.state.hasFromImage())
} }
func TestOnbuild(t *testing.T) { func TestOnbuild(t *testing.T) {
@@ -201,8 +201,8 @@ func TestOnbuild(t *testing.T) {
Expression: "ADD . /app/src", Expression: "ADD . /app/src",
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "ADD . /app/src", sb.state.runConfig.OnBuild[0]) assert.Check(t, is.Equal("ADD . /app/src", sb.state.runConfig.OnBuild[0]))
} }
func TestWorkdir(t *testing.T) { func TestWorkdir(t *testing.T) {
@@ -217,8 +217,8 @@ func TestWorkdir(t *testing.T) {
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, workingDir, sb.state.runConfig.WorkingDir) assert.Check(t, is.Equal(workingDir, sb.state.runConfig.WorkingDir))
} }
func TestCmd(t *testing.T) { func TestCmd(t *testing.T) {
@@ -233,7 +233,7 @@ func TestCmd(t *testing.T) {
}, },
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
var expectedCommand strslice.StrSlice var expectedCommand strslice.StrSlice
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
@@ -242,8 +242,8 @@ func TestCmd(t *testing.T) {
expectedCommand = strslice.StrSlice(append([]string{"/bin/sh"}, "-c", command)) expectedCommand = strslice.StrSlice(append([]string{"/bin/sh"}, "-c", command))
} }
assert.Equal(t, expectedCommand, sb.state.runConfig.Cmd) assert.Check(t, is.DeepEqual(expectedCommand, sb.state.runConfig.Cmd))
assert.True(t, sb.state.cmdSet) assert.Check(t, sb.state.cmdSet)
} }
func TestHealthcheckNone(t *testing.T) { func TestHealthcheckNone(t *testing.T) {
@@ -255,10 +255,10 @@ func TestHealthcheckNone(t *testing.T) {
}, },
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.Healthcheck) assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
assert.Equal(t, []string{"NONE"}, sb.state.runConfig.Healthcheck.Test) assert.Check(t, is.DeepEqual([]string{"NONE"}, sb.state.runConfig.Healthcheck.Test))
} }
func TestHealthcheckCmd(t *testing.T) { func TestHealthcheckCmd(t *testing.T) {
@@ -272,10 +272,10 @@ func TestHealthcheckCmd(t *testing.T) {
}, },
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.Healthcheck) assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
assert.Equal(t, expectedTest, sb.state.runConfig.Healthcheck.Test) assert.Check(t, is.DeepEqual(expectedTest, sb.state.runConfig.Healthcheck.Test))
} }
func TestEntrypoint(t *testing.T) { func TestEntrypoint(t *testing.T) {
@@ -290,8 +290,8 @@ func TestEntrypoint(t *testing.T) {
}, },
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.Entrypoint) assert.Assert(t, sb.state.runConfig.Entrypoint != nil)
var expectedEntrypoint strslice.StrSlice var expectedEntrypoint strslice.StrSlice
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
@@ -299,7 +299,7 @@ func TestEntrypoint(t *testing.T) {
} else { } else {
expectedEntrypoint = strslice.StrSlice(append([]string{"/bin/sh"}, "-c", entrypointCmd)) expectedEntrypoint = strslice.StrSlice(append([]string{"/bin/sh"}, "-c", entrypointCmd))
} }
assert.Equal(t, expectedEntrypoint, sb.state.runConfig.Entrypoint) assert.Check(t, is.DeepEqual(expectedEntrypoint, sb.state.runConfig.Entrypoint))
} }
func TestExpose(t *testing.T) { func TestExpose(t *testing.T) {
@@ -311,14 +311,14 @@ func TestExpose(t *testing.T) {
Ports: []string{exposedPort}, Ports: []string{exposedPort},
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.ExposedPorts) assert.Assert(t, sb.state.runConfig.ExposedPorts != nil)
require.Len(t, sb.state.runConfig.ExposedPorts, 1) assert.Assert(t, is.Len(sb.state.runConfig.ExposedPorts, 1))
portsMapping, err := nat.ParsePortSpec(exposedPort) portsMapping, err := nat.ParsePortSpec(exposedPort)
require.NoError(t, err) assert.NilError(t, err)
assert.Contains(t, sb.state.runConfig.ExposedPorts, portsMapping[0].Port) assert.Check(t, is.Contains(sb.state.runConfig.ExposedPorts, portsMapping[0].Port))
} }
func TestUser(t *testing.T) { func TestUser(t *testing.T) {
@@ -329,8 +329,8 @@ func TestUser(t *testing.T) {
User: "test", User: "test",
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "test", sb.state.runConfig.User) assert.Check(t, is.Equal("test", sb.state.runConfig.User))
} }
func TestVolume(t *testing.T) { func TestVolume(t *testing.T) {
@@ -343,10 +343,10 @@ func TestVolume(t *testing.T) {
Volumes: []string{exposedVolume}, Volumes: []string{exposedVolume},
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.Volumes) assert.Assert(t, sb.state.runConfig.Volumes != nil)
assert.Len(t, sb.state.runConfig.Volumes, 1) assert.Check(t, is.Len(sb.state.runConfig.Volumes, 1))
assert.Contains(t, sb.state.runConfig.Volumes, exposedVolume) assert.Check(t, is.Contains(sb.state.runConfig.Volumes, exposedVolume))
} }
func TestStopSignal(t *testing.T) { func TestStopSignal(t *testing.T) {
@@ -362,8 +362,8 @@ func TestStopSignal(t *testing.T) {
Signal: signal, Signal: signal,
} }
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, signal, sb.state.runConfig.StopSignal) assert.Check(t, is.Equal(signal, sb.state.runConfig.StopSignal))
} }
func TestArg(t *testing.T) { func TestArg(t *testing.T) {
@@ -374,10 +374,10 @@ func TestArg(t *testing.T) {
argVal := "bar" argVal := "bar"
cmd := &instructions.ArgCommand{Key: argName, Value: &argVal} cmd := &instructions.ArgCommand{Key: argName, Value: &argVal}
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
expected := map[string]string{argName: argVal} expected := map[string]string{argName: argVal}
assert.Equal(t, expected, sb.state.buildArgs.GetAllAllowed()) assert.Check(t, is.DeepEqual(expected, sb.state.buildArgs.GetAllAllowed()))
} }
func TestShell(t *testing.T) { func TestShell(t *testing.T) {
@@ -388,10 +388,10 @@ func TestShell(t *testing.T) {
cmd := &instructions.ShellCommand{Shell: strslice.StrSlice{shellCmd}} cmd := &instructions.ShellCommand{Shell: strslice.StrSlice{shellCmd}}
err := dispatch(sb, cmd) err := dispatch(sb, cmd)
require.NoError(t, err) assert.NilError(t, err)
expectedShell := strslice.StrSlice([]string{shellCmd}) expectedShell := strslice.StrSlice([]string{shellCmd})
assert.Equal(t, expectedShell, sb.state.runConfig.Shell) assert.Check(t, is.DeepEqual(expectedShell, sb.state.runConfig.Shell))
} }
func TestPrependEnvOnCmd(t *testing.T) { func TestPrependEnvOnCmd(t *testing.T) {
@@ -403,7 +403,7 @@ func TestPrependEnvOnCmd(t *testing.T) {
cmdWithEnv := prependEnvOnCmd(buildArgs, args, cmd) cmdWithEnv := prependEnvOnCmd(buildArgs, args, cmd)
expected := strslice.StrSlice([]string{ expected := strslice.StrSlice([]string{
"|3", "NO_PROXY=YA", "args=not", "sorted=nope", "foo", "bar"}) "|3", "NO_PROXY=YA", "args=not", "sorted=nope", "foo", "bar"})
assert.Equal(t, expected, cmdWithEnv) assert.Check(t, is.DeepEqual(expected, cmdWithEnv))
} }
func TestRunWithBuildArgs(t *testing.T) { func TestRunWithBuildArgs(t *testing.T) {
@@ -422,8 +422,8 @@ func TestRunWithBuildArgs(t *testing.T) {
imageCache := &mockImageCache{ imageCache := &mockImageCache{
getCacheFunc: func(parentID string, cfg *container.Config) (string, error) { getCacheFunc: func(parentID string, cfg *container.Config) (string, error) {
// Check the runConfig.Cmd sent to probeCache() // Check the runConfig.Cmd sent to probeCache()
assert.Equal(t, cachedCmd, cfg.Cmd) assert.Check(t, is.DeepEqual(cachedCmd, cfg.Cmd))
assert.Equal(t, strslice.StrSlice(nil), cfg.Entrypoint) assert.Check(t, is.DeepEqual(strslice.StrSlice(nil), cfg.Entrypoint))
return "", nil return "", nil
}, },
} }
@@ -441,21 +441,21 @@ func TestRunWithBuildArgs(t *testing.T) {
} }
mockBackend.containerCreateFunc = func(config types.ContainerCreateConfig) (container.ContainerCreateCreatedBody, error) { mockBackend.containerCreateFunc = func(config types.ContainerCreateConfig) (container.ContainerCreateCreatedBody, error) {
// Check the runConfig.Cmd sent to create() // Check the runConfig.Cmd sent to create()
assert.Equal(t, cmdWithShell, config.Config.Cmd) assert.Check(t, is.DeepEqual(cmdWithShell, config.Config.Cmd))
assert.Contains(t, config.Config.Env, "one=two") assert.Check(t, is.Contains(config.Config.Env, "one=two"))
assert.Equal(t, strslice.StrSlice{""}, config.Config.Entrypoint) assert.Check(t, is.DeepEqual(strslice.StrSlice{""}, config.Config.Entrypoint))
return container.ContainerCreateCreatedBody{ID: "12345"}, nil return container.ContainerCreateCreatedBody{ID: "12345"}, nil
} }
mockBackend.commitFunc = func(cfg backend.CommitConfig) (image.ID, error) { mockBackend.commitFunc = func(cfg backend.CommitConfig) (image.ID, error) {
// Check the runConfig.Cmd sent to commit() // Check the runConfig.Cmd sent to commit()
assert.Equal(t, origCmd, cfg.Config.Cmd) assert.Check(t, is.DeepEqual(origCmd, cfg.Config.Cmd))
assert.Equal(t, cachedCmd, cfg.ContainerConfig.Cmd) assert.Check(t, is.DeepEqual(cachedCmd, cfg.ContainerConfig.Cmd))
assert.Equal(t, strslice.StrSlice(nil), cfg.Config.Entrypoint) assert.Check(t, is.DeepEqual(strslice.StrSlice(nil), cfg.Config.Entrypoint))
return "", nil return "", nil
} }
from := &instructions.Stage{BaseName: "abcdef"} from := &instructions.Stage{BaseName: "abcdef"}
err := initializeStage(sb, from) err := initializeStage(sb, from)
require.NoError(t, err) assert.NilError(t, err)
sb.state.buildArgs.AddArg("one", strPtr("two")) sb.state.buildArgs.AddArg("one", strPtr("two"))
run := &instructions.RunCommand{ run := &instructions.RunCommand{
ShellDependantCmdLine: instructions.ShellDependantCmdLine{ ShellDependantCmdLine: instructions.ShellDependantCmdLine{
@@ -463,8 +463,8 @@ func TestRunWithBuildArgs(t *testing.T) {
PrependShell: true, PrependShell: true,
}, },
} }
require.NoError(t, dispatch(sb, run)) assert.NilError(t, dispatch(sb, run))
// Check that runConfig.Cmd has not been modified by run // Check that runConfig.Cmd has not been modified by run
assert.Equal(t, origCmd, sb.state.runConfig.Cmd) assert.Check(t, is.DeepEqual(origCmd, sb.state.runConfig.Cmd))
} }

View File

@@ -7,8 +7,8 @@ import (
"github.com/docker/docker/builder/dockerfile/command" "github.com/docker/docker/builder/dockerfile/command"
"github.com/docker/docker/builder/dockerfile/parser" "github.com/docker/docker/builder/dockerfile/parser"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestCommandsExactlyOneArgument(t *testing.T) { func TestCommandsExactlyOneArgument(t *testing.T) {
@@ -21,9 +21,9 @@ func TestCommandsExactlyOneArgument(t *testing.T) {
for _, command := range commands { for _, command := range commands {
ast, err := parser.Parse(strings.NewReader(command)) ast, err := parser.Parse(strings.NewReader(command))
require.NoError(t, err) assert.NilError(t, err)
_, err = ParseInstruction(ast.AST.Children[0]) _, err = ParseInstruction(ast.AST.Children[0])
assert.EqualError(t, err, errExactlyOneArgument(command).Error()) assert.Check(t, is.Error(err, errExactlyOneArgument(command).Error()))
} }
} }
@@ -39,9 +39,9 @@ func TestCommandsAtLeastOneArgument(t *testing.T) {
for _, command := range commands { for _, command := range commands {
ast, err := parser.Parse(strings.NewReader(command)) ast, err := parser.Parse(strings.NewReader(command))
require.NoError(t, err) assert.NilError(t, err)
_, err = ParseInstruction(ast.AST.Children[0]) _, err = ParseInstruction(ast.AST.Children[0])
assert.EqualError(t, err, errAtLeastOneArgument(command).Error()) assert.Check(t, is.Error(err, errAtLeastOneArgument(command).Error()))
} }
} }
@@ -53,9 +53,9 @@ func TestCommandsNoDestinationArgument(t *testing.T) {
for _, command := range commands { for _, command := range commands {
ast, err := parser.Parse(strings.NewReader(command + " arg1")) ast, err := parser.Parse(strings.NewReader(command + " arg1"))
require.NoError(t, err) assert.NilError(t, err)
_, err = ParseInstruction(ast.AST.Children[0]) _, err = ParseInstruction(ast.AST.Children[0])
assert.EqualError(t, err, errNoDestinationArgument(command).Error()) assert.Check(t, is.Error(err, errNoDestinationArgument(command).Error()))
} }
} }
@@ -80,7 +80,7 @@ func TestCommandsTooManyArguments(t *testing.T) {
}, },
} }
_, err := ParseInstruction(node) _, err := ParseInstruction(node)
assert.EqualError(t, err, errTooManyArguments(command).Error()) assert.Check(t, is.Error(err, errTooManyArguments(command).Error()))
} }
} }
@@ -102,7 +102,7 @@ func TestCommandsBlankNames(t *testing.T) {
}, },
} }
_, err := ParseInstruction(node) _, err := ParseInstruction(node)
assert.EqualError(t, err, errBlankCommandNames(command).Error()) assert.Check(t, is.Error(err, errBlankCommandNames(command).Error()))
} }
} }
@@ -120,11 +120,11 @@ func TestHealthCheckCmd(t *testing.T) {
}, },
} }
cmd, err := ParseInstruction(node) cmd, err := ParseInstruction(node)
assert.NoError(t, err) assert.Check(t, err)
hc, ok := cmd.(*HealthCheckCommand) hc, ok := cmd.(*HealthCheckCommand)
assert.True(t, ok) assert.Check(t, ok)
expected := []string{"CMD-SHELL", "hello world"} expected := []string{"CMD-SHELL", "hello world"}
assert.Equal(t, expected, hc.Health.Test) assert.Check(t, is.DeepEqual(expected, hc.Health.Test))
} }
func TestParseOptInterval(t *testing.T) { func TestParseOptInterval(t *testing.T) {
@@ -138,7 +138,7 @@ func TestParseOptInterval(t *testing.T) {
flInterval.Value = "1ms" flInterval.Value = "1ms"
_, err = parseOptInterval(flInterval) _, err = parseOptInterval(flInterval)
require.NoError(t, err) assert.NilError(t, err)
} }
func TestErrorCases(t *testing.T) { func TestErrorCases(t *testing.T) {

View File

@@ -6,8 +6,8 @@ import (
"testing" "testing"
"github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/idtools"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestChownFlagParsing(t *testing.T) { func TestChownFlagParsing(t *testing.T) {
@@ -99,8 +99,8 @@ othergrp:x:6666:
} { } {
t.Run(testcase.name, func(t *testing.T) { t.Run(testcase.name, func(t *testing.T) {
idPair, err := parseChownFlag(testcase.chownStr, contextDir, testcase.idMapping) idPair, err := parseChownFlag(testcase.chownStr, contextDir, testcase.idMapping)
require.NoError(t, err, "Failed to parse chown flag: %q", testcase.chownStr) assert.NilError(t, err, "Failed to parse chown flag: %q", testcase.chownStr)
assert.Equal(t, testcase.expected, idPair, "chown flag mapping failure") assert.Check(t, is.DeepEqual(testcase.expected, idPair), "chown flag mapping failure")
}) })
} }
@@ -132,7 +132,7 @@ othergrp:x:6666:
} { } {
t.Run(testcase.name, func(t *testing.T) { t.Run(testcase.name, func(t *testing.T) {
_, err := parseChownFlag(testcase.chownStr, contextDir, testcase.idMapping) _, err := parseChownFlag(testcase.chownStr, contextDir, testcase.idMapping)
assert.EqualError(t, err, testcase.descr, "Expected error string doesn't match") assert.Check(t, is.Error(err, testcase.descr), "Expected error string doesn't match")
}) })
} }
} }

View File

@@ -12,8 +12,8 @@ import (
"github.com/docker/docker/builder/remotecontext" "github.com/docker/docker/builder/remotecontext"
"github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/archive"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestEmptyDockerfile(t *testing.T) { func TestEmptyDockerfile(t *testing.T) {
@@ -60,7 +60,7 @@ func TestNonExistingDockerfile(t *testing.T) {
func readAndCheckDockerfile(t *testing.T, testName, contextDir, dockerfilePath, expectedError string) { func readAndCheckDockerfile(t *testing.T, testName, contextDir, dockerfilePath, expectedError string) {
tarStream, err := archive.Tar(contextDir, archive.Uncompressed) tarStream, err := archive.Tar(contextDir, archive.Uncompressed)
require.NoError(t, err) assert.NilError(t, err)
defer func() { defer func() {
if err = tarStream.Close(); err != nil { if err = tarStream.Close(); err != nil {
@@ -77,7 +77,7 @@ func readAndCheckDockerfile(t *testing.T, testName, contextDir, dockerfilePath,
Source: tarStream, Source: tarStream,
} }
_, _, err = remotecontext.Detect(config) _, _, err = remotecontext.Detect(config)
assert.EqualError(t, err, expectedError) assert.Check(t, is.Error(err, expectedError))
} }
func TestCopyRunConfig(t *testing.T) { func TestCopyRunConfig(t *testing.T) {
@@ -124,9 +124,9 @@ func TestCopyRunConfig(t *testing.T) {
Env: defaultEnv, Env: defaultEnv,
} }
runConfigCopy := copyRunConfig(runConfig, testcase.modifiers...) runConfigCopy := copyRunConfig(runConfig, testcase.modifiers...)
assert.Equal(t, testcase.expected, runConfigCopy, testcase.doc) assert.Check(t, is.DeepEqual(testcase.expected, runConfigCopy), testcase.doc)
// Assert the original was not modified // Assert the original was not modified
assert.NotEqual(t, runConfig, runConfigCopy, testcase.doc) assert.Check(t, runConfig != runConfigCopy, testcase.doc)
} }
} }
@@ -156,7 +156,7 @@ func fullMutableRunConfig() *container.Config {
func TestDeepCopyRunConfig(t *testing.T) { func TestDeepCopyRunConfig(t *testing.T) {
runConfig := fullMutableRunConfig() runConfig := fullMutableRunConfig()
copy := copyRunConfig(runConfig) copy := copyRunConfig(runConfig)
assert.Equal(t, fullMutableRunConfig(), copy) assert.Check(t, is.DeepEqual(fullMutableRunConfig(), copy))
copy.Cmd[1] = "arg2" copy.Cmd[1] = "arg2"
copy.Env[1] = "env2=new" copy.Env[1] = "env2=new"
@@ -166,5 +166,5 @@ func TestDeepCopyRunConfig(t *testing.T) {
copy.OnBuild[0] = "start" copy.OnBuild[0] = "start"
copy.Labels["label3"] = "value3" copy.Labels["label3"] = "value3"
copy.Shell[0] = "sh" copy.Shell[0] = "sh"
assert.Equal(t, fullMutableRunConfig(), runConfig) assert.Check(t, is.DeepEqual(fullMutableRunConfig(), runConfig))
} }

View File

@@ -7,7 +7,8 @@ import (
"testing" "testing"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestNormalizeDest(t *testing.T) { func TestNormalizeDest(t *testing.T) {
@@ -42,10 +43,10 @@ func TestNormalizeDest(t *testing.T) {
msg := fmt.Sprintf("Input: %s, %s", testcase.current, testcase.requested) msg := fmt.Sprintf("Input: %s, %s", testcase.current, testcase.requested)
actual, err := normalizeDest(testcase.current, testcase.requested, "windows") actual, err := normalizeDest(testcase.current, testcase.requested, "windows")
if testcase.etext == "" { if testcase.etext == "" {
if !assert.NoError(t, err, msg) { if !assert.Check(t, err, msg) {
continue continue
} }
assert.Equal(t, testcase.expected, actual, msg) assert.Check(t, is.Equal(testcase.expected, actual), msg)
} else { } else {
testutil.ErrorContains(t, err, testcase.etext) testutil.ErrorContains(t, err, testcase.etext)
} }

View File

@@ -3,25 +3,26 @@ package parser // import "github.com/docker/docker/builder/dockerfile/parser"
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestParseNameValOldFormat(t *testing.T) { func TestParseNameValOldFormat(t *testing.T) {
directive := Directive{} directive := Directive{}
node, err := parseNameVal("foo bar", "LABEL", &directive) node, err := parseNameVal("foo bar", "LABEL", &directive)
assert.NoError(t, err) assert.Check(t, err)
expected := &Node{ expected := &Node{
Value: "foo", Value: "foo",
Next: &Node{Value: "bar"}, Next: &Node{Value: "bar"},
} }
assert.Equal(t, expected, node) assert.Check(t, is.DeepEqual(expected, node))
} }
func TestParseNameValNewFormat(t *testing.T) { func TestParseNameValNewFormat(t *testing.T) {
directive := Directive{} directive := Directive{}
node, err := parseNameVal("foo=bar thing=star", "LABEL", &directive) node, err := parseNameVal("foo=bar thing=star", "LABEL", &directive)
assert.NoError(t, err) assert.Check(t, err)
expected := &Node{ expected := &Node{
Value: "foo", Value: "foo",
@@ -35,7 +36,7 @@ func TestParseNameValNewFormat(t *testing.T) {
}, },
}, },
} }
assert.Equal(t, expected, node) assert.Check(t, is.DeepEqual(expected, node))
} }
func TestNodeFromLabels(t *testing.T) { func TestNodeFromLabels(t *testing.T) {
@@ -61,7 +62,7 @@ func TestNodeFromLabels(t *testing.T) {
} }
node := NodeFromLabels(labels) node := NodeFromLabels(labels)
assert.Equal(t, expected, node) assert.Check(t, is.DeepEqual(expected, node))
} }
@@ -70,5 +71,5 @@ func TestParseNameValWithoutVal(t *testing.T) {
// In Config.Env, a variable without `=` is removed from the environment. (#31634) // In Config.Env, a variable without `=` is removed from the environment. (#31634)
// However, in Dockerfile, we don't allow "unsetting" an environment variable. (#11922) // However, in Dockerfile, we don't allow "unsetting" an environment variable. (#11922)
_, err := parseNameVal("foo", "ENV", &directive) _, err := parseNameVal("foo", "ENV", &directive)
assert.Error(t, err, "ENV must have two arguments") assert.Check(t, is.ErrorContains(err, ""), "ENV must have two arguments")
} }

View File

@@ -11,8 +11,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
const testDir = "testfiles" const testDir = "testfiles"
@@ -21,11 +21,11 @@ const testFileLineInfo = "testfile-line/Dockerfile"
func getDirs(t *testing.T, dir string) []string { func getDirs(t *testing.T, dir string) []string {
f, err := os.Open(dir) f, err := os.Open(dir)
require.NoError(t, err) assert.NilError(t, err)
defer f.Close() defer f.Close()
dirs, err := f.Readdirnames(0) dirs, err := f.Readdirnames(0)
require.NoError(t, err) assert.NilError(t, err)
return dirs return dirs
} }
@@ -34,11 +34,11 @@ func TestParseErrorCases(t *testing.T) {
dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile") dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile")
df, err := os.Open(dockerfile) df, err := os.Open(dockerfile)
require.NoError(t, err, dockerfile) assert.NilError(t, err, dockerfile)
defer df.Close() defer df.Close()
_, err = Parse(df) _, err = Parse(df)
assert.Error(t, err, dockerfile) assert.Check(t, is.ErrorContains(err, ""), dockerfile)
} }
} }
@@ -48,20 +48,20 @@ func TestParseCases(t *testing.T) {
resultfile := filepath.Join(testDir, dir, "result") resultfile := filepath.Join(testDir, dir, "result")
df, err := os.Open(dockerfile) df, err := os.Open(dockerfile)
require.NoError(t, err, dockerfile) assert.NilError(t, err, dockerfile)
defer df.Close() defer df.Close()
result, err := Parse(df) result, err := Parse(df)
require.NoError(t, err, dockerfile) assert.NilError(t, err, dockerfile)
content, err := ioutil.ReadFile(resultfile) content, err := ioutil.ReadFile(resultfile)
require.NoError(t, err, resultfile) assert.NilError(t, err, resultfile)
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
// CRLF --> CR to match Unix behavior // CRLF --> CR to match Unix behavior
content = bytes.Replace(content, []byte{'\x0d', '\x0a'}, []byte{'\x0a'}, -1) content = bytes.Replace(content, []byte{'\x0d', '\x0a'}, []byte{'\x0a'}, -1)
} }
assert.Equal(t, result.AST.Dump()+"\n", string(content), "In "+dockerfile) assert.Check(t, is.Equal(result.AST.Dump()+"\n", string(content)), "In "+dockerfile)
} }
} }
@@ -103,22 +103,22 @@ func TestParseWords(t *testing.T) {
for _, test := range tests { for _, test := range tests {
words := parseWords(test["input"][0], NewDefaultDirective()) words := parseWords(test["input"][0], NewDefaultDirective())
assert.Equal(t, test["expect"], words) assert.Check(t, is.DeepEqual(test["expect"], words))
} }
} }
func TestParseIncludesLineNumbers(t *testing.T) { func TestParseIncludesLineNumbers(t *testing.T) {
df, err := os.Open(testFileLineInfo) df, err := os.Open(testFileLineInfo)
require.NoError(t, err) assert.NilError(t, err)
defer df.Close() defer df.Close()
result, err := Parse(df) result, err := Parse(df)
require.NoError(t, err) assert.NilError(t, err)
ast := result.AST ast := result.AST
assert.Equal(t, 5, ast.StartLine) assert.Check(t, is.Equal(5, ast.StartLine))
assert.Equal(t, 31, ast.endLine) assert.Check(t, is.Equal(31, ast.endLine))
assert.Len(t, ast.Children, 3) assert.Check(t, is.Len(ast.Children, 3))
expected := [][]int{ expected := [][]int{
{5, 5}, {5, 5},
{11, 12}, {11, 12},
@@ -126,7 +126,7 @@ func TestParseIncludesLineNumbers(t *testing.T) {
} }
for i, child := range ast.Children { for i, child := range ast.Children {
msg := fmt.Sprintf("Child %d", i) msg := fmt.Sprintf("Child %d", i)
assert.Equal(t, expected[i], []int{child.StartLine, child.endLine}, msg) assert.Check(t, is.DeepEqual(expected[i], []int{child.StartLine, child.endLine}), msg)
} }
} }
@@ -153,13 +153,13 @@ RUN indented \
`) `)
result, err := Parse(dockerfile) result, err := Parse(dockerfile)
require.NoError(t, err) assert.NilError(t, err)
warnings := result.Warnings warnings := result.Warnings
assert.Len(t, warnings, 3) assert.Check(t, is.Len(warnings, 3))
assert.Contains(t, warnings[0], "Empty continuation line found in") assert.Check(t, is.Contains(warnings[0], "Empty continuation line found in"))
assert.Contains(t, warnings[0], "RUN something following more") assert.Check(t, is.Contains(warnings[0], "RUN something following more"))
assert.Contains(t, warnings[1], "RUN another thing") assert.Check(t, is.Contains(warnings[1], "RUN another thing"))
assert.Contains(t, warnings[2], "will become errors in a future release") assert.Check(t, is.Contains(warnings[2], "will become errors in a future release"))
} }
func TestParseReturnsScannerErrors(t *testing.T) { func TestParseReturnsScannerErrors(t *testing.T) {
@@ -170,5 +170,5 @@ func TestParseReturnsScannerErrors(t *testing.T) {
LABEL test=%s LABEL test=%s
`, label)) `, label))
_, err := Parse(dockerfile) _, err := Parse(dockerfile)
assert.EqualError(t, err, "dockerfile line greater than max allowed size of 65535") assert.Check(t, is.Error(err, "dockerfile line greater than max allowed size of 65535"))
} }

View File

@@ -7,7 +7,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestShellParser4EnvVars(t *testing.T) { func TestShellParser4EnvVars(t *testing.T) {
@@ -15,7 +16,7 @@ func TestShellParser4EnvVars(t *testing.T) {
lineCount := 0 lineCount := 0
file, err := os.Open(fn) file, err := os.Open(fn)
assert.NoError(t, err) assert.Check(t, err)
defer file.Close() defer file.Close()
shlex := NewLex('\\') shlex := NewLex('\\')
@@ -37,7 +38,7 @@ func TestShellParser4EnvVars(t *testing.T) {
} }
words := strings.Split(line, "|") words := strings.Split(line, "|")
assert.Len(t, words, 3) assert.Check(t, is.Len(words, 3))
platform := strings.TrimSpace(words[0]) platform := strings.TrimSpace(words[0])
source := strings.TrimSpace(words[1]) source := strings.TrimSpace(words[1])
@@ -52,10 +53,10 @@ func TestShellParser4EnvVars(t *testing.T) {
((platform == "U" || platform == "A") && runtime.GOOS != "windows") { ((platform == "U" || platform == "A") && runtime.GOOS != "windows") {
newWord, err := shlex.ProcessWord(source, envs) newWord, err := shlex.ProcessWord(source, envs)
if expected == "error" { if expected == "error" {
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
} else { } else {
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, newWord, expected) assert.Check(t, is.Equal(newWord, expected))
} }
} }
} }

View File

@@ -7,14 +7,15 @@ import (
"testing" "testing"
"time" "time"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/moby/buildkit/session/filesync" "github.com/moby/buildkit/session/filesync"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
func TestFSCache(t *testing.T) { func TestFSCache(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "fscache") tmpDir, err := ioutil.TempDir("", "fscache")
assert.Nil(t, err) assert.Check(t, err)
defer os.RemoveAll(tmpDir) defer os.RemoveAll(tmpDir)
backend := NewNaiveCacheBackend(filepath.Join(tmpDir, "backend")) backend := NewNaiveCacheBackend(filepath.Join(tmpDir, "backend"))
@@ -26,84 +27,84 @@ func TestFSCache(t *testing.T) {
} }
fscache, err := NewFSCache(opt) fscache, err := NewFSCache(opt)
assert.Nil(t, err) assert.Check(t, err)
defer fscache.Close() defer fscache.Close()
err = fscache.RegisterTransport("test", &testTransport{}) err = fscache.RegisterTransport("test", &testTransport{})
assert.Nil(t, err) assert.Check(t, err)
src1, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data", "bar"}) src1, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data", "bar"})
assert.Nil(t, err) assert.Check(t, err)
dt, err := ioutil.ReadFile(filepath.Join(src1.Root().Path(), "foo")) dt, err := ioutil.ReadFile(filepath.Join(src1.Root().Path(), "foo"))
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, string(dt), "data") assert.Check(t, is.Equal(string(dt), "data"))
// same id doesn't recalculate anything // same id doesn't recalculate anything
src2, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data2", "bar"}) src2, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data2", "bar"})
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, src1.Root().Path(), src2.Root().Path()) assert.Check(t, is.Equal(src1.Root().Path(), src2.Root().Path()))
dt, err = ioutil.ReadFile(filepath.Join(src1.Root().Path(), "foo")) dt, err = ioutil.ReadFile(filepath.Join(src1.Root().Path(), "foo"))
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, string(dt), "data") assert.Check(t, is.Equal(string(dt), "data"))
assert.Nil(t, src2.Close()) assert.Check(t, src2.Close())
src3, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo2", "data2", "bar"}) src3, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo2", "data2", "bar"})
assert.Nil(t, err) assert.Check(t, err)
assert.NotEqual(t, src1.Root().Path(), src3.Root().Path()) assert.Check(t, src1.Root().Path() != src3.Root().Path())
dt, err = ioutil.ReadFile(filepath.Join(src3.Root().Path(), "foo2")) dt, err = ioutil.ReadFile(filepath.Join(src3.Root().Path(), "foo2"))
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, string(dt), "data2") assert.Check(t, is.Equal(string(dt), "data2"))
s, err := fscache.DiskUsage() s, err := fscache.DiskUsage()
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, s, int64(0)) assert.Check(t, is.Equal(s, int64(0)))
assert.Nil(t, src3.Close()) assert.Check(t, src3.Close())
s, err = fscache.DiskUsage() s, err = fscache.DiskUsage()
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, s, int64(5)) assert.Check(t, is.Equal(s, int64(5)))
// new upload with the same shared key shoutl overwrite // new upload with the same shared key shoutl overwrite
src4, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo3", "data3", "bar"}) src4, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo3", "data3", "bar"})
assert.Nil(t, err) assert.Check(t, err)
assert.NotEqual(t, src1.Root().Path(), src3.Root().Path()) assert.Check(t, src1.Root().Path() != src3.Root().Path())
dt, err = ioutil.ReadFile(filepath.Join(src3.Root().Path(), "foo3")) dt, err = ioutil.ReadFile(filepath.Join(src3.Root().Path(), "foo3"))
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, string(dt), "data3") assert.Check(t, is.Equal(string(dt), "data3"))
assert.Equal(t, src4.Root().Path(), src3.Root().Path()) assert.Check(t, is.Equal(src4.Root().Path(), src3.Root().Path()))
assert.Nil(t, src4.Close()) assert.Check(t, src4.Close())
s, err = fscache.DiskUsage() s, err = fscache.DiskUsage()
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, s, int64(10)) assert.Check(t, is.Equal(s, int64(10)))
// this one goes over the GC limit // this one goes over the GC limit
src5, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo4", "datadata", "baz"}) src5, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo4", "datadata", "baz"})
assert.Nil(t, err) assert.Check(t, err)
assert.Nil(t, src5.Close()) assert.Check(t, src5.Close())
// GC happens async // GC happens async
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
// only last insertion after GC // only last insertion after GC
s, err = fscache.DiskUsage() s, err = fscache.DiskUsage()
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, s, int64(8)) assert.Check(t, is.Equal(s, int64(8)))
// prune deletes everything // prune deletes everything
released, err := fscache.Prune(context.TODO()) released, err := fscache.Prune(context.TODO())
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, released, uint64(8)) assert.Check(t, is.Equal(released, uint64(8)))
s, err = fscache.DiskUsage() s, err = fscache.DiskUsage()
assert.Nil(t, err) assert.Check(t, err)
assert.Equal(t, s, int64(0)) assert.Check(t, is.Equal(s, int64(0)))
} }
type testTransport struct { type testTransport struct {

View File

@@ -13,40 +13,40 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestParseRemoteURL(t *testing.T) { func TestParseRemoteURL(t *testing.T) {
dir, err := parseRemoteURL("git://github.com/user/repo.git") dir, err := parseRemoteURL("git://github.com/user/repo.git")
require.NoError(t, err) assert.NilError(t, err)
assert.NotEmpty(t, dir) assert.Check(t, len(dir) != 0)
assert.Equal(t, gitRepo{"git://github.com/user/repo.git", "master", ""}, dir) assert.Check(t, is.DeepEqual(gitRepo{"git://github.com/user/repo.git", "master", ""}, dir))
dir, err = parseRemoteURL("git://github.com/user/repo.git#mybranch:mydir/mysubdir/") dir, err = parseRemoteURL("git://github.com/user/repo.git#mybranch:mydir/mysubdir/")
require.NoError(t, err) assert.NilError(t, err)
assert.NotEmpty(t, dir) assert.Check(t, len(dir) != 0)
assert.Equal(t, gitRepo{"git://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir) assert.Check(t, is.DeepEqual(gitRepo{"git://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir))
dir, err = parseRemoteURL("https://github.com/user/repo.git") dir, err = parseRemoteURL("https://github.com/user/repo.git")
require.NoError(t, err) assert.NilError(t, err)
assert.NotEmpty(t, dir) assert.Check(t, len(dir) != 0)
assert.Equal(t, gitRepo{"https://github.com/user/repo.git", "master", ""}, dir) assert.Check(t, is.DeepEqual(gitRepo{"https://github.com/user/repo.git", "master", ""}, dir))
dir, err = parseRemoteURL("https://github.com/user/repo.git#mybranch:mydir/mysubdir/") dir, err = parseRemoteURL("https://github.com/user/repo.git#mybranch:mydir/mysubdir/")
require.NoError(t, err) assert.NilError(t, err)
assert.NotEmpty(t, dir) assert.Check(t, len(dir) != 0)
assert.Equal(t, gitRepo{"https://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir) assert.Check(t, is.DeepEqual(gitRepo{"https://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir))
dir, err = parseRemoteURL("git@github.com:user/repo.git") dir, err = parseRemoteURL("git@github.com:user/repo.git")
require.NoError(t, err) assert.NilError(t, err)
assert.NotEmpty(t, dir) assert.Check(t, len(dir) != 0)
assert.Equal(t, gitRepo{"git@github.com:user/repo.git", "master", ""}, dir) assert.Check(t, is.DeepEqual(gitRepo{"git@github.com:user/repo.git", "master", ""}, dir))
dir, err = parseRemoteURL("git@github.com:user/repo.git#mybranch:mydir/mysubdir/") dir, err = parseRemoteURL("git@github.com:user/repo.git#mybranch:mydir/mysubdir/")
require.NoError(t, err) assert.NilError(t, err)
assert.NotEmpty(t, dir) assert.Check(t, len(dir) != 0)
assert.Equal(t, gitRepo{"git@github.com:user/repo.git", "mybranch", "mydir/mysubdir/"}, dir) assert.Check(t, is.DeepEqual(gitRepo{"git@github.com:user/repo.git", "mybranch", "mydir/mysubdir/"}, dir))
} }
func TestCloneArgsSmartHttp(t *testing.T) { func TestCloneArgsSmartHttp(t *testing.T) {
@@ -63,7 +63,7 @@ func TestCloneArgsSmartHttp(t *testing.T) {
args := fetchArgs(serverURL.String(), "master") args := fetchArgs(serverURL.String(), "master")
exp := []string{"fetch", "--depth", "1", "origin", "master"} exp := []string{"fetch", "--depth", "1", "origin", "master"}
assert.Equal(t, exp, args) assert.Check(t, is.DeepEqual(exp, args))
} }
func TestCloneArgsDumbHttp(t *testing.T) { func TestCloneArgsDumbHttp(t *testing.T) {
@@ -79,13 +79,13 @@ func TestCloneArgsDumbHttp(t *testing.T) {
args := fetchArgs(serverURL.String(), "master") args := fetchArgs(serverURL.String(), "master")
exp := []string{"fetch", "origin", "master"} exp := []string{"fetch", "origin", "master"}
assert.Equal(t, exp, args) assert.Check(t, is.DeepEqual(exp, args))
} }
func TestCloneArgsGit(t *testing.T) { func TestCloneArgsGit(t *testing.T) {
args := fetchArgs("git://github.com/docker/docker", "master") args := fetchArgs("git://github.com/docker/docker", "master")
exp := []string{"fetch", "--depth", "1", "origin", "master"} exp := []string{"fetch", "--depth", "1", "origin", "master"}
assert.Equal(t, exp, args) assert.Check(t, is.DeepEqual(exp, args))
} }
func gitGetConfig(name string) string { func gitGetConfig(name string) string {
@@ -100,7 +100,7 @@ func gitGetConfig(name string) string {
func TestCheckoutGit(t *testing.T) { func TestCheckoutGit(t *testing.T) {
root, err := ioutil.TempDir("", "docker-build-git-checkout") root, err := ioutil.TempDir("", "docker-build-git-checkout")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(root) defer os.RemoveAll(root)
autocrlf := gitGetConfig("core.autocrlf") autocrlf := gitGetConfig("core.autocrlf")
@@ -115,22 +115,22 @@ func TestCheckoutGit(t *testing.T) {
gitDir := filepath.Join(root, "repo") gitDir := filepath.Join(root, "repo")
_, err = git("init", gitDir) _, err = git("init", gitDir)
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com") _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "config", "user.name", "Docker test") _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test")
require.NoError(t, err) assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644) err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644)
require.NoError(t, err) assert.NilError(t, err)
subDir := filepath.Join(gitDir, "subdir") subDir := filepath.Join(gitDir, "subdir")
require.NoError(t, os.Mkdir(subDir, 0755)) assert.NilError(t, os.Mkdir(subDir, 0755))
err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644) err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644)
require.NoError(t, err) assert.NilError(t, err)
if runtime.GOOS != "windows" { if runtime.GOOS != "windows" {
if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil { if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
@@ -143,58 +143,58 @@ func TestCheckoutGit(t *testing.T) {
} }
_, err = gitWithinDir(gitDir, "add", "-A") _, err = gitWithinDir(gitDir, "add", "-A")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "commit", "-am", "First commit") _, err = gitWithinDir(gitDir, "commit", "-am", "First commit")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "checkout", "-b", "test") _, err = gitWithinDir(gitDir, "checkout", "-b", "test")
require.NoError(t, err) assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644) err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644)
require.NoError(t, err) assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644) err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644)
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "add", "-A") _, err = gitWithinDir(gitDir, "add", "-A")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit") _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "checkout", "master") _, err = gitWithinDir(gitDir, "checkout", "master")
require.NoError(t, err) assert.NilError(t, err)
// set up submodule // set up submodule
subrepoDir := filepath.Join(root, "subrepo") subrepoDir := filepath.Join(root, "subrepo")
_, err = git("init", subrepoDir) _, err = git("init", subrepoDir)
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(subrepoDir, "config", "user.email", "test@docker.com") _, err = gitWithinDir(subrepoDir, "config", "user.email", "test@docker.com")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(subrepoDir, "config", "user.name", "Docker test") _, err = gitWithinDir(subrepoDir, "config", "user.name", "Docker test")
require.NoError(t, err) assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644) err = ioutil.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644)
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(subrepoDir, "add", "-A") _, err = gitWithinDir(subrepoDir, "add", "-A")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(subrepoDir, "commit", "-am", "Subrepo initial") _, err = gitWithinDir(subrepoDir, "commit", "-am", "Subrepo initial")
require.NoError(t, err) assert.NilError(t, err)
cmd := exec.Command("git", "submodule", "add", subrepoDir, "sub") // this command doesn't work with --work-tree cmd := exec.Command("git", "submodule", "add", subrepoDir, "sub") // this command doesn't work with --work-tree
cmd.Dir = gitDir cmd.Dir = gitDir
require.NoError(t, cmd.Run()) assert.NilError(t, cmd.Run())
_, err = gitWithinDir(gitDir, "add", "-A") _, err = gitWithinDir(gitDir, "add", "-A")
require.NoError(t, err) assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "commit", "-am", "With submodule") _, err = gitWithinDir(gitDir, "commit", "-am", "With submodule")
require.NoError(t, err) assert.NilError(t, err)
type singleCase struct { type singleCase struct {
frag string frag string
@@ -232,24 +232,24 @@ func TestCheckoutGit(t *testing.T) {
r, err := cloneGitRepo(gitRepo{remote: gitDir, ref: ref, subdir: subdir}) r, err := cloneGitRepo(gitRepo{remote: gitDir, ref: ref, subdir: subdir})
if c.fail { if c.fail {
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
continue continue
} }
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(r) defer os.RemoveAll(r)
if c.submodule { if c.submodule {
b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile")) b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile"))
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "subcontents", string(b)) assert.Check(t, is.Equal("subcontents", string(b)))
} else { } else {
_, err := os.Stat(filepath.Join(r, "sub/subfile")) _, err := os.Stat(filepath.Join(r, "sub/subfile"))
require.Error(t, err) assert.Assert(t, is.ErrorContains(err, ""))
require.True(t, os.IsNotExist(err)) assert.Assert(t, os.IsNotExist(err))
} }
b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile")) b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, c.exp, string(b)) assert.Check(t, is.Equal(c.exp, string(b)))
} }
} }

View File

@@ -3,14 +3,14 @@ package remotecontext // import "github.com/docker/docker/builder/remotecontext"
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestDetectContentType(t *testing.T) { func TestDetectContentType(t *testing.T) {
input := []byte("That is just a plain text") input := []byte("That is just a plain text")
contentType, _, err := detectContentType(input) contentType, _, err := detectContentType(input)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "text/plain", contentType) assert.Check(t, is.Equal("text/plain", contentType))
} }

View File

@@ -11,9 +11,9 @@ import (
"github.com/docker/docker/builder" "github.com/docker/docker/builder"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
var binaryContext = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00} //xz magic var binaryContext = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00} //xz magic
@@ -189,12 +189,12 @@ func TestDownloadRemote(t *testing.T) {
mux.Handle("/", http.FileServer(http.Dir(contextDir.Path()))) mux.Handle("/", http.FileServer(http.Dir(contextDir.Path())))
contentType, content, err := downloadRemote(remoteURL) contentType, content, err := downloadRemote(remoteURL)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, mimeTypes.TextPlain, contentType) assert.Check(t, is.Equal(mimeTypes.TextPlain, contentType))
raw, err := ioutil.ReadAll(content) raw, err := ioutil.ReadAll(content)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, dockerfileContents, string(raw)) assert.Check(t, is.Equal(dockerfileContents, string(raw)))
} }
func TestGetWithStatusError(t *testing.T) { func TestGetWithStatusError(t *testing.T) {
@@ -226,11 +226,11 @@ func TestGetWithStatusError(t *testing.T) {
response, err := GetWithStatusError(ts.URL) response, err := GetWithStatusError(ts.URL)
if testcase.expectedErr == "" { if testcase.expectedErr == "" {
require.NoError(t, err) assert.NilError(t, err)
body, err := readBody(response.Body) body, err := readBody(response.Body)
require.NoError(t, err) assert.NilError(t, err)
assert.Contains(t, string(body), testcase.expectedBody) assert.Check(t, is.Contains(string(body), testcase.expectedBody))
} else { } else {
testutil.ErrorContains(t, err, testcase.expectedErr) testutil.ErrorContains(t, err, testcase.expectedErr)
} }

View File

@@ -11,10 +11,10 @@ import (
"github.com/docker/docker/api" "github.com/docker/docker/api"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/env" "github.com/gotestyourself/gotestyourself/env"
"github.com/gotestyourself/gotestyourself/skip" "github.com/gotestyourself/gotestyourself/skip"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestNewEnvClient(t *testing.T) { func TestNewEnvClient(t *testing.T) {
@@ -89,19 +89,19 @@ func TestNewEnvClient(t *testing.T) {
env.PatchAll(t, c.envs) env.PatchAll(t, c.envs)
apiclient, err := NewEnvClient() apiclient, err := NewEnvClient()
if c.expectedError != "" { if c.expectedError != "" {
assert.Error(t, err, c.doc) assert.Check(t, is.ErrorContains(err, ""), c.doc)
assert.Equal(t, c.expectedError, err.Error(), c.doc) assert.Check(t, is.Equal(c.expectedError, err.Error()), c.doc)
} else { } else {
assert.NoError(t, err, c.doc) assert.Check(t, err, c.doc)
version := apiclient.ClientVersion() version := apiclient.ClientVersion()
assert.Equal(t, c.expectedVersion, version, c.doc) assert.Check(t, is.Equal(c.expectedVersion, version), c.doc)
} }
if c.envs["DOCKER_TLS_VERIFY"] != "" { if c.envs["DOCKER_TLS_VERIFY"] != "" {
// pedantic checking that this is handled correctly // pedantic checking that this is handled correctly
tr := apiclient.client.Transport.(*http.Transport) tr := apiclient.client.Transport.(*http.Transport)
assert.NotNil(t, tr.TLSClientConfig, c.doc) assert.Check(t, tr.TLSClientConfig != nil, c.doc)
assert.Equal(t, tr.TLSClientConfig.InsecureSkipVerify, false, c.doc) assert.Check(t, is.Equal(tr.TLSClientConfig.InsecureSkipVerify, false), c.doc)
} }
} }
} }
@@ -128,7 +128,7 @@ func TestGetAPIPath(t *testing.T) {
for _, testcase := range testcases { for _, testcase := range testcases {
c := Client{version: testcase.version, basePath: "/"} c := Client{version: testcase.version, basePath: "/"}
actual := c.getAPIPath(testcase.path, testcase.query) actual := c.getAPIPath(testcase.path, testcase.query)
assert.Equal(t, actual, testcase.expected) assert.Check(t, is.Equal(actual, testcase.expected))
} }
} }
@@ -165,7 +165,7 @@ func TestParseHostURL(t *testing.T) {
if testcase.expectedErr != "" { if testcase.expectedErr != "" {
testutil.ErrorContains(t, err, testcase.expectedErr) testutil.ErrorContains(t, err, testcase.expectedErr)
} }
assert.Equal(t, testcase.expected, actual) assert.Check(t, is.DeepEqual(testcase.expected, actual))
} }
} }
@@ -181,7 +181,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
assert.Equal(t, client.version, api.DefaultVersion) assert.Check(t, is.Equal(client.version, api.DefaultVersion))
expected := "1.22" expected := "1.22"
os.Setenv("DOCKER_API_VERSION", expected) os.Setenv("DOCKER_API_VERSION", expected)
@@ -189,7 +189,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
assert.Equal(t, expected, client.version) assert.Check(t, is.Equal(expected, client.version))
} }
// TestNegotiateAPIVersionEmpty asserts that client.Client can // TestNegotiateAPIVersionEmpty asserts that client.Client can
@@ -198,7 +198,7 @@ func TestNegotiateAPIVersionEmpty(t *testing.T) {
defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": ""}) defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": ""})
client, err := NewEnvClient() client, err := NewEnvClient()
require.NoError(t, err) assert.NilError(t, err)
ping := types.Ping{ ping := types.Ping{
APIVersion: "", APIVersion: "",
@@ -215,14 +215,14 @@ func TestNegotiateAPIVersionEmpty(t *testing.T) {
// test downgrade // test downgrade
client.NegotiateAPIVersionPing(ping) client.NegotiateAPIVersionPing(ping)
assert.Equal(t, expected, client.version) assert.Check(t, is.Equal(expected, client.version))
} }
// TestNegotiateAPIVersion asserts that client.Client can // TestNegotiateAPIVersion asserts that client.Client can
// negotiate a compatible APIVersion with the server // negotiate a compatible APIVersion with the server
func TestNegotiateAPIVersion(t *testing.T) { func TestNegotiateAPIVersion(t *testing.T) {
client, err := NewEnvClient() client, err := NewEnvClient()
require.NoError(t, err) assert.NilError(t, err)
expected := "1.21" expected := "1.21"
ping := types.Ping{ ping := types.Ping{
@@ -236,14 +236,14 @@ func TestNegotiateAPIVersion(t *testing.T) {
// test downgrade // test downgrade
client.NegotiateAPIVersionPing(ping) client.NegotiateAPIVersionPing(ping)
assert.Equal(t, expected, client.version) assert.Check(t, is.Equal(expected, client.version))
// set the client version to something older, and verify that we keep the // set the client version to something older, and verify that we keep the
// original setting. // original setting.
expected = "1.20" expected = "1.20"
client.version = expected client.version = expected
client.NegotiateAPIVersionPing(ping) client.NegotiateAPIVersionPing(ping)
assert.Equal(t, expected, client.version) assert.Check(t, is.Equal(expected, client.version))
} }
@@ -254,7 +254,7 @@ func TestNegotiateAPVersionOverride(t *testing.T) {
defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": expected})() defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": expected})()
client, err := NewEnvClient() client, err := NewEnvClient()
require.NoError(t, err) assert.NilError(t, err)
ping := types.Ping{ ping := types.Ping{
APIVersion: "1.24", APIVersion: "1.24",
@@ -264,7 +264,7 @@ func TestNegotiateAPVersionOverride(t *testing.T) {
// test that we honored the env var // test that we honored the env var
client.NegotiateAPIVersionPing(ping) client.NegotiateAPIVersionPing(ping)
assert.Equal(t, expected, client.version) assert.Check(t, is.Equal(expected, client.version))
} }
type roundTripFunc func(*http.Request) (*http.Response, error) type roundTripFunc func(*http.Request) (*http.Response, error)
@@ -309,9 +309,9 @@ func TestClientRedirect(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
req, err := http.NewRequest(tc.httpMethod, "/redirectme", nil) req, err := http.NewRequest(tc.httpMethod, "/redirectme", nil)
assert.NoError(t, err) assert.Check(t, err)
resp, err := client.Do(req) resp, err := client.Do(req)
assert.Equal(t, tc.expectedErr, err) assert.Check(t, is.DeepEqual(tc.expectedErr, err))
assert.Equal(t, tc.statusCode, resp.StatusCode) assert.Check(t, is.Equal(tc.statusCode, resp.StatusCode))
} }
} }

View File

@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -21,7 +22,7 @@ func TestConfigCreateUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, err := client.ConfigCreate(context.Background(), swarm.ConfigSpec{}) _, err := client.ConfigCreate(context.Background(), swarm.ConfigSpec{})
assert.EqualError(t, err, `"config create" requires API version 1.30, but the Docker daemon API version is 1.29`) assert.Check(t, is.Error(err, `"config create" requires API version 1.30, but the Docker daemon API version is 1.29`))
} }
func TestConfigCreateError(t *testing.T) { func TestConfigCreateError(t *testing.T) {

View File

@@ -10,8 +10,9 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -44,7 +45,7 @@ func TestConfigInspectUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, _, err := client.ConfigInspectWithRaw(context.Background(), "nothing") _, _, err := client.ConfigInspectWithRaw(context.Background(), "nothing")
assert.EqualError(t, err, `"config inspect" requires API version 1.30, but the Docker daemon API version is 1.29`) assert.Check(t, is.Error(err, `"config inspect" requires API version 1.30, but the Docker daemon API version is 1.29`))
} }
func TestConfigInspectError(t *testing.T) { func TestConfigInspectError(t *testing.T) {

View File

@@ -12,7 +12,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -22,7 +23,7 @@ func TestConfigListUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, err := client.ConfigList(context.Background(), types.ConfigListOptions{}) _, err := client.ConfigList(context.Background(), types.ConfigListOptions{})
assert.EqualError(t, err, `"config list" requires API version 1.30, but the Docker daemon API version is 1.29`) assert.Check(t, is.Error(err, `"config list" requires API version 1.30, but the Docker daemon API version is 1.29`))
} }
func TestConfigListError(t *testing.T) { func TestConfigListError(t *testing.T) {

View File

@@ -8,7 +8,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -18,7 +19,7 @@ func TestConfigRemoveUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
err := client.ConfigRemove(context.Background(), "config_id") err := client.ConfigRemove(context.Background(), "config_id")
assert.EqualError(t, err, `"config remove" requires API version 1.30, but the Docker daemon API version is 1.29`) assert.Check(t, is.Error(err, `"config remove" requires API version 1.30, but the Docker daemon API version is 1.29`))
} }
func TestConfigRemoveError(t *testing.T) { func TestConfigRemoveError(t *testing.T) {

View File

@@ -9,7 +9,8 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -19,7 +20,7 @@ func TestConfigUpdateUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
err := client.ConfigUpdate(context.Background(), "config_id", swarm.Version{}, swarm.ConfigSpec{}) err := client.ConfigUpdate(context.Background(), "config_id", swarm.Version{}, swarm.ConfigSpec{})
assert.EqualError(t, err, `"config update" requires API version 1.30, but the Docker daemon API version is 1.29`) assert.Check(t, is.Error(err, `"config update" requires API version 1.30, but the Docker daemon API version is 1.29`))
} }
func TestConfigUpdateError(t *testing.T) { func TestConfigUpdateError(t *testing.T) {

View File

@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -24,7 +25,7 @@ func TestContainersPruneError(t *testing.T) {
filters := filters.NewArgs() filters := filters.NewArgs()
_, err := client.ContainersPrune(context.Background(), filters) _, err := client.ContainersPrune(context.Background(), filters)
assert.EqualError(t, err, "Error response from daemon: Server error") assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
} }
func TestContainersPrune(t *testing.T) { func TestContainersPrune(t *testing.T) {
@@ -99,7 +100,7 @@ func TestContainersPrune(t *testing.T) {
query := req.URL.Query() query := req.URL.Query()
for key, expected := range listCase.expectedQueryParams { for key, expected := range listCase.expectedQueryParams {
actual := query.Get(key) actual := query.Get(key)
assert.Equal(t, expected, actual) assert.Check(t, is.Equal(expected, actual))
} }
content, err := json.Marshal(types.ContainersPruneReport{ content, err := json.Marshal(types.ContainersPruneReport{
ContainersDeleted: []string{"container_id1", "container_id2"}, ContainersDeleted: []string{"container_id1", "container_id2"},
@@ -117,8 +118,8 @@ func TestContainersPrune(t *testing.T) {
} }
report, err := client.ContainersPrune(context.Background(), listCase.filters) report, err := client.ContainersPrune(context.Background(), listCase.filters)
assert.NoError(t, err) assert.Check(t, err)
assert.Len(t, report.ContainersDeleted, 2) assert.Check(t, is.Len(report.ContainersDeleted, 2))
assert.Equal(t, uint64(9999), report.SpaceReclaimed) assert.Check(t, is.Equal(uint64(9999), report.SpaceReclaimed))
} }
} }

View File

@@ -9,7 +9,8 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -18,7 +19,7 @@ func TestContainerRemoveError(t *testing.T) {
client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
} }
err := client.ContainerRemove(context.Background(), "container_id", types.ContainerRemoveOptions{}) err := client.ContainerRemove(context.Background(), "container_id", types.ContainerRemoveOptions{})
assert.EqualError(t, err, "Error response from daemon: Server error") assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
} }
func TestContainerRemoveNotFoundError(t *testing.T) { func TestContainerRemoveNotFoundError(t *testing.T) {
@@ -26,8 +27,8 @@ func TestContainerRemoveNotFoundError(t *testing.T) {
client: newMockClient(errorMock(http.StatusNotFound, "missing")), client: newMockClient(errorMock(http.StatusNotFound, "missing")),
} }
err := client.ContainerRemove(context.Background(), "container_id", types.ContainerRemoveOptions{}) err := client.ContainerRemove(context.Background(), "container_id", types.ContainerRemoveOptions{})
assert.EqualError(t, err, "Error: No such container: container_id") assert.Check(t, is.Error(err, "Error: No such container: container_id"))
assert.True(t, IsErrNotFound(err)) assert.Check(t, IsErrNotFound(err))
} }
func TestContainerRemove(t *testing.T) { func TestContainerRemove(t *testing.T) {
@@ -61,5 +62,5 @@ func TestContainerRemove(t *testing.T) {
RemoveVolumes: true, RemoveVolumes: true,
Force: true, Force: true,
}) })
assert.NoError(t, err) assert.Check(t, err)
} }

View File

@@ -4,8 +4,9 @@ import (
"net/http" "net/http"
"testing" "testing"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -15,7 +16,7 @@ func TestDistributionInspectUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, err := client.DistributionInspect(context.Background(), "foobar:1.0", "") _, err := client.DistributionInspect(context.Background(), "foobar:1.0", "")
assert.EqualError(t, err, `"distribution inspect" requires API version 1.30, but the Docker daemon API version is 1.29`) assert.Check(t, is.Error(err, `"distribution inspect" requires API version 1.30, but the Docker daemon API version is 1.29`))
} }
func TestDistributionInspectWithEmptyID(t *testing.T) { func TestDistributionInspectWithEmptyID(t *testing.T) {

View File

@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -24,7 +25,7 @@ func TestImagesPruneError(t *testing.T) {
filters := filters.NewArgs() filters := filters.NewArgs()
_, err := client.ImagesPrune(context.Background(), filters) _, err := client.ImagesPrune(context.Background(), filters)
assert.EqualError(t, err, "Error response from daemon: Server error") assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
} }
func TestImagesPrune(t *testing.T) { func TestImagesPrune(t *testing.T) {
@@ -87,7 +88,7 @@ func TestImagesPrune(t *testing.T) {
query := req.URL.Query() query := req.URL.Query()
for key, expected := range listCase.expectedQueryParams { for key, expected := range listCase.expectedQueryParams {
actual := query.Get(key) actual := query.Get(key)
assert.Equal(t, expected, actual) assert.Check(t, is.Equal(expected, actual))
} }
content, err := json.Marshal(types.ImagesPruneReport{ content, err := json.Marshal(types.ImagesPruneReport{
ImagesDeleted: []types.ImageDeleteResponseItem{ ImagesDeleted: []types.ImageDeleteResponseItem{
@@ -112,8 +113,8 @@ func TestImagesPrune(t *testing.T) {
} }
report, err := client.ImagesPrune(context.Background(), listCase.filters) report, err := client.ImagesPrune(context.Background(), listCase.filters)
assert.NoError(t, err) assert.Check(t, err)
assert.Len(t, report.ImagesDeleted, 2) assert.Check(t, is.Len(report.ImagesDeleted, 2))
assert.Equal(t, uint64(9999), report.SpaceReclaimed) assert.Check(t, is.Equal(uint64(9999), report.SpaceReclaimed))
} }
} }

View File

@@ -10,7 +10,8 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -20,7 +21,7 @@ func TestImageRemoveError(t *testing.T) {
} }
_, err := client.ImageRemove(context.Background(), "image_id", types.ImageRemoveOptions{}) _, err := client.ImageRemove(context.Background(), "image_id", types.ImageRemoveOptions{})
assert.EqualError(t, err, "Error response from daemon: Server error") assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
} }
func TestImageRemoveImageNotFound(t *testing.T) { func TestImageRemoveImageNotFound(t *testing.T) {
@@ -29,8 +30,8 @@ func TestImageRemoveImageNotFound(t *testing.T) {
} }
_, err := client.ImageRemove(context.Background(), "unknown", types.ImageRemoveOptions{}) _, err := client.ImageRemove(context.Background(), "unknown", types.ImageRemoveOptions{})
assert.EqualError(t, err, "Error: No such image: unknown") assert.Check(t, is.Error(err, "Error: No such image: unknown"))
assert.True(t, IsErrNotFound(err)) assert.Check(t, IsErrNotFound(err))
} }
func TestImageRemove(t *testing.T) { func TestImageRemove(t *testing.T) {

View File

@@ -11,8 +11,9 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -22,7 +23,7 @@ func TestNetworkInspectError(t *testing.T) {
} }
_, err := client.NetworkInspect(context.Background(), "nothing", types.NetworkInspectOptions{}) _, err := client.NetworkInspect(context.Background(), "nothing", types.NetworkInspectOptions{})
assert.EqualError(t, err, "Error response from daemon: Server error") assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
} }
func TestNetworkInspectNotFoundError(t *testing.T) { func TestNetworkInspectNotFoundError(t *testing.T) {
@@ -31,8 +32,8 @@ func TestNetworkInspectNotFoundError(t *testing.T) {
} }
_, err := client.NetworkInspect(context.Background(), "unknown", types.NetworkInspectOptions{}) _, err := client.NetworkInspect(context.Background(), "unknown", types.NetworkInspectOptions{})
assert.EqualError(t, err, "Error: No such network: unknown") assert.Check(t, is.Error(err, "Error: No such network: unknown"))
assert.True(t, IsErrNotFound(err)) assert.Check(t, IsErrNotFound(err))
} }
func TestNetworkInspectWithEmptyID(t *testing.T) { func TestNetworkInspectWithEmptyID(t *testing.T) {
@@ -113,5 +114,5 @@ func TestNetworkInspect(t *testing.T) {
} }
_, err = client.NetworkInspect(context.Background(), "network_id", types.NetworkInspectOptions{Scope: "global"}) _, err = client.NetworkInspect(context.Background(), "network_id", types.NetworkInspectOptions{Scope: "global"})
assert.EqualError(t, err, "Error: No such network: network_id") assert.Check(t, is.Error(err, "Error: No such network: network_id"))
} }

View File

@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -89,7 +90,7 @@ func TestNetworksPrune(t *testing.T) {
query := req.URL.Query() query := req.URL.Query()
for key, expected := range listCase.expectedQueryParams { for key, expected := range listCase.expectedQueryParams {
actual := query.Get(key) actual := query.Get(key)
assert.Equal(t, expected, actual) assert.Check(t, is.Equal(expected, actual))
} }
content, err := json.Marshal(types.NetworksPruneReport{ content, err := json.Marshal(types.NetworksPruneReport{
NetworksDeleted: []string{"network_id1", "network_id2"}, NetworksDeleted: []string{"network_id1", "network_id2"},
@@ -106,7 +107,7 @@ func TestNetworksPrune(t *testing.T) {
} }
report, err := client.NetworksPrune(context.Background(), listCase.filters) report, err := client.NetworksPrune(context.Background(), listCase.filters)
assert.NoError(t, err) assert.Check(t, err)
assert.Len(t, report.NetworksDeleted, 2) assert.Check(t, is.Len(report.NetworksDeleted, 2))
} }
} }

View File

@@ -7,7 +7,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -31,15 +32,15 @@ func TestPingFail(t *testing.T) {
} }
ping, err := client.Ping(context.Background()) ping, err := client.Ping(context.Background())
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
assert.Equal(t, false, ping.Experimental) assert.Check(t, is.Equal(false, ping.Experimental))
assert.Equal(t, "", ping.APIVersion) assert.Check(t, is.Equal("", ping.APIVersion))
withHeader = true withHeader = true
ping2, err := client.Ping(context.Background()) ping2, err := client.Ping(context.Background())
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
assert.Equal(t, true, ping2.Experimental) assert.Check(t, is.Equal(true, ping2.Experimental))
assert.Equal(t, "awesome", ping2.APIVersion) assert.Check(t, is.Equal("awesome", ping2.APIVersion))
} }
// TestPingWithError tests the case where there is a protocol error in the ping. // TestPingWithError tests the case where there is a protocol error in the ping.
@@ -57,9 +58,9 @@ func TestPingWithError(t *testing.T) {
} }
ping, err := client.Ping(context.Background()) ping, err := client.Ping(context.Background())
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
assert.Equal(t, false, ping.Experimental) assert.Check(t, is.Equal(false, ping.Experimental))
assert.Equal(t, "", ping.APIVersion) assert.Check(t, is.Equal("", ping.APIVersion))
} }
// TestPingSuccess tests that we are able to get the expected API headers/ping // TestPingSuccess tests that we are able to get the expected API headers/ping
@@ -76,7 +77,7 @@ func TestPingSuccess(t *testing.T) {
}), }),
} }
ping, err := client.Ping(context.Background()) ping, err := client.Ping(context.Background())
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
assert.Equal(t, true, ping.Experimental) assert.Check(t, is.Equal(true, ping.Experimental))
assert.Equal(t, "awesome", ping.APIVersion) assert.Check(t, is.Equal("awesome", ping.APIVersion))
} }

View File

@@ -9,7 +9,7 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -46,7 +46,7 @@ func TestSetHostHeader(t *testing.T) {
for c, test := range testCases { for c, test := range testCases {
hostURL, err := ParseHostURL(test.host) hostURL, err := ParseHostURL(test.host)
require.NoError(t, err) assert.NilError(t, err)
client := &Client{ client := &Client{
client: newMockClient(func(req *http.Request) (*http.Response, error) { client: newMockClient(func(req *http.Request) (*http.Response, error) {
@@ -71,7 +71,7 @@ func TestSetHostHeader(t *testing.T) {
} }
_, err = client.sendRequest(context.Background(), "GET", testURL, nil, nil, nil) _, err = client.sendRequest(context.Background(), "GET", testURL, nil, nil, nil)
require.NoError(t, err) assert.NilError(t, err)
} }
} }

View File

@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -21,7 +22,7 @@ func TestSecretCreateUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, err := client.SecretCreate(context.Background(), swarm.SecretSpec{}) _, err := client.SecretCreate(context.Background(), swarm.SecretSpec{})
assert.EqualError(t, err, `"secret create" requires API version 1.25, but the Docker daemon API version is 1.24`) assert.Check(t, is.Error(err, `"secret create" requires API version 1.25, but the Docker daemon API version is 1.24`))
} }
func TestSecretCreateError(t *testing.T) { func TestSecretCreateError(t *testing.T) {

View File

@@ -10,8 +10,9 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -21,7 +22,7 @@ func TestSecretInspectUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, _, err := client.SecretInspectWithRaw(context.Background(), "nothing") _, _, err := client.SecretInspectWithRaw(context.Background(), "nothing")
assert.EqualError(t, err, `"secret inspect" requires API version 1.25, but the Docker daemon API version is 1.24`) assert.Check(t, is.Error(err, `"secret inspect" requires API version 1.25, but the Docker daemon API version is 1.24`))
} }
func TestSecretInspectError(t *testing.T) { func TestSecretInspectError(t *testing.T) {

View File

@@ -12,7 +12,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -22,7 +23,7 @@ func TestSecretListUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
_, err := client.SecretList(context.Background(), types.SecretListOptions{}) _, err := client.SecretList(context.Background(), types.SecretListOptions{})
assert.EqualError(t, err, `"secret list" requires API version 1.25, but the Docker daemon API version is 1.24`) assert.Check(t, is.Error(err, `"secret list" requires API version 1.25, but the Docker daemon API version is 1.24`))
} }
func TestSecretListError(t *testing.T) { func TestSecretListError(t *testing.T) {

View File

@@ -8,7 +8,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -18,7 +19,7 @@ func TestSecretRemoveUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
err := client.SecretRemove(context.Background(), "secret_id") err := client.SecretRemove(context.Background(), "secret_id")
assert.EqualError(t, err, `"secret remove" requires API version 1.25, but the Docker daemon API version is 1.24`) assert.Check(t, is.Error(err, `"secret remove" requires API version 1.25, but the Docker daemon API version is 1.24`))
} }
func TestSecretRemoveError(t *testing.T) { func TestSecretRemoveError(t *testing.T) {

View File

@@ -9,7 +9,8 @@ import (
"testing" "testing"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -19,7 +20,7 @@ func TestSecretUpdateUnsupported(t *testing.T) {
client: &http.Client{}, client: &http.Client{},
} }
err := client.SecretUpdate(context.Background(), "secret_id", swarm.Version{}, swarm.SecretSpec{}) err := client.SecretUpdate(context.Background(), "secret_id", swarm.Version{}, swarm.SecretSpec{})
assert.EqualError(t, err, `"secret update" requires API version 1.25, but the Docker daemon API version is 1.24`) assert.Check(t, is.Error(err, `"secret update" requires API version 1.25, but the Docker daemon API version is 1.24`))
} }
func TestSecretUpdateError(t *testing.T) { func TestSecretUpdateError(t *testing.T) {

View File

@@ -12,9 +12,10 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
registrytypes "github.com/docker/docker/api/types/registry" registrytypes "github.com/docker/docker/api/types/registry"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/opencontainers/image-spec/specs-go/v1" "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -73,8 +74,8 @@ func TestServiceCreateCompatiblePlatforms(t *testing.T) {
return nil, err return nil, err
} }
assert.Equal(t, "foobar:1.0@sha256:c0537ff6a5218ef531ece93d4984efc99bbf3f7497c0a7726c88e2bb7584dc96", serviceSpec.TaskTemplate.ContainerSpec.Image) assert.Check(t, is.Equal("foobar:1.0@sha256:c0537ff6a5218ef531ece93d4984efc99bbf3f7497c0a7726c88e2bb7584dc96", serviceSpec.TaskTemplate.ContainerSpec.Image))
assert.Len(t, serviceSpec.TaskTemplate.Placement.Platforms, 1) assert.Check(t, is.Len(serviceSpec.TaskTemplate.Placement.Platforms, 1))
p := serviceSpec.TaskTemplate.Placement.Platforms[0] p := serviceSpec.TaskTemplate.Placement.Platforms[0]
b, err := json.Marshal(types.ServiceCreateResponse{ b, err := json.Marshal(types.ServiceCreateResponse{
@@ -115,8 +116,8 @@ func TestServiceCreateCompatiblePlatforms(t *testing.T) {
spec := swarm.ServiceSpec{TaskTemplate: swarm.TaskSpec{ContainerSpec: &swarm.ContainerSpec{Image: "foobar:1.0"}}} spec := swarm.ServiceSpec{TaskTemplate: swarm.TaskSpec{ContainerSpec: &swarm.ContainerSpec{Image: "foobar:1.0"}}}
r, err := client.ServiceCreate(context.Background(), spec, types.ServiceCreateOptions{QueryRegistry: true}) r, err := client.ServiceCreate(context.Background(), spec, types.ServiceCreateOptions{QueryRegistry: true})
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "service_linux_amd64", r.ID) assert.Check(t, is.Equal("service_linux_amd64", r.ID))
} }
func TestServiceCreateDigestPinning(t *testing.T) { func TestServiceCreateDigestPinning(t *testing.T) {

View File

@@ -8,7 +8,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -18,7 +19,7 @@ func TestServiceRemoveError(t *testing.T) {
} }
err := client.ServiceRemove(context.Background(), "service_id") err := client.ServiceRemove(context.Background(), "service_id")
assert.EqualError(t, err, "Error response from daemon: Server error") assert.Check(t, is.Error(err, "Error response from daemon: Server error"))
} }
func TestServiceRemoveNotFoundError(t *testing.T) { func TestServiceRemoveNotFoundError(t *testing.T) {
@@ -27,8 +28,8 @@ func TestServiceRemoveNotFoundError(t *testing.T) {
} }
err := client.ServiceRemove(context.Background(), "service_id") err := client.ServiceRemove(context.Background(), "service_id")
assert.EqualError(t, err, "Error: No such service: service_id") assert.Check(t, is.Error(err, "Error: No such service: service_id"))
assert.True(t, IsErrNotFound(err)) assert.Check(t, IsErrNotFound(err))
} }
func TestServiceRemove(t *testing.T) { func TestServiceRemove(t *testing.T) {

View File

@@ -11,8 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -55,6 +55,6 @@ func TestSwarmGetUnlockKey(t *testing.T) {
} }
resp, err := client.SwarmGetUnlockKey(context.Background()) resp, err := client.SwarmGetUnlockKey(context.Background())
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, unlockKey, resp.UnlockKey) assert.Check(t, is.Equal(unlockKey, resp.UnlockKey))
} }

View File

@@ -11,9 +11,9 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -32,7 +32,7 @@ func TestVolumeInspectNotFound(t *testing.T) {
} }
_, err := client.VolumeInspect(context.Background(), "unknown") _, err := client.VolumeInspect(context.Background(), "unknown")
assert.True(t, IsErrNotFound(err)) assert.Check(t, IsErrNotFound(err))
} }
func TestVolumeInspectWithEmptyID(t *testing.T) { func TestVolumeInspectWithEmptyID(t *testing.T) {
@@ -75,6 +75,6 @@ func TestVolumeInspect(t *testing.T) {
} }
volume, err := client.VolumeInspect(context.Background(), "volume_id") volume, err := client.VolumeInspect(context.Background(), "volume_id")
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, expected, volume) assert.Check(t, is.DeepEqual(expected, volume))
} }

View File

@@ -6,8 +6,9 @@ import (
"testing" "testing"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
) )
func TestDaemonParseShmSize(t *testing.T) { func TestDaemonParseShmSize(t *testing.T) {
@@ -16,7 +17,7 @@ func TestDaemonParseShmSize(t *testing.T) {
conf := &config.Config{} conf := &config.Config{}
installConfigFlags(conf, flags) installConfigFlags(conf, flags)
// By default `--default-shm-size=64M` // By default `--default-shm-size=64M`
assert.Equal(t, int64(64*1024*1024), conf.ShmSize.Value()) assert.Check(t, is.Equal(int64(64*1024*1024), conf.ShmSize.Value()))
assert.NoError(t, flags.Set("default-shm-size", "128M")) assert.Check(t, flags.Set("default-shm-size", "128M"))
assert.Equal(t, int64(128*1024*1024), conf.ShmSize.Value()) assert.Check(t, is.Equal(int64(128*1024*1024), conf.ShmSize.Value()))
} }

View File

@@ -5,11 +5,11 @@ import (
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func defaultOptions(configFile string) *daemonOptions { func defaultOptions(configFile string) *daemonOptions {
@@ -27,8 +27,8 @@ func TestLoadDaemonCliConfigWithoutOverriding(t *testing.T) {
opts.Debug = true opts.Debug = true
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
if !loadedConfig.Debug { if !loadedConfig.Debug {
t.Fatalf("expected debug to be copied from the common flags, got false") t.Fatalf("expected debug to be copied from the common flags, got false")
} }
@@ -40,9 +40,9 @@ func TestLoadDaemonCliConfigWithTLS(t *testing.T) {
opts.TLS = true opts.TLS = true
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.Equal(t, "/tmp/ca.pem", loadedConfig.CommonTLSOptions.CAFile) assert.Check(t, is.Equal("/tmp/ca.pem", loadedConfig.CommonTLSOptions.CAFile))
} }
func TestLoadDaemonCliConfigWithConflicts(t *testing.T) { func TestLoadDaemonCliConfigWithConflicts(t *testing.T) {
@@ -53,9 +53,9 @@ func TestLoadDaemonCliConfigWithConflicts(t *testing.T) {
opts := defaultOptions(configFile) opts := defaultOptions(configFile)
flags := opts.flags flags := opts.flags
assert.NoError(t, flags.Set("config-file", configFile)) assert.Check(t, flags.Set("config-file", configFile))
assert.NoError(t, flags.Set("label", "l1=bar")) assert.Check(t, flags.Set("label", "l1=bar"))
assert.NoError(t, flags.Set("label", "l2=baz")) assert.Check(t, flags.Set("label", "l2=baz"))
_, err := loadDaemonCliConfig(opts) _, err := loadDaemonCliConfig(opts)
testutil.ErrorContains(t, err, "as a flag and in the configuration file: labels") testutil.ErrorContains(t, err, "as a flag and in the configuration file: labels")
@@ -69,9 +69,9 @@ func TestLoadDaemonCliWithConflictingNodeGenericResources(t *testing.T) {
opts := defaultOptions(configFile) opts := defaultOptions(configFile)
flags := opts.flags flags := opts.flags
assert.NoError(t, flags.Set("config-file", configFile)) assert.Check(t, flags.Set("config-file", configFile))
assert.NoError(t, flags.Set("node-generic-resource", "r1=bar")) assert.Check(t, flags.Set("node-generic-resource", "r1=bar"))
assert.NoError(t, flags.Set("node-generic-resource", "r2=baz")) assert.Check(t, flags.Set("node-generic-resource", "r2=baz"))
_, err := loadDaemonCliConfig(opts) _, err := loadDaemonCliConfig(opts)
testutil.ErrorContains(t, err, "as a flag and in the configuration file: node-generic-resources") testutil.ErrorContains(t, err, "as a flag and in the configuration file: node-generic-resources")
@@ -81,22 +81,22 @@ func TestLoadDaemonCliWithConflictingLabels(t *testing.T) {
opts := defaultOptions("") opts := defaultOptions("")
flags := opts.flags flags := opts.flags
assert.NoError(t, flags.Set("label", "foo=bar")) assert.Check(t, flags.Set("label", "foo=bar"))
assert.NoError(t, flags.Set("label", "foo=baz")) assert.Check(t, flags.Set("label", "foo=baz"))
_, err := loadDaemonCliConfig(opts) _, err := loadDaemonCliConfig(opts)
assert.EqualError(t, err, "conflict labels for foo=baz and foo=bar") assert.Check(t, is.Error(err, "conflict labels for foo=baz and foo=bar"))
} }
func TestLoadDaemonCliWithDuplicateLabels(t *testing.T) { func TestLoadDaemonCliWithDuplicateLabels(t *testing.T) {
opts := defaultOptions("") opts := defaultOptions("")
flags := opts.flags flags := opts.flags
assert.NoError(t, flags.Set("label", "foo=the-same")) assert.Check(t, flags.Set("label", "foo=the-same"))
assert.NoError(t, flags.Set("label", "foo=the-same")) assert.Check(t, flags.Set("label", "foo=the-same"))
_, err := loadDaemonCliConfig(opts) _, err := loadDaemonCliConfig(opts)
assert.NoError(t, err) assert.Check(t, err)
} }
func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) { func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) {
@@ -107,9 +107,9 @@ func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) {
opts.TLSOptions.CAFile = "/tmp/ca.pem" opts.TLSOptions.CAFile = "/tmp/ca.pem"
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.Equal(t, loadedConfig.TLS, true) assert.Check(t, is.Equal(loadedConfig.TLS, true))
} }
func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) { func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) {
@@ -120,9 +120,9 @@ func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) {
opts.TLSOptions.CAFile = "/tmp/ca.pem" opts.TLSOptions.CAFile = "/tmp/ca.pem"
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.True(t, loadedConfig.TLS) assert.Check(t, loadedConfig.TLS)
} }
func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) { func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) {
@@ -133,9 +133,9 @@ func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) {
opts.TLSOptions.CAFile = "/tmp/ca.pem" opts.TLSOptions.CAFile = "/tmp/ca.pem"
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.False(t, loadedConfig.TLS) assert.Check(t, !loadedConfig.TLS)
} }
func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) { func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) {
@@ -144,10 +144,10 @@ func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.Equal(t, "warn", loadedConfig.LogLevel) assert.Check(t, is.Equal("warn", loadedConfig.LogLevel))
assert.Equal(t, logrus.WarnLevel, logrus.GetLevel()) assert.Check(t, is.Equal(logrus.WarnLevel, logrus.GetLevel()))
} }
func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) { func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) {
@@ -157,10 +157,10 @@ func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.Equal(t, "/etc/certs/ca.pem", loadedConfig.CommonTLSOptions.CAFile) assert.Check(t, is.Equal("/etc/certs/ca.pem", loadedConfig.CommonTLSOptions.CAFile))
assert.Equal(t, "syslog", loadedConfig.LogConfig.Type) assert.Check(t, is.Equal("syslog", loadedConfig.LogConfig.Type))
} }
func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) { func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) {
@@ -174,10 +174,10 @@ func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.Len(t, loadedConfig.AllowNondistributableArtifacts, 1) assert.Check(t, is.Len(loadedConfig.AllowNondistributableArtifacts, 1))
assert.Len(t, loadedConfig.Mirrors, 1) assert.Check(t, is.Len(loadedConfig.Mirrors, 1))
assert.Len(t, loadedConfig.InsecureRegistries, 1) assert.Check(t, is.Len(loadedConfig.InsecureRegistries, 1))
} }

View File

@@ -6,9 +6,9 @@ import (
"testing" "testing"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) { func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) {
@@ -19,17 +19,17 @@ func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
opts.Debug = true opts.Debug = true
opts.LogLevel = "info" opts.LogLevel = "info"
assert.NoError(t, opts.flags.Set("selinux-enabled", "true")) assert.Check(t, opts.flags.Set("selinux-enabled", "true"))
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.True(t, loadedConfig.Debug) assert.Check(t, loadedConfig.Debug)
assert.Equal(t, "info", loadedConfig.LogLevel) assert.Check(t, is.Equal("info", loadedConfig.LogLevel))
assert.True(t, loadedConfig.EnableSelinuxSupport) assert.Check(t, loadedConfig.EnableSelinuxSupport)
assert.Equal(t, "json-file", loadedConfig.LogConfig.Type) assert.Check(t, is.Equal("json-file", loadedConfig.LogConfig.Type))
assert.Equal(t, "1k", loadedConfig.LogConfig.Config["max-size"]) assert.Check(t, is.Equal("1k", loadedConfig.LogConfig.Config["max-size"]))
} }
func TestLoadDaemonConfigWithNetwork(t *testing.T) { func TestLoadDaemonConfigWithNetwork(t *testing.T) {
@@ -39,11 +39,11 @@ func TestLoadDaemonConfigWithNetwork(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.Equal(t, "127.0.0.2", loadedConfig.IP) assert.Check(t, is.Equal("127.0.0.2", loadedConfig.IP))
assert.Equal(t, "127.0.0.1", loadedConfig.DefaultIP.String()) assert.Check(t, is.Equal("127.0.0.1", loadedConfig.DefaultIP.String()))
} }
func TestLoadDaemonConfigWithMapOptions(t *testing.T) { func TestLoadDaemonConfigWithMapOptions(t *testing.T) {
@@ -56,14 +56,14 @@ func TestLoadDaemonConfigWithMapOptions(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.NotNil(t, loadedConfig.ClusterOpts) assert.Check(t, loadedConfig.ClusterOpts != nil)
expectedPath := "/var/lib/docker/discovery_certs/ca.pem" expectedPath := "/var/lib/docker/discovery_certs/ca.pem"
assert.Equal(t, expectedPath, loadedConfig.ClusterOpts["kv.cacertfile"]) assert.Check(t, is.Equal(expectedPath, loadedConfig.ClusterOpts["kv.cacertfile"]))
assert.NotNil(t, loadedConfig.LogConfig.Config) assert.Check(t, loadedConfig.LogConfig.Config != nil)
assert.Equal(t, "test", loadedConfig.LogConfig.Config["tag"]) assert.Check(t, is.Equal("test", loadedConfig.LogConfig.Config["tag"]))
} }
func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) { func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) {
@@ -73,17 +73,17 @@ func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.False(t, loadedConfig.EnableUserlandProxy) assert.Check(t, !loadedConfig.EnableUserlandProxy)
// make sure reloading doesn't generate configuration // make sure reloading doesn't generate configuration
// conflicts after normalizing boolean values. // conflicts after normalizing boolean values.
reload := func(reloadedConfig *config.Config) { reload := func(reloadedConfig *config.Config) {
assert.False(t, reloadedConfig.EnableUserlandProxy) assert.Check(t, !reloadedConfig.EnableUserlandProxy)
} }
assert.NoError(t, config.Reload(opts.configFile, opts.flags, reload)) assert.Check(t, config.Reload(opts.configFile, opts.flags, reload))
} }
func TestLoadDaemonConfigWithTrueDefaultValuesLeaveDefaults(t *testing.T) { func TestLoadDaemonConfigWithTrueDefaultValuesLeaveDefaults(t *testing.T) {
@@ -92,8 +92,8 @@ func TestLoadDaemonConfigWithTrueDefaultValuesLeaveDefaults(t *testing.T) {
opts := defaultOptions(tempFile.Path()) opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts) loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, loadedConfig) assert.Assert(t, loadedConfig != nil)
assert.True(t, loadedConfig.EnableUserlandProxy) assert.Check(t, loadedConfig.EnableUserlandProxy)
} }

View File

@@ -6,8 +6,9 @@ import (
cliconfig "github.com/docker/docker/cli/config" cliconfig "github.com/docker/docker/cli/config"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
) )
func TestCommonOptionsInstallFlags(t *testing.T) { func TestCommonOptionsInstallFlags(t *testing.T) {
@@ -20,10 +21,10 @@ func TestCommonOptionsInstallFlags(t *testing.T) {
"--tlscert=\"/foo/cert\"", "--tlscert=\"/foo/cert\"",
"--tlskey=\"/foo/key\"", "--tlskey=\"/foo/key\"",
}) })
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "/foo/cafile", opts.TLSOptions.CAFile) assert.Check(t, is.Equal("/foo/cafile", opts.TLSOptions.CAFile))
assert.Equal(t, "/foo/cert", opts.TLSOptions.CertFile) assert.Check(t, is.Equal("/foo/cert", opts.TLSOptions.CertFile))
assert.Equal(t, opts.TLSOptions.KeyFile, "/foo/key") assert.Check(t, is.Equal(opts.TLSOptions.KeyFile, "/foo/key"))
} }
func defaultPath(filename string) string { func defaultPath(filename string) string {
@@ -36,8 +37,8 @@ func TestCommonOptionsInstallFlagsWithDefaults(t *testing.T) {
opts.InstallFlags(flags) opts.InstallFlags(flags)
err := flags.Parse([]string{}) err := flags.Parse([]string{})
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, defaultPath("ca.pem"), opts.TLSOptions.CAFile) assert.Check(t, is.Equal(defaultPath("ca.pem"), opts.TLSOptions.CAFile))
assert.Equal(t, defaultPath("cert.pem"), opts.TLSOptions.CertFile) assert.Check(t, is.Equal(defaultPath("cert.pem"), opts.TLSOptions.CertFile))
assert.Equal(t, defaultPath("key.pem"), opts.TLSOptions.KeyFile) assert.Check(t, is.Equal(defaultPath("key.pem"), opts.TLSOptions.KeyFile))
} }

View File

@@ -11,7 +11,7 @@ import (
swarmtypes "github.com/docker/docker/api/types/swarm" swarmtypes "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/daemon/logger/jsonfilelog" "github.com/docker/docker/daemon/logger/jsonfilelog"
"github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/signal"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
func TestContainerStopSignal(t *testing.T) { func TestContainerStopSignal(t *testing.T) {
@@ -74,7 +74,7 @@ func TestContainerSecretReferenceDestTarget(t *testing.T) {
func TestContainerLogPathSetForJSONFileLogger(t *testing.T) { func TestContainerLogPathSetForJSONFileLogger(t *testing.T) {
containerRoot, err := ioutil.TempDir("", "TestContainerLogPathSetForJSONFileLogger") containerRoot, err := ioutil.TempDir("", "TestContainerLogPathSetForJSONFileLogger")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(containerRoot) defer os.RemoveAll(containerRoot)
c := &Container{ c := &Container{
@@ -89,17 +89,17 @@ func TestContainerLogPathSetForJSONFileLogger(t *testing.T) {
} }
logger, err := c.StartLogger() logger, err := c.StartLogger()
require.NoError(t, err) assert.NilError(t, err)
defer logger.Close() defer logger.Close()
expectedLogPath, err := filepath.Abs(filepath.Join(containerRoot, fmt.Sprintf("%s-json.log", c.ID))) expectedLogPath, err := filepath.Abs(filepath.Join(containerRoot, fmt.Sprintf("%s-json.log", c.ID)))
require.NoError(t, err) assert.NilError(t, err)
require.Equal(t, c.LogPath, expectedLogPath) assert.Equal(t, c.LogPath, expectedLogPath)
} }
func TestContainerLogPathSetForRingLogger(t *testing.T) { func TestContainerLogPathSetForRingLogger(t *testing.T) {
containerRoot, err := ioutil.TempDir("", "TestContainerLogPathSetForRingLogger") containerRoot, err := ioutil.TempDir("", "TestContainerLogPathSetForRingLogger")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(containerRoot) defer os.RemoveAll(containerRoot)
c := &Container{ c := &Container{
@@ -117,10 +117,10 @@ func TestContainerLogPathSetForRingLogger(t *testing.T) {
} }
logger, err := c.StartLogger() logger, err := c.StartLogger()
require.NoError(t, err) assert.NilError(t, err)
defer logger.Close() defer logger.Close()
expectedLogPath, err := filepath.Abs(filepath.Join(containerRoot, fmt.Sprintf("%s-json.log", c.ID))) expectedLogPath, err := filepath.Abs(filepath.Join(containerRoot, fmt.Sprintf("%s-json.log", c.ID)))
require.NoError(t, err) assert.NilError(t, err)
require.Equal(t, c.LogPath, expectedLogPath) assert.Equal(t, c.LogPath, expectedLogPath)
} }

View File

@@ -8,8 +8,9 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
containertypes "github.com/docker/docker/api/types/container" containertypes "github.com/docker/docker/api/types/container"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pborman/uuid" "github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
) )
var root string var root string
@@ -109,56 +110,56 @@ func TestNames(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
assert.NoError(t, db.ReserveName("name1", "containerid1")) assert.Check(t, db.ReserveName("name1", "containerid1"))
assert.NoError(t, db.ReserveName("name1", "containerid1")) // idempotent assert.Check(t, db.ReserveName("name1", "containerid1")) // idempotent
assert.NoError(t, db.ReserveName("name2", "containerid2")) assert.Check(t, db.ReserveName("name2", "containerid2"))
assert.EqualError(t, db.ReserveName("name2", "containerid3"), ErrNameReserved.Error()) assert.Check(t, is.Error(db.ReserveName("name2", "containerid3"), ErrNameReserved.Error()))
// Releasing a name allows the name to point to something else later. // Releasing a name allows the name to point to something else later.
assert.NoError(t, db.ReleaseName("name2")) assert.Check(t, db.ReleaseName("name2"))
assert.NoError(t, db.ReserveName("name2", "containerid3")) assert.Check(t, db.ReserveName("name2", "containerid3"))
view := db.Snapshot() view := db.Snapshot()
id, err := view.GetID("name1") id, err := view.GetID("name1")
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "containerid1", id) assert.Check(t, is.Equal("containerid1", id))
id, err = view.GetID("name2") id, err = view.GetID("name2")
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "containerid3", id) assert.Check(t, is.Equal("containerid3", id))
_, err = view.GetID("notreserved") _, err = view.GetID("notreserved")
assert.EqualError(t, err, ErrNameNotReserved.Error()) assert.Check(t, is.Error(err, ErrNameNotReserved.Error()))
// Releasing and re-reserving a name doesn't affect the snapshot. // Releasing and re-reserving a name doesn't affect the snapshot.
assert.NoError(t, db.ReleaseName("name2")) assert.Check(t, db.ReleaseName("name2"))
assert.NoError(t, db.ReserveName("name2", "containerid4")) assert.Check(t, db.ReserveName("name2", "containerid4"))
id, err = view.GetID("name1") id, err = view.GetID("name1")
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "containerid1", id) assert.Check(t, is.Equal("containerid1", id))
id, err = view.GetID("name2") id, err = view.GetID("name2")
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "containerid3", id) assert.Check(t, is.Equal("containerid3", id))
// GetAllNames // GetAllNames
assert.Equal(t, map[string][]string{"containerid1": {"name1"}, "containerid3": {"name2"}}, view.GetAllNames()) assert.Check(t, is.DeepEqual(map[string][]string{"containerid1": {"name1"}, "containerid3": {"name2"}}, view.GetAllNames()))
assert.NoError(t, db.ReserveName("name3", "containerid1")) assert.Check(t, db.ReserveName("name3", "containerid1"))
assert.NoError(t, db.ReserveName("name4", "containerid1")) assert.Check(t, db.ReserveName("name4", "containerid1"))
view = db.Snapshot() view = db.Snapshot()
assert.Equal(t, map[string][]string{"containerid1": {"name1", "name3", "name4"}, "containerid4": {"name2"}}, view.GetAllNames()) assert.Check(t, is.DeepEqual(map[string][]string{"containerid1": {"name1", "name3", "name4"}, "containerid4": {"name2"}}, view.GetAllNames()))
// Release containerid1's names with Delete even though no container exists // Release containerid1's names with Delete even though no container exists
assert.NoError(t, db.Delete(&Container{ID: "containerid1"})) assert.Check(t, db.Delete(&Container{ID: "containerid1"}))
// Reusing one of those names should work // Reusing one of those names should work
assert.NoError(t, db.ReserveName("name1", "containerid4")) assert.Check(t, db.ReserveName("name1", "containerid4"))
view = db.Snapshot() view = db.Snapshot()
assert.Equal(t, map[string][]string{"containerid4": {"name1", "name2"}}, view.GetAllNames()) assert.Check(t, is.DeepEqual(map[string][]string{"containerid4": {"name1", "name2"}}, view.GetAllNames()))
} }
// Test case for GitHub issue 35920 // Test case for GitHub issue 35920

View File

@@ -8,7 +8,7 @@ import (
"github.com/docker/docker/api/types/swarm/runtime" "github.com/docker/docker/api/types/swarm/runtime"
swarmapi "github.com/docker/swarmkit/api" swarmapi "github.com/docker/swarmkit/api"
google_protobuf3 "github.com/gogo/protobuf/types" google_protobuf3 "github.com/gogo/protobuf/types"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
func TestServiceConvertFromGRPCRuntimeContainer(t *testing.T) { func TestServiceConvertFromGRPCRuntimeContainer(t *testing.T) {
@@ -178,12 +178,12 @@ func TestServiceConvertToGRPCIsolation(t *testing.T) {
}, },
} }
res, err := ServiceSpecToGRPC(s) res, err := ServiceSpecToGRPC(s)
require.NoError(t, err) assert.NilError(t, err)
v, ok := res.Task.Runtime.(*swarmapi.TaskSpec_Container) v, ok := res.Task.Runtime.(*swarmapi.TaskSpec_Container)
if !ok { if !ok {
t.Fatal("expected type swarmapi.TaskSpec_Container") t.Fatal("expected type swarmapi.TaskSpec_Container")
} }
require.Equal(t, c.to, v.Container.Isolation) assert.Equal(t, c.to, v.Container.Isolation)
}) })
} }
} }
@@ -228,7 +228,7 @@ func TestServiceConvertFromGRPCIsolation(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
require.Equal(t, c.to, svc.Spec.TaskTemplate.ContainerSpec.Isolation) assert.Equal(t, c.to, svc.Spec.TaskTemplate.ContainerSpec.Isolation)
}) })
} }
} }

View File

@@ -5,7 +5,7 @@ import (
container "github.com/docker/docker/api/types/container" container "github.com/docker/docker/api/types/container"
swarmapi "github.com/docker/swarmkit/api" swarmapi "github.com/docker/swarmkit/api"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
func TestIsolationConversion(t *testing.T) { func TestIsolationConversion(t *testing.T) {
@@ -31,7 +31,7 @@ func TestIsolationConversion(t *testing.T) {
}, },
} }
config := containerConfig{task: &task} config := containerConfig{task: &task}
require.Equal(t, c.to, config.hostConfig().Isolation) assert.Equal(t, c.to, config.hostConfig().Isolation)
}) })
} }
} }

View File

@@ -9,9 +9,10 @@ import (
"github.com/docker/docker/daemon/discovery" "github.com/docker/docker/daemon/discovery"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
) )
func TestDaemonConfigurationNotFound(t *testing.T) { func TestDaemonConfigurationNotFound(t *testing.T) {
@@ -59,7 +60,7 @@ func TestFindConfigurationConflicts(t *testing.T) {
flags := pflag.NewFlagSet("test", pflag.ContinueOnError) flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("authorization-plugins", "", "") flags.String("authorization-plugins", "", "")
assert.NoError(t, flags.Set("authorization-plugins", "asdf")) assert.Check(t, flags.Set("authorization-plugins", "asdf"))
testutil.ErrorContains(t, testutil.ErrorContains(t,
findConfigurationConflicts(config, flags), findConfigurationConflicts(config, flags),
@@ -72,8 +73,8 @@ func TestFindConfigurationConflictsWithNamedOptions(t *testing.T) {
var hosts []string var hosts []string
flags.VarP(opts.NewNamedListOptsRef("hosts", &hosts, opts.ValidateHost), "host", "H", "Daemon socket(s) to connect to") flags.VarP(opts.NewNamedListOptsRef("hosts", &hosts, opts.ValidateHost), "host", "H", "Daemon socket(s) to connect to")
assert.NoError(t, flags.Set("host", "tcp://127.0.0.1:4444")) assert.Check(t, flags.Set("host", "tcp://127.0.0.1:4444"))
assert.NoError(t, flags.Set("host", "unix:///var/run/docker.sock")) assert.Check(t, flags.Set("host", "unix:///var/run/docker.sock"))
testutil.ErrorContains(t, findConfigurationConflicts(config, flags), "hosts") testutil.ErrorContains(t, findConfigurationConflicts(config, flags), "hosts")
} }
@@ -424,7 +425,7 @@ func TestReloadSetConfigFileNotExist(t *testing.T) {
flags.Set("config-file", configFile) flags.Set("config-file", configFile)
err := Reload(configFile, flags, func(c *Config) {}) err := Reload(configFile, flags, func(c *Config) {})
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
testutil.ErrorContains(t, err, "unable to configure the Docker daemon with file") testutil.ErrorContains(t, err, "unable to configure the Docker daemon with file")
} }
@@ -438,8 +439,8 @@ func TestReloadDefaultConfigNotExist(t *testing.T) {
err := Reload(configFile, flags, func(c *Config) { err := Reload(configFile, flags, func(c *Config) {
reloaded = true reloaded = true
}) })
assert.Nil(t, err) assert.Check(t, err)
assert.True(t, reloaded) assert.Check(t, reloaded)
} }
// TestReloadBadDefaultConfig tests that when `--config-file` is not set // TestReloadBadDefaultConfig tests that when `--config-file` is not set
@@ -457,7 +458,7 @@ func TestReloadBadDefaultConfig(t *testing.T) {
flags := pflag.NewFlagSet("test", pflag.ContinueOnError) flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("config-file", configFile, "") flags.String("config-file", configFile, "")
err = Reload(configFile, flags, func(c *Config) {}) err = Reload(configFile, flags, func(c *Config) {})
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
testutil.ErrorContains(t, err, "unable to configure the Docker daemon with file") testutil.ErrorContains(t, err, "unable to configure the Docker daemon with file")
} }
@@ -484,5 +485,5 @@ func TestReloadWithDuplicateLabels(t *testing.T) {
flags.String("config-file", configFile, "") flags.String("config-file", configFile, "")
flags.StringSlice("labels", lbls, "") flags.StringSlice("labels", lbls, "")
err := Reload(configFile, flags, func(c *Config) {}) err := Reload(configFile, flags, func(c *Config) {})
assert.NoError(t, err) assert.Check(t, err)
} }

View File

@@ -7,10 +7,10 @@ import (
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
units "github.com/docker/go-units" units "github.com/docker/go-units"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetConflictFreeConfiguration(t *testing.T) { func TestGetConflictFreeConfiguration(t *testing.T) {
@@ -39,9 +39,9 @@ func TestGetConflictFreeConfiguration(t *testing.T) {
flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "") flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "")
cc, err := getConflictFreeConfiguration(file.Path(), flags) cc, err := getConflictFreeConfiguration(file.Path(), flags)
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, cc.Debug) assert.Check(t, cc.Debug)
expectedUlimits := map[string]*units.Ulimit{ expectedUlimits := map[string]*units.Ulimit{
"nofile": { "nofile": {
@@ -51,7 +51,7 @@ func TestGetConflictFreeConfiguration(t *testing.T) {
}, },
} }
assert.Equal(t, expectedUlimits, cc.Ulimits) assert.Check(t, is.DeepEqual(expectedUlimits, cc.Ulimits))
} }
func TestDaemonConfigurationMerge(t *testing.T) { func TestDaemonConfigurationMerge(t *testing.T) {
@@ -91,17 +91,17 @@ func TestDaemonConfigurationMerge(t *testing.T) {
flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "") flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "")
cc, err := MergeDaemonConfigurations(c, flags, file.Path()) cc, err := MergeDaemonConfigurations(c, flags, file.Path())
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, cc.Debug) assert.Check(t, cc.Debug)
assert.True(t, cc.AutoRestart) assert.Check(t, cc.AutoRestart)
expectedLogConfig := LogConfig{ expectedLogConfig := LogConfig{
Type: "syslog", Type: "syslog",
Config: map[string]string{"tag": "test_tag"}, Config: map[string]string{"tag": "test_tag"},
} }
assert.Equal(t, expectedLogConfig, cc.LogConfig) assert.Check(t, is.DeepEqual(expectedLogConfig, cc.LogConfig))
expectedUlimits := map[string]*units.Ulimit{ expectedUlimits := map[string]*units.Ulimit{
"nofile": { "nofile": {
@@ -111,7 +111,7 @@ func TestDaemonConfigurationMerge(t *testing.T) {
}, },
} }
assert.Equal(t, expectedUlimits, cc.Ulimits) assert.Check(t, is.DeepEqual(expectedUlimits, cc.Ulimits))
} }
func TestDaemonConfigurationMergeShmSize(t *testing.T) { func TestDaemonConfigurationMergeShmSize(t *testing.T) {
@@ -127,8 +127,8 @@ func TestDaemonConfigurationMergeShmSize(t *testing.T) {
flags.Var(&shmSize, "default-shm-size", "") flags.Var(&shmSize, "default-shm-size", "")
cc, err := MergeDaemonConfigurations(c, flags, file.Path()) cc, err := MergeDaemonConfigurations(c, flags, file.Path())
require.NoError(t, err) assert.NilError(t, err)
expectedValue := 1 * 1024 * 1024 * 1024 expectedValue := 1 * 1024 * 1024 * 1024
assert.Equal(t, int64(expectedValue), cc.ShmSize.Value()) assert.Check(t, is.Equal(int64(expectedValue), cc.ShmSize.Value()))
} }

View File

@@ -7,9 +7,9 @@ import (
"testing" "testing"
"github.com/docker/docker/opts" "github.com/docker/docker/opts"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestDaemonConfigurationMerge(t *testing.T) { func TestDaemonConfigurationMerge(t *testing.T) {
@@ -46,15 +46,15 @@ func TestDaemonConfigurationMerge(t *testing.T) {
flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "") flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "")
cc, err := MergeDaemonConfigurations(c, flags, configFile) cc, err := MergeDaemonConfigurations(c, flags, configFile)
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, cc.Debug) assert.Check(t, cc.Debug)
assert.True(t, cc.AutoRestart) assert.Check(t, cc.AutoRestart)
expectedLogConfig := LogConfig{ expectedLogConfig := LogConfig{
Type: "syslog", Type: "syslog",
Config: map[string]string{"tag": "test_tag"}, Config: map[string]string{"tag": "test_tag"},
} }
assert.Equal(t, expectedLogConfig, cc.LogConfig) assert.Check(t, is.DeepEqual(expectedLogConfig, cc.LogConfig))
} }

View File

@@ -9,7 +9,7 @@ import (
containertypes "github.com/docker/docker/api/types/container" containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
// TestContainerWarningHostAndPublishPorts that a warning is returned when setting network mode to host and specifying published ports. // TestContainerWarningHostAndPublishPorts that a warning is returned when setting network mode to host and specifying published ports.
@@ -38,7 +38,7 @@ func TestContainerWarningHostAndPublishPorts(t *testing.T) {
} }
d := &Daemon{configStore: cs} d := &Daemon{configStore: cs}
wrns, err := d.verifyContainerSettings("", hostConfig, &containertypes.Config{}, false) wrns, err := d.verifyContainerSettings("", hostConfig, &containertypes.Config{}, false)
require.NoError(t, err) assert.NilError(t, err)
require.Equal(t, tc.warnings, wrns) assert.DeepEqual(t, tc.warnings, wrns)
} }
} }

View File

@@ -5,7 +5,7 @@ import (
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
"github.com/docker/docker/errdefs" "github.com/docker/docker/errdefs"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
) )
// Test case for 35752 // Test case for 35752
@@ -17,5 +17,5 @@ func TestVerifyNetworkingConfig(t *testing.T) {
EndpointsConfig: endpoints, EndpointsConfig: endpoints,
} }
err := verifyNetworkingConfig(nwConfig) err := verifyNetworkingConfig(nwConfig)
assert.True(t, errdefs.IsInvalidParameter(err)) assert.Check(t, errdefs.IsInvalidParameter(err))
} }

View File

@@ -11,8 +11,8 @@ import (
"github.com/docker/docker/oci" "github.com/docker/docker/oci"
"github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/mount"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/assert" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
const mountsFixture = `142 78 0:38 / / rw,relatime - aufs none rw,si=573b861da0b3a05b,dio const mountsFixture = `142 78 0:38 / / rw,relatime - aufs none rw,si=573b861da0b3a05b,dio
@@ -138,7 +138,7 @@ func TestTmpfsDevShmSizeOverride(t *testing.T) {
// convert ms to spec // convert ms to spec
spec := oci.DefaultSpec() spec := oci.DefaultSpec()
err := setMounts(&d, &spec, c, ms) err := setMounts(&d, &spec, c, ms)
assert.NoError(t, err) assert.Check(t, err)
// Check the resulting spec for the correct size // Check the resulting spec for the correct size
found := false found := false
@@ -149,7 +149,7 @@ func TestTmpfsDevShmSizeOverride(t *testing.T) {
continue continue
} }
t.Logf("%+v\n", m.Options) t.Logf("%+v\n", m.Options)
assert.Equal(t, "size="+size, o) assert.Check(t, is.Equal("size="+size, o))
found = true found = true
} }
} }
@@ -163,7 +163,7 @@ func TestValidateContainerIsolationLinux(t *testing.T) {
d := Daemon{} d := Daemon{}
_, err := d.verifyContainerSettings("linux", &containertypes.HostConfig{Isolation: containertypes.IsolationHyperV}, nil, false) _, err := d.verifyContainerSettings("linux", &containertypes.HostConfig{Isolation: containertypes.IsolationHyperV}, nil, false)
assert.EqualError(t, err, "invalid isolation 'hyperv' on linux") assert.Check(t, is.Error(err, "invalid isolation 'hyperv' on linux"))
} }
func TestShouldUnmountRoot(t *testing.T) { func TestShouldUnmountRoot(t *testing.T) {
@@ -222,7 +222,7 @@ func TestShouldUnmountRoot(t *testing.T) {
if test.info != nil { if test.info != nil {
test.info.Optional = options.Optional test.info.Optional = options.Optional
} }
assert.Equal(t, expect, shouldUnmountRoot(test.root, test.info)) assert.Check(t, is.Equal(expect, shouldUnmountRoot(test.root, test.info)))
}) })
} }
}) })

View File

@@ -19,8 +19,9 @@ import (
"github.com/docker/docker/volume/store" "github.com/docker/docker/volume/store"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/docker/libnetwork" "github.com/docker/libnetwork"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert"
) )
// //
@@ -312,7 +313,7 @@ func TestValidateContainerIsolation(t *testing.T) {
d := Daemon{} d := Daemon{}
_, err := d.verifyContainerSettings(runtime.GOOS, &containertypes.HostConfig{Isolation: containertypes.Isolation("invalid")}, nil, false) _, err := d.verifyContainerSettings(runtime.GOOS, &containertypes.HostConfig{Isolation: containertypes.Isolation("invalid")}, nil, false)
assert.EqualError(t, err, "invalid isolation 'invalid' on "+runtime.GOOS) assert.Check(t, is.Error(err, "invalid isolation 'invalid' on "+runtime.GOOS))
} }
func TestFindNetworkErrorType(t *testing.T) { func TestFindNetworkErrorType(t *testing.T) {
@@ -320,6 +321,6 @@ func TestFindNetworkErrorType(t *testing.T) {
_, err := d.FindNetwork("fakeNet") _, err := d.FindNetwork("fakeNet")
_, ok := errors.Cause(err).(libnetwork.ErrNoSuchNetwork) _, ok := errors.Cause(err).(libnetwork.ErrNoSuchNetwork)
if !errdefs.IsNotFound(err) || !ok { if !errdefs.IsNotFound(err) || !ok {
assert.Fail(t, "The FindNetwork method MUST always return an error that implements the NotFound interface and is ErrNoSuchNetwork") t.Error("The FindNetwork method MUST always return an error that implements the NotFound interface and is ErrNoSuchNetwork")
} }
} }

View File

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

View File

@@ -10,12 +10,12 @@ import (
containertypes "github.com/docker/docker/api/types/container" containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container" "github.com/docker/docker/container"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
func newDaemonWithTmpRoot(t *testing.T) (*Daemon, func()) { func newDaemonWithTmpRoot(t *testing.T) (*Daemon, func()) {
tmp, err := ioutil.TempDir("", "docker-daemon-unix-test-") tmp, err := ioutil.TempDir("", "docker-daemon-unix-test-")
require.NoError(t, err) assert.NilError(t, err)
d := &Daemon{ d := &Daemon{
repository: tmp, repository: tmp,
root: tmp, root: tmp,

View File

@@ -5,8 +5,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestDiscoveryOptsErrors(t *testing.T) { func TestDiscoveryOptsErrors(t *testing.T) {
@@ -42,26 +42,26 @@ func TestDiscoveryOptsErrors(t *testing.T) {
for _, testcase := range testcases { for _, testcase := range testcases {
_, _, err := discoveryOpts(testcase.opts) _, _, err := discoveryOpts(testcase.opts)
assert.Error(t, err, testcase.doc) assert.Check(t, is.ErrorContains(err, ""), testcase.doc)
} }
} }
func TestDiscoveryOpts(t *testing.T) { func TestDiscoveryOpts(t *testing.T) {
clusterOpts := map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "20"} clusterOpts := map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "20"}
heartbeat, ttl, err := discoveryOpts(clusterOpts) heartbeat, ttl, err := discoveryOpts(clusterOpts)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, 10*time.Second, heartbeat) assert.Check(t, is.Equal(10*time.Second, heartbeat))
assert.Equal(t, 20*time.Second, ttl) assert.Check(t, is.Equal(20*time.Second, ttl))
clusterOpts = map[string]string{"discovery.heartbeat": "10"} clusterOpts = map[string]string{"discovery.heartbeat": "10"}
heartbeat, ttl, err = discoveryOpts(clusterOpts) heartbeat, ttl, err = discoveryOpts(clusterOpts)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, 10*time.Second, heartbeat) assert.Check(t, is.Equal(10*time.Second, heartbeat))
assert.Equal(t, 10*defaultDiscoveryTTLFactor*time.Second, ttl) assert.Check(t, is.Equal(10*defaultDiscoveryTTLFactor*time.Second, ttl))
clusterOpts = map[string]string{"discovery.ttl": "30"} clusterOpts = map[string]string{"discovery.ttl": "30"}
heartbeat, ttl, err = discoveryOpts(clusterOpts) heartbeat, ttl, err = discoveryOpts(clusterOpts)
require.NoError(t, err) assert.NilError(t, err)
if ttl != 30*time.Second { if ttl != 30*time.Second {
t.Fatalf("TTL - Expected : %v, Actual : %v", 30*time.Second, ttl) t.Fatalf("TTL - Expected : %v, Actual : %v", 30*time.Second, ttl)

View File

@@ -17,8 +17,8 @@ import (
"github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/reexec"
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
var ( var (
@@ -189,7 +189,7 @@ func TestCleanupWithNoDirs(t *testing.T) {
defer os.RemoveAll(tmp) defer os.RemoveAll(tmp)
err := d.Cleanup() err := d.Cleanup()
assert.NoError(t, err) assert.Check(t, err)
} }
func TestCleanupWithDir(t *testing.T) { func TestCleanupWithDir(t *testing.T) {
@@ -210,11 +210,11 @@ func TestMountedFalseResponse(t *testing.T) {
defer os.RemoveAll(tmp) defer os.RemoveAll(tmp)
err := d.Create("1", "", nil) err := d.Create("1", "", nil)
require.NoError(t, err) assert.NilError(t, err)
response, err := d.mounted(d.getDiffPath("1")) response, err := d.mounted(d.getDiffPath("1"))
require.NoError(t, err) assert.NilError(t, err)
assert.False(t, response) assert.Check(t, !response)
} }
func TestMountedTrueResponse(t *testing.T) { func TestMountedTrueResponse(t *testing.T) {
@@ -223,16 +223,16 @@ func TestMountedTrueResponse(t *testing.T) {
defer d.Cleanup() defer d.Cleanup()
err := d.Create("1", "", nil) err := d.Create("1", "", nil)
require.NoError(t, err) assert.NilError(t, err)
err = d.Create("2", "1", nil) err = d.Create("2", "1", nil)
require.NoError(t, err) assert.NilError(t, err)
_, err = d.Get("2", "") _, err = d.Get("2", "")
require.NoError(t, err) assert.NilError(t, err)
response, err := d.mounted(d.pathCache["2"]) response, err := d.mounted(d.pathCache["2"])
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, response) assert.Check(t, response)
} }
func TestMountWithParent(t *testing.T) { func TestMountWithParent(t *testing.T) {
@@ -567,7 +567,7 @@ func TestStatus(t *testing.T) {
} }
status := d.Status() status := d.Status()
assert.Len(t, status, 4) assert.Check(t, is.Len(status, 4))
rootDir := status[0] rootDir := status[0]
dirs := status[2] dirs := status[2]
@@ -670,18 +670,18 @@ func testMountMoreThan42Layers(t *testing.T, mountPath string) {
current = hash(current) current = hash(current)
err := d.CreateReadWrite(current, parent, nil) err := d.CreateReadWrite(current, parent, nil)
require.NoError(t, err, "current layer %d", i) assert.NilError(t, err, "current layer %d", i)
point, err := driverGet(d, current, "") point, err := driverGet(d, current, "")
require.NoError(t, err, "current layer %d", i) assert.NilError(t, err, "current layer %d", i)
f, err := os.Create(path.Join(point, current)) f, err := os.Create(path.Join(point, current))
require.NoError(t, err, "current layer %d", i) assert.NilError(t, err, "current layer %d", i)
f.Close() f.Close()
if i%10 == 0 { if i%10 == 0 {
err := os.Remove(path.Join(point, parent)) err := os.Remove(path.Join(point, parent))
require.NoError(t, err, "current layer %d", i) assert.NilError(t, err, "current layer %d", i)
expected-- expected--
} }
last = current last = current
@@ -689,10 +689,10 @@ func testMountMoreThan42Layers(t *testing.T, mountPath string) {
// Perform the actual mount for the top most image // Perform the actual mount for the top most image
point, err := driverGet(d, last, "") point, err := driverGet(d, last, "")
require.NoError(t, err) assert.NilError(t, err)
files, err := ioutil.ReadDir(point) files, err := ioutil.ReadDir(point)
require.NoError(t, err) assert.NilError(t, err)
assert.Len(t, files, expected) assert.Check(t, is.Len(files, expected))
} }
func TestMountMoreThan42Layers(t *testing.T) { func TestMountMoreThan42Layers(t *testing.T) {

View File

@@ -14,8 +14,8 @@ import (
"github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/parsers/kernel"
"github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/system"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@@ -24,16 +24,16 @@ func TestIsCopyFileRangeSyscallAvailable(t *testing.T) {
// 1. That copyFileRangeEnabled is being set to true when copy_file_range syscall is available // 1. That copyFileRangeEnabled is being set to true when copy_file_range syscall is available
// 2. That isCopyFileRangeSyscallAvailable() works on "new" kernels // 2. That isCopyFileRangeSyscallAvailable() works on "new" kernels
v, err := kernel.GetKernelVersion() v, err := kernel.GetKernelVersion()
require.NoError(t, err) assert.NilError(t, err)
copyWithFileRange := true copyWithFileRange := true
copyWithFileClone := false copyWithFileClone := false
doCopyTest(t, &copyWithFileRange, &copyWithFileClone) doCopyTest(t, &copyWithFileRange, &copyWithFileClone)
if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 5, Minor: 0}) < 0 { if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 5, Minor: 0}) < 0 {
assert.False(t, copyWithFileRange) assert.Check(t, !copyWithFileRange)
} else { } else {
assert.True(t, copyWithFileRange) assert.Check(t, copyWithFileRange)
} }
} }
@@ -52,47 +52,47 @@ func TestCopyWithoutRange(t *testing.T) {
func TestCopyDir(t *testing.T) { func TestCopyDir(t *testing.T) {
srcDir, err := ioutil.TempDir("", "srcDir") srcDir, err := ioutil.TempDir("", "srcDir")
require.NoError(t, err) assert.NilError(t, err)
populateSrcDir(t, srcDir, 3) populateSrcDir(t, srcDir, 3)
dstDir, err := ioutil.TempDir("", "testdst") dstDir, err := ioutil.TempDir("", "testdst")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(dstDir) defer os.RemoveAll(dstDir)
assert.NoError(t, DirCopy(srcDir, dstDir, Content, false)) assert.Check(t, DirCopy(srcDir, dstDir, Content, false))
require.NoError(t, filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error { assert.NilError(t, filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error {
if err != nil { if err != nil {
return err return err
} }
// Rebase path // Rebase path
relPath, err := filepath.Rel(srcDir, srcPath) relPath, err := filepath.Rel(srcDir, srcPath)
require.NoError(t, err) assert.NilError(t, err)
if relPath == "." { if relPath == "." {
return nil return nil
} }
dstPath := filepath.Join(dstDir, relPath) dstPath := filepath.Join(dstDir, relPath)
require.NoError(t, err) assert.NilError(t, err)
// If we add non-regular dirs and files to the test // If we add non-regular dirs and files to the test
// then we need to add more checks here. // then we need to add more checks here.
dstFileInfo, err := os.Lstat(dstPath) dstFileInfo, err := os.Lstat(dstPath)
require.NoError(t, err) assert.NilError(t, err)
srcFileSys := f.Sys().(*syscall.Stat_t) srcFileSys := f.Sys().(*syscall.Stat_t)
dstFileSys := dstFileInfo.Sys().(*syscall.Stat_t) dstFileSys := dstFileInfo.Sys().(*syscall.Stat_t)
t.Log(relPath) t.Log(relPath)
if srcFileSys.Dev == dstFileSys.Dev { if srcFileSys.Dev == dstFileSys.Dev {
assert.NotEqual(t, srcFileSys.Ino, dstFileSys.Ino) assert.Check(t, srcFileSys.Ino != dstFileSys.Ino)
} }
// Todo: check size, and ctim is not equal // Todo: check size, and ctim is not equal
/// on filesystems that have granular ctimes /// on filesystems that have granular ctimes
assert.Equal(t, srcFileSys.Mode, dstFileSys.Mode) assert.Check(t, is.DeepEqual(srcFileSys.Mode, dstFileSys.Mode))
assert.Equal(t, srcFileSys.Uid, dstFileSys.Uid) assert.Check(t, is.DeepEqual(srcFileSys.Uid, dstFileSys.Uid))
assert.Equal(t, srcFileSys.Gid, dstFileSys.Gid) assert.Check(t, is.DeepEqual(srcFileSys.Gid, dstFileSys.Gid))
assert.Equal(t, srcFileSys.Mtim, dstFileSys.Mtim) assert.Check(t, is.DeepEqual(srcFileSys.Mtim, dstFileSys.Mtim))
return nil return nil
})) }))
@@ -115,22 +115,22 @@ func populateSrcDir(t *testing.T, srcDir string, remainingDepth int) {
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
dirName := filepath.Join(srcDir, fmt.Sprintf("srcdir-%d", i)) dirName := filepath.Join(srcDir, fmt.Sprintf("srcdir-%d", i))
// Owner all bits set // Owner all bits set
require.NoError(t, os.Mkdir(dirName, randomMode(0700))) assert.NilError(t, os.Mkdir(dirName, randomMode(0700)))
populateSrcDir(t, dirName, remainingDepth-1) populateSrcDir(t, dirName, remainingDepth-1)
require.NoError(t, system.Chtimes(dirName, aTime, mTime)) assert.NilError(t, system.Chtimes(dirName, aTime, mTime))
} }
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
fileName := filepath.Join(srcDir, fmt.Sprintf("srcfile-%d", i)) fileName := filepath.Join(srcDir, fmt.Sprintf("srcfile-%d", i))
// Owner read bit set // Owner read bit set
require.NoError(t, ioutil.WriteFile(fileName, []byte{}, randomMode(0400))) assert.NilError(t, ioutil.WriteFile(fileName, []byte{}, randomMode(0400)))
require.NoError(t, system.Chtimes(fileName, aTime, mTime)) assert.NilError(t, system.Chtimes(fileName, aTime, mTime))
} }
} }
func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) { func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) {
dir, err := ioutil.TempDir("", "docker-copy-check") dir, err := ioutil.TempDir("", "docker-copy-check")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
srcFilename := filepath.Join(dir, "srcFilename") srcFilename := filepath.Join(dir, "srcFilename")
dstFilename := filepath.Join(dir, "dstilename") dstFilename := filepath.Join(dir, "dstilename")
@@ -138,42 +138,42 @@ func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) {
r := rand.New(rand.NewSource(0)) r := rand.New(rand.NewSource(0))
buf := make([]byte, 1024) buf := make([]byte, 1024)
_, err = r.Read(buf) _, err = r.Read(buf)
require.NoError(t, err) assert.NilError(t, err)
require.NoError(t, ioutil.WriteFile(srcFilename, buf, 0777)) assert.NilError(t, ioutil.WriteFile(srcFilename, buf, 0777))
fileinfo, err := os.Stat(srcFilename) fileinfo, err := os.Stat(srcFilename)
require.NoError(t, err) assert.NilError(t, err)
require.NoError(t, copyRegular(srcFilename, dstFilename, fileinfo, copyWithFileRange, copyWithFileClone)) assert.NilError(t, copyRegular(srcFilename, dstFilename, fileinfo, copyWithFileRange, copyWithFileClone))
readBuf, err := ioutil.ReadFile(dstFilename) readBuf, err := ioutil.ReadFile(dstFilename)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, buf, readBuf) assert.Check(t, is.DeepEqual(buf, readBuf))
} }
func TestCopyHardlink(t *testing.T) { func TestCopyHardlink(t *testing.T) {
var srcFile1FileInfo, srcFile2FileInfo, dstFile1FileInfo, dstFile2FileInfo unix.Stat_t var srcFile1FileInfo, srcFile2FileInfo, dstFile1FileInfo, dstFile2FileInfo unix.Stat_t
srcDir, err := ioutil.TempDir("", "srcDir") srcDir, err := ioutil.TempDir("", "srcDir")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(srcDir) defer os.RemoveAll(srcDir)
dstDir, err := ioutil.TempDir("", "dstDir") dstDir, err := ioutil.TempDir("", "dstDir")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(dstDir) defer os.RemoveAll(dstDir)
srcFile1 := filepath.Join(srcDir, "file1") srcFile1 := filepath.Join(srcDir, "file1")
srcFile2 := filepath.Join(srcDir, "file2") srcFile2 := filepath.Join(srcDir, "file2")
dstFile1 := filepath.Join(dstDir, "file1") dstFile1 := filepath.Join(dstDir, "file1")
dstFile2 := filepath.Join(dstDir, "file2") dstFile2 := filepath.Join(dstDir, "file2")
require.NoError(t, ioutil.WriteFile(srcFile1, []byte{}, 0777)) assert.NilError(t, ioutil.WriteFile(srcFile1, []byte{}, 0777))
require.NoError(t, os.Link(srcFile1, srcFile2)) assert.NilError(t, os.Link(srcFile1, srcFile2))
assert.NoError(t, DirCopy(srcDir, dstDir, Content, false)) assert.Check(t, DirCopy(srcDir, dstDir, Content, false))
require.NoError(t, unix.Stat(srcFile1, &srcFile1FileInfo)) assert.NilError(t, unix.Stat(srcFile1, &srcFile1FileInfo))
require.NoError(t, unix.Stat(srcFile2, &srcFile2FileInfo)) assert.NilError(t, unix.Stat(srcFile2, &srcFile2FileInfo))
require.Equal(t, srcFile1FileInfo.Ino, srcFile2FileInfo.Ino) assert.Equal(t, srcFile1FileInfo.Ino, srcFile2FileInfo.Ino)
require.NoError(t, unix.Stat(dstFile1, &dstFile1FileInfo)) assert.NilError(t, unix.Stat(dstFile1, &dstFile1FileInfo))
require.NoError(t, unix.Stat(dstFile2, &dstFile2FileInfo)) assert.NilError(t, unix.Stat(dstFile2, &dstFile2FileInfo))
assert.Equal(t, dstFile1FileInfo.Ino, dstFile2FileInfo.Ino) assert.Check(t, is.Equal(dstFile1FileInfo.Ino, dstFile2FileInfo.Ino))
} }

View File

@@ -6,32 +6,31 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require"
) )
func TestIsEmptyDir(t *testing.T) { func TestIsEmptyDir(t *testing.T) {
tmp, err := ioutil.TempDir("", "test-is-empty-dir") tmp, err := ioutil.TempDir("", "test-is-empty-dir")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(tmp) defer os.RemoveAll(tmp)
d := filepath.Join(tmp, "empty-dir") d := filepath.Join(tmp, "empty-dir")
err = os.Mkdir(d, 0755) err = os.Mkdir(d, 0755)
require.NoError(t, err) assert.NilError(t, err)
empty := isEmptyDir(d) empty := isEmptyDir(d)
assert.True(t, empty) assert.Check(t, empty)
d = filepath.Join(tmp, "dir-with-subdir") d = filepath.Join(tmp, "dir-with-subdir")
err = os.MkdirAll(filepath.Join(d, "subdir"), 0755) err = os.MkdirAll(filepath.Join(d, "subdir"), 0755)
require.NoError(t, err) assert.NilError(t, err)
empty = isEmptyDir(d) empty = isEmptyDir(d)
assert.False(t, empty) assert.Check(t, !empty)
d = filepath.Join(tmp, "dir-with-empty-file") d = filepath.Join(tmp, "dir-with-empty-file")
err = os.Mkdir(d, 0755) err = os.Mkdir(d, 0755)
require.NoError(t, err) assert.NilError(t, err)
_, err = ioutil.TempFile(d, "file") _, err = ioutil.TempFile(d, "file")
require.NoError(t, err) assert.NilError(t, err)
empty = isEmptyDir(d) empty = isEmptyDir(d)
assert.False(t, empty) assert.Check(t, !empty)
} }

View File

@@ -9,7 +9,7 @@ import (
contdriver "github.com/containerd/continuity/driver" contdriver "github.com/containerd/continuity/driver"
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
// DriverBenchExists benchmarks calls to exist // DriverBenchExists benchmarks calls to exist
@@ -251,7 +251,7 @@ func DriverBenchDeepLayerRead(b *testing.B, layerCount int, drivername string, d
} }
b.StopTimer() b.StopTimer()
require.Equal(b, content, c) assert.DeepEqual(b, content, c)
b.StartTimer() b.StartTimer()
} }
} }

View File

@@ -16,8 +16,8 @@ import (
"github.com/docker/docker/daemon/graphdriver/quota" "github.com/docker/docker/daemon/graphdriver/quota"
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
"github.com/docker/go-units" "github.com/docker/go-units"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@@ -36,9 +36,9 @@ type Driver struct {
func newDriver(t testing.TB, name string, options []string) *Driver { func newDriver(t testing.TB, name string, options []string) *Driver {
root, err := ioutil.TempDir("", "docker-graphtest-") root, err := ioutil.TempDir("", "docker-graphtest-")
require.NoError(t, err) assert.NilError(t, err)
require.NoError(t, os.MkdirAll(root, 0755)) assert.NilError(t, os.MkdirAll(root, 0755))
d, err := graphdriver.GetDriver(name, nil, graphdriver.Options{DriverOptions: options, Root: root}) d, err := graphdriver.GetDriver(name, nil, graphdriver.Options{DriverOptions: options, Root: root})
if err != nil { if err != nil {
t.Logf("graphdriver: %v\n", err) t.Logf("graphdriver: %v\n", err)
@@ -85,10 +85,10 @@ func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...str
defer PutDriver(t) defer PutDriver(t)
err := driver.Create("empty", "", nil) err := driver.Create("empty", "", nil)
require.NoError(t, err) assert.NilError(t, err)
defer func() { defer func() {
require.NoError(t, driver.Remove("empty")) assert.NilError(t, driver.Remove("empty"))
}() }()
if !driver.Exists("empty") { if !driver.Exists("empty") {
@@ -96,14 +96,14 @@ func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...str
} }
dir, err := driver.Get("empty", "") dir, err := driver.Get("empty", "")
require.NoError(t, err) assert.NilError(t, err)
verifyFile(t, dir.Path(), 0755|os.ModeDir, 0, 0) verifyFile(t, dir.Path(), 0755|os.ModeDir, 0, 0)
// Verify that the directory is empty // Verify that the directory is empty
fis, err := readDir(dir, dir.Path()) fis, err := readDir(dir, dir.Path())
require.NoError(t, err) assert.NilError(t, err)
assert.Len(t, fis, 0) assert.Check(t, is.Len(fis, 0))
driver.Put("empty") driver.Put("empty")
} }
@@ -115,7 +115,7 @@ func DriverTestCreateBase(t testing.TB, drivername string, driverOptions ...stri
createBase(t, driver, "Base") createBase(t, driver, "Base")
defer func() { defer func() {
require.NoError(t, driver.Remove("Base")) assert.NilError(t, driver.Remove("Base"))
}() }()
verifyBase(t, driver, "Base") verifyBase(t, driver, "Base")
} }
@@ -127,13 +127,13 @@ func DriverTestCreateSnap(t testing.TB, drivername string, driverOptions ...stri
createBase(t, driver, "Base") createBase(t, driver, "Base")
defer func() { defer func() {
require.NoError(t, driver.Remove("Base")) assert.NilError(t, driver.Remove("Base"))
}() }()
err := driver.Create("Snap", "Base", nil) err := driver.Create("Snap", "Base", nil)
require.NoError(t, err) assert.NilError(t, err)
defer func() { defer func() {
require.NoError(t, driver.Remove("Snap")) assert.NilError(t, driver.Remove("Snap"))
}() }()
verifyBase(t, driver, "Snap") verifyBase(t, driver, "Snap")

View File

@@ -9,25 +9,25 @@ import (
contdriver "github.com/containerd/continuity/driver" contdriver "github.com/containerd/continuity/driver"
"github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/daemon/graphdriver"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
func verifyFile(t testing.TB, path string, mode os.FileMode, uid, gid uint32) { func verifyFile(t testing.TB, path string, mode os.FileMode, uid, gid uint32) {
fi, err := os.Stat(path) fi, err := os.Stat(path)
require.NoError(t, err) assert.NilError(t, err)
actual := fi.Mode() actual := fi.Mode()
assert.Equal(t, mode&os.ModeType, actual&os.ModeType, path) assert.Check(t, is.Equal(mode&os.ModeType, actual&os.ModeType), path)
assert.Equal(t, mode&os.ModePerm, actual&os.ModePerm, path) assert.Check(t, is.Equal(mode&os.ModePerm, actual&os.ModePerm), path)
assert.Equal(t, mode&os.ModeSticky, actual&os.ModeSticky, path) assert.Check(t, is.Equal(mode&os.ModeSticky, actual&os.ModeSticky), path)
assert.Equal(t, mode&os.ModeSetuid, actual&os.ModeSetuid, path) assert.Check(t, is.Equal(mode&os.ModeSetuid, actual&os.ModeSetuid), path)
assert.Equal(t, mode&os.ModeSetgid, actual&os.ModeSetgid, path) assert.Check(t, is.Equal(mode&os.ModeSetgid, actual&os.ModeSetgid), path)
if stat, ok := fi.Sys().(*syscall.Stat_t); ok { if stat, ok := fi.Sys().(*syscall.Stat_t); ok {
assert.Equal(t, uid, stat.Uid, path) assert.Check(t, is.Equal(uid, stat.Uid), path)
assert.Equal(t, gid, stat.Gid, path) assert.Check(t, is.Equal(gid, stat.Gid), path)
} }
} }
@@ -37,24 +37,24 @@ func createBase(t testing.TB, driver graphdriver.Driver, name string) {
defer unix.Umask(oldmask) defer unix.Umask(oldmask)
err := driver.CreateReadWrite(name, "", nil) err := driver.CreateReadWrite(name, "", nil)
require.NoError(t, err) assert.NilError(t, err)
dirFS, err := driver.Get(name, "") dirFS, err := driver.Get(name, "")
require.NoError(t, err) assert.NilError(t, err)
defer driver.Put(name) defer driver.Put(name)
subdir := dirFS.Join(dirFS.Path(), "a subdir") subdir := dirFS.Join(dirFS.Path(), "a subdir")
require.NoError(t, dirFS.Mkdir(subdir, 0705|os.ModeSticky)) assert.NilError(t, dirFS.Mkdir(subdir, 0705|os.ModeSticky))
require.NoError(t, dirFS.Lchown(subdir, 1, 2)) assert.NilError(t, dirFS.Lchown(subdir, 1, 2))
file := dirFS.Join(dirFS.Path(), "a file") file := dirFS.Join(dirFS.Path(), "a file")
err = contdriver.WriteFile(dirFS, file, []byte("Some data"), 0222|os.ModeSetuid) err = contdriver.WriteFile(dirFS, file, []byte("Some data"), 0222|os.ModeSetuid)
require.NoError(t, err) assert.NilError(t, err)
} }
func verifyBase(t testing.TB, driver graphdriver.Driver, name string) { func verifyBase(t testing.TB, driver graphdriver.Driver, name string) {
dirFS, err := driver.Get(name, "") dirFS, err := driver.Get(name, "")
require.NoError(t, err) assert.NilError(t, err)
defer driver.Put(name) defer driver.Put(name)
subdir := dirFS.Join(dirFS.Path(), "a subdir") subdir := dirFS.Join(dirFS.Path(), "a subdir")
@@ -64,6 +64,6 @@ func verifyBase(t testing.TB, driver graphdriver.Driver, name string) {
verifyFile(t, file, 0222|os.ModeSetuid, 0, 0) verifyFile(t, file, 0222|os.ModeSetuid, 0, 0)
files, err := readDir(dirFS, dirFS.Path()) files, err := readDir(dirFS, dirFS.Path())
require.NoError(t, err) assert.NilError(t, err)
assert.Len(t, files, 2) assert.Check(t, is.Len(files, 2))
} }

View File

@@ -10,9 +10,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@@ -80,14 +80,14 @@ func wrapMountTest(imageFileName string, enableQuota bool, testFunc func(t *test
} }
} }
require.NoError(t, err, "mount failed: %s", out) assert.NilError(t, err, "mount failed: %s", out)
defer func() { defer func() {
require.NoError(t, unix.Unmount(mountPoint, 0)) assert.NilError(t, unix.Unmount(mountPoint, 0))
}() }()
backingFsDev, err := makeBackingFsDev(mountPoint) backingFsDev, err := makeBackingFsDev(mountPoint)
require.NoError(t, err) assert.NilError(t, err)
testFunc(t, mountPoint, backingFsDev) testFunc(t, mountPoint, backingFsDev)
} }
@@ -95,58 +95,58 @@ func wrapMountTest(imageFileName string, enableQuota bool, testFunc func(t *test
func testBlockDevQuotaDisabled(t *testing.T, mountPoint, backingFsDev string) { func testBlockDevQuotaDisabled(t *testing.T, mountPoint, backingFsDev string) {
hasSupport, err := hasQuotaSupport(backingFsDev) hasSupport, err := hasQuotaSupport(backingFsDev)
require.NoError(t, err) assert.NilError(t, err)
assert.False(t, hasSupport) assert.Check(t, !hasSupport)
} }
func testBlockDevQuotaEnabled(t *testing.T, mountPoint, backingFsDev string) { func testBlockDevQuotaEnabled(t *testing.T, mountPoint, backingFsDev string) {
hasSupport, err := hasQuotaSupport(backingFsDev) hasSupport, err := hasQuotaSupport(backingFsDev)
require.NoError(t, err) assert.NilError(t, err)
assert.True(t, hasSupport) assert.Check(t, hasSupport)
} }
func wrapQuotaTest(testFunc func(t *testing.T, ctrl *Control, mountPoint, testDir, testSubDir string)) func(t *testing.T, mountPoint, backingFsDev string) { func wrapQuotaTest(testFunc func(t *testing.T, ctrl *Control, mountPoint, testDir, testSubDir string)) func(t *testing.T, mountPoint, backingFsDev string) {
return func(t *testing.T, mountPoint, backingFsDev string) { return func(t *testing.T, mountPoint, backingFsDev string) {
testDir, err := ioutil.TempDir(mountPoint, "per-test") testDir, err := ioutil.TempDir(mountPoint, "per-test")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(testDir) defer os.RemoveAll(testDir)
ctrl, err := NewControl(testDir) ctrl, err := NewControl(testDir)
require.NoError(t, err) assert.NilError(t, err)
testSubDir, err := ioutil.TempDir(testDir, "quota-test") testSubDir, err := ioutil.TempDir(testDir, "quota-test")
require.NoError(t, err) assert.NilError(t, err)
testFunc(t, ctrl, mountPoint, testDir, testSubDir) testFunc(t, ctrl, mountPoint, testDir, testSubDir)
} }
} }
func testSmallerThanQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) { func testSmallerThanQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) {
require.NoError(t, ctrl.SetQuota(testSubDir, Quota{testQuotaSize})) assert.NilError(t, ctrl.SetQuota(testSubDir, Quota{testQuotaSize}))
smallerThanQuotaFile := filepath.Join(testSubDir, "smaller-than-quota") smallerThanQuotaFile := filepath.Join(testSubDir, "smaller-than-quota")
require.NoError(t, ioutil.WriteFile(smallerThanQuotaFile, make([]byte, testQuotaSize/2), 0644)) assert.NilError(t, ioutil.WriteFile(smallerThanQuotaFile, make([]byte, testQuotaSize/2), 0644))
require.NoError(t, os.Remove(smallerThanQuotaFile)) assert.NilError(t, os.Remove(smallerThanQuotaFile))
} }
func testBiggerThanQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) { func testBiggerThanQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) {
// Make sure the quota is being enforced // Make sure the quota is being enforced
// TODO: When we implement this under EXT4, we need to shed CAP_SYS_RESOURCE, otherwise // TODO: When we implement this under EXT4, we need to shed CAP_SYS_RESOURCE, otherwise
// we're able to violate quota without issue // we're able to violate quota without issue
require.NoError(t, ctrl.SetQuota(testSubDir, Quota{testQuotaSize})) assert.NilError(t, ctrl.SetQuota(testSubDir, Quota{testQuotaSize}))
biggerThanQuotaFile := filepath.Join(testSubDir, "bigger-than-quota") biggerThanQuotaFile := filepath.Join(testSubDir, "bigger-than-quota")
err := ioutil.WriteFile(biggerThanQuotaFile, make([]byte, testQuotaSize+1), 0644) err := ioutil.WriteFile(biggerThanQuotaFile, make([]byte, testQuotaSize+1), 0644)
require.Error(t, err) assert.Assert(t, is.ErrorContains(err, ""))
if err == io.ErrShortWrite { if err == io.ErrShortWrite {
require.NoError(t, os.Remove(biggerThanQuotaFile)) assert.NilError(t, os.Remove(biggerThanQuotaFile))
} }
} }
func testRetrieveQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) { func testRetrieveQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) {
// Validate that we can retrieve quota // Validate that we can retrieve quota
require.NoError(t, ctrl.SetQuota(testSubDir, Quota{testQuotaSize})) assert.NilError(t, ctrl.SetQuota(testSubDir, Quota{testQuotaSize}))
var q Quota var q Quota
require.NoError(t, ctrl.GetQuota(testSubDir, &q)) assert.NilError(t, ctrl.GetQuota(testSubDir, &q))
assert.EqualValues(t, testQuotaSize, q.Size) assert.Check(t, is.Equal(testQuotaSize, q.Size))
} }

View File

@@ -7,7 +7,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestParseInitVersion(t *testing.T) { func TestParseInitVersion(t *testing.T) {
@@ -43,10 +44,10 @@ func TestParseInitVersion(t *testing.T) {
for _, test := range tests { for _, test := range tests {
ver, err := parseInitVersion(string(test.version)) ver, err := parseInitVersion(string(test.version))
if test.invalid { if test.invalid {
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
} else { } else {
assert.NoError(t, err) assert.Check(t, err)
} }
assert.Equal(t, test.result, ver) assert.Check(t, is.DeepEqual(test.result, ver))
} }
} }

View File

@@ -7,8 +7,8 @@ import (
"github.com/docker/docker/container" "github.com/docker/docker/container"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/docker/docker/daemon/exec" "github.com/docker/docker/daemon/exec"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/assert" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestGetInspectData(t *testing.T) { func TestGetInspectData(t *testing.T) {
@@ -25,9 +25,9 @@ func TestGetInspectData(t *testing.T) {
} }
_, err := d.getInspectData(c) _, err := d.getInspectData(c)
assert.Error(t, err) assert.Check(t, is.ErrorContains(err, ""))
c.Dead = true c.Dead = true
_, err = d.getInspectData(c) _, err = d.getInspectData(c)
assert.NoError(t, err) assert.Check(t, err)
} }

View File

@@ -10,7 +10,8 @@ import (
"github.com/docker/docker/api/types/plugins/logdriver" "github.com/docker/docker/api/types/plugins/logdriver"
protoio "github.com/gogo/protobuf/io" protoio "github.com/gogo/protobuf/io"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
// mockLoggingPlugin implements the loggingPlugin interface for testing purposes // mockLoggingPlugin implements the loggingPlugin interface for testing purposes
@@ -88,7 +89,7 @@ func (l *mockLoggingPlugin) ReadLogs(info Info, config ReadConfig) (io.ReadClose
func newMockPluginAdapter(t *testing.T) Logger { func newMockPluginAdapter(t *testing.T) Logger {
r, w := io.Pipe() r, w := io.Pipe()
f, err := ioutil.TempFile("", "mock-plugin-adapter") f, err := ioutil.TempFile("", "mock-plugin-adapter")
assert.NoError(t, err) assert.Check(t, err)
enc := logdriver.NewLogEntryEncoder(w) enc := logdriver.NewLogEntryEncoder(w)
a := &pluginAdapterWithRead{ a := &pluginAdapterWithRead{
@@ -116,11 +117,11 @@ func TestAdapterReadLogs(t *testing.T) {
} }
for _, msg := range testMsg { for _, msg := range testMsg {
m := msg.copy() m := msg.copy()
assert.NoError(t, l.Log(m)) assert.Check(t, l.Log(m))
} }
lr, ok := l.(LogReader) lr, ok := l.(LogReader)
assert.NotNil(t, ok) assert.Check(t, ok != nil)
lw := lr.ReadLogs(ReadConfig{}) lw := lr.ReadLogs(ReadConfig{})
@@ -135,7 +136,7 @@ func TestAdapterReadLogs(t *testing.T) {
select { select {
case _, ok := <-lw.Msg: case _, ok := <-lw.Msg:
assert.False(t, ok, "expected message channel to be closed") assert.Check(t, !ok, "expected message channel to be closed")
case <-time.After(10 * time.Second): case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for message channel to close") t.Fatal("timeout waiting for message channel to close")
@@ -153,11 +154,11 @@ func TestAdapterReadLogs(t *testing.T) {
} }
x := Message{Line: []byte("Too infinity and beyond!"), Timestamp: time.Now()} x := Message{Line: []byte("Too infinity and beyond!"), Timestamp: time.Now()}
assert.NoError(t, l.Log(x.copy())) assert.Check(t, l.Log(x.copy()))
select { select {
case msg, ok := <-lw.Msg: case msg, ok := <-lw.Msg:
assert.NotNil(t, ok, "message channel unexpectedly closed") assert.Check(t, ok != nil, "message channel unexpectedly closed")
testMessageEqual(t, &x, msg) testMessageEqual(t, &x, msg)
case <-time.After(10 * time.Second): case <-time.After(10 * time.Second):
t.Fatal("timeout reading logs") t.Fatal("timeout reading logs")
@@ -166,15 +167,15 @@ func TestAdapterReadLogs(t *testing.T) {
l.Close() l.Close()
select { select {
case msg, ok := <-lw.Msg: case msg, ok := <-lw.Msg:
assert.False(t, ok, "expected message channel to be closed") assert.Check(t, !ok, "expected message channel to be closed")
assert.Nil(t, msg) assert.Check(t, is.Nil(msg))
case <-time.After(10 * time.Second): case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for logger to close") t.Fatal("timeout waiting for logger to close")
} }
} }
func testMessageEqual(t *testing.T, a, b *Message) { func testMessageEqual(t *testing.T, a, b *Message) {
assert.Equal(t, a.Line, b.Line) assert.Check(t, is.DeepEqual(a.Line, b.Line))
assert.Equal(t, a.Timestamp.UnixNano(), b.Timestamp.UnixNano()) assert.Check(t, is.DeepEqual(a.Timestamp.UnixNano(), b.Timestamp.UnixNano()))
assert.Equal(t, a.Source, b.Source) assert.Check(t, is.Equal(a.Source, b.Source))
} }

View File

@@ -21,7 +21,8 @@ import (
"github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger"
"github.com/docker/docker/daemon/logger/loggerutils" "github.com/docker/docker/daemon/logger/loggerutils"
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
const ( const (
@@ -544,17 +545,17 @@ func TestCollectBatchMultilinePattern(t *testing.T) {
// Verify single multiline event // Verify single multiline event
argument := <-mockClient.putLogEventsArgument argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput") assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 1, len(argument.LogEvents), "Expected single multiline event") assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Equal(t, logline+"\n"+logline+"\n", *argument.LogEvents[0].Message, "Received incorrect multiline message") assert.Check(t, is.Equal(logline+"\n"+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
stream.Close() stream.Close()
// Verify single event // Verify single event
argument = <-mockClient.putLogEventsArgument argument = <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput") assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 1, len(argument.LogEvents), "Expected single multiline event") assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Equal(t, "xxxx "+logline+"\n", *argument.LogEvents[0].Message, "Received incorrect multiline message") assert.Check(t, is.Equal("xxxx "+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
} }
func BenchmarkCollectBatch(b *testing.B) { func BenchmarkCollectBatch(b *testing.B) {
@@ -657,9 +658,9 @@ func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) {
// Verify single multiline event is flushed after maximum event buffer age (batchPublishFrequency) // Verify single multiline event is flushed after maximum event buffer age (batchPublishFrequency)
argument := <-mockClient.putLogEventsArgument argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput") assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 1, len(argument.LogEvents), "Expected single multiline event") assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Equal(t, logline+"\n"+logline+"\n", *argument.LogEvents[0].Message, "Received incorrect multiline message") assert.Check(t, is.Equal(logline+"\n"+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
// Log an event 1 second later // Log an event 1 second later
stream.Log(&logger.Message{ stream.Log(&logger.Message{
@@ -672,9 +673,9 @@ func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) {
// Verify the event buffer is truly flushed - we should only receive a single event // Verify the event buffer is truly flushed - we should only receive a single event
argument = <-mockClient.putLogEventsArgument argument = <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput") assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 1, len(argument.LogEvents), "Expected single multiline event") assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Equal(t, logline+"\n", *argument.LogEvents[0].Message, "Received incorrect multiline message") assert.Check(t, is.Equal(logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
stream.Close() stream.Close()
} }
@@ -719,9 +720,9 @@ func TestCollectBatchMultilinePatternNegativeEventAge(t *testing.T) {
// Verify single multiline event is flushed with a negative event buffer age // Verify single multiline event is flushed with a negative event buffer age
argument := <-mockClient.putLogEventsArgument argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput") assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 1, len(argument.LogEvents), "Expected single multiline event") assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Equal(t, logline+"\n"+logline+"\n", *argument.LogEvents[0].Message, "Received incorrect multiline message") assert.Check(t, is.Equal(logline+"\n"+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
stream.Close() stream.Close()
} }
@@ -772,10 +773,10 @@ func TestCollectBatchMultilinePatternMaxEventSize(t *testing.T) {
// We expect a maximum sized event with no new line characters and a // We expect a maximum sized event with no new line characters and a
// second short event with a new line character at the end // second short event with a new line character at the end
argument := <-mockClient.putLogEventsArgument argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput") assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 2, len(argument.LogEvents), "Expected two events") assert.Check(t, is.Equal(2, len(argument.LogEvents)), "Expected two events")
assert.Equal(t, longline, *argument.LogEvents[0].Message, "Received incorrect multiline message") assert.Check(t, is.Equal(longline, *argument.LogEvents[0].Message), "Received incorrect multiline message")
assert.Equal(t, shortline+"\n", *argument.LogEvents[1].Message, "Received incorrect multiline message") assert.Check(t, is.Equal(shortline+"\n", *argument.LogEvents[1].Message), "Received incorrect multiline message")
stream.Close() stream.Close()
} }
@@ -1069,8 +1070,8 @@ func TestParseLogOptionsMultilinePattern(t *testing.T) {
} }
multilinePattern, err := parseMultilineOptions(info) multilinePattern, err := parseMultilineOptions(info)
assert.Nil(t, err, "Received unexpected error") assert.Check(t, err, "Received unexpected error")
assert.True(t, multilinePattern.MatchString("xxxx"), "No multiline pattern match found") assert.Check(t, multilinePattern.MatchString("xxxx"), "No multiline pattern match found")
} }
func TestParseLogOptionsDatetimeFormat(t *testing.T) { func TestParseLogOptionsDatetimeFormat(t *testing.T) {
@@ -1094,8 +1095,8 @@ func TestParseLogOptionsDatetimeFormat(t *testing.T) {
}, },
} }
multilinePattern, err := parseMultilineOptions(info) multilinePattern, err := parseMultilineOptions(info)
assert.Nil(t, err, "Received unexpected error") assert.Check(t, err, "Received unexpected error")
assert.True(t, multilinePattern.MatchString(dt.match), "No multiline pattern match found") assert.Check(t, multilinePattern.MatchString(dt.match), "No multiline pattern match found")
}) })
} }
} }
@@ -1109,8 +1110,8 @@ func TestValidateLogOptionsDatetimeFormatAndMultilinePattern(t *testing.T) {
conflictingLogOptionsError := "you cannot configure log opt 'awslogs-datetime-format' and 'awslogs-multiline-pattern' at the same time" conflictingLogOptionsError := "you cannot configure log opt 'awslogs-datetime-format' and 'awslogs-multiline-pattern' at the same time"
err := ValidateLogOpt(cfg) err := ValidateLogOpt(cfg)
assert.NotNil(t, err, "Expected an error") assert.Check(t, err != nil, "Expected an error")
assert.Equal(t, err.Error(), conflictingLogOptionsError, "Received invalid error") assert.Check(t, is.Equal(err.Error(), conflictingLogOptionsError), "Received invalid error")
} }
func TestCreateTagSuccess(t *testing.T) { func TestCreateTagSuccess(t *testing.T) {
@@ -1155,7 +1156,7 @@ func BenchmarkUnwrapEvents(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
res := unwrapEvents(events) res := unwrapEvents(events)
assert.Len(b, res, maximumLogEventsPerPut) assert.Check(b, is.Len(res, maximumLogEventsPerPut))
} }
} }
@@ -1188,15 +1189,15 @@ func TestNewAWSLogsClientCredentialEndpointDetect(t *testing.T) {
info.Config["awslogs-credentials-endpoint"] = "/creds" info.Config["awslogs-credentials-endpoint"] = "/creds"
c, err := newAWSLogsClient(info) c, err := newAWSLogsClient(info)
assert.NoError(t, err) assert.Check(t, err)
client := c.(*cloudwatchlogs.CloudWatchLogs) client := c.(*cloudwatchlogs.CloudWatchLogs)
creds, err := client.Config.Credentials.Get() creds, err := client.Config.Credentials.Get()
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, expectedAccessKeyID, creds.AccessKeyID) assert.Check(t, is.Equal(expectedAccessKeyID, creds.AccessKeyID))
assert.Equal(t, expectedSecretAccessKey, creds.SecretAccessKey) assert.Check(t, is.Equal(expectedSecretAccessKey, creds.SecretAccessKey))
} }
func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) { func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) {
@@ -1218,15 +1219,15 @@ func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) {
} }
c, err := newAWSLogsClient(info) c, err := newAWSLogsClient(info)
assert.NoError(t, err) assert.Check(t, err)
client := c.(*cloudwatchlogs.CloudWatchLogs) client := c.(*cloudwatchlogs.CloudWatchLogs)
creds, err := client.Config.Credentials.Get() creds, err := client.Config.Credentials.Get()
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, expectedAccessKeyID, creds.AccessKeyID) assert.Check(t, is.Equal(expectedAccessKeyID, creds.AccessKeyID))
assert.Equal(t, expectedSecretAccessKey, creds.SecretAccessKey) assert.Check(t, is.Equal(expectedSecretAccessKey, creds.SecretAccessKey))
} }
@@ -1247,13 +1248,13 @@ func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "example") tmpfile, err := ioutil.TempFile("", "example")
defer os.Remove(tmpfile.Name()) // clean up defer os.Remove(tmpfile.Name()) // clean up
assert.NoError(t, err) assert.Check(t, err)
_, err = tmpfile.Write(content) _, err = tmpfile.Write(content)
assert.NoError(t, err) assert.Check(t, err)
err = tmpfile.Close() err = tmpfile.Close()
assert.NoError(t, err) assert.Check(t, err)
os.Unsetenv("AWS_ACCESS_KEY_ID") os.Unsetenv("AWS_ACCESS_KEY_ID")
os.Unsetenv("AWS_SECRET_ACCESS_KEY") os.Unsetenv("AWS_SECRET_ACCESS_KEY")
@@ -1266,13 +1267,13 @@ func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) {
} }
c, err := newAWSLogsClient(info) c, err := newAWSLogsClient(info)
assert.NoError(t, err) assert.Check(t, err)
client := c.(*cloudwatchlogs.CloudWatchLogs) client := c.(*cloudwatchlogs.CloudWatchLogs)
creds, err := client.Config.Credentials.Get() creds, err := client.Config.Credentials.Get()
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, expectedAccessKeyID, creds.AccessKeyID) assert.Check(t, is.Equal(expectedAccessKeyID, creds.AccessKeyID))
assert.Equal(t, expectedSecretAccessKey, creds.SecretAccessKey) assert.Check(t, is.Equal(expectedSecretAccessKey, creds.SecretAccessKey))
} }

View File

@@ -13,9 +13,9 @@ import (
"github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger"
"github.com/docker/docker/daemon/logger/jsonfilelog/jsonlog" "github.com/docker/docker/daemon/logger/jsonfilelog/jsonlog"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestJSONFileLogger(t *testing.T) { func TestJSONFileLogger(t *testing.T) {
@@ -63,7 +63,7 @@ func TestJSONFileLoggerWithTags(t *testing.T) {
cname := "test-container" cname := "test-container"
tmp, err := ioutil.TempDir("", "docker-logger-") tmp, err := ioutil.TempDir("", "docker-logger-")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(tmp) defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "container.log") filename := filepath.Join(tmp, "container.log")
@@ -76,26 +76,26 @@ func TestJSONFileLoggerWithTags(t *testing.T) {
LogPath: filename, LogPath: filename,
}) })
require.NoError(t, err) assert.NilError(t, err)
defer l.Close() defer l.Close()
err = l.Log(&logger.Message{Line: []byte("line1"), Source: "src1"}) err = l.Log(&logger.Message{Line: []byte("line1"), Source: "src1"})
require.NoError(t, err) assert.NilError(t, err)
err = l.Log(&logger.Message{Line: []byte("line2"), Source: "src2"}) err = l.Log(&logger.Message{Line: []byte("line2"), Source: "src2"})
require.NoError(t, err) assert.NilError(t, err)
err = l.Log(&logger.Message{Line: []byte("line3"), Source: "src3"}) err = l.Log(&logger.Message{Line: []byte("line3"), Source: "src3"})
require.NoError(t, err) assert.NilError(t, err)
res, err := ioutil.ReadFile(filename) res, err := ioutil.ReadFile(filename)
require.NoError(t, err) assert.NilError(t, err)
expected := `{"log":"line1\n","stream":"src1","attrs":{"tag":"a7317399f3f8/test-container"},"time":"0001-01-01T00:00:00Z"} expected := `{"log":"line1\n","stream":"src1","attrs":{"tag":"a7317399f3f8/test-container"},"time":"0001-01-01T00:00:00Z"}
{"log":"line2\n","stream":"src2","attrs":{"tag":"a7317399f3f8/test-container"},"time":"0001-01-01T00:00:00Z"} {"log":"line2\n","stream":"src2","attrs":{"tag":"a7317399f3f8/test-container"},"time":"0001-01-01T00:00:00Z"}
{"log":"line3\n","stream":"src3","attrs":{"tag":"a7317399f3f8/test-container"},"time":"0001-01-01T00:00:00Z"} {"log":"line3\n","stream":"src3","attrs":{"tag":"a7317399f3f8/test-container"},"time":"0001-01-01T00:00:00Z"}
` `
assert.Equal(t, expected, string(res)) assert.Check(t, is.Equal(expected, string(res)))
} }
func BenchmarkJSONFileLoggerLog(b *testing.B) { func BenchmarkJSONFileLoggerLog(b *testing.B) {
@@ -113,7 +113,7 @@ func BenchmarkJSONFileLoggerLog(b *testing.B) {
"second": "label_foo", "second": "label_foo",
}, },
}) })
require.NoError(b, err) assert.NilError(b, err)
defer jsonlogger.Close() defer jsonlogger.Close()
msg := &logger.Message{ msg := &logger.Message{
@@ -123,7 +123,7 @@ func BenchmarkJSONFileLoggerLog(b *testing.B) {
} }
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
require.NoError(b, marshalMessage(msg, nil, buf)) assert.NilError(b, marshalMessage(msg, nil, buf))
b.SetBytes(int64(buf.Len())) b.SetBytes(int64(buf.Len()))
b.ResetTimer() b.ResetTimer()

View File

@@ -7,8 +7,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require"
) )
func TestJSONLogsMarshalJSONBuf(t *testing.T) { func TestJSONLogsMarshalJSONBuf(t *testing.T) {
@@ -35,8 +34,8 @@ func TestJSONLogsMarshalJSONBuf(t *testing.T) {
for jsonLog, expression := range logs { for jsonLog, expression := range logs {
var buf bytes.Buffer var buf bytes.Buffer
err := jsonLog.MarshalJSONBuf(&buf) err := jsonLog.MarshalJSONBuf(&buf)
require.NoError(t, err) assert.NilError(t, err)
assert.Regexp(t, regexp.MustCompile(expression), buf.String()) assert.Regexp(t, regexp.MustCompile(expression), buf.String())
assert.NoError(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{})) assert.Check(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{}))
} }
} }

View File

@@ -5,8 +5,8 @@ import (
"time" "time"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestFastTimeMarshalJSONWithInvalidYear(t *testing.T) { func TestFastTimeMarshalJSONWithInvalidYear(t *testing.T) {
@@ -22,14 +22,14 @@ func TestFastTimeMarshalJSONWithInvalidYear(t *testing.T) {
func TestFastTimeMarshalJSON(t *testing.T) { func TestFastTimeMarshalJSON(t *testing.T) {
aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC) aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC)
json, err := fastTimeMarshalJSON(aTime) json, err := fastTimeMarshalJSON(aTime)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "\"2015-05-29T11:01:02.000000003Z\"", json) assert.Check(t, is.Equal("\"2015-05-29T11:01:02.000000003Z\"", json))
location, err := time.LoadLocation("Europe/Paris") location, err := time.LoadLocation("Europe/Paris")
require.NoError(t, err) assert.NilError(t, err)
aTime = time.Date(2015, 5, 29, 11, 1, 2, 3, location) aTime = time.Date(2015, 5, 29, 11, 1, 2, 3, location)
json, err = fastTimeMarshalJSON(aTime) json, err = fastTimeMarshalJSON(aTime)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "\"2015-05-29T11:01:02.000000003+02:00\"", json) assert.Check(t, is.Equal("\"2015-05-29T11:01:02.000000003+02:00\"", json))
} }

View File

@@ -6,8 +6,8 @@ import (
"time" "time"
"github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/require"
) )
func BenchmarkJSONFileLoggerReadLogs(b *testing.B) { func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
@@ -25,7 +25,7 @@ func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
"second": "label_foo", "second": "label_foo",
}, },
}) })
require.NoError(b, err) assert.NilError(b, err)
defer jsonlogger.Close() defer jsonlogger.Close()
msg := &logger.Message{ msg := &logger.Message{
@@ -35,7 +35,7 @@ func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
} }
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
require.NoError(b, marshalMessage(msg, nil, buf)) assert.NilError(b, marshalMessage(msg, nil, buf))
b.SetBytes(int64(buf.Len())) b.SetBytes(int64(buf.Len()))
b.ResetTimer() b.ResetTimer()

View File

@@ -11,8 +11,8 @@ import (
"time" "time"
"github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/env" "github.com/gotestyourself/gotestyourself/env"
"github.com/stretchr/testify/require"
) )
// Validate options // Validate options
@@ -99,19 +99,19 @@ func TestNewWithProxy(t *testing.T) {
}, },
ContainerID: "containeriid", ContainerID: "containeriid",
}) })
require.NoError(t, err) assert.NilError(t, err)
splunkLogger := logger.(*splunkLoggerInline) splunkLogger := logger.(*splunkLoggerInline)
proxyFunc := splunkLogger.transport.Proxy proxyFunc := splunkLogger.transport.Proxy
require.NotNil(t, proxyFunc) assert.Assert(t, proxyFunc != nil)
req, err := http.NewRequest("GET", splunkURL, nil) req, err := http.NewRequest("GET", splunkURL, nil)
require.NoError(t, err) assert.NilError(t, err)
proxyURL, err := proxyFunc(req) proxyURL, err := proxyFunc(req)
require.NoError(t, err) assert.NilError(t, err)
require.NotNil(t, proxyURL) assert.Assert(t, proxyURL != nil)
require.Equal(t, proxy, proxyURL.String()) assert.Equal(t, proxy, proxyURL.String())
} }
// Test default settings // Test default settings
@@ -483,10 +483,10 @@ func TestRawFormat(t *testing.T) {
} }
hostname, err := info.Hostname() hostname, err := info.Hostname()
require.NoError(t, err) assert.NilError(t, err)
loggerDriver, err := New(info) loggerDriver, err := New(info)
require.NoError(t, err) assert.NilError(t, err)
if !hec.connectionVerified { if !hec.connectionVerified {
t.Fatal("By default connection should be verified") t.Fatal("By default connection should be verified")

View File

@@ -4,15 +4,16 @@ import (
"bytes" "bytes"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestNewParse(t *testing.T) { func TestNewParse(t *testing.T) {
tm, err := NewParse("foo", "this is a {{ . }}") tm, err := NewParse("foo", "this is a {{ . }}")
assert.NoError(t, err) assert.Check(t, err)
var b bytes.Buffer var b bytes.Buffer
assert.NoError(t, tm.Execute(&b, "string")) assert.Check(t, tm.Execute(&b, "string"))
want := "this is a string" want := "this is a string"
assert.Equal(t, want, b.String()) assert.Check(t, is.Equal(want, b.String()))
} }

View File

@@ -8,8 +8,8 @@ import (
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/docker/docker/oci" "github.com/docker/docker/oci"
"github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/idtools"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/assert" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
// TestTmpfsDevShmNoDupMount checks that a user-specified /dev/shm tmpfs // TestTmpfsDevShmNoDupMount checks that a user-specified /dev/shm tmpfs
@@ -36,17 +36,17 @@ func TestTmpfsDevShmNoDupMount(t *testing.T) {
// Mimick the code flow of daemon.createSpec(), enough to reproduce the issue // Mimick the code flow of daemon.createSpec(), enough to reproduce the issue
ms, err := d.setupMounts(c) ms, err := d.setupMounts(c)
assert.NoError(t, err) assert.Check(t, err)
ms = append(ms, c.IpcMounts()...) ms = append(ms, c.IpcMounts()...)
tmpfsMounts, err := c.TmpfsMounts() tmpfsMounts, err := c.TmpfsMounts()
assert.NoError(t, err) assert.Check(t, err)
ms = append(ms, tmpfsMounts...) ms = append(ms, tmpfsMounts...)
s := oci.DefaultSpec() s := oci.DefaultSpec()
err = setMounts(&d, &s, c, ms) err = setMounts(&d, &s, c, ms)
assert.NoError(t, err) assert.Check(t, err)
} }
// TestIpcPrivateVsReadonly checks that in case of IpcMode: private // TestIpcPrivateVsReadonly checks that in case of IpcMode: private
@@ -70,19 +70,19 @@ func TestIpcPrivateVsReadonly(t *testing.T) {
// We can't call createSpec() so mimick the minimal part // We can't call createSpec() so mimick the minimal part
// of its code flow, just enough to reproduce the issue. // of its code flow, just enough to reproduce the issue.
ms, err := d.setupMounts(c) ms, err := d.setupMounts(c)
assert.NoError(t, err) assert.Check(t, err)
s := oci.DefaultSpec() s := oci.DefaultSpec()
s.Root.Readonly = c.HostConfig.ReadonlyRootfs s.Root.Readonly = c.HostConfig.ReadonlyRootfs
err = setMounts(&d, &s, c, ms) err = setMounts(&d, &s, c, ms)
assert.NoError(t, err) assert.Check(t, err)
// Find the /dev/shm mount in ms, check it does not have ro // Find the /dev/shm mount in ms, check it does not have ro
for _, m := range s.Mounts { for _, m := range s.Mounts {
if m.Destination != "/dev/shm" { if m.Destination != "/dev/shm" {
continue continue
} }
assert.Equal(t, false, inSlice(m.Options, "ro")) assert.Check(t, is.Equal(false, inSlice(m.Options, "ro")))
} }
} }

View File

@@ -12,7 +12,8 @@ import (
_ "github.com/docker/docker/pkg/discovery/memory" _ "github.com/docker/docker/pkg/discovery/memory"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/docker/libnetwork" "github.com/docker/libnetwork"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestDaemonReloadLabels(t *testing.T) { func TestDaemonReloadLabels(t *testing.T) {
@@ -97,7 +98,7 @@ func TestDaemonReloadAllowNondistributableArtifacts(t *testing.T) {
sort.Strings(registries) sort.Strings(registries)
sort.Strings(actual) sort.Strings(actual)
assert.Equal(t, registries, actual) assert.Check(t, is.DeepEqual(registries, actual))
} }
func TestDaemonReloadMirrors(t *testing.T) { func TestDaemonReloadMirrors(t *testing.T) {

View File

@@ -7,19 +7,19 @@ import (
"testing" "testing"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
// LoadOrCreateTrustKey // LoadOrCreateTrustKey
func TestLoadOrCreateTrustKeyInvalidKeyFile(t *testing.T) { func TestLoadOrCreateTrustKeyInvalidKeyFile(t *testing.T) {
tmpKeyFolderPath, err := ioutil.TempDir("", "api-trustkey-test") tmpKeyFolderPath, err := ioutil.TempDir("", "api-trustkey-test")
require.NoError(t, err) assert.NilError(t, err)
defer os.RemoveAll(tmpKeyFolderPath) defer os.RemoveAll(tmpKeyFolderPath)
tmpKeyFile, err := ioutil.TempFile(tmpKeyFolderPath, "keyfile") tmpKeyFile, err := ioutil.TempFile(tmpKeyFolderPath, "keyfile")
require.NoError(t, err) assert.NilError(t, err)
_, err = loadOrCreateTrustKey(tmpKeyFile.Name()) _, err = loadOrCreateTrustKey(tmpKeyFile.Name())
testutil.ErrorContains(t, err, "Error loading key file") testutil.ErrorContains(t, err, "Error loading key file")
@@ -33,11 +33,11 @@ func TestLoadOrCreateTrustKeyCreateKeyWhenFileDoesNotExist(t *testing.T) {
tmpKeyFile := tmpKeyFolderPath.Join("keyfile") tmpKeyFile := tmpKeyFolderPath.Join("keyfile")
key, err := loadOrCreateTrustKey(tmpKeyFile) key, err := loadOrCreateTrustKey(tmpKeyFile)
require.NoError(t, err) assert.NilError(t, err)
assert.NotNil(t, key) assert.Check(t, key != nil)
_, err = os.Stat(tmpKeyFile) _, err = os.Stat(tmpKeyFile)
require.NoError(t, err, "key file doesn't exist") assert.NilError(t, err, "key file doesn't exist")
} }
func TestLoadOrCreateTrustKeyCreateKeyWhenDirectoryDoesNotExist(t *testing.T) { func TestLoadOrCreateTrustKeyCreateKeyWhenDirectoryDoesNotExist(t *testing.T) {
@@ -46,27 +46,27 @@ func TestLoadOrCreateTrustKeyCreateKeyWhenDirectoryDoesNotExist(t *testing.T) {
tmpKeyFile := tmpKeyFolderPath.Join("folder/hierarchy/keyfile") tmpKeyFile := tmpKeyFolderPath.Join("folder/hierarchy/keyfile")
key, err := loadOrCreateTrustKey(tmpKeyFile) key, err := loadOrCreateTrustKey(tmpKeyFile)
require.NoError(t, err) assert.NilError(t, err)
assert.NotNil(t, key) assert.Check(t, key != nil)
_, err = os.Stat(tmpKeyFile) _, err = os.Stat(tmpKeyFile)
require.NoError(t, err, "key file doesn't exist") assert.NilError(t, err, "key file doesn't exist")
} }
func TestLoadOrCreateTrustKeyCreateKeyNoPath(t *testing.T) { func TestLoadOrCreateTrustKeyCreateKeyNoPath(t *testing.T) {
defer os.Remove("keyfile") defer os.Remove("keyfile")
key, err := loadOrCreateTrustKey("keyfile") key, err := loadOrCreateTrustKey("keyfile")
require.NoError(t, err) assert.NilError(t, err)
assert.NotNil(t, key) assert.Check(t, key != nil)
_, err = os.Stat("keyfile") _, err = os.Stat("keyfile")
require.NoError(t, err, "key file doesn't exist") assert.NilError(t, err, "key file doesn't exist")
} }
func TestLoadOrCreateTrustKeyLoadValidKey(t *testing.T) { func TestLoadOrCreateTrustKeyLoadValidKey(t *testing.T) {
tmpKeyFile := filepath.Join("testdata", "keyfile") tmpKeyFile := filepath.Join("testdata", "keyfile")
key, err := loadOrCreateTrustKey(tmpKeyFile) key, err := loadOrCreateTrustKey(tmpKeyFile)
require.NoError(t, err) assert.NilError(t, err)
expected := "AWX2:I27X:WQFX:IOMK:CNAK:O7PW:VYNB:ZLKC:CVAE:YJP2:SI4A:XXAY" expected := "AWX2:I27X:WQFX:IOMK:CNAK:O7PW:VYNB:ZLKC:CVAE:YJP2:SI4A:XXAY"
assert.Contains(t, key.String(), expected) assert.Check(t, is.Contains(key.String(), expected))
} }

View File

@@ -6,7 +6,7 @@ import (
"testing" "testing"
"github.com/docker/docker/layer" "github.com/docker/docker/layer"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
func TestV1IDService(t *testing.T) { func TestV1IDService(t *testing.T) {
@@ -24,7 +24,7 @@ func TestV1IDService(t *testing.T) {
ns := v1IDService.namespace() ns := v1IDService.namespace()
require.Equal(t, "v1id", ns) assert.Equal(t, "v1id", ns)
testVectors := []struct { testVectors := []struct {
registry string registry string

View File

@@ -11,16 +11,17 @@ import (
"testing" "testing"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
digest "github.com/opencontainers/go-digest" digest "github.com/opencontainers/go-digest"
"github.com/stretchr/testify/assert"
) )
func defaultFSStoreBackend(t *testing.T) (StoreBackend, func()) { func defaultFSStoreBackend(t *testing.T) (StoreBackend, func()) {
tmpdir, err := ioutil.TempDir("", "images-fs-store") tmpdir, err := ioutil.TempDir("", "images-fs-store")
assert.NoError(t, err) assert.Check(t, err)
fsBackend, err := NewFSStoreBackend(tmpdir) fsBackend, err := NewFSStoreBackend(tmpdir)
assert.NoError(t, err) assert.Check(t, err)
return fsBackend, func() { os.RemoveAll(tmpdir) } return fsBackend, func() { os.RemoveAll(tmpdir) }
} }
@@ -30,12 +31,12 @@ func TestFSGetInvalidData(t *testing.T) {
defer cleanup() defer cleanup()
id, err := store.Set([]byte("foobar")) id, err := store.Set([]byte("foobar"))
assert.NoError(t, err) assert.Check(t, err)
dgst := digest.Digest(id) dgst := digest.Digest(id)
err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, string(dgst.Algorithm()), dgst.Hex()), []byte("foobar2"), 0600) err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, string(dgst.Algorithm()), dgst.Hex()), []byte("foobar2"), 0600)
assert.NoError(t, err) assert.Check(t, err)
_, err = store.Get(id) _, err = store.Get(id)
testutil.ErrorContains(t, err, "failed to verify") testutil.ErrorContains(t, err, "failed to verify")
@@ -47,7 +48,7 @@ func TestFSInvalidSet(t *testing.T) {
id := digest.FromBytes([]byte("foobar")) id := digest.FromBytes([]byte("foobar"))
err := os.Mkdir(filepath.Join(store.(*fs).root, contentDirName, string(id.Algorithm()), id.Hex()), 0700) err := os.Mkdir(filepath.Join(store.(*fs).root, contentDirName, string(id.Algorithm()), id.Hex()), 0700)
assert.NoError(t, err) assert.Check(t, err)
_, err = store.Set([]byte("foobar")) _, err = store.Set([]byte("foobar"))
testutil.ErrorContains(t, err, "failed to write digest data") testutil.ErrorContains(t, err, "failed to write digest data")
@@ -55,7 +56,7 @@ func TestFSInvalidSet(t *testing.T) {
func TestFSInvalidRoot(t *testing.T) { func TestFSInvalidRoot(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "images-fs-store") tmpdir, err := ioutil.TempDir("", "images-fs-store")
assert.NoError(t, err) assert.Check(t, err)
defer os.RemoveAll(tmpdir) defer os.RemoveAll(tmpdir)
tcases := []struct { tcases := []struct {
@@ -70,10 +71,10 @@ func TestFSInvalidRoot(t *testing.T) {
root := filepath.Join(tmpdir, tc.root) root := filepath.Join(tmpdir, tc.root)
filePath := filepath.Join(tmpdir, tc.invalidFile) filePath := filepath.Join(tmpdir, tc.invalidFile)
err := os.MkdirAll(filepath.Dir(filePath), 0700) err := os.MkdirAll(filepath.Dir(filePath), 0700)
assert.NoError(t, err) assert.Check(t, err)
f, err := os.Create(filePath) f, err := os.Create(filePath)
assert.NoError(t, err) assert.Check(t, err)
f.Close() f.Close()
_, err = NewFSStoreBackend(root) _, err = NewFSStoreBackend(root)
@@ -89,10 +90,10 @@ func TestFSMetadataGetSet(t *testing.T) {
defer cleanup() defer cleanup()
id, err := store.Set([]byte("foo")) id, err := store.Set([]byte("foo"))
assert.NoError(t, err) assert.Check(t, err)
id2, err := store.Set([]byte("bar")) id2, err := store.Set([]byte("bar"))
assert.NoError(t, err) assert.Check(t, err)
tcases := []struct { tcases := []struct {
id digest.Digest id digest.Digest
@@ -106,12 +107,12 @@ func TestFSMetadataGetSet(t *testing.T) {
for _, tc := range tcases { for _, tc := range tcases {
err = store.SetMetadata(tc.id, tc.key, tc.value) err = store.SetMetadata(tc.id, tc.key, tc.value)
assert.NoError(t, err) assert.Check(t, err)
actual, err := store.GetMetadata(tc.id, tc.key) actual, err := store.GetMetadata(tc.id, tc.key)
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, tc.value, actual) assert.Check(t, is.DeepEqual(tc.value, actual))
} }
_, err = store.GetMetadata(id2, "tkey2") _, err = store.GetMetadata(id2, "tkey2")
@@ -130,19 +131,19 @@ func TestFSInvalidWalker(t *testing.T) {
defer cleanup() defer cleanup()
fooID, err := store.Set([]byte("foo")) fooID, err := store.Set([]byte("foo"))
assert.NoError(t, err) assert.Check(t, err)
err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, "sha256/foobar"), []byte("foobar"), 0600) err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, "sha256/foobar"), []byte("foobar"), 0600)
assert.NoError(t, err) assert.Check(t, err)
n := 0 n := 0
err = store.Walk(func(id digest.Digest) error { err = store.Walk(func(id digest.Digest) error {
assert.Equal(t, fooID, id) assert.Check(t, is.Equal(fooID, id))
n++ n++
return nil return nil
}) })
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, 1, n) assert.Check(t, is.Equal(1, n))
} }
func TestFSGetSet(t *testing.T) { func TestFSGetSet(t *testing.T) {
@@ -159,12 +160,12 @@ func TestFSGetSet(t *testing.T) {
randomInput := make([]byte, 8*1024) randomInput := make([]byte, 8*1024)
_, err := rand.Read(randomInput) _, err := rand.Read(randomInput)
assert.NoError(t, err) assert.Check(t, err)
// skipping use of digest pkg because it is used by the implementation // skipping use of digest pkg because it is used by the implementation
h := sha256.New() h := sha256.New()
_, err = h.Write(randomInput) _, err = h.Write(randomInput)
assert.NoError(t, err) assert.Check(t, err)
tcases = append(tcases, tcase{ tcases = append(tcases, tcase{
input: randomInput, input: randomInput,
@@ -173,14 +174,14 @@ func TestFSGetSet(t *testing.T) {
for _, tc := range tcases { for _, tc := range tcases {
id, err := store.Set([]byte(tc.input)) id, err := store.Set([]byte(tc.input))
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, tc.expected, id) assert.Check(t, is.Equal(tc.expected, id))
} }
for _, tc := range tcases { for _, tc := range tcases {
data, err := store.Get(tc.expected) data, err := store.Get(tc.expected)
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, tc.input, data) assert.Check(t, is.DeepEqual(tc.input, data))
} }
} }
@@ -209,22 +210,22 @@ func TestFSDelete(t *testing.T) {
defer cleanup() defer cleanup()
id, err := store.Set([]byte("foo")) id, err := store.Set([]byte("foo"))
assert.NoError(t, err) assert.Check(t, err)
id2, err := store.Set([]byte("bar")) id2, err := store.Set([]byte("bar"))
assert.NoError(t, err) assert.Check(t, err)
err = store.Delete(id) err = store.Delete(id)
assert.NoError(t, err) assert.Check(t, err)
_, err = store.Get(id) _, err = store.Get(id)
testutil.ErrorContains(t, err, "failed to get digest") testutil.ErrorContains(t, err, "failed to get digest")
_, err = store.Get(id2) _, err = store.Get(id2)
assert.NoError(t, err) assert.Check(t, err)
err = store.Delete(id2) err = store.Delete(id2)
assert.NoError(t, err) assert.Check(t, err)
_, err = store.Get(id2) _, err = store.Get(id2)
testutil.ErrorContains(t, err, "failed to get digest") testutil.ErrorContains(t, err, "failed to get digest")
@@ -235,10 +236,10 @@ func TestFSWalker(t *testing.T) {
defer cleanup() defer cleanup()
id, err := store.Set([]byte("foo")) id, err := store.Set([]byte("foo"))
assert.NoError(t, err) assert.Check(t, err)
id2, err := store.Set([]byte("bar")) id2, err := store.Set([]byte("bar"))
assert.NoError(t, err) assert.Check(t, err)
tcases := make(map[digest.Digest]struct{}) tcases := make(map[digest.Digest]struct{})
tcases[id] = struct{}{} tcases[id] = struct{}{}
@@ -249,9 +250,9 @@ func TestFSWalker(t *testing.T) {
n++ n++
return nil return nil
}) })
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, 2, n) assert.Check(t, is.Equal(2, n))
assert.Len(t, tcases, 0) assert.Check(t, is.Len(tcases, 0))
} }
func TestFSWalkerStopOnError(t *testing.T) { func TestFSWalkerStopOnError(t *testing.T) {
@@ -259,7 +260,7 @@ func TestFSWalkerStopOnError(t *testing.T) {
defer cleanup() defer cleanup()
id, err := store.Set([]byte("foo")) id, err := store.Set([]byte("foo"))
assert.NoError(t, err) assert.Check(t, err)
tcases := make(map[digest.Digest]struct{}) tcases := make(map[digest.Digest]struct{})
tcases[id] = struct{}{} tcases[id] = struct{}{}

View File

@@ -9,8 +9,8 @@ import (
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/layer" "github.com/docker/docker/layer"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
const sampleImageJSON = `{ const sampleImageJSON = `{
@@ -25,13 +25,13 @@ const sampleImageJSON = `{
func TestNewFromJSON(t *testing.T) { func TestNewFromJSON(t *testing.T) {
img, err := NewFromJSON([]byte(sampleImageJSON)) img, err := NewFromJSON([]byte(sampleImageJSON))
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, sampleImageJSON, string(img.RawJSON())) assert.Check(t, is.Equal(sampleImageJSON, string(img.RawJSON())))
} }
func TestNewFromJSONWithInvalidJSON(t *testing.T) { func TestNewFromJSONWithInvalidJSON(t *testing.T) {
_, err := NewFromJSON([]byte("{}")) _, err := NewFromJSON([]byte("{}"))
assert.EqualError(t, err, "invalid image JSON, no RootFS key") assert.Check(t, is.Error(err, "invalid image JSON, no RootFS key"))
} }
func TestMarshalKeyOrder(t *testing.T) { func TestMarshalKeyOrder(t *testing.T) {
@@ -42,7 +42,7 @@ func TestMarshalKeyOrder(t *testing.T) {
Architecture: "c", Architecture: "c",
}, },
}) })
assert.NoError(t, err) assert.Check(t, err)
expectedOrder := []string{"architecture", "author", "comment"} expectedOrder := []string{"architecture", "author", "comment"}
var indexes []int var indexes []int
@@ -71,10 +71,10 @@ func TestImage(t *testing.T) {
computedID: ID(cid), computedID: ID(cid),
} }
assert.Equal(t, cid, img.ImageID()) assert.Check(t, is.Equal(cid, img.ImageID()))
assert.Equal(t, cid, img.ID().String()) assert.Check(t, is.Equal(cid, img.ID().String()))
assert.Equal(t, os, img.OperatingSystem()) assert.Check(t, is.Equal(os, img.OperatingSystem()))
assert.Equal(t, config, img.RunConfig()) assert.Check(t, is.DeepEqual(config, img.RunConfig()))
} }
func TestImageOSNotEmpty(t *testing.T) { func TestImageOSNotEmpty(t *testing.T) {
@@ -85,7 +85,7 @@ func TestImageOSNotEmpty(t *testing.T) {
}, },
OSVersion: "osversion", OSVersion: "osversion",
} }
assert.Equal(t, os, img.OperatingSystem()) assert.Check(t, is.Equal(os, img.OperatingSystem()))
} }
func TestNewChildImageFromImageWithRootFS(t *testing.T) { func TestNewChildImageFromImageWithRootFS(t *testing.T) {
@@ -109,16 +109,16 @@ func TestNewChildImageFromImageWithRootFS(t *testing.T) {
newImage := NewChildImage(parent, childConfig, "platform") newImage := NewChildImage(parent, childConfig, "platform")
expectedDiffIDs := []layer.DiffID{layer.DiffID("ba5e"), layer.DiffID("abcdef")} expectedDiffIDs := []layer.DiffID{layer.DiffID("ba5e"), layer.DiffID("abcdef")}
assert.Equal(t, expectedDiffIDs, newImage.RootFS.DiffIDs) assert.Check(t, is.DeepEqual(expectedDiffIDs, newImage.RootFS.DiffIDs))
assert.Equal(t, childConfig.Author, newImage.Author) assert.Check(t, is.Equal(childConfig.Author, newImage.Author))
assert.Equal(t, childConfig.Config, newImage.Config) assert.Check(t, is.DeepEqual(childConfig.Config, newImage.Config))
assert.Equal(t, *childConfig.ContainerConfig, newImage.ContainerConfig) assert.Check(t, is.DeepEqual(*childConfig.ContainerConfig, newImage.ContainerConfig))
assert.Equal(t, "platform", newImage.OS) assert.Check(t, is.Equal("platform", newImage.OS))
assert.Equal(t, childConfig.Config, newImage.Config) assert.Check(t, is.DeepEqual(childConfig.Config, newImage.Config))
assert.Len(t, newImage.History, 2) assert.Check(t, is.Len(newImage.History, 2))
assert.Equal(t, childConfig.Comment, newImage.History[1].Comment) assert.Check(t, is.Equal(childConfig.Comment, newImage.History[1].Comment))
// RootFS should be copied not mutated // RootFS should be copied not mutated
assert.NotEqual(t, parent.RootFS.DiffIDs, newImage.RootFS.DiffIDs) assert.Check(t, parent.RootFS.DiffIDs != newImage.RootFS.DiffIDs)
} }

View File

@@ -7,8 +7,9 @@ import (
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/docker/docker/layer" "github.com/docker/docker/layer"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/stretchr/testify/assert"
) )
func TestRestore(t *testing.T) { func TestRestore(t *testing.T) {
@@ -16,53 +17,53 @@ func TestRestore(t *testing.T) {
defer cleanup() defer cleanup()
id1, err := fs.Set([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`)) id1, err := fs.Set([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err) assert.Check(t, err)
_, err = fs.Set([]byte(`invalid`)) _, err = fs.Set([]byte(`invalid`))
assert.NoError(t, err) assert.Check(t, err)
id2, err := fs.Set([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`)) id2, err := fs.Set([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
assert.NoError(t, err) assert.Check(t, err)
err = fs.SetMetadata(id2, "parent", []byte(id1)) err = fs.SetMetadata(id2, "parent", []byte(id1))
assert.NoError(t, err) assert.Check(t, err)
mlgrMap := make(map[string]LayerGetReleaser) mlgrMap := make(map[string]LayerGetReleaser)
mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{} mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{}
is, err := NewImageStore(fs, mlgrMap) is, err := NewImageStore(fs, mlgrMap)
assert.NoError(t, err) assert.Check(t, err)
assert.Len(t, is.Map(), 2) assert.Check(t, is.Len(is.Map(), 2))
img1, err := is.Get(ID(id1)) img1, err := is.Get(ID(id1))
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, ID(id1), img1.computedID) assert.Check(t, is.Equal(ID(id1), img1.computedID))
assert.Equal(t, string(id1), img1.computedID.String()) assert.Check(t, is.Equal(string(id1), img1.computedID.String()))
img2, err := is.Get(ID(id2)) img2, err := is.Get(ID(id2))
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "abc", img1.Comment) assert.Check(t, is.Equal("abc", img1.Comment))
assert.Equal(t, "def", img2.Comment) assert.Check(t, is.Equal("def", img2.Comment))
_, err = is.GetParent(ID(id1)) _, err = is.GetParent(ID(id1))
testutil.ErrorContains(t, err, "failed to read metadata") 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.Check(t, err)
assert.Equal(t, ID(id1), p) assert.Check(t, is.Equal(ID(id1), p))
children := is.Children(ID(id1)) children := is.Children(ID(id1))
assert.Len(t, children, 1) assert.Check(t, is.Len(children, 1))
assert.Equal(t, ID(id2), children[0]) assert.Check(t, is.Equal(ID(id2), children[0]))
assert.Len(t, is.Heads(), 1) assert.Check(t, is.Len(is.Heads(), 1))
sid1, err := is.Search(string(id1)[:10]) sid1, err := is.Search(string(id1)[:10])
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, ID(id1), sid1) assert.Check(t, is.Equal(ID(id1), sid1))
sid1, err = is.Search(digest.Digest(id1).Hex()[:6]) sid1, err = is.Search(digest.Digest(id1).Hex()[:6])
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, ID(id1), sid1) assert.Check(t, is.Equal(ID(id1), sid1))
invalidPattern := digest.Digest(id1).Hex()[1:6] invalidPattern := digest.Digest(id1).Hex()[1:6]
_, err = is.Search(invalidPattern) _, err = is.Search(invalidPattern)
@@ -74,31 +75,31 @@ func TestAddDelete(t *testing.T) {
defer cleanup() defer cleanup()
id1, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`)) id1, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, ID("sha256:8d25a9c45df515f9d0fe8e4a6b1c64dd3b965a84790ddbcc7954bb9bc89eb993"), id1) assert.Check(t, is.Equal(ID("sha256:8d25a9c45df515f9d0fe8e4a6b1c64dd3b965a84790ddbcc7954bb9bc89eb993"), id1))
img, err := is.Get(id1) img, err := is.Get(id1)
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, "abc", img.Comment) assert.Check(t, is.Equal("abc", img.Comment))
id2, err := is.Create([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`)) id2, err := is.Create([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
assert.NoError(t, err) assert.Check(t, err)
err = is.SetParent(id2, id1) err = is.SetParent(id2, id1)
assert.NoError(t, err) assert.Check(t, err)
pid1, err := is.GetParent(id2) pid1, err := is.GetParent(id2)
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, pid1, id1) assert.Check(t, is.Equal(pid1, id1))
_, err = is.Delete(id1) _, err = is.Delete(id1)
assert.NoError(t, err) assert.Check(t, err)
_, err = is.Get(id1) _, err = is.Get(id1)
testutil.ErrorContains(t, err, "failed to get digest") testutil.ErrorContains(t, err, "failed to get digest")
_, err = is.Get(id2) _, err = is.Get(id2)
assert.NoError(t, err) assert.Check(t, err)
_, err = is.GetParent(id2) _, err = is.GetParent(id2)
testutil.ErrorContains(t, err, "failed to read metadata") testutil.ErrorContains(t, err, "failed to read metadata")
@@ -109,14 +110,14 @@ func TestSearchAfterDelete(t *testing.T) {
defer cleanup() defer cleanup()
id, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`)) id, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err) assert.Check(t, err)
id1, err := is.Search(string(id)[:15]) id1, err := is.Search(string(id)[:15])
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, id1, id) assert.Check(t, is.Equal(id1, id))
_, err = is.Delete(id) _, err = is.Delete(id)
assert.NoError(t, err) assert.Check(t, err)
_, err = is.Search(string(id)[:15]) _, err = is.Search(string(id)[:15])
testutil.ErrorContains(t, err, "No such image") testutil.ErrorContains(t, err, "No such image")
@@ -127,20 +128,20 @@ func TestParentReset(t *testing.T) {
defer cleanup() defer cleanup()
id, err := is.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`)) id, err := is.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err) assert.Check(t, err)
id2, err := is.Create([]byte(`{"comment": "abc2", "rootfs": {"type": "layers"}}`)) id2, err := is.Create([]byte(`{"comment": "abc2", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err) assert.Check(t, err)
id3, err := is.Create([]byte(`{"comment": "abc3", "rootfs": {"type": "layers"}}`)) id3, err := is.Create([]byte(`{"comment": "abc3", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err) assert.Check(t, err)
assert.NoError(t, is.SetParent(id, id2)) assert.Check(t, is.SetParent(id, id2))
assert.Len(t, is.Children(id2), 1) assert.Check(t, is.Len(is.Children(id2), 1))
assert.NoError(t, is.SetParent(id, id3)) assert.Check(t, is.SetParent(id, id3))
assert.Len(t, is.Children(id2), 0) assert.Check(t, is.Len(is.Children(id2), 0))
assert.Len(t, is.Children(id3), 1) assert.Check(t, is.Len(is.Children(id3), 1))
} }
func defaultImageStore(t *testing.T) (Store, func()) { func defaultImageStore(t *testing.T) (Store, func()) {
@@ -149,7 +150,7 @@ func defaultImageStore(t *testing.T) (Store, func()) {
mlgrMap := make(map[string]LayerGetReleaser) mlgrMap := make(map[string]LayerGetReleaser)
mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{} mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{}
store, err := NewImageStore(fsBackend, mlgrMap) store, err := NewImageStore(fsBackend, mlgrMap)
assert.NoError(t, err) assert.Check(t, err)
return store, cleanup return store, cleanup
} }
@@ -159,17 +160,17 @@ func TestGetAndSetLastUpdated(t *testing.T) {
defer cleanup() defer cleanup()
id, err := store.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`)) id, err := store.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err) assert.Check(t, err)
updated, err := store.GetLastUpdated(id) updated, err := store.GetLastUpdated(id)
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, updated.IsZero(), true) assert.Check(t, is.Equal(updated.IsZero(), true))
assert.NoError(t, store.SetLastUpdated(id)) assert.Check(t, store.SetLastUpdated(id))
updated, err = store.GetLastUpdated(id) updated, err = store.GetLastUpdated(id)
assert.NoError(t, err) assert.Check(t, err)
assert.Equal(t, updated.IsZero(), false) assert.Check(t, is.Equal(updated.IsZero(), false))
} }
func TestStoreLen(t *testing.T) { func TestStoreLen(t *testing.T) {
@@ -179,7 +180,7 @@ func TestStoreLen(t *testing.T) {
expected := 10 expected := 10
for i := 0; i < expected; i++ { for i := 0; i < expected; i++ {
_, err := store.Create([]byte(fmt.Sprintf(`{"comment": "abc%d", "rootfs": {"type": "layers"}}`, i))) _, err := store.Create([]byte(fmt.Sprintf(`{"comment": "abc%d", "rootfs": {"type": "layers"}}`, i)))
assert.NoError(t, err) assert.NilError(t, err)
} }
numImages := store.Len() numImages := store.Len()
assert.Equal(t, expected, numImages) assert.Equal(t, expected, numImages)

View File

@@ -11,11 +11,11 @@ import (
"github.com/docker/docker/integration-cli/cli/build/fakecontext" "github.com/docker/docker/integration-cli/cli/build/fakecontext"
"github.com/docker/docker/integration-cli/cli/build/fakestorage" "github.com/docker/docker/integration-cli/cli/build/fakestorage"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
type testingT interface { type testingT interface {
require.TestingT assert.TestingT
logT logT
Fatal(args ...interface{}) Fatal(args ...interface{})
Fatalf(string, ...interface{}) Fatalf(string, ...interface{})

View File

@@ -15,13 +15,13 @@ import (
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/docker/docker/internal/test/environment" "github.com/docker/docker/internal/test/environment"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
) )
var testEnv *environment.Execution var testEnv *environment.Execution
type testingT interface { type testingT interface {
require.TestingT assert.TestingT
logT logT
Fatal(args ...interface{}) Fatal(args ...interface{})
Fatalf(string, ...interface{}) Fatalf(string, ...interface{})

View File

@@ -24,14 +24,14 @@ import (
"github.com/docker/go-connections/sockets" "github.com/docker/go-connections/sockets"
"github.com/docker/go-connections/tlsconfig" "github.com/docker/go-connections/tlsconfig"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/icmd" "github.com/gotestyourself/gotestyourself/icmd"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
type testingT interface { type testingT interface {
require.TestingT assert.TestingT
logT logT
Fatalf(string, ...interface{}) Fatalf(string, ...interface{})
} }
@@ -487,20 +487,20 @@ func (d *Daemon) handleUserns() {
// LoadBusybox image into the daemon // LoadBusybox image into the daemon
func (d *Daemon) LoadBusybox(t testingT) { func (d *Daemon) LoadBusybox(t testingT) {
clientHost, err := client.NewEnvClient() clientHost, err := client.NewEnvClient()
require.NoError(t, err, "failed to create client") assert.NilError(t, err, "failed to create client")
defer clientHost.Close() defer clientHost.Close()
ctx := context.Background() ctx := context.Background()
reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"}) reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"})
require.NoError(t, err, "failed to download busybox") assert.NilError(t, err, "failed to download busybox")
defer reader.Close() defer reader.Close()
client, err := d.NewClient() client, err := d.NewClient()
require.NoError(t, err, "failed to create client") assert.NilError(t, err, "failed to create client")
defer client.Close() defer client.Close()
resp, err := client.ImageLoad(ctx, reader, true) resp, err := client.ImageLoad(ctx, reader, true)
require.NoError(t, err, "failed to load busybox") assert.NilError(t, err, "failed to load busybox")
defer resp.Body.Close() defer resp.Body.Close()
} }
@@ -563,11 +563,11 @@ func (d *Daemon) WaitRun(contID string) error {
} }
// Info returns the info struct for this daemon // Info returns the info struct for this daemon
func (d *Daemon) Info(t require.TestingT) types.Info { func (d *Daemon) Info(t assert.TestingT) types.Info {
apiclient, err := client.NewClientWithOpts(client.WithHost((d.Sock()))) apiclient, err := client.NewClientWithOpts(client.WithHost((d.Sock())))
require.NoError(t, err) assert.NilError(t, err)
info, err := apiclient.Info(context.Background()) info, err := apiclient.Info(context.Background())
require.NoError(t, err) assert.NilError(t, err)
return info return info
} }

View File

@@ -11,8 +11,8 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -235,12 +235,12 @@ func (d *Swarm) CheckServiceUpdateState(service string) func(*check.C) (interfac
func (d *Swarm) CheckPluginRunning(plugin string) func(c *check.C) (interface{}, check.CommentInterface) { func (d *Swarm) CheckPluginRunning(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) { return func(c *check.C) (interface{}, check.CommentInterface) {
apiclient, err := d.NewClient() apiclient, err := d.NewClient()
require.NoError(c, err) assert.NilError(c, err)
resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin) resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin)
if client.IsErrNotFound(err) { if client.IsErrNotFound(err) {
return false, check.Commentf("%v", err) return false, check.Commentf("%v", err)
} }
require.NoError(c, err) assert.NilError(c, err)
return resp.Enabled, check.Commentf("%+v", resp) return resp.Enabled, check.Commentf("%+v", resp)
} }
} }
@@ -249,12 +249,12 @@ func (d *Swarm) CheckPluginRunning(plugin string) func(c *check.C) (interface{},
func (d *Swarm) CheckPluginImage(plugin string) func(c *check.C) (interface{}, check.CommentInterface) { func (d *Swarm) CheckPluginImage(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) { return func(c *check.C) (interface{}, check.CommentInterface) {
apiclient, err := d.NewClient() apiclient, err := d.NewClient()
require.NoError(c, err) assert.NilError(c, err)
resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin) resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin)
if client.IsErrNotFound(err) { if client.IsErrNotFound(err) {
return false, check.Commentf("%v", err) return false, check.Commentf("%v", err)
} }
require.NoError(c, err) assert.NilError(c, err)
return resp.PluginReference, check.Commentf("%+v", resp) return resp.PluginReference, check.Commentf("%+v", resp)
} }
} }

View File

@@ -18,10 +18,10 @@ import (
"github.com/docker/docker/integration-cli/cli/build/fakestorage" "github.com/docker/docker/integration-cli/cli/build/fakestorage"
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/moby/buildkit/session" "github.com/moby/buildkit/session"
"github.com/moby/buildkit/session/filesync" "github.com/moby/buildkit/session/filesync"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
) )
@@ -296,12 +296,12 @@ func (s *DockerSuite) TestBuildOnBuildCache(c *check.C) {
"/build", "/build",
request.RawContent(ctx.AsTarReader(c)), request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar")) request.ContentType("application/x-tar"))
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode) assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(out), "Successfully built") assert.Check(c, is.Contains(string(out), "Successfully built"))
return out return out
} }
@@ -316,15 +316,15 @@ func (s *DockerSuite) TestBuildOnBuildCache(c *check.C) {
out := build(dockerfile) out := build(dockerfile)
imageIDs := getImageIDsFromBuild(c, out) imageIDs := getImageIDsFromBuild(c, out)
assert.Len(c, imageIDs, 2) assert.Check(c, is.Len(imageIDs, 2))
parentID, childID := imageIDs[0], imageIDs[1] parentID, childID := imageIDs[0], imageIDs[1]
client := testEnv.APIClient() client := testEnv.APIClient()
// check parentID is correct // check parentID is correct
image, _, err := client.ImageInspectWithRaw(context.Background(), childID) image, _, err := client.ImageInspectWithRaw(context.Background(), childID)
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, parentID, image.Parent) assert.Check(c, is.Equal(parentID, image.Parent))
} }
func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) { func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
@@ -333,12 +333,12 @@ func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
// tag the image to upload it to the private registry // tag the image to upload it to the private registry
err := client.ImageTag(context.TODO(), "busybox", repoName) err := client.ImageTag(context.TODO(), "busybox", repoName)
assert.Nil(c, err) assert.Check(c, err)
// push the image to the registry // push the image to the registry
rc, err := client.ImagePush(context.TODO(), repoName, types.ImagePushOptions{RegistryAuth: "{}"}) rc, err := client.ImagePush(context.TODO(), repoName, types.ImagePushOptions{RegistryAuth: "{}"})
assert.Nil(c, err) assert.Check(c, err)
_, err = io.Copy(ioutil.Discard, rc) _, err = io.Copy(ioutil.Discard, rc)
assert.Nil(c, err) assert.Check(c, err)
dockerfile := fmt.Sprintf(` dockerfile := fmt.Sprintf(`
FROM %s AS foo FROM %s AS foo
@@ -356,12 +356,12 @@ func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
"/build?pull=1", "/build?pull=1",
request.RawContent(ctx.AsTarReader(c)), request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar")) request.ContentType("application/x-tar"))
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode) assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(out), "Successfully built") assert.Check(c, is.Contains(string(out), "Successfully built"))
} }
func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) { func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
@@ -374,11 +374,11 @@ func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
Mode: 0600, Mode: 0600,
Typeflag: tar.TypeReg, Typeflag: tar.TypeReg,
}) })
require.NoError(c, err) assert.NilError(c, err)
_, err = tw.Write(dt) _, err = tw.Write(dt)
require.NoError(c, err) assert.NilError(c, err)
err = tw.Close() err = tw.Close()
require.NoError(c, err) assert.NilError(c, err)
server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{ server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
"test.tar": buffer, "test.tar": buffer,
@@ -400,12 +400,12 @@ func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
"/build", "/build",
request.RawContent(ctx.AsTarReader(c)), request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar")) request.ContentType("application/x-tar"))
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode) assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(out), "Successfully built") assert.Check(c, is.Contains(string(out), "Successfully built"))
} }
func (s *DockerSuite) TestBuildChownOnCopy(c *check.C) { func (s *DockerSuite) TestBuildChownOnCopy(c *check.C) {
@@ -433,8 +433,8 @@ func (s *DockerSuite) TestBuildChownOnCopy(c *check.C) {
c.Assert(res.StatusCode, checker.Equals, http.StatusOK) c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(out), "Successfully built") assert.Check(c, is.Contains(string(out), "Successfully built"))
} }
func (s *DockerSuite) TestBuildCopyCacheOnFileChange(c *check.C) { func (s *DockerSuite) TestBuildCopyCacheOnFileChange(c *check.C) {
@@ -454,11 +454,11 @@ COPY file /file`
request.RawContent(ctx.AsTarReader(c)), request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar")) request.ContentType("application/x-tar"))
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode) assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
ids := getImageIDsFromBuild(c, out) ids := getImageIDsFromBuild(c, out)
return ids[len(ids)-1] return ids[len(ids)-1]
@@ -493,11 +493,11 @@ ADD file /file`
request.RawContent(ctx.AsTarReader(c)), request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar")) request.ContentType("application/x-tar"))
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode) assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
ids := getImageIDsFromBuild(c, out) ids := getImageIDsFromBuild(c, out)
return ids[len(ids)-1] return ids[len(ids)-1]
@@ -530,7 +530,7 @@ func (s *DockerSuite) TestBuildWithSession(c *check.C) {
defer fctx.Close() defer fctx.Close()
out := testBuildWithSession(c, fctx.Dir, dockerfile) out := testBuildWithSession(c, fctx.Dir, dockerfile)
assert.Contains(c, out, "some content") assert.Check(c, is.Contains(out, "some content"))
fctx.Add("second", "contentcontent") fctx.Add("second", "contentcontent")
@@ -540,20 +540,20 @@ func (s *DockerSuite) TestBuildWithSession(c *check.C) {
` `
out = testBuildWithSession(c, fctx.Dir, dockerfile) out = testBuildWithSession(c, fctx.Dir, dockerfile)
assert.Equal(c, strings.Count(out, "Using cache"), 2) assert.Check(c, is.Equal(strings.Count(out, "Using cache"), 2))
assert.Contains(c, out, "contentcontent") assert.Check(c, is.Contains(out, "contentcontent"))
client := testEnv.APIClient() client := testEnv.APIClient()
du, err := client.DiskUsage(context.TODO()) du, err := client.DiskUsage(context.TODO())
assert.Nil(c, err) assert.Check(c, err)
assert.True(c, du.BuilderSize > 10) assert.Check(c, du.BuilderSize > 10)
out = testBuildWithSession(c, fctx.Dir, dockerfile) out = testBuildWithSession(c, fctx.Dir, dockerfile)
assert.Equal(c, strings.Count(out, "Using cache"), 4) assert.Check(c, is.Equal(strings.Count(out, "Using cache"), 4))
du2, err := client.DiskUsage(context.TODO()) du2, err := client.DiskUsage(context.TODO())
assert.Nil(c, err) assert.Check(c, err)
assert.Equal(c, du.BuilderSize, du2.BuilderSize) assert.Check(c, is.Equal(du.BuilderSize, du2.BuilderSize))
// rebuild with regular tar, confirm cache still applies // rebuild with regular tar, confirm cache still applies
fctx.Add("Dockerfile", dockerfile) fctx.Add("Dockerfile", dockerfile)
@@ -561,26 +561,26 @@ func (s *DockerSuite) TestBuildWithSession(c *check.C) {
"/build", "/build",
request.RawContent(fctx.AsTarReader(c)), request.RawContent(fctx.AsTarReader(c)),
request.ContentType("application/x-tar")) request.ContentType("application/x-tar"))
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode) assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
outBytes, err := request.ReadBody(body) outBytes, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(outBytes), "Successfully built") assert.Check(c, is.Contains(string(outBytes), "Successfully built"))
assert.Equal(c, strings.Count(string(outBytes), "Using cache"), 4) assert.Check(c, is.Equal(strings.Count(string(outBytes), "Using cache"), 4))
_, err = client.BuildCachePrune(context.TODO()) _, err = client.BuildCachePrune(context.TODO())
assert.Nil(c, err) assert.Check(c, err)
du, err = client.DiskUsage(context.TODO()) du, err = client.DiskUsage(context.TODO())
assert.Nil(c, err) assert.Check(c, err)
assert.Equal(c, du.BuilderSize, int64(0)) assert.Check(c, is.Equal(du.BuilderSize, int64(0)))
} }
func testBuildWithSession(c *check.C, dir, dockerfile string) (outStr string) { func testBuildWithSession(c *check.C, dir, dockerfile string) (outStr string) {
client := testEnv.APIClient() client := testEnv.APIClient()
sess, err := session.NewSession("foo1", "foo") sess, err := session.NewSession("foo1", "foo")
assert.Nil(c, err) assert.Check(c, err)
fsProvider := filesync.NewFSSyncProvider([]filesync.SyncedDir{ fsProvider := filesync.NewFSSyncProvider([]filesync.SyncedDir{
{Dir: dir}, {Dir: dir},
@@ -601,17 +601,17 @@ func testBuildWithSession(c *check.C, dir, dockerfile string) (outStr string) {
if err != nil { if err != nil {
return err return err
} }
assert.Equal(c, res.StatusCode, http.StatusOK) assert.Check(c, is.DeepEqual(res.StatusCode, http.StatusOK))
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(out), "Successfully built") assert.Check(c, is.Contains(string(out), "Successfully built"))
sess.Close() sess.Close()
outStr = string(out) outStr = string(out)
return nil return nil
}) })
err = g.Wait() err = g.Wait()
assert.Nil(c, err) assert.Check(c, err)
return return
} }
@@ -633,8 +633,8 @@ ENV foo bar`
c.Assert(res.StatusCode, checker.Equals, http.StatusOK) c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
out, err := request.ReadBody(body) out, err := request.ReadBody(body)
require.NoError(c, err) assert.NilError(c, err)
assert.Contains(c, string(out), "Successfully built") assert.Check(c, is.Contains(string(out), "Successfully built"))
} }
type buildLine struct { type buildLine struct {
@@ -651,7 +651,7 @@ func getImageIDsFromBuild(c *check.C, output []byte) []string {
continue continue
} }
entry := buildLine{} entry := buildLine{}
require.NoError(c, json.Unmarshal(line, &entry)) assert.NilError(c, json.Unmarshal(line, &entry))
if entry.Aux.ID != "" { if entry.Aux.ID != "" {
ids = append(ids, entry.Aux.ID) ids = append(ids, entry.Aux.ID)
} }

View File

@@ -31,9 +31,9 @@ import (
"github.com/docker/docker/volume" "github.com/docker/docker/volume"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/poll" "github.com/gotestyourself/gotestyourself/poll"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -2027,47 +2027,47 @@ func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) {
&containertypes.HostConfig{Mounts: []mounttypes.Mount{x.spec}}, &containertypes.HostConfig{Mounts: []mounttypes.Mount{x.spec}},
&networktypes.NetworkingConfig{}, &networktypes.NetworkingConfig{},
"") "")
require.NoError(c, err) assert.NilError(c, err)
containerInspect, err := apiclient.ContainerInspect(ctx, container.ID) containerInspect, err := apiclient.ContainerInspect(ctx, container.ID)
require.NoError(c, err) assert.NilError(c, err)
mps := containerInspect.Mounts mps := containerInspect.Mounts
require.Len(c, mps, 1) assert.Assert(c, is.Len(mps, 1))
mountPoint := mps[0] mountPoint := mps[0]
if x.expected.Source != "" { if x.expected.Source != "" {
assert.Equal(c, x.expected.Source, mountPoint.Source) assert.Check(c, is.Equal(x.expected.Source, mountPoint.Source))
} }
if x.expected.Name != "" { if x.expected.Name != "" {
assert.Equal(c, x.expected.Name, mountPoint.Name) assert.Check(c, is.Equal(x.expected.Name, mountPoint.Name))
} }
if x.expected.Driver != "" { if x.expected.Driver != "" {
assert.Equal(c, x.expected.Driver, mountPoint.Driver) assert.Check(c, is.Equal(x.expected.Driver, mountPoint.Driver))
} }
if x.expected.Propagation != "" { if x.expected.Propagation != "" {
assert.Equal(c, x.expected.Propagation, mountPoint.Propagation) assert.Check(c, is.Equal(x.expected.Propagation, mountPoint.Propagation))
} }
assert.Equal(c, x.expected.RW, mountPoint.RW) assert.Check(c, is.Equal(x.expected.RW, mountPoint.RW))
assert.Equal(c, x.expected.Type, mountPoint.Type) assert.Check(c, is.Equal(x.expected.Type, mountPoint.Type))
assert.Equal(c, x.expected.Mode, mountPoint.Mode) assert.Check(c, is.Equal(x.expected.Mode, mountPoint.Mode))
assert.Equal(c, x.expected.Destination, mountPoint.Destination) assert.Check(c, is.Equal(x.expected.Destination, mountPoint.Destination))
err = apiclient.ContainerStart(ctx, container.ID, types.ContainerStartOptions{}) err = apiclient.ContainerStart(ctx, container.ID, types.ContainerStartOptions{})
require.NoError(c, err) assert.NilError(c, err)
poll.WaitOn(c, containerExit(apiclient, container.ID), poll.WithDelay(time.Second)) poll.WaitOn(c, containerExit(apiclient, container.ID), poll.WithDelay(time.Second))
err = apiclient.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{ err = apiclient.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{
RemoveVolumes: true, RemoveVolumes: true,
Force: true, Force: true,
}) })
require.NoError(c, err) assert.NilError(c, err)
switch { switch {
// Named volumes still exist after the container is removed // Named volumes still exist after the container is removed
case x.spec.Type == "volume" && len(x.spec.Source) > 0: case x.spec.Type == "volume" && len(x.spec.Source) > 0:
_, err := apiclient.VolumeInspect(ctx, mountPoint.Name) _, err := apiclient.VolumeInspect(ctx, mountPoint.Name)
require.NoError(c, err) assert.NilError(c, err)
// Bind mounts are never removed with the container // Bind mounts are never removed with the container
case x.spec.Type == "bind": case x.spec.Type == "bind":
@@ -2075,7 +2075,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) {
// anonymous volumes are removed // anonymous volumes are removed
default: default:
_, err := apiclient.VolumeInspect(ctx, mountPoint.Name) _, err := apiclient.VolumeInspect(ctx, mountPoint.Name)
assert.True(c, client.IsErrNotFound(err)) assert.Check(c, client.IsErrNotFound(err))
} }
} }
} }

View File

@@ -13,8 +13,8 @@ import (
"github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/mount"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -65,12 +65,12 @@ func (s *DockerSuite) TestContainersAPICreateMountsBindNamedPipe(c *check.C) {
}, },
}, },
nil, name) nil, name)
require.NoError(c, err) assert.NilError(c, err)
err = client.ContainerStart(ctx, name, types.ContainerStartOptions{}) err = client.ContainerStart(ctx, name, types.ContainerStartOptions{})
require.NoError(c, err) assert.NilError(c, err)
err = <-ch err = <-ch
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, text, strings.TrimSpace(string(b))) assert.Check(c, is.Equal(text, strings.TrimSpace(string(b))))
} }

View File

@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/checker"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func (s *DockerSuite) TestInspectAPIContainerResponse(c *check.C) { func (s *DockerSuite) TestInspectAPIContainerResponse(c *check.C) {
@@ -115,8 +116,8 @@ func (s *DockerSuite) TestInspectAPIImageResponse(c *check.C) {
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(imageJSON.RepoTags, checker.HasLen, 2) c.Assert(imageJSON.RepoTags, checker.HasLen, 2)
assert.Contains(c, imageJSON.RepoTags, "busybox:latest") assert.Check(c, is.Contains(imageJSON.RepoTags, "busybox:latest"))
assert.Contains(c, imageJSON.RepoTags, "busybox:mytag") assert.Check(c, is.Contains(imageJSON.RepoTags, "busybox:mytag"))
} }
// #17131, #17139, #17173 // #17131, #17139, #17173

View File

@@ -25,8 +25,8 @@ import (
"github.com/docker/docker/integration-cli/request" "github.com/docker/docker/integration-cli/request"
"github.com/docker/swarmkit/ca" "github.com/docker/swarmkit/ca"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -1012,16 +1012,16 @@ func (s *DockerSwarmSuite) TestAPINetworkInspectWithScope(c *check.C) {
name := "test-scoped-network" name := "test-scoped-network"
ctx := context.Background() ctx := context.Background()
apiclient, err := d.NewClient() apiclient, err := d.NewClient()
require.NoError(c, err) assert.NilError(c, err)
resp, err := apiclient.NetworkCreate(ctx, name, types.NetworkCreate{Driver: "overlay"}) resp, err := apiclient.NetworkCreate(ctx, name, types.NetworkCreate{Driver: "overlay"})
require.NoError(c, err) assert.NilError(c, err)
network, err := apiclient.NetworkInspect(ctx, name, types.NetworkInspectOptions{}) network, err := apiclient.NetworkInspect(ctx, name, types.NetworkInspectOptions{})
require.NoError(c, err) assert.NilError(c, err)
assert.Equal(c, "swarm", network.Scope) assert.Check(c, is.Equal("swarm", network.Scope))
assert.Equal(c, resp.ID, network.ID) assert.Check(c, is.Equal(resp.ID, network.ID))
_, err = apiclient.NetworkInspect(ctx, name, types.NetworkInspectOptions{Scope: "local"}) _, err = apiclient.NetworkInspect(ctx, name, types.NetworkInspectOptions{Scope: "local"})
assert.True(c, client.IsErrNotFound(err)) assert.Check(c, client.IsErrNotFound(err))
} }

View File

@@ -15,8 +15,9 @@ import (
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/cli/build"
"github.com/go-check/check" "github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/stretchr/testify/assert"
) )
var ( var (
@@ -403,7 +404,7 @@ func (s *DockerRegistrySuite) TestInspectImageWithDigests(c *check.C) {
c.Assert(err, checker.IsNil) c.Assert(err, checker.IsNil)
c.Assert(imageJSON, checker.HasLen, 1) c.Assert(imageJSON, checker.HasLen, 1)
c.Assert(imageJSON[0].RepoDigests, checker.HasLen, 1) c.Assert(imageJSON[0].RepoDigests, checker.HasLen, 1)
assert.Contains(c, imageJSON[0].RepoDigests, imageReference) assert.Check(c, is.Contains(imageJSON[0].RepoDigests, imageReference))
} }
func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c *check.C) { func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c *check.C) {

View File

@@ -15,8 +15,8 @@ import (
"github.com/docker/docker/integration-cli/cli/build/fakecontext" "github.com/docker/docker/integration-cli/cli/build/fakecontext"
"github.com/docker/docker/integration/internal/request" "github.com/docker/docker/integration/internal/request"
"github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/jsonmessage"
"github.com/stretchr/testify/assert" "github.com/gotestyourself/gotestyourself/assert"
"github.com/stretchr/testify/require" is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestBuildWithRemoveAndForceRemove(t *testing.T) { func TestBuildWithRemoveAndForceRemove(t *testing.T) {
@@ -94,21 +94,21 @@ func TestBuildWithRemoveAndForceRemove(t *testing.T) {
buff := bytes.NewBuffer(nil) buff := bytes.NewBuffer(nil)
tw := tar.NewWriter(buff) tw := tar.NewWriter(buff)
require.NoError(t, tw.WriteHeader(&tar.Header{ assert.NilError(t, tw.WriteHeader(&tar.Header{
Name: "Dockerfile", Name: "Dockerfile",
Size: int64(len(dockerfile)), Size: int64(len(dockerfile)),
})) }))
_, err := tw.Write(dockerfile) _, err := tw.Write(dockerfile)
require.NoError(t, err) assert.NilError(t, err)
require.NoError(t, tw.Close()) assert.NilError(t, tw.Close())
resp, err := client.ImageBuild(ctx, buff, types.ImageBuildOptions{Remove: c.rm, ForceRemove: c.forceRm, NoCache: true}) resp, err := client.ImageBuild(ctx, buff, types.ImageBuildOptions{Remove: c.rm, ForceRemove: c.forceRm, NoCache: true})
require.NoError(t, err) assert.NilError(t, err)
defer resp.Body.Close() defer resp.Body.Close()
filter, err := buildContainerIdsFilter(resp.Body) filter, err := buildContainerIdsFilter(resp.Body)
require.NoError(t, err) assert.NilError(t, err)
remainingContainers, err := client.ContainerList(ctx, types.ContainerListOptions{Filters: filter, All: true}) remainingContainers, err := client.ContainerList(ctx, types.ContainerListOptions{Filters: filter, All: true})
require.NoError(t, err) assert.NilError(t, err)
require.Equal(t, c.numberOfIntermediateContainers, len(remainingContainers), "Expected %v remaining intermediate containers, got %v", c.numberOfIntermediateContainers, len(remainingContainers)) assert.Equal(t, c.numberOfIntermediateContainers, len(remainingContainers), "Expected %v remaining intermediate containers, got %v", c.numberOfIntermediateContainers, len(remainingContainers))
}) })
} }
} }
@@ -158,16 +158,16 @@ func TestBuildMultiStageParentConfig(t *testing.T) {
ForceRemove: true, ForceRemove: true,
Tags: []string{"build1"}, Tags: []string{"build1"},
}) })
require.NoError(t, err) assert.NilError(t, err)
_, err = io.Copy(ioutil.Discard, resp.Body) _, err = io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close() resp.Body.Close()
require.NoError(t, err) assert.NilError(t, err)
image, _, err := apiclient.ImageInspectWithRaw(ctx, "build1") image, _, err := apiclient.ImageInspectWithRaw(ctx, "build1")
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, "/foo/sub2", image.Config.WorkingDir) assert.Check(t, is.Equal("/foo/sub2", image.Config.WorkingDir))
assert.Contains(t, image.Config.Env, "WHO=parent") assert.Check(t, is.Contains(image.Config.Env, "WHO=parent"))
} }
func TestBuildWithEmptyLayers(t *testing.T) { func TestBuildWithEmptyLayers(t *testing.T) {
@@ -192,10 +192,10 @@ func TestBuildWithEmptyLayers(t *testing.T) {
Remove: true, Remove: true,
ForceRemove: true, ForceRemove: true,
}) })
require.NoError(t, err) assert.NilError(t, err)
_, err = io.Copy(ioutil.Discard, resp.Body) _, err = io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close() resp.Body.Close()
require.NoError(t, err) assert.NilError(t, err)
} }
// TestBuildMultiStageOnBuild checks that ONBUILD commands are applied to // TestBuildMultiStageOnBuild checks that ONBUILD commands are applied to
@@ -228,20 +228,20 @@ RUN cat somefile`
}) })
out := bytes.NewBuffer(nil) out := bytes.NewBuffer(nil)
require.NoError(t, err) assert.NilError(t, err)
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
resp.Body.Close() resp.Body.Close()
require.NoError(t, err) assert.NilError(t, err)
assert.Contains(t, out.String(), "Successfully built") assert.Check(t, is.Contains(out.String(), "Successfully built"))
imageIDs, err := getImageIDsFromBuild(out.Bytes()) imageIDs, err := getImageIDsFromBuild(out.Bytes())
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, 3, len(imageIDs)) assert.Check(t, is.Equal(3, len(imageIDs)))
image, _, err := apiclient.ImageInspectWithRaw(context.Background(), imageIDs[2]) image, _, err := apiclient.ImageInspectWithRaw(context.Background(), imageIDs[2])
require.NoError(t, err) assert.NilError(t, err)
assert.Contains(t, image.Config.Env, "bar=baz") assert.Check(t, is.Contains(image.Config.Env, "bar=baz"))
} }
// #35403 #36122 // #35403 #36122
@@ -260,7 +260,7 @@ COPY bar /`
writeTarRecord(t, w, "../foo", "foocontents0") writeTarRecord(t, w, "../foo", "foocontents0")
writeTarRecord(t, w, "/bar", "barcontents0") writeTarRecord(t, w, "/bar", "barcontents0")
err := w.Close() err := w.Close()
require.NoError(t, err) assert.NilError(t, err)
apiclient := testEnv.APIClient() apiclient := testEnv.APIClient()
resp, err := apiclient.ImageBuild(ctx, resp, err := apiclient.ImageBuild(ctx,
@@ -271,10 +271,10 @@ COPY bar /`
}) })
out := bytes.NewBuffer(nil) out := bytes.NewBuffer(nil)
require.NoError(t, err) assert.NilError(t, err)
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
resp.Body.Close() resp.Body.Close()
require.NoError(t, err) assert.NilError(t, err)
// repeat with changed data should not cause cache hits // repeat with changed data should not cause cache hits
@@ -284,7 +284,7 @@ COPY bar /`
writeTarRecord(t, w, "../foo", "foocontents1") writeTarRecord(t, w, "../foo", "foocontents1")
writeTarRecord(t, w, "/bar", "barcontents1") writeTarRecord(t, w, "/bar", "barcontents1")
err = w.Close() err = w.Close()
require.NoError(t, err) assert.NilError(t, err)
resp, err = apiclient.ImageBuild(ctx, resp, err = apiclient.ImageBuild(ctx,
buf, buf,
@@ -294,10 +294,10 @@ COPY bar /`
}) })
out = bytes.NewBuffer(nil) out = bytes.NewBuffer(nil)
require.NoError(t, err) assert.NilError(t, err)
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
resp.Body.Close() resp.Body.Close()
require.NoError(t, err) assert.NilError(t, err)
require.NotContains(t, out.String(), "Using cache") require.NotContains(t, out.String(), "Using cache")
} }
@@ -333,12 +333,12 @@ RUN [ ! -f foo ]
}) })
out := bytes.NewBuffer(nil) out := bytes.NewBuffer(nil)
require.NoError(t, err) assert.NilError(t, err)
_, err = io.Copy(out, resp.Body) _, err = io.Copy(out, resp.Body)
resp.Body.Close() resp.Body.Close()
require.NoError(t, err) assert.NilError(t, err)
assert.Contains(t, out.String(), "Successfully built") assert.Check(t, is.Contains(out.String(), "Successfully built"))
} }
func writeTarRecord(t *testing.T, w *tar.Writer, fn, contents string) { func writeTarRecord(t *testing.T, w *tar.Writer, fn, contents string) {
@@ -348,9 +348,9 @@ func writeTarRecord(t *testing.T, w *tar.Writer, fn, contents string) {
Size: int64(len(contents)), Size: int64(len(contents)),
Typeflag: '0', Typeflag: '0',
}) })
require.NoError(t, err) assert.NilError(t, err)
_, err = w.Write([]byte(contents)) _, err = w.Write([]byte(contents))
require.NoError(t, err) assert.NilError(t, err)
} }
type buildLine struct { type buildLine struct {

View File

@@ -14,9 +14,9 @@ import (
"github.com/docker/docker/integration/internal/swarm" "github.com/docker/docker/integration/internal/swarm"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/stdcopy"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/skip" "github.com/gotestyourself/gotestyourself/skip"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@@ -27,14 +27,14 @@ func TestConfigList(t *testing.T) {
d := swarm.NewSwarm(t, testEnv) d := swarm.NewSwarm(t, testEnv)
defer d.Stop(t) defer d.Stop(t)
client, err := client.NewClientWithOpts(client.WithHost((d.Sock()))) client, err := client.NewClientWithOpts(client.WithHost((d.Sock())))
require.NoError(t, err) assert.NilError(t, err)
ctx := context.Background() ctx := context.Background()
// This test case is ported from the original TestConfigsEmptyList // This test case is ported from the original TestConfigsEmptyList
configs, err := client.ConfigList(ctx, types.ConfigListOptions{}) configs, err := client.ConfigList(ctx, types.ConfigListOptions{})
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, len(configs), 0) assert.Check(t, is.Equal(len(configs), 0))
testName0 := "test0" testName0 := "test0"
testName1 := "test1" testName1 := "test1"
@@ -57,8 +57,8 @@ func TestConfigList(t *testing.T) {
// test by `config ls` // test by `config ls`
entries, err := client.ConfigList(ctx, types.ConfigListOptions{}) entries, err := client.ConfigList(ctx, types.ConfigListOptions{})
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, names(entries), testNames) assert.Check(t, is.DeepEqual(names(entries), testNames))
testCases := []struct { testCases := []struct {
filters filters.Args filters filters.Args
@@ -92,8 +92,8 @@ func TestConfigList(t *testing.T) {
entries, err = client.ConfigList(ctx, types.ConfigListOptions{ entries, err = client.ConfigList(ctx, types.ConfigListOptions{
Filters: tc.filters, Filters: tc.filters,
}) })
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, names(entries), tc.expected) assert.Check(t, is.DeepEqual(names(entries), tc.expected))
} }
} }
@@ -106,8 +106,8 @@ func createConfig(ctx context.Context, t *testing.T, client client.APIClient, na
}, },
Data: data, Data: data,
}) })
require.NoError(t, err) assert.NilError(t, err)
assert.NotEqual(t, config.ID, "") assert.Check(t, config.ID != "")
return config.ID return config.ID
} }
@@ -118,7 +118,7 @@ func TestConfigsCreateAndDelete(t *testing.T) {
d := swarm.NewSwarm(t, testEnv) d := swarm.NewSwarm(t, testEnv)
defer d.Stop(t) defer d.Stop(t)
client, err := client.NewClientWithOpts(client.WithHost((d.Sock()))) client, err := client.NewClientWithOpts(client.WithHost((d.Sock())))
require.NoError(t, err) assert.NilError(t, err)
ctx := context.Background() ctx := context.Background()
@@ -128,12 +128,12 @@ func TestConfigsCreateAndDelete(t *testing.T) {
configID := createConfig(ctx, t, client, testName, []byte("TESTINGDATA"), nil) configID := createConfig(ctx, t, client, testName, []byte("TESTINGDATA"), nil)
insp, _, err := client.ConfigInspectWithRaw(ctx, configID) insp, _, err := client.ConfigInspectWithRaw(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, insp.Spec.Name, testName) assert.Check(t, is.Equal(insp.Spec.Name, testName))
// This test case is ported from the original TestConfigsDelete // This test case is ported from the original TestConfigsDelete
err = client.ConfigRemove(ctx, configID) err = client.ConfigRemove(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
insp, _, err = client.ConfigInspectWithRaw(ctx, configID) insp, _, err = client.ConfigInspectWithRaw(ctx, configID)
testutil.ErrorContains(t, err, "No such config") testutil.ErrorContains(t, err, "No such config")
@@ -146,7 +146,7 @@ func TestConfigsUpdate(t *testing.T) {
d := swarm.NewSwarm(t, testEnv) d := swarm.NewSwarm(t, testEnv)
defer d.Stop(t) defer d.Stop(t)
client, err := client.NewClientWithOpts(client.WithHost((d.Sock()))) client, err := client.NewClientWithOpts(client.WithHost((d.Sock())))
require.NoError(t, err) assert.NilError(t, err)
ctx := context.Background() ctx := context.Background()
@@ -156,35 +156,35 @@ func TestConfigsUpdate(t *testing.T) {
configID := createConfig(ctx, t, client, testName, []byte("TESTINGDATA"), nil) configID := createConfig(ctx, t, client, testName, []byte("TESTINGDATA"), nil)
insp, _, err := client.ConfigInspectWithRaw(ctx, configID) insp, _, err := client.ConfigInspectWithRaw(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, insp.ID, configID) assert.Check(t, is.Equal(insp.ID, configID))
// test UpdateConfig with full ID // test UpdateConfig with full ID
insp.Spec.Labels = map[string]string{"test": "test1"} insp.Spec.Labels = map[string]string{"test": "test1"}
err = client.ConfigUpdate(ctx, configID, insp.Version, insp.Spec) err = client.ConfigUpdate(ctx, configID, insp.Version, insp.Spec)
require.NoError(t, err) assert.NilError(t, err)
insp, _, err = client.ConfigInspectWithRaw(ctx, configID) insp, _, err = client.ConfigInspectWithRaw(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, insp.Spec.Labels["test"], "test1") assert.Check(t, is.Equal(insp.Spec.Labels["test"], "test1"))
// test UpdateConfig with full name // test UpdateConfig with full name
insp.Spec.Labels = map[string]string{"test": "test2"} insp.Spec.Labels = map[string]string{"test": "test2"}
err = client.ConfigUpdate(ctx, testName, insp.Version, insp.Spec) err = client.ConfigUpdate(ctx, testName, insp.Version, insp.Spec)
require.NoError(t, err) assert.NilError(t, err)
insp, _, err = client.ConfigInspectWithRaw(ctx, configID) insp, _, err = client.ConfigInspectWithRaw(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, insp.Spec.Labels["test"], "test2") assert.Check(t, is.Equal(insp.Spec.Labels["test"], "test2"))
// test UpdateConfig with prefix ID // test UpdateConfig with prefix ID
insp.Spec.Labels = map[string]string{"test": "test3"} insp.Spec.Labels = map[string]string{"test": "test3"}
err = client.ConfigUpdate(ctx, configID[:1], insp.Version, insp.Spec) err = client.ConfigUpdate(ctx, configID[:1], insp.Version, insp.Spec)
require.NoError(t, err) assert.NilError(t, err)
insp, _, err = client.ConfigInspectWithRaw(ctx, configID) insp, _, err = client.ConfigInspectWithRaw(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, insp.Spec.Labels["test"], "test3") assert.Check(t, is.Equal(insp.Spec.Labels["test"], "test3"))
// test UpdateConfig in updating Data which is not supported in daemon // test UpdateConfig in updating Data which is not supported in daemon
// this test will produce an error in func UpdateConfig // this test will produce an error in func UpdateConfig
@@ -207,7 +207,7 @@ func TestTemplatedConfig(t *testing.T) {
Data: []byte("this is a secret"), Data: []byte("this is a secret"),
} }
referencedSecret, err := client.SecretCreate(ctx, referencedSecretSpec) referencedSecret, err := client.SecretCreate(ctx, referencedSecretSpec)
assert.NoError(t, err) assert.Check(t, err)
referencedConfigSpec := swarmtypes.ConfigSpec{ referencedConfigSpec := swarmtypes.ConfigSpec{
Annotations: swarmtypes.Annotations{ Annotations: swarmtypes.Annotations{
@@ -216,7 +216,7 @@ func TestTemplatedConfig(t *testing.T) {
Data: []byte("this is a config"), Data: []byte("this is a config"),
} }
referencedConfig, err := client.ConfigCreate(ctx, referencedConfigSpec) referencedConfig, err := client.ConfigCreate(ctx, referencedConfigSpec)
assert.NoError(t, err) assert.Check(t, err)
configSpec := swarmtypes.ConfigSpec{ configSpec := swarmtypes.ConfigSpec{
Annotations: swarmtypes.Annotations{ Annotations: swarmtypes.Annotations{
@@ -231,7 +231,7 @@ func TestTemplatedConfig(t *testing.T) {
} }
templatedConfig, err := client.ConfigCreate(ctx, configSpec) templatedConfig, err := client.ConfigCreate(ctx, configSpec)
assert.NoError(t, err) assert.Check(t, err)
serviceID := swarm.CreateService(t, d, serviceID := swarm.CreateService(t, d,
swarm.ServiceWithConfig( swarm.ServiceWithConfig(
@@ -309,8 +309,8 @@ func TestTemplatedConfig(t *testing.T) {
func assertAttachedStream(t *testing.T, attach types.HijackedResponse, expect string) { func assertAttachedStream(t *testing.T, attach types.HijackedResponse, expect string) {
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
_, err := stdcopy.StdCopy(buf, buf, attach.Reader) _, err := stdcopy.StdCopy(buf, buf, attach.Reader)
require.NoError(t, err) assert.NilError(t, err)
assert.Contains(t, buf.String(), expect) assert.Check(t, is.Contains(buf.String(), expect))
} }
func waitAndAssert(t *testing.T, timeout time.Duration, f func(*testing.T) bool) { func waitAndAssert(t *testing.T, timeout time.Duration, f func(*testing.T) bool) {
@@ -336,7 +336,7 @@ func TestConfigInspect(t *testing.T) {
d := swarm.NewSwarm(t, testEnv) d := swarm.NewSwarm(t, testEnv)
defer d.Stop(t) defer d.Stop(t)
client, err := client.NewClientWithOpts(client.WithHost((d.Sock()))) client, err := client.NewClientWithOpts(client.WithHost((d.Sock())))
require.NoError(t, err) assert.NilError(t, err)
ctx := context.Background() ctx := context.Background()
@@ -344,11 +344,11 @@ func TestConfigInspect(t *testing.T) {
configID := createConfig(ctx, t, client, testName, []byte("TESTINGDATA"), nil) configID := createConfig(ctx, t, client, testName, []byte("TESTINGDATA"), nil)
insp, body, err := client.ConfigInspectWithRaw(ctx, configID) insp, body, err := client.ConfigInspectWithRaw(ctx, configID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, insp.Spec.Name, testName) assert.Check(t, is.Equal(insp.Spec.Name, testName))
var config swarmtypes.Config var config swarmtypes.Config
err = json.Unmarshal(body, &config) err = json.Unmarshal(body, &config)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, config, insp) assert.Check(t, is.DeepEqual(config, insp))
} }

View File

@@ -9,8 +9,9 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
"github.com/docker/docker/integration/internal/container" "github.com/docker/docker/integration/internal/container"
"github.com/docker/docker/internal/testutil" "github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/skip" "github.com/gotestyourself/gotestyourself/skip"
"github.com/stretchr/testify/require"
) )
func TestCopyFromContainerPathDoesNotExist(t *testing.T) { func TestCopyFromContainerPathDoesNotExist(t *testing.T) {
@@ -21,7 +22,7 @@ func TestCopyFromContainerPathDoesNotExist(t *testing.T) {
cid := container.Create(t, ctx, apiclient) cid := container.Create(t, ctx, apiclient)
_, _, err := apiclient.CopyFromContainer(ctx, cid, "/dne") _, _, err := apiclient.CopyFromContainer(ctx, cid, "/dne")
require.True(t, client.IsErrNotFound(err)) assert.Assert(t, client.IsErrNotFound(err))
expected := fmt.Sprintf("No such container:path: %s:%s", cid, "/dne") expected := fmt.Sprintf("No such container:path: %s:%s", cid, "/dne")
testutil.ErrorContains(t, err, expected) testutil.ErrorContains(t, err, expected)
} }
@@ -35,7 +36,7 @@ func TestCopyFromContainerPathIsNotDir(t *testing.T) {
cid := container.Create(t, ctx, apiclient) cid := container.Create(t, ctx, apiclient)
_, _, err := apiclient.CopyFromContainer(ctx, cid, "/etc/passwd/") _, _, err := apiclient.CopyFromContainer(ctx, cid, "/etc/passwd/")
require.Contains(t, err.Error(), "not a directory") assert.Assert(t, is.Contains(err.Error(), "not a directory"))
} }
func TestCopyToContainerPathDoesNotExist(t *testing.T) { func TestCopyToContainerPathDoesNotExist(t *testing.T) {
@@ -47,7 +48,7 @@ func TestCopyToContainerPathDoesNotExist(t *testing.T) {
cid := container.Create(t, ctx, apiclient) cid := container.Create(t, ctx, apiclient)
err := apiclient.CopyToContainer(ctx, cid, "/dne", nil, types.CopyToContainerOptions{}) err := apiclient.CopyToContainer(ctx, cid, "/dne", nil, types.CopyToContainerOptions{})
require.True(t, client.IsErrNotFound(err)) assert.Assert(t, client.IsErrNotFound(err))
expected := fmt.Sprintf("No such container:path: %s:%s", cid, "/dne") expected := fmt.Sprintf("No such container:path: %s:%s", cid, "/dne")
testutil.ErrorContains(t, err, expected) testutil.ErrorContains(t, err, expected)
} }
@@ -61,5 +62,5 @@ func TestCopyToContainerPathIsNotDir(t *testing.T) {
cid := container.Create(t, ctx, apiclient) cid := container.Create(t, ctx, apiclient)
err := apiclient.CopyToContainer(ctx, cid, "/etc/passwd/", nil, types.CopyToContainerOptions{}) err := apiclient.CopyToContainer(ctx, cid, "/etc/passwd/", nil, types.CopyToContainerOptions{})
require.Contains(t, err.Error(), "not a directory") assert.Assert(t, is.Contains(err.Error(), "not a directory"))
} }

View File

@@ -11,8 +11,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/integration-cli/daemon"
"github.com/docker/docker/integration/internal/container" "github.com/docker/docker/integration/internal/container"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/skip" "github.com/gotestyourself/gotestyourself/skip"
"github.com/stretchr/testify/assert"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@@ -35,7 +35,7 @@ func TestContainerStartOnDaemonRestart(t *testing.T) {
defer d.Stop(t) defer d.Stop(t)
client, err := d.NewClient() client, err := d.NewClient()
assert.NoError(t, err, "error creating client") assert.Check(t, err, "error creating client")
ctx := context.Background() ctx := context.Background()
@@ -43,36 +43,36 @@ func TestContainerStartOnDaemonRestart(t *testing.T) {
defer client.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) defer client.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true})
err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{}) err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{})
assert.NoError(t, err, "error starting test container") assert.Check(t, err, "error starting test container")
inspect, err := client.ContainerInspect(ctx, cID) inspect, err := client.ContainerInspect(ctx, cID)
assert.NoError(t, err, "error getting inspect data") assert.Check(t, err, "error getting inspect data")
ppid := getContainerdShimPid(t, inspect) ppid := getContainerdShimPid(t, inspect)
err = d.Kill() err = d.Kill()
assert.NoError(t, err, "failed to kill test daemon") assert.Check(t, err, "failed to kill test daemon")
err = unix.Kill(inspect.State.Pid, unix.SIGKILL) err = unix.Kill(inspect.State.Pid, unix.SIGKILL)
assert.NoError(t, err, "failed to kill container process") assert.Check(t, err, "failed to kill container process")
err = unix.Kill(ppid, unix.SIGKILL) err = unix.Kill(ppid, unix.SIGKILL)
assert.NoError(t, err, "failed to kill containerd-shim") assert.Check(t, err, "failed to kill containerd-shim")
d.Start(t, "--iptables=false") d.Start(t, "--iptables=false")
err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{}) err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{})
assert.NoError(t, err, "failed to start test container") assert.Check(t, err, "failed to start test container")
} }
func getContainerdShimPid(t *testing.T, c types.ContainerJSON) int { func getContainerdShimPid(t *testing.T, c types.ContainerJSON) int {
statB, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/stat", c.State.Pid)) statB, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/stat", c.State.Pid))
assert.NoError(t, err, "error looking up containerd-shim pid") assert.Check(t, err, "error looking up containerd-shim pid")
// ppid is the 4th entry in `/proc/pid/stat` // ppid is the 4th entry in `/proc/pid/stat`
ppid, err := strconv.Atoi(strings.Fields(string(statB))[3]) ppid, err := strconv.Atoi(strings.Fields(string(statB))[3])
assert.NoError(t, err, "error converting ppid field to int") assert.Check(t, err, "error converting ppid field to int")
assert.NotEqual(t, ppid, 1, "got unexpected ppid") assert.Check(t, ppid != 1, "got unexpected ppid")
return ppid return ppid
} }

View File

@@ -9,9 +9,9 @@ import (
"github.com/docker/docker/integration/internal/container" "github.com/docker/docker/integration/internal/container"
"github.com/docker/docker/integration/internal/request" "github.com/docker/docker/integration/internal/request"
"github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/archive"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/poll" "github.com/gotestyourself/gotestyourself/poll"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestDiff(t *testing.T) { func TestDiff(t *testing.T) {
@@ -38,6 +38,6 @@ func TestDiff(t *testing.T) {
} }
items, err := client.ContainerDiff(ctx, cID) items, err := client.ContainerDiff(ctx, cID)
require.NoError(t, err) assert.NilError(t, err)
assert.Equal(t, expected, items) assert.Check(t, is.DeepEqual(expected, items))
} }

View File

@@ -9,7 +9,8 @@ import (
"github.com/docker/docker/api/types/strslice" "github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/integration/internal/container" "github.com/docker/docker/integration/internal/container"
"github.com/docker/docker/integration/internal/request" "github.com/docker/docker/integration/internal/request"
"github.com/stretchr/testify/require" "github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
) )
func TestExec(t *testing.T) { func TestExec(t *testing.T) {
@@ -27,7 +28,7 @@ func TestExec(t *testing.T) {
Cmd: strslice.StrSlice([]string{"sh", "-c", "env"}), Cmd: strslice.StrSlice([]string{"sh", "-c", "env"}),
}, },
) )
require.NoError(t, err) assert.NilError(t, err)
resp, err := client.ContainerExecAttach(ctx, id.ID, resp, err := client.ContainerExecAttach(ctx, id.ID,
types.ExecStartCheck{ types.ExecStartCheck{
@@ -35,12 +36,12 @@ func TestExec(t *testing.T) {
Tty: false, Tty: false,
}, },
) )
require.NoError(t, err) assert.NilError(t, err)
defer resp.Close() defer resp.Close()
r, err := ioutil.ReadAll(resp.Reader) r, err := ioutil.ReadAll(resp.Reader)
require.NoError(t, err) assert.NilError(t, err)
out := string(r) out := string(r)
require.NoError(t, err) assert.NilError(t, err)
require.Contains(t, out, "PWD=/tmp", "exec command not running in expected /tmp working directory") assert.Assert(t, is.Contains(out, "PWD=/tmp"), "exec command not running in expected /tmp working directory")
require.Contains(t, out, "FOO=BAR", "exec command not running with expected environment variable FOO") assert.Assert(t, is.Contains(out, "FOO=BAR"), "exec command not running with expected environment variable FOO")
} }

Some files were not shown because too many files have changed in this diff Show More