Merge pull request #513 from thaJeztah/18.03-backport-test-improvements

[18.03] Updates to integration tests, migrate to "gotestyourself"
This commit is contained in:
Andrew Hsu
2018-04-18 16:19:12 -07:00
committed by GitHub
332 changed files with 7318 additions and 10643 deletions
+2 -1
View File
@@ -182,7 +182,8 @@ RUN echo "source $PWD/hack/make/.integration-test-helpers" >> /etc/bash.bashrc
COPY contrib/download-frozen-image-v2.sh /go/src/github.com/docker/docker/contrib/
RUN ./contrib/download-frozen-image-v2.sh /docker-frozen-images \
buildpack-deps:jessie@sha256:dd86dced7c9cd2a724e779730f0a53f93b7ef42228d4344b25ce9a42a1486251 \
busybox:1.27-glibc@sha256:8c8f261a462eead45ab8e610d3e8f7a1e4fd1cd9bed5bc0a0c386784ab105d8e \
busybox:latest@sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0 \
busybox:glibc@sha256:0b55a30394294ab23b9afd58fab94e61a923f5834fba7ddbae7f8e0c11ba85e6 \
debian:jessie@sha256:287a20c5f73087ab406e6b364833e3fb7b3ae63ca0eb3486555dc27ed32c6e60 \
hello-world:latest@sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
# See also ensureFrozenImagesLinux() in "integration-cli/fixtures_linux_daemon_test.go" (which needs to be updated when adding images to this list)
+2 -1
View File
@@ -147,7 +147,8 @@ RUN ln -sv $PWD/contrib/completion/bash/docker /etc/bash_completion.d/docker
COPY contrib/download-frozen-image-v2.sh /go/src/github.com/docker/docker/contrib/
RUN ./contrib/download-frozen-image-v2.sh /docker-frozen-images \
buildpack-deps:jessie@sha256:dd86dced7c9cd2a724e779730f0a53f93b7ef42228d4344b25ce9a42a1486251 \
busybox:1.27-glibc@sha256:8c8f261a462eead45ab8e610d3e8f7a1e4fd1cd9bed5bc0a0c386784ab105d8e \
busybox:latest@sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0 \
busybox:glibc@sha256:0b55a30394294ab23b9afd58fab94e61a923f5834fba7ddbae7f8e0c11ba85e6 \
debian:jessie@sha256:287a20c5f73087ab406e6b364833e3fb7b3ae63ca0eb3486555dc27ed32c6e60 \
hello-world:latest@sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
# See also ensureFrozenImagesLinux() in "integration-cli/fixtures_linux_daemon_test.go" (which needs to be updated when adding images to this list)
+2 -1
View File
@@ -133,7 +133,8 @@ RUN ln -sv $PWD/contrib/completion/bash/docker /etc/bash_completion.d/docker
COPY contrib/download-frozen-image-v2.sh /go/src/github.com/docker/docker/contrib/
RUN ./contrib/download-frozen-image-v2.sh /docker-frozen-images \
buildpack-deps:jessie@sha256:dd86dced7c9cd2a724e779730f0a53f93b7ef42228d4344b25ce9a42a1486251 \
busybox:1.27-glibc@sha256:8c8f261a462eead45ab8e610d3e8f7a1e4fd1cd9bed5bc0a0c386784ab105d8e \
busybox:latest@sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0 \
busybox:glibc@sha256:0b55a30394294ab23b9afd58fab94e61a923f5834fba7ddbae7f8e0c11ba85e6 \
debian:jessie@sha256:287a20c5f73087ab406e6b364833e3fb7b3ae63ca0eb3486555dc27ed32c6e60 \
hello-world:latest@sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
# See also ensureFrozenImagesLinux() in "integration-cli/fixtures_linux_daemon_test.go" (which needs to be updated when adding images to this list)
+2 -1
View File
@@ -17,7 +17,8 @@ WORKDIR /go/src/github.com/docker/docker/
COPY contrib/download-frozen-image-v2.sh contrib/download-frozen-image-v2.sh
RUN contrib/download-frozen-image-v2.sh /output/docker-frozen-images \
buildpack-deps:jessie@sha256:dd86dced7c9cd2a724e779730f0a53f93b7ef42228d4344b25ce9a42a1486251 \
busybox:1.27-glibc@sha256:8c8f261a462eead45ab8e610d3e8f7a1e4fd1cd9bed5bc0a0c386784ab105d8e \
busybox:latest@sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0 \
busybox:glibc@sha256:0b55a30394294ab23b9afd58fab94e61a923f5834fba7ddbae7f8e0c11ba85e6 \
debian:jessie@sha256:287a20c5f73087ab406e6b364833e3fb7b3ae63ca0eb3486555dc27ed32c6e60 \
hello-world:latest@sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
+2 -1
View File
@@ -131,7 +131,8 @@ RUN ln -sv $PWD/contrib/completion/bash/docker /etc/bash_completion.d/docker
COPY contrib/download-frozen-image-v2.sh /go/src/github.com/docker/docker/contrib/
RUN ./contrib/download-frozen-image-v2.sh /docker-frozen-images \
buildpack-deps:jessie@sha256:dd86dced7c9cd2a724e779730f0a53f93b7ef42228d4344b25ce9a42a1486251 \
busybox:1.27-glibc@sha256:8c8f261a462eead45ab8e610d3e8f7a1e4fd1cd9bed5bc0a0c386784ab105d8e \
busybox:latest@sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0 \
busybox:glibc@sha256:0b55a30394294ab23b9afd58fab94e61a923f5834fba7ddbae7f8e0c11ba85e6 \
debian:jessie@sha256:287a20c5f73087ab406e6b364833e3fb7b3ae63ca0eb3486555dc27ed32c6e60 \
hello-world:latest@sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
# See also ensureFrozenImagesLinux() in "integration-cli/fixtures_linux_daemon_test.go" (which needs to be updated when adding images to this list)
+2 -1
View File
@@ -125,7 +125,8 @@ RUN ln -sv $PWD/contrib/completion/bash/docker /etc/bash_completion.d/docker
COPY contrib/download-frozen-image-v2.sh /go/src/github.com/docker/docker/contrib/
RUN ./contrib/download-frozen-image-v2.sh /docker-frozen-images \
buildpack-deps:jessie@sha256:dd86dced7c9cd2a724e779730f0a53f93b7ef42228d4344b25ce9a42a1486251 \
busybox:1.27-glibc@sha256:8c8f261a462eead45ab8e610d3e8f7a1e4fd1cd9bed5bc0a0c386784ab105d8e \
busybox:latest@sha256:bbc3a03235220b170ba48a157dd097dd1379299370e1ed99ce976df0355d24f0 \
busybox:glibc@sha256:0b55a30394294ab23b9afd58fab94e61a923f5834fba7ddbae7f8e0c11ba85e6 \
debian:jessie@sha256:287a20c5f73087ab406e6b364833e3fb7b3ae63ca0eb3486555dc27ed32c6e60 \
hello-world:latest@sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
# See also ensureFrozenImagesLinux() in "integration-cli/fixtures_linux_daemon_test.go" (which needs to be updated when adding images to this list)
+2 -2
View File
@@ -8,11 +8,11 @@ questions you may have as an aspiring Moby contributor.
Moby has two test suites (and one legacy test suite):
* Unit tests - use standard `go test` and
[testify](https://github.com/stretchr/testify) assertions. They are located in
[gotestyourself/assert](https://godoc.org/github.com/gotestyourself/gotestyourself/assert) assertions. They are located in
the package they test. Unit tests should be fast and test only their own
package.
* API integration tests - use standard `go test` and
[testify](https://github.com/stretchr/testify) assertions. They are located in
[gotestyourself/assert](https://godoc.org/github.com/gotestyourself/gotestyourself/assert) assertions. They are located in
`./integration/<component>` directories, where `component` is: container,
image, volume, etc. These tests perform HTTP requests to an API endpoint and
check the HTTP response and daemon state after the call.
@@ -3,7 +3,8 @@ package middleware // import "github.com/docker/docker/api/server/middleware"
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestMaskSecretKeys(t *testing.T) {
@@ -53,6 +54,6 @@ func TestMaskSecretKeys(t *testing.T) {
for _, testcase := range tests {
maskSecretKeys(testcase.input, testcase.path)
assert.Equal(t, testcase.expected, testcase.input)
assert.Check(t, is.DeepEqual(testcase.expected, testcase.input))
}
}
@@ -7,7 +7,8 @@ import (
"testing"
"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"
)
@@ -17,7 +18,7 @@ func TestVersionMiddlewareVersion(t *testing.T) {
expectedVersion := defaultVersion
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
v := httputils.VersionFromContext(ctx)
assert.Equal(t, expectedVersion, v)
assert.Check(t, is.Equal(expectedVersion, v))
return nil
}
@@ -56,9 +57,9 @@ func TestVersionMiddlewareVersion(t *testing.T) {
err := h(ctx, resp, req, map[string]string{"version": test.reqVersion})
if test.errString != "" {
assert.EqualError(t, err, test.errString)
assert.Check(t, is.Error(err, test.errString))
} else {
assert.NoError(t, err)
assert.Check(t, err)
}
}
}
@@ -66,7 +67,7 @@ func TestVersionMiddlewareVersion(t *testing.T) {
func TestVersionMiddlewareWithErrorsReturnsHeaders(t *testing.T) {
handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
v := httputils.VersionFromContext(ctx)
assert.NotEmpty(t, v)
assert.Check(t, len(v) != 0)
return nil
}
@@ -81,11 +82,11 @@ func TestVersionMiddlewareWithErrorsReturnsHeaders(t *testing.T) {
vars := map[string]string{"version": "0.1"}
err := h(ctx, resp, req, vars)
assert.Error(t, err)
assert.Check(t, is.ErrorContains(err, ""))
hdr := resp.Result().Header
assert.Contains(t, hdr.Get("Server"), "Docker/"+defaultVersion)
assert.Contains(t, hdr.Get("Server"), runtime.GOOS)
assert.Equal(t, hdr.Get("API-Version"), defaultVersion)
assert.Equal(t, hdr.Get("OSType"), runtime.GOOS)
assert.Check(t, is.Contains(hdr.Get("Server"), "Docker/"+defaultVersion))
assert.Check(t, is.Contains(hdr.Get("Server"), runtime.GOOS))
assert.Check(t, is.Equal(hdr.Get("API-Version"), defaultVersion))
assert.Check(t, is.Equal(hdr.Get("OSType"), runtime.GOOS))
}
@@ -4,8 +4,8 @@ import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestParseArgs(t *testing.T) {
@@ -22,10 +22,10 @@ func TestParseArgs(t *testing.T) {
for i := range flagArgs {
args, err = ParseFlag(flagArgs[i], args)
require.NoError(t, err)
assert.NilError(t, err)
}
assert.Len(t, args.Get("created"), 1)
assert.Len(t, args.Get("image.name"), 2)
assert.Check(t, is.Len(args.Get("created"), 1))
assert.Check(t, is.Len(args.Get("image.name"), 2))
}
func TestParseArgsEdgeCase(t *testing.T) {
@@ -231,7 +231,7 @@ func TestArgsMatch(t *testing.T) {
}
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)
}
@@ -255,8 +255,7 @@ func TestArgsMatch(t *testing.T) {
}
for args, field := range differs {
assert.False(t, args.Match(field, source),
"Expected field %s to not match %s", field, source)
assert.Check(t, !args.Match(field, source), "Expected field %s to not match %s", field, source)
}
}
@@ -2,9 +2,11 @@ package dockerfile // import "github.com/docker/docker/builder/dockerfile"
import (
"bytes"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func strPtr(source string) *string {
@@ -39,7 +41,7 @@ func TestGetAllAllowed(t *testing.T) {
"ArgFromMeta": "frommeta1",
"ArgFromMetaOverridden": "fromdockerfile3",
}
assert.Equal(t, expected, all)
assert.Check(t, is.DeepEqual(expected, all))
}
func TestGetAllMeta(t *testing.T) {
@@ -61,7 +63,7 @@ func TestGetAllMeta(t *testing.T) {
"ArgOverriddenByOptions": "fromopt2",
"ArgNoDefaultInMetaFromOptions": "fromopt3",
}
assert.Equal(t, expected, all)
assert.Check(t, is.DeepEqual(expected, all))
}
func TestWarnOnUnusedBuildArgs(t *testing.T) {
@@ -77,10 +79,10 @@ func TestWarnOnUnusedBuildArgs(t *testing.T) {
buffer := new(bytes.Buffer)
buildArgs.WarnOnUnusedBuildArgs(buffer)
out := buffer.String()
assert.NotContains(t, out, "ThisArgIsUsed")
assert.NotContains(t, out, "HTTPS_PROXY")
assert.NotContains(t, out, "HTTP_PROXY")
assert.Contains(t, out, "ThisArgIsNotUsed")
assert.Assert(t, !strings.Contains(out, "ThisArgIsUsed"), out)
assert.Assert(t, !strings.Contains(out, "HTTPS_PROXY"), out)
assert.Assert(t, !strings.Contains(out, "HTTP_PROXY"), out)
assert.Check(t, is.Contains(out, "ThisArgIsNotUsed"))
}
func TestIsUnreferencedBuiltin(t *testing.T) {
@@ -93,8 +95,8 @@ func TestIsUnreferencedBuiltin(t *testing.T) {
buildArgs.AddArg("ThisArgIsUsed", nil)
buildArgs.AddArg("HTTPS_PROXY", nil)
assert.True(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsUsed"))
assert.True(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsNotUsed"))
assert.True(t, buildArgs.IsReferencedOrNotBuiltin("HTTPS_PROXY"))
assert.False(t, buildArgs.IsReferencedOrNotBuiltin("HTTP_PROXY"))
assert.Check(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsUsed"))
assert.Check(t, buildArgs.IsReferencedOrNotBuiltin("ThisArgIsNotUsed"))
assert.Check(t, buildArgs.IsReferencedOrNotBuiltin("HTTPS_PROXY"))
assert.Check(t, !buildArgs.IsReferencedOrNotBuiltin("HTTP_PROXY"))
}
@@ -5,13 +5,14 @@ import (
"testing"
"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) {
dockerfile := "FROM scratch"
result, err := parser.Parse(strings.NewReader(dockerfile))
assert.NoError(t, err)
assert.Check(t, err)
labels := map[string]string{
"org.e": "cli-e",
@@ -27,8 +28,8 @@ func TestAddNodesForLabelOption(t *testing.T) {
"FROM scratch",
`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 {
assert.Equal(t, expected[i], v.Original)
assert.Check(t, is.Equal(expected[i], v.Original))
}
}
@@ -5,8 +5,9 @@ import (
"testing"
"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/stretchr/testify/assert"
)
func TestIsExistingDirectory(t *testing.T) {
@@ -39,10 +40,10 @@ func TestIsExistingDirectory(t *testing.T) {
for _, testcase := range testcases {
result, err := isExistingDirectory(&copyEndpoint{driver: containerfs.NewLocalDriver(), path: testcase.path})
if !assert.NoError(t, err) {
if !assert.Check(t, err) {
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)
}
filename := getFilenameForDownload(testcase.path, &resp)
assert.Equal(t, testcase.expected, filename)
assert.Check(t, is.Equal(testcase.expected, filename))
}
}
@@ -16,8 +16,8 @@ import (
"github.com/docker/docker/image"
"github.com/docker/docker/pkg/system"
"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func newBuilderWithMockBackend() *Builder {
@@ -49,13 +49,13 @@ func TestEnv2Variables(t *testing.T) {
},
}
err := dispatch(sb, envCommand)
require.NoError(t, err)
assert.NilError(t, err)
expected := []string{
"var1=val1",
"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) {
@@ -68,12 +68,12 @@ func TestEnvValueWithExistingRunConfigEnv(t *testing.T) {
},
}
err := dispatch(sb, envCommand)
require.NoError(t, err)
assert.NilError(t, err)
expected := []string{
"var1=val1",
"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) {
@@ -82,8 +82,8 @@ func TestMaintainer(t *testing.T) {
sb := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults())
cmd := &instructions.MaintainerCommand{Maintainer: maintainerEntry}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.Equal(t, maintainerEntry, sb.state.maintainer)
assert.NilError(t, err)
assert.Check(t, is.Equal(maintainerEntry, sb.state.maintainer))
}
func TestLabel(t *testing.T) {
@@ -98,10 +98,10 @@ func TestLabel(t *testing.T) {
},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
require.Contains(t, sb.state.runConfig.Labels, labelName)
assert.Equal(t, sb.state.runConfig.Labels[labelName], labelValue)
assert.Assert(t, is.Contains(sb.state.runConfig.Labels, labelName))
assert.Check(t, is.Equal(sb.state.runConfig.Labels[labelName], labelValue))
}
func TestFromScratch(t *testing.T) {
@@ -113,22 +113,22 @@ func TestFromScratch(t *testing.T) {
err := initializeStage(sb, cmd)
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
}
require.NoError(t, err)
assert.True(t, sb.state.hasFromImage())
assert.Equal(t, "", sb.state.imageID)
assert.NilError(t, err)
assert.Check(t, sb.state.hasFromImage())
assert.Check(t, is.Equal("", sb.state.imageID))
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) {
tag, expected := ":sometag", "expectedthisid"
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
}
b := newBuilderWithMockBackend()
@@ -146,21 +146,21 @@ func TestFromWithArg(t *testing.T) {
err := processMetaArg(metaArg, shell.NewLex('\\'), args)
sb := newDispatchRequest(b, '\\', nil, args, newStagesBuildResults())
require.NoError(t, err)
assert.NilError(t, err)
err = initializeStage(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
assert.Equal(t, expected, sb.state.imageID)
assert.Equal(t, expected, sb.state.baseImage.ImageID())
assert.Len(t, sb.state.buildArgs.GetAllAllowed(), 0)
assert.Len(t, sb.state.buildArgs.GetAllMeta(), 1)
assert.Check(t, is.Equal(expected, sb.state.imageID))
assert.Check(t, is.Equal(expected, sb.state.baseImage.ImageID()))
assert.Check(t, is.Len(sb.state.buildArgs.GetAllAllowed(), 0))
assert.Check(t, is.Len(sb.state.buildArgs.GetAllMeta(), 1))
}
func TestFromWithUndefinedArg(t *testing.T) {
tag, expected := "sometag", "expectedthisid"
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
}
b := newBuilderWithMockBackend()
@@ -173,8 +173,8 @@ func TestFromWithUndefinedArg(t *testing.T) {
BaseName: "alpine${THETAG}",
}
err := initializeStage(sb, cmd)
require.NoError(t, err)
assert.Equal(t, expected, sb.state.imageID)
assert.NilError(t, err)
assert.Check(t, is.Equal(expected, sb.state.imageID))
}
func TestFromMultiStageWithNamedStage(t *testing.T) {
@@ -185,13 +185,13 @@ func TestFromMultiStageWithNamedStage(t *testing.T) {
firstSB := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), previousResults)
secondSB := newDispatchRequest(b, '\\', nil, newBuildArgs(make(map[string]*string)), previousResults)
err := initializeStage(firstSB, firstFrom)
require.NoError(t, err)
assert.True(t, firstSB.state.hasFromImage())
assert.NilError(t, err)
assert.Check(t, firstSB.state.hasFromImage())
previousResults.indexed["base"] = firstSB.state.runConfig
previousResults.flat = append(previousResults.flat, firstSB.state.runConfig)
err = initializeStage(secondSB, secondFrom)
require.NoError(t, err)
assert.True(t, secondSB.state.hasFromImage())
assert.NilError(t, err)
assert.Check(t, secondSB.state.hasFromImage())
}
func TestOnbuild(t *testing.T) {
@@ -201,8 +201,8 @@ func TestOnbuild(t *testing.T) {
Expression: "ADD . /app/src",
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.Equal(t, "ADD . /app/src", sb.state.runConfig.OnBuild[0])
assert.NilError(t, err)
assert.Check(t, is.Equal("ADD . /app/src", sb.state.runConfig.OnBuild[0]))
}
func TestWorkdir(t *testing.T) {
@@ -217,8 +217,8 @@ func TestWorkdir(t *testing.T) {
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.Equal(t, workingDir, sb.state.runConfig.WorkingDir)
assert.NilError(t, err)
assert.Check(t, is.Equal(workingDir, sb.state.runConfig.WorkingDir))
}
func TestCmd(t *testing.T) {
@@ -233,7 +233,7 @@ func TestCmd(t *testing.T) {
},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
var expectedCommand strslice.StrSlice
if runtime.GOOS == "windows" {
@@ -242,8 +242,8 @@ func TestCmd(t *testing.T) {
expectedCommand = strslice.StrSlice(append([]string{"/bin/sh"}, "-c", command))
}
assert.Equal(t, expectedCommand, sb.state.runConfig.Cmd)
assert.True(t, sb.state.cmdSet)
assert.Check(t, is.DeepEqual(expectedCommand, sb.state.runConfig.Cmd))
assert.Check(t, sb.state.cmdSet)
}
func TestHealthcheckNone(t *testing.T) {
@@ -255,10 +255,10 @@ func TestHealthcheckNone(t *testing.T) {
},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.Healthcheck)
assert.Equal(t, []string{"NONE"}, sb.state.runConfig.Healthcheck.Test)
assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
assert.Check(t, is.DeepEqual([]string{"NONE"}, sb.state.runConfig.Healthcheck.Test))
}
func TestHealthcheckCmd(t *testing.T) {
@@ -272,10 +272,10 @@ func TestHealthcheckCmd(t *testing.T) {
},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.Healthcheck)
assert.Equal(t, expectedTest, sb.state.runConfig.Healthcheck.Test)
assert.Assert(t, sb.state.runConfig.Healthcheck != nil)
assert.Check(t, is.DeepEqual(expectedTest, sb.state.runConfig.Healthcheck.Test))
}
func TestEntrypoint(t *testing.T) {
@@ -290,8 +290,8 @@ func TestEntrypoint(t *testing.T) {
},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
require.NotNil(t, sb.state.runConfig.Entrypoint)
assert.NilError(t, err)
assert.Assert(t, sb.state.runConfig.Entrypoint != nil)
var expectedEntrypoint strslice.StrSlice
if runtime.GOOS == "windows" {
@@ -299,7 +299,7 @@ func TestEntrypoint(t *testing.T) {
} else {
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) {
@@ -311,14 +311,14 @@ func TestExpose(t *testing.T) {
Ports: []string{exposedPort},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
require.NotNil(t, sb.state.runConfig.ExposedPorts)
require.Len(t, sb.state.runConfig.ExposedPorts, 1)
assert.Assert(t, sb.state.runConfig.ExposedPorts != nil)
assert.Assert(t, is.Len(sb.state.runConfig.ExposedPorts, 1))
portsMapping, err := nat.ParsePortSpec(exposedPort)
require.NoError(t, err)
assert.Contains(t, sb.state.runConfig.ExposedPorts, portsMapping[0].Port)
assert.NilError(t, err)
assert.Check(t, is.Contains(sb.state.runConfig.ExposedPorts, portsMapping[0].Port))
}
func TestUser(t *testing.T) {
@@ -329,8 +329,8 @@ func TestUser(t *testing.T) {
User: "test",
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.Equal(t, "test", sb.state.runConfig.User)
assert.NilError(t, err)
assert.Check(t, is.Equal("test", sb.state.runConfig.User))
}
func TestVolume(t *testing.T) {
@@ -343,10 +343,10 @@ func TestVolume(t *testing.T) {
Volumes: []string{exposedVolume},
}
err := dispatch(sb, cmd)
require.NoError(t, err)
require.NotNil(t, sb.state.runConfig.Volumes)
assert.Len(t, sb.state.runConfig.Volumes, 1)
assert.Contains(t, sb.state.runConfig.Volumes, exposedVolume)
assert.NilError(t, err)
assert.Assert(t, sb.state.runConfig.Volumes != nil)
assert.Check(t, is.Len(sb.state.runConfig.Volumes, 1))
assert.Check(t, is.Contains(sb.state.runConfig.Volumes, exposedVolume))
}
func TestStopSignal(t *testing.T) {
@@ -362,8 +362,8 @@ func TestStopSignal(t *testing.T) {
Signal: signal,
}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.Equal(t, signal, sb.state.runConfig.StopSignal)
assert.NilError(t, err)
assert.Check(t, is.Equal(signal, sb.state.runConfig.StopSignal))
}
func TestArg(t *testing.T) {
@@ -374,10 +374,10 @@ func TestArg(t *testing.T) {
argVal := "bar"
cmd := &instructions.ArgCommand{Key: argName, Value: &argVal}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
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) {
@@ -388,10 +388,10 @@ func TestShell(t *testing.T) {
cmd := &instructions.ShellCommand{Shell: strslice.StrSlice{shellCmd}}
err := dispatch(sb, cmd)
require.NoError(t, err)
assert.NilError(t, err)
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) {
@@ -403,7 +403,7 @@ func TestPrependEnvOnCmd(t *testing.T) {
cmdWithEnv := prependEnvOnCmd(buildArgs, args, cmd)
expected := strslice.StrSlice([]string{
"|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) {
@@ -422,8 +422,8 @@ func TestRunWithBuildArgs(t *testing.T) {
imageCache := &mockImageCache{
getCacheFunc: func(parentID string, cfg *container.Config) (string, error) {
// Check the runConfig.Cmd sent to probeCache()
assert.Equal(t, cachedCmd, cfg.Cmd)
assert.Equal(t, strslice.StrSlice(nil), cfg.Entrypoint)
assert.Check(t, is.DeepEqual(cachedCmd, cfg.Cmd))
assert.Check(t, is.DeepEqual(strslice.StrSlice(nil), cfg.Entrypoint))
return "", nil
},
}
@@ -441,21 +441,21 @@ func TestRunWithBuildArgs(t *testing.T) {
}
mockBackend.containerCreateFunc = func(config types.ContainerCreateConfig) (container.ContainerCreateCreatedBody, error) {
// Check the runConfig.Cmd sent to create()
assert.Equal(t, cmdWithShell, config.Config.Cmd)
assert.Contains(t, config.Config.Env, "one=two")
assert.Equal(t, strslice.StrSlice{""}, config.Config.Entrypoint)
assert.Check(t, is.DeepEqual(cmdWithShell, config.Config.Cmd))
assert.Check(t, is.Contains(config.Config.Env, "one=two"))
assert.Check(t, is.DeepEqual(strslice.StrSlice{""}, config.Config.Entrypoint))
return container.ContainerCreateCreatedBody{ID: "12345"}, nil
}
mockBackend.commitFunc = func(cfg backend.CommitConfig) (image.ID, error) {
// Check the runConfig.Cmd sent to commit()
assert.Equal(t, origCmd, cfg.Config.Cmd)
assert.Equal(t, cachedCmd, cfg.ContainerConfig.Cmd)
assert.Equal(t, strslice.StrSlice(nil), cfg.Config.Entrypoint)
assert.Check(t, is.DeepEqual(origCmd, cfg.Config.Cmd))
assert.Check(t, is.DeepEqual(cachedCmd, cfg.ContainerConfig.Cmd))
assert.Check(t, is.DeepEqual(strslice.StrSlice(nil), cfg.Config.Entrypoint))
return "", nil
}
from := &instructions.Stage{BaseName: "abcdef"}
err := initializeStage(sb, from)
require.NoError(t, err)
assert.NilError(t, err)
sb.state.buildArgs.AddArg("one", strPtr("two"))
run := &instructions.RunCommand{
ShellDependantCmdLine: instructions.ShellDependantCmdLine{
@@ -463,8 +463,8 @@ func TestRunWithBuildArgs(t *testing.T) {
PrependShell: true,
},
}
require.NoError(t, dispatch(sb, run))
assert.NilError(t, dispatch(sb, 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))
}
@@ -7,8 +7,8 @@ import (
"github.com/docker/docker/builder/dockerfile/command"
"github.com/docker/docker/builder/dockerfile/parser"
"github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestCommandsExactlyOneArgument(t *testing.T) {
@@ -21,9 +21,9 @@ func TestCommandsExactlyOneArgument(t *testing.T) {
for _, command := range commands {
ast, err := parser.Parse(strings.NewReader(command))
require.NoError(t, err)
assert.NilError(t, err)
_, 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 {
ast, err := parser.Parse(strings.NewReader(command))
require.NoError(t, err)
assert.NilError(t, err)
_, 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 {
ast, err := parser.Parse(strings.NewReader(command + " arg1"))
require.NoError(t, err)
assert.NilError(t, err)
_, 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)
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)
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)
assert.NoError(t, err)
assert.Check(t, err)
hc, ok := cmd.(*HealthCheckCommand)
assert.True(t, ok)
assert.Check(t, ok)
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) {
@@ -138,7 +138,7 @@ func TestParseOptInterval(t *testing.T) {
flInterval.Value = "1ms"
_, err = parseOptInterval(flInterval)
require.NoError(t, err)
assert.NilError(t, err)
}
func TestErrorCases(t *testing.T) {
@@ -6,8 +6,8 @@ import (
"testing"
"github.com/docker/docker/pkg/idtools"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestChownFlagParsing(t *testing.T) {
@@ -99,8 +99,8 @@ othergrp:x:6666:
} {
t.Run(testcase.name, func(t *testing.T) {
idPair, err := parseChownFlag(testcase.chownStr, contextDir, testcase.idMapping)
require.NoError(t, err, "Failed to parse chown flag: %q", testcase.chownStr)
assert.Equal(t, testcase.expected, idPair, "chown flag mapping failure")
assert.NilError(t, err, "Failed to parse chown flag: %q", testcase.chownStr)
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) {
_, 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")
})
}
}
@@ -12,8 +12,8 @@ import (
"github.com/docker/docker/builder/remotecontext"
"github.com/docker/docker/pkg/archive"
"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestEmptyDockerfile(t *testing.T) {
@@ -60,7 +60,7 @@ func TestNonExistingDockerfile(t *testing.T) {
func readAndCheckDockerfile(t *testing.T, testName, contextDir, dockerfilePath, expectedError string) {
tarStream, err := archive.Tar(contextDir, archive.Uncompressed)
require.NoError(t, err)
assert.NilError(t, err)
defer func() {
if err = tarStream.Close(); err != nil {
@@ -77,7 +77,7 @@ func readAndCheckDockerfile(t *testing.T, testName, contextDir, dockerfilePath,
Source: tarStream,
}
_, _, err = remotecontext.Detect(config)
assert.EqualError(t, err, expectedError)
assert.Check(t, is.Error(err, expectedError))
}
func TestCopyRunConfig(t *testing.T) {
@@ -124,9 +124,9 @@ func TestCopyRunConfig(t *testing.T) {
Env: defaultEnv,
}
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.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) {
runConfig := fullMutableRunConfig()
copy := copyRunConfig(runConfig)
assert.Equal(t, fullMutableRunConfig(), copy)
assert.Check(t, is.DeepEqual(fullMutableRunConfig(), copy))
copy.Cmd[1] = "arg2"
copy.Env[1] = "env2=new"
@@ -166,5 +166,5 @@ func TestDeepCopyRunConfig(t *testing.T) {
copy.OnBuild[0] = "start"
copy.Labels["label3"] = "value3"
copy.Shell[0] = "sh"
assert.Equal(t, fullMutableRunConfig(), runConfig)
assert.Check(t, is.DeepEqual(fullMutableRunConfig(), runConfig))
}
@@ -7,7 +7,8 @@ import (
"testing"
"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) {
@@ -42,10 +43,10 @@ func TestNormalizeDest(t *testing.T) {
msg := fmt.Sprintf("Input: %s, %s", testcase.current, testcase.requested)
actual, err := normalizeDest(testcase.current, testcase.requested, "windows")
if testcase.etext == "" {
if !assert.NoError(t, err, msg) {
if !assert.Check(t, err, msg) {
continue
}
assert.Equal(t, testcase.expected, actual, msg)
assert.Check(t, is.Equal(testcase.expected, actual), msg)
} else {
testutil.ErrorContains(t, err, testcase.etext)
}
@@ -3,25 +3,29 @@ package parser // import "github.com/docker/docker/builder/dockerfile/parser"
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/google/go-cmp/cmp"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestParseNameValOldFormat(t *testing.T) {
directive := Directive{}
node, err := parseNameVal("foo bar", "LABEL", &directive)
assert.NoError(t, err)
assert.Check(t, err)
expected := &Node{
Value: "foo",
Next: &Node{Value: "bar"},
}
assert.Equal(t, expected, node)
assert.DeepEqual(t, expected, node, cmpNodeOpt)
}
var cmpNodeOpt = cmp.AllowUnexported(Node{})
func TestParseNameValNewFormat(t *testing.T) {
directive := Directive{}
node, err := parseNameVal("foo=bar thing=star", "LABEL", &directive)
assert.NoError(t, err)
assert.Check(t, err)
expected := &Node{
Value: "foo",
@@ -35,7 +39,7 @@ func TestParseNameValNewFormat(t *testing.T) {
},
},
}
assert.Equal(t, expected, node)
assert.DeepEqual(t, expected, node, cmpNodeOpt)
}
func TestNodeFromLabels(t *testing.T) {
@@ -61,8 +65,7 @@ func TestNodeFromLabels(t *testing.T) {
}
node := NodeFromLabels(labels)
assert.Equal(t, expected, node)
assert.DeepEqual(t, expected, node, cmpNodeOpt)
}
func TestParseNameValWithoutVal(t *testing.T) {
@@ -70,5 +73,5 @@ func TestParseNameValWithoutVal(t *testing.T) {
// In Config.Env, a variable without `=` is removed from the environment. (#31634)
// However, in Dockerfile, we don't allow "unsetting" an environment variable. (#11922)
_, 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")
}
@@ -11,8 +11,8 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
const testDir = "testfiles"
@@ -21,11 +21,11 @@ const testFileLineInfo = "testfile-line/Dockerfile"
func getDirs(t *testing.T, dir string) []string {
f, err := os.Open(dir)
require.NoError(t, err)
assert.NilError(t, err)
defer f.Close()
dirs, err := f.Readdirnames(0)
require.NoError(t, err)
assert.NilError(t, err)
return dirs
}
@@ -34,11 +34,11 @@ func TestParseErrorCases(t *testing.T) {
dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile")
df, err := os.Open(dockerfile)
require.NoError(t, err, dockerfile)
assert.NilError(t, err, dockerfile)
defer df.Close()
_, 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")
df, err := os.Open(dockerfile)
require.NoError(t, err, dockerfile)
assert.NilError(t, err, dockerfile)
defer df.Close()
result, err := Parse(df)
require.NoError(t, err, dockerfile)
assert.NilError(t, err, dockerfile)
content, err := ioutil.ReadFile(resultfile)
require.NoError(t, err, resultfile)
assert.NilError(t, err, resultfile)
if runtime.GOOS == "windows" {
// CRLF --> CR to match Unix behavior
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 {
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) {
df, err := os.Open(testFileLineInfo)
require.NoError(t, err)
assert.NilError(t, err)
defer df.Close()
result, err := Parse(df)
require.NoError(t, err)
assert.NilError(t, err)
ast := result.AST
assert.Equal(t, 5, ast.StartLine)
assert.Equal(t, 31, ast.endLine)
assert.Len(t, ast.Children, 3)
assert.Check(t, is.Equal(5, ast.StartLine))
assert.Check(t, is.Equal(31, ast.endLine))
assert.Check(t, is.Len(ast.Children, 3))
expected := [][]int{
{5, 5},
{11, 12},
@@ -126,7 +126,7 @@ func TestParseIncludesLineNumbers(t *testing.T) {
}
for i, child := range ast.Children {
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)
require.NoError(t, err)
assert.NilError(t, err)
warnings := result.Warnings
assert.Len(t, warnings, 3)
assert.Contains(t, warnings[0], "Empty continuation line found in")
assert.Contains(t, warnings[0], "RUN something following more")
assert.Contains(t, warnings[1], "RUN another thing")
assert.Contains(t, warnings[2], "will become errors in a future release")
assert.Check(t, is.Len(warnings, 3))
assert.Check(t, is.Contains(warnings[0], "Empty continuation line found in"))
assert.Check(t, is.Contains(warnings[0], "RUN something following more"))
assert.Check(t, is.Contains(warnings[1], "RUN another thing"))
assert.Check(t, is.Contains(warnings[2], "will become errors in a future release"))
}
func TestParseReturnsScannerErrors(t *testing.T) {
@@ -170,5 +170,5 @@ func TestParseReturnsScannerErrors(t *testing.T) {
LABEL test=%s
`, label))
_, 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"))
}
@@ -7,7 +7,8 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestShellParser4EnvVars(t *testing.T) {
@@ -15,7 +16,7 @@ func TestShellParser4EnvVars(t *testing.T) {
lineCount := 0
file, err := os.Open(fn)
assert.NoError(t, err)
assert.Check(t, err)
defer file.Close()
shlex := NewLex('\\')
@@ -37,7 +38,7 @@ func TestShellParser4EnvVars(t *testing.T) {
}
words := strings.Split(line, "|")
assert.Len(t, words, 3)
assert.Check(t, is.Len(words, 3))
platform := strings.TrimSpace(words[0])
source := strings.TrimSpace(words[1])
@@ -52,10 +53,10 @@ func TestShellParser4EnvVars(t *testing.T) {
((platform == "U" || platform == "A") && runtime.GOOS != "windows") {
newWord, err := shlex.ProcessWord(source, envs)
if expected == "error" {
assert.Error(t, err)
assert.Check(t, is.ErrorContains(err, ""))
} else {
assert.NoError(t, err)
assert.Equal(t, newWord, expected)
assert.Check(t, err)
assert.Check(t, is.Equal(newWord, expected))
}
}
}
@@ -7,14 +7,15 @@ import (
"testing"
"time"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/moby/buildkit/session/filesync"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
func TestFSCache(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "fscache")
assert.Nil(t, err)
assert.Check(t, err)
defer os.RemoveAll(tmpDir)
backend := NewNaiveCacheBackend(filepath.Join(tmpDir, "backend"))
@@ -26,84 +27,84 @@ func TestFSCache(t *testing.T) {
}
fscache, err := NewFSCache(opt)
assert.Nil(t, err)
assert.Check(t, err)
defer fscache.Close()
err = fscache.RegisterTransport("test", &testTransport{})
assert.Nil(t, err)
assert.Check(t, err)
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"))
assert.Nil(t, err)
assert.Equal(t, string(dt), "data")
assert.Check(t, err)
assert.Check(t, is.Equal(string(dt), "data"))
// same id doesn't recalculate anything
src2, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data2", "bar"})
assert.Nil(t, err)
assert.Equal(t, src1.Root().Path(), src2.Root().Path())
assert.Check(t, err)
assert.Check(t, is.Equal(src1.Root().Path(), src2.Root().Path()))
dt, err = ioutil.ReadFile(filepath.Join(src1.Root().Path(), "foo"))
assert.Nil(t, err)
assert.Equal(t, string(dt), "data")
assert.Nil(t, src2.Close())
assert.Check(t, err)
assert.Check(t, is.Equal(string(dt), "data"))
assert.Check(t, src2.Close())
src3, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo2", "data2", "bar"})
assert.Nil(t, err)
assert.NotEqual(t, src1.Root().Path(), src3.Root().Path())
assert.Check(t, err)
assert.Check(t, src1.Root().Path() != src3.Root().Path())
dt, err = ioutil.ReadFile(filepath.Join(src3.Root().Path(), "foo2"))
assert.Nil(t, err)
assert.Equal(t, string(dt), "data2")
assert.Check(t, err)
assert.Check(t, is.Equal(string(dt), "data2"))
s, err := fscache.DiskUsage()
assert.Nil(t, err)
assert.Equal(t, s, int64(0))
assert.Check(t, err)
assert.Check(t, is.Equal(s, int64(0)))
assert.Nil(t, src3.Close())
assert.Check(t, src3.Close())
s, err = fscache.DiskUsage()
assert.Nil(t, err)
assert.Equal(t, s, int64(5))
assert.Check(t, err)
assert.Check(t, is.Equal(s, int64(5)))
// new upload with the same shared key shoutl overwrite
src4, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo3", "data3", "bar"})
assert.Nil(t, err)
assert.NotEqual(t, src1.Root().Path(), src3.Root().Path())
assert.Check(t, err)
assert.Check(t, src1.Root().Path() != src3.Root().Path())
dt, err = ioutil.ReadFile(filepath.Join(src3.Root().Path(), "foo3"))
assert.Nil(t, err)
assert.Equal(t, string(dt), "data3")
assert.Equal(t, src4.Root().Path(), src3.Root().Path())
assert.Nil(t, src4.Close())
assert.Check(t, err)
assert.Check(t, is.Equal(string(dt), "data3"))
assert.Check(t, is.Equal(src4.Root().Path(), src3.Root().Path()))
assert.Check(t, src4.Close())
s, err = fscache.DiskUsage()
assert.Nil(t, err)
assert.Equal(t, s, int64(10))
assert.Check(t, err)
assert.Check(t, is.Equal(s, int64(10)))
// this one goes over the GC limit
src5, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo4", "datadata", "baz"})
assert.Nil(t, err)
assert.Nil(t, src5.Close())
assert.Check(t, err)
assert.Check(t, src5.Close())
// GC happens async
time.Sleep(100 * time.Millisecond)
// only last insertion after GC
s, err = fscache.DiskUsage()
assert.Nil(t, err)
assert.Equal(t, s, int64(8))
assert.Check(t, err)
assert.Check(t, is.Equal(s, int64(8)))
// prune deletes everything
released, err := fscache.Prune(context.TODO())
assert.Nil(t, err)
assert.Equal(t, released, uint64(8))
assert.Check(t, err)
assert.Check(t, is.Equal(released, uint64(8)))
s, err = fscache.DiskUsage()
assert.Nil(t, err)
assert.Equal(t, s, int64(0))
assert.Check(t, err)
assert.Check(t, is.Equal(s, int64(0)))
}
type testTransport struct {
@@ -13,42 +13,39 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/google/go-cmp/cmp"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestParseRemoteURL(t *testing.T) {
dir, err := parseRemoteURL("git://github.com/user/repo.git")
require.NoError(t, err)
assert.NotEmpty(t, dir)
assert.Equal(t, gitRepo{"git://github.com/user/repo.git", "master", ""}, dir)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(gitRepo{"git://github.com/user/repo.git", "master", ""}, dir, cmpGitRepoOpt))
dir, err = parseRemoteURL("git://github.com/user/repo.git#mybranch:mydir/mysubdir/")
require.NoError(t, err)
assert.NotEmpty(t, dir)
assert.Equal(t, gitRepo{"git://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(gitRepo{"git://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir, cmpGitRepoOpt))
dir, err = parseRemoteURL("https://github.com/user/repo.git")
require.NoError(t, err)
assert.NotEmpty(t, dir)
assert.Equal(t, gitRepo{"https://github.com/user/repo.git", "master", ""}, dir)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(gitRepo{"https://github.com/user/repo.git", "master", ""}, dir, cmpGitRepoOpt))
dir, err = parseRemoteURL("https://github.com/user/repo.git#mybranch:mydir/mysubdir/")
require.NoError(t, err)
assert.NotEmpty(t, dir)
assert.Equal(t, gitRepo{"https://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(gitRepo{"https://github.com/user/repo.git", "mybranch", "mydir/mysubdir/"}, dir, cmpGitRepoOpt))
dir, err = parseRemoteURL("git@github.com:user/repo.git")
require.NoError(t, err)
assert.NotEmpty(t, dir)
assert.Equal(t, gitRepo{"git@github.com:user/repo.git", "master", ""}, dir)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(gitRepo{"git@github.com:user/repo.git", "master", ""}, dir, cmpGitRepoOpt))
dir, err = parseRemoteURL("git@github.com:user/repo.git#mybranch:mydir/mysubdir/")
require.NoError(t, err)
assert.NotEmpty(t, dir)
assert.Equal(t, gitRepo{"git@github.com:user/repo.git", "mybranch", "mydir/mysubdir/"}, dir)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(gitRepo{"git@github.com:user/repo.git", "mybranch", "mydir/mysubdir/"}, dir, cmpGitRepoOpt))
}
var cmpGitRepoOpt = cmp.AllowUnexported(gitRepo{})
func TestCloneArgsSmartHttp(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
@@ -63,7 +60,7 @@ func TestCloneArgsSmartHttp(t *testing.T) {
args := fetchArgs(serverURL.String(), "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) {
@@ -79,13 +76,13 @@ func TestCloneArgsDumbHttp(t *testing.T) {
args := fetchArgs(serverURL.String(), "master")
exp := []string{"fetch", "origin", "master"}
assert.Equal(t, exp, args)
assert.Check(t, is.DeepEqual(exp, args))
}
func TestCloneArgsGit(t *testing.T) {
args := fetchArgs("git://github.com/docker/docker", "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 {
@@ -100,7 +97,7 @@ func gitGetConfig(name string) string {
func TestCheckoutGit(t *testing.T) {
root, err := ioutil.TempDir("", "docker-build-git-checkout")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(root)
autocrlf := gitGetConfig("core.autocrlf")
@@ -115,22 +112,22 @@ func TestCheckoutGit(t *testing.T) {
gitDir := filepath.Join(root, "repo")
_, err = git("init", gitDir)
require.NoError(t, err)
assert.NilError(t, err)
_, 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")
require.NoError(t, err)
assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644)
require.NoError(t, err)
assert.NilError(t, err)
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)
require.NoError(t, err)
assert.NilError(t, err)
if runtime.GOOS != "windows" {
if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
@@ -143,58 +140,58 @@ func TestCheckoutGit(t *testing.T) {
}
_, err = gitWithinDir(gitDir, "add", "-A")
require.NoError(t, err)
assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "commit", "-am", "First commit")
require.NoError(t, err)
assert.NilError(t, err)
_, 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)
require.NoError(t, err)
assert.NilError(t, err)
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")
require.NoError(t, err)
assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit")
require.NoError(t, err)
assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "checkout", "master")
require.NoError(t, err)
assert.NilError(t, err)
// set up submodule
subrepoDir := filepath.Join(root, "subrepo")
_, err = git("init", subrepoDir)
require.NoError(t, err)
assert.NilError(t, err)
_, 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")
require.NoError(t, err)
assert.NilError(t, err)
err = ioutil.WriteFile(filepath.Join(subrepoDir, "subfile"), []byte("subcontents"), 0644)
require.NoError(t, err)
assert.NilError(t, err)
_, err = gitWithinDir(subrepoDir, "add", "-A")
require.NoError(t, err)
assert.NilError(t, err)
_, 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.Dir = gitDir
require.NoError(t, cmd.Run())
assert.NilError(t, cmd.Run())
_, err = gitWithinDir(gitDir, "add", "-A")
require.NoError(t, err)
assert.NilError(t, err)
_, err = gitWithinDir(gitDir, "commit", "-am", "With submodule")
require.NoError(t, err)
assert.NilError(t, err)
type singleCase struct {
frag string
@@ -232,24 +229,24 @@ func TestCheckoutGit(t *testing.T) {
r, err := cloneGitRepo(gitRepo{remote: gitDir, ref: ref, subdir: subdir})
if c.fail {
assert.Error(t, err)
assert.Check(t, is.ErrorContains(err, ""))
continue
}
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(r)
if c.submodule {
b, err := ioutil.ReadFile(filepath.Join(r, "sub/subfile"))
require.NoError(t, err)
assert.Equal(t, "subcontents", string(b))
assert.NilError(t, err)
assert.Check(t, is.Equal("subcontents", string(b)))
} else {
_, err := os.Stat(filepath.Join(r, "sub/subfile"))
require.Error(t, err)
require.True(t, os.IsNotExist(err))
assert.Assert(t, is.ErrorContains(err, ""))
assert.Assert(t, os.IsNotExist(err))
}
b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
require.NoError(t, err)
assert.Equal(t, c.exp, string(b))
assert.NilError(t, err)
assert.Check(t, is.Equal(c.exp, string(b)))
}
}
@@ -3,14 +3,14 @@ package remotecontext // import "github.com/docker/docker/builder/remotecontext"
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestDetectContentType(t *testing.T) {
input := []byte("That is just a plain text")
contentType, _, err := detectContentType(input)
require.NoError(t, err)
assert.Equal(t, "text/plain", contentType)
assert.NilError(t, err)
assert.Check(t, is.Equal("text/plain", contentType))
}
@@ -11,9 +11,9 @@ import (
"github.com/docker/docker/builder"
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
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())))
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)
require.NoError(t, err)
assert.Equal(t, dockerfileContents, string(raw))
assert.NilError(t, err)
assert.Check(t, is.Equal(dockerfileContents, string(raw)))
}
func TestGetWithStatusError(t *testing.T) {
@@ -226,11 +226,11 @@ func TestGetWithStatusError(t *testing.T) {
response, err := GetWithStatusError(ts.URL)
if testcase.expectedErr == "" {
require.NoError(t, err)
assert.NilError(t, err)
body, err := readBody(response.Body)
require.NoError(t, err)
assert.Contains(t, string(body), testcase.expectedBody)
assert.NilError(t, err)
assert.Check(t, is.Contains(string(body), testcase.expectedBody))
} else {
testutil.ErrorContains(t, err, testcase.expectedErr)
}
+28 -23
View File
@@ -11,10 +11,10 @@ import (
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
"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/skip"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewEnvClient(t *testing.T) {
@@ -89,19 +89,18 @@ func TestNewEnvClient(t *testing.T) {
env.PatchAll(t, c.envs)
apiclient, err := NewEnvClient()
if c.expectedError != "" {
assert.Error(t, err, c.doc)
assert.Equal(t, c.expectedError, err.Error(), c.doc)
assert.Check(t, is.Error(err, c.expectedError), c.doc)
} else {
assert.NoError(t, err, c.doc)
assert.Check(t, err, c.doc)
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"] != "" {
// pedantic checking that this is handled correctly
tr := apiclient.client.Transport.(*http.Transport)
assert.NotNil(t, tr.TLSClientConfig, c.doc)
assert.Equal(t, tr.TLSClientConfig.InsecureSkipVerify, false, c.doc)
assert.Assert(t, tr.TLSClientConfig != nil, c.doc)
assert.Check(t, is.Equal(tr.TLSClientConfig.InsecureSkipVerify, false), c.doc)
}
}
}
@@ -128,7 +127,7 @@ func TestGetAPIPath(t *testing.T) {
for _, testcase := range testcases {
c := Client{version: testcase.version, basePath: "/"}
actual := c.getAPIPath(testcase.path, testcase.query)
assert.Equal(t, actual, testcase.expected)
assert.Check(t, is.Equal(actual, testcase.expected))
}
}
@@ -165,7 +164,7 @@ func TestParseHostURL(t *testing.T) {
if testcase.expectedErr != "" {
testutil.ErrorContains(t, err, testcase.expectedErr)
}
assert.Equal(t, testcase.expected, actual)
assert.Check(t, is.DeepEqual(testcase.expected, actual))
}
}
@@ -181,7 +180,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) {
if err != nil {
t.Fatal(err)
}
assert.Equal(t, client.version, api.DefaultVersion)
assert.Check(t, is.Equal(client.version, api.DefaultVersion))
expected := "1.22"
os.Setenv("DOCKER_API_VERSION", expected)
@@ -189,7 +188,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) {
if err != nil {
t.Fatal(err)
}
assert.Equal(t, expected, client.version)
assert.Check(t, is.Equal(expected, client.version))
}
// TestNegotiateAPIVersionEmpty asserts that client.Client can
@@ -198,7 +197,7 @@ func TestNegotiateAPIVersionEmpty(t *testing.T) {
defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": ""})
client, err := NewEnvClient()
require.NoError(t, err)
assert.NilError(t, err)
ping := types.Ping{
APIVersion: "",
@@ -215,14 +214,14 @@ func TestNegotiateAPIVersionEmpty(t *testing.T) {
// test downgrade
client.NegotiateAPIVersionPing(ping)
assert.Equal(t, expected, client.version)
assert.Check(t, is.Equal(expected, client.version))
}
// TestNegotiateAPIVersion asserts that client.Client can
// negotiate a compatible APIVersion with the server
func TestNegotiateAPIVersion(t *testing.T) {
client, err := NewEnvClient()
require.NoError(t, err)
assert.NilError(t, err)
expected := "1.21"
ping := types.Ping{
@@ -236,14 +235,14 @@ func TestNegotiateAPIVersion(t *testing.T) {
// test downgrade
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
// original setting.
expected = "1.20"
client.version = expected
client.NegotiateAPIVersionPing(ping)
assert.Equal(t, expected, client.version)
assert.Check(t, is.Equal(expected, client.version))
}
@@ -254,7 +253,7 @@ func TestNegotiateAPVersionOverride(t *testing.T) {
defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": expected})()
client, err := NewEnvClient()
require.NoError(t, err)
assert.NilError(t, err)
ping := types.Ping{
APIVersion: "1.24",
@@ -264,7 +263,7 @@ func TestNegotiateAPVersionOverride(t *testing.T) {
// test that we honored the env var
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)
@@ -298,7 +297,7 @@ func TestClientRedirect(t *testing.T) {
cases := []struct {
httpMethod string
expectedErr error
expectedErr *url.Error
statusCode int
}{
{http.MethodGet, nil, 301},
@@ -309,9 +308,15 @@ func TestClientRedirect(t *testing.T) {
for _, tc := range cases {
req, err := http.NewRequest(tc.httpMethod, "/redirectme", nil)
assert.NoError(t, err)
assert.Check(t, err)
resp, err := client.Do(req)
assert.Equal(t, tc.expectedErr, err)
assert.Equal(t, tc.statusCode, resp.StatusCode)
assert.Check(t, is.Equal(tc.statusCode, resp.StatusCode))
if tc.expectedErr == nil {
assert.Check(t, is.Nil(err))
} else {
urlError, ok := err.(*url.Error)
assert.Assert(t, ok, "%T is not *url.Error", err)
assert.Check(t, is.Equal(*tc.expectedErr, *urlError))
}
}
}
@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types"
"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"
)
@@ -21,7 +22,7 @@ func TestConfigCreateUnsupported(t *testing.T) {
client: &http.Client{},
}
_, 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) {
@@ -10,8 +10,9 @@ import (
"testing"
"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/stretchr/testify/assert"
"golang.org/x/net/context"
)
@@ -44,7 +45,7 @@ func TestConfigInspectUnsupported(t *testing.T) {
client: &http.Client{},
}
_, _, 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) {
+3 -2
View File
@@ -12,7 +12,8 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"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"
)
@@ -22,7 +23,7 @@ func TestConfigListUnsupported(t *testing.T) {
client: &http.Client{},
}
_, 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) {
@@ -8,7 +8,8 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context"
)
@@ -18,7 +19,7 @@ func TestConfigRemoveUnsupported(t *testing.T) {
client: &http.Client{},
}
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) {
@@ -9,7 +9,8 @@ import (
"testing"
"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"
)
@@ -19,7 +20,7 @@ func TestConfigUpdateUnsupported(t *testing.T) {
client: &http.Client{},
}
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) {
@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types"
"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"
)
@@ -24,7 +25,7 @@ func TestContainersPruneError(t *testing.T) {
filters := filters.NewArgs()
_, 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) {
@@ -99,7 +100,7 @@ func TestContainersPrune(t *testing.T) {
query := req.URL.Query()
for key, expected := range listCase.expectedQueryParams {
actual := query.Get(key)
assert.Equal(t, expected, actual)
assert.Check(t, is.Equal(expected, actual))
}
content, err := json.Marshal(types.ContainersPruneReport{
ContainersDeleted: []string{"container_id1", "container_id2"},
@@ -117,8 +118,8 @@ func TestContainersPrune(t *testing.T) {
}
report, err := client.ContainersPrune(context.Background(), listCase.filters)
assert.NoError(t, err)
assert.Len(t, report.ContainersDeleted, 2)
assert.Equal(t, uint64(9999), report.SpaceReclaimed)
assert.Check(t, err)
assert.Check(t, is.Len(report.ContainersDeleted, 2))
assert.Check(t, is.Equal(uint64(9999), report.SpaceReclaimed))
}
}
@@ -9,7 +9,8 @@ import (
"testing"
"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"
)
@@ -18,7 +19,7 @@ func TestContainerRemoveError(t *testing.T) {
client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")),
}
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) {
@@ -26,8 +27,8 @@ func TestContainerRemoveNotFoundError(t *testing.T) {
client: newMockClient(errorMock(http.StatusNotFound, "missing")),
}
err := client.ContainerRemove(context.Background(), "container_id", types.ContainerRemoveOptions{})
assert.EqualError(t, err, "Error: No such container: container_id")
assert.True(t, IsErrNotFound(err))
assert.Check(t, is.Error(err, "Error: No such container: container_id"))
assert.Check(t, IsErrNotFound(err))
}
func TestContainerRemove(t *testing.T) {
@@ -61,5 +62,5 @@ func TestContainerRemove(t *testing.T) {
RemoveVolumes: true,
Force: true,
})
assert.NoError(t, err)
assert.Check(t, err)
}
@@ -4,8 +4,9 @@ import (
"net/http"
"testing"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
@@ -15,7 +16,7 @@ func TestDistributionInspectUnsupported(t *testing.T) {
client: &http.Client{},
}
_, 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) {
+7 -6
View File
@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types"
"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"
)
@@ -24,7 +25,7 @@ func TestImagesPruneError(t *testing.T) {
filters := filters.NewArgs()
_, 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) {
@@ -87,7 +88,7 @@ func TestImagesPrune(t *testing.T) {
query := req.URL.Query()
for key, expected := range listCase.expectedQueryParams {
actual := query.Get(key)
assert.Equal(t, expected, actual)
assert.Check(t, is.Equal(expected, actual))
}
content, err := json.Marshal(types.ImagesPruneReport{
ImagesDeleted: []types.ImageDeleteResponseItem{
@@ -112,8 +113,8 @@ func TestImagesPrune(t *testing.T) {
}
report, err := client.ImagesPrune(context.Background(), listCase.filters)
assert.NoError(t, err)
assert.Len(t, report.ImagesDeleted, 2)
assert.Equal(t, uint64(9999), report.SpaceReclaimed)
assert.Check(t, err)
assert.Check(t, is.Len(report.ImagesDeleted, 2))
assert.Check(t, is.Equal(uint64(9999), report.SpaceReclaimed))
}
}
@@ -10,7 +10,8 @@ import (
"testing"
"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"
)
@@ -20,7 +21,7 @@ func TestImageRemoveError(t *testing.T) {
}
_, 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) {
@@ -29,8 +30,8 @@ func TestImageRemoveImageNotFound(t *testing.T) {
}
_, err := client.ImageRemove(context.Background(), "unknown", types.ImageRemoveOptions{})
assert.EqualError(t, err, "Error: No such image: unknown")
assert.True(t, IsErrNotFound(err))
assert.Check(t, is.Error(err, "Error: No such image: unknown"))
assert.Check(t, IsErrNotFound(err))
}
func TestImageRemove(t *testing.T) {
@@ -11,8 +11,9 @@ import (
"github.com/docker/docker/api/types"
"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/stretchr/testify/assert"
"golang.org/x/net/context"
)
@@ -22,7 +23,7 @@ func TestNetworkInspectError(t *testing.T) {
}
_, 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) {
@@ -31,8 +32,8 @@ func TestNetworkInspectNotFoundError(t *testing.T) {
}
_, err := client.NetworkInspect(context.Background(), "unknown", types.NetworkInspectOptions{})
assert.EqualError(t, err, "Error: No such network: unknown")
assert.True(t, IsErrNotFound(err))
assert.Check(t, is.Error(err, "Error: No such network: unknown"))
assert.Check(t, IsErrNotFound(err))
}
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"})
assert.EqualError(t, err, "Error: No such network: network_id")
assert.Check(t, is.Error(err, "Error: No such network: network_id"))
}
@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types"
"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"
)
@@ -89,7 +90,7 @@ func TestNetworksPrune(t *testing.T) {
query := req.URL.Query()
for key, expected := range listCase.expectedQueryParams {
actual := query.Get(key)
assert.Equal(t, expected, actual)
assert.Check(t, is.Equal(expected, actual))
}
content, err := json.Marshal(types.NetworksPruneReport{
NetworksDeleted: []string{"network_id1", "network_id2"},
@@ -106,7 +107,7 @@ func TestNetworksPrune(t *testing.T) {
}
report, err := client.NetworksPrune(context.Background(), listCase.filters)
assert.NoError(t, err)
assert.Len(t, report.NetworksDeleted, 2)
assert.Check(t, err)
assert.Check(t, is.Len(report.NetworksDeleted, 2))
}
}
+14 -13
View File
@@ -7,7 +7,8 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context"
)
@@ -31,15 +32,15 @@ func TestPingFail(t *testing.T) {
}
ping, err := client.Ping(context.Background())
assert.Error(t, err)
assert.Equal(t, false, ping.Experimental)
assert.Equal(t, "", ping.APIVersion)
assert.Check(t, is.ErrorContains(err, ""))
assert.Check(t, is.Equal(false, ping.Experimental))
assert.Check(t, is.Equal("", ping.APIVersion))
withHeader = true
ping2, err := client.Ping(context.Background())
assert.Error(t, err)
assert.Equal(t, true, ping2.Experimental)
assert.Equal(t, "awesome", ping2.APIVersion)
assert.Check(t, is.ErrorContains(err, ""))
assert.Check(t, is.Equal(true, ping2.Experimental))
assert.Check(t, is.Equal("awesome", ping2.APIVersion))
}
// 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())
assert.Error(t, err)
assert.Equal(t, false, ping.Experimental)
assert.Equal(t, "", ping.APIVersion)
assert.Check(t, is.ErrorContains(err, ""))
assert.Check(t, is.Equal(false, ping.Experimental))
assert.Check(t, is.Equal("", ping.APIVersion))
}
// 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())
assert.Error(t, err)
assert.Equal(t, true, ping.Experimental)
assert.Equal(t, "awesome", ping.APIVersion)
assert.Check(t, is.ErrorContains(err, ""))
assert.Check(t, is.Equal(true, ping.Experimental))
assert.Check(t, is.Equal("awesome", ping.APIVersion))
}
+3 -3
View File
@@ -9,7 +9,7 @@ import (
"testing"
"github.com/docker/docker/api/types"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
"golang.org/x/net/context"
)
@@ -46,7 +46,7 @@ func TestSetHostHeader(t *testing.T) {
for c, test := range testCases {
hostURL, err := ParseHostURL(test.host)
require.NoError(t, err)
assert.NilError(t, err)
client := &Client{
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)
require.NoError(t, err)
assert.NilError(t, err)
}
}
@@ -11,7 +11,8 @@ import (
"github.com/docker/docker/api/types"
"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"
)
@@ -21,7 +22,7 @@ func TestSecretCreateUnsupported(t *testing.T) {
client: &http.Client{},
}
_, 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) {
@@ -10,8 +10,9 @@ import (
"testing"
"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/stretchr/testify/assert"
"golang.org/x/net/context"
)
@@ -21,7 +22,7 @@ func TestSecretInspectUnsupported(t *testing.T) {
client: &http.Client{},
}
_, _, 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) {
+3 -2
View File
@@ -12,7 +12,8 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"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"
)
@@ -22,7 +23,7 @@ func TestSecretListUnsupported(t *testing.T) {
client: &http.Client{},
}
_, 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) {
@@ -8,7 +8,8 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context"
)
@@ -18,7 +19,7 @@ func TestSecretRemoveUnsupported(t *testing.T) {
client: &http.Client{},
}
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) {
@@ -9,7 +9,8 @@ import (
"testing"
"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"
)
@@ -19,7 +20,7 @@ func TestSecretUpdateUnsupported(t *testing.T) {
client: &http.Client{},
}
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) {
@@ -12,9 +12,10 @@ import (
"github.com/docker/docker/api/types"
registrytypes "github.com/docker/docker/api/types/registry"
"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/image-spec/specs-go/v1"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
@@ -73,8 +74,8 @@ func TestServiceCreateCompatiblePlatforms(t *testing.T) {
return nil, err
}
assert.Equal(t, "foobar:1.0@sha256:c0537ff6a5218ef531ece93d4984efc99bbf3f7497c0a7726c88e2bb7584dc96", serviceSpec.TaskTemplate.ContainerSpec.Image)
assert.Len(t, serviceSpec.TaskTemplate.Placement.Platforms, 1)
assert.Check(t, is.Equal("foobar:1.0@sha256:c0537ff6a5218ef531ece93d4984efc99bbf3f7497c0a7726c88e2bb7584dc96", serviceSpec.TaskTemplate.ContainerSpec.Image))
assert.Check(t, is.Len(serviceSpec.TaskTemplate.Placement.Platforms, 1))
p := serviceSpec.TaskTemplate.Placement.Platforms[0]
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"}}}
r, err := client.ServiceCreate(context.Background(), spec, types.ServiceCreateOptions{QueryRegistry: true})
assert.NoError(t, err)
assert.Equal(t, "service_linux_amd64", r.ID)
assert.Check(t, err)
assert.Check(t, is.Equal("service_linux_amd64", r.ID))
}
func TestServiceCreateDigestPinning(t *testing.T) {
@@ -8,7 +8,8 @@ import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context"
)
@@ -18,7 +19,7 @@ func TestServiceRemoveError(t *testing.T) {
}
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) {
@@ -27,8 +28,8 @@ func TestServiceRemoveNotFoundError(t *testing.T) {
}
err := client.ServiceRemove(context.Background(), "service_id")
assert.EqualError(t, err, "Error: No such service: service_id")
assert.True(t, IsErrNotFound(err))
assert.Check(t, is.Error(err, "Error: No such service: service_id"))
assert.Check(t, IsErrNotFound(err))
}
func TestServiceRemove(t *testing.T) {
@@ -11,8 +11,8 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context"
)
@@ -55,6 +55,6 @@ func TestSwarmGetUnlockKey(t *testing.T) {
}
resp, err := client.SwarmGetUnlockKey(context.Background())
require.NoError(t, err)
assert.Equal(t, unlockKey, resp.UnlockKey)
assert.NilError(t, err)
assert.Check(t, is.Equal(unlockKey, resp.UnlockKey))
}
@@ -11,9 +11,9 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
)
@@ -32,7 +32,7 @@ func TestVolumeInspectNotFound(t *testing.T) {
}
_, err := client.VolumeInspect(context.Background(), "unknown")
assert.True(t, IsErrNotFound(err))
assert.Check(t, IsErrNotFound(err))
}
func TestVolumeInspectWithEmptyID(t *testing.T) {
@@ -75,6 +75,6 @@ func TestVolumeInspect(t *testing.T) {
}
volume, err := client.VolumeInspect(context.Background(), "volume_id")
require.NoError(t, err)
assert.Equal(t, expected, volume)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(expected, volume))
}
@@ -6,8 +6,9 @@ import (
"testing"
"github.com/docker/docker/daemon/config"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)
func TestDaemonParseShmSize(t *testing.T) {
@@ -16,7 +17,7 @@ func TestDaemonParseShmSize(t *testing.T) {
conf := &config.Config{}
installConfigFlags(conf, flags)
// By default `--default-shm-size=64M`
assert.Equal(t, int64(64*1024*1024), conf.ShmSize.Value())
assert.NoError(t, flags.Set("default-shm-size", "128M"))
assert.Equal(t, int64(128*1024*1024), conf.ShmSize.Value())
assert.Check(t, is.Equal(int64(64*1024*1024), conf.ShmSize.Value()))
assert.Check(t, flags.Set("default-shm-size", "128M"))
assert.Check(t, is.Equal(int64(128*1024*1024), conf.ShmSize.Value()))
}
+41 -41
View File
@@ -5,11 +5,11 @@ import (
"github.com/docker/docker/daemon/config"
"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/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func defaultOptions(configFile string) *daemonOptions {
@@ -27,8 +27,8 @@ func TestLoadDaemonCliConfigWithoutOverriding(t *testing.T) {
opts.Debug = true
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
if !loadedConfig.Debug {
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
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.Equal(t, "/tmp/ca.pem", loadedConfig.CommonTLSOptions.CAFile)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, is.Equal("/tmp/ca.pem", loadedConfig.CommonTLSOptions.CAFile))
}
func TestLoadDaemonCliConfigWithConflicts(t *testing.T) {
@@ -53,9 +53,9 @@ func TestLoadDaemonCliConfigWithConflicts(t *testing.T) {
opts := defaultOptions(configFile)
flags := opts.flags
assert.NoError(t, flags.Set("config-file", configFile))
assert.NoError(t, flags.Set("label", "l1=bar"))
assert.NoError(t, flags.Set("label", "l2=baz"))
assert.Check(t, flags.Set("config-file", configFile))
assert.Check(t, flags.Set("label", "l1=bar"))
assert.Check(t, flags.Set("label", "l2=baz"))
_, err := loadDaemonCliConfig(opts)
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)
flags := opts.flags
assert.NoError(t, flags.Set("config-file", configFile))
assert.NoError(t, flags.Set("node-generic-resource", "r1=bar"))
assert.NoError(t, flags.Set("node-generic-resource", "r2=baz"))
assert.Check(t, flags.Set("config-file", configFile))
assert.Check(t, flags.Set("node-generic-resource", "r1=bar"))
assert.Check(t, flags.Set("node-generic-resource", "r2=baz"))
_, err := loadDaemonCliConfig(opts)
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("")
flags := opts.flags
assert.NoError(t, flags.Set("label", "foo=bar"))
assert.NoError(t, flags.Set("label", "foo=baz"))
assert.Check(t, flags.Set("label", "foo=bar"))
assert.Check(t, flags.Set("label", "foo=baz"))
_, 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) {
opts := defaultOptions("")
flags := opts.flags
assert.NoError(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"))
assert.Check(t, flags.Set("label", "foo=the-same"))
_, err := loadDaemonCliConfig(opts)
assert.NoError(t, err)
assert.Check(t, err)
}
func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) {
@@ -107,9 +107,9 @@ func TestLoadDaemonCliConfigWithTLSVerify(t *testing.T) {
opts.TLSOptions.CAFile = "/tmp/ca.pem"
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.Equal(t, loadedConfig.TLS, true)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, is.Equal(loadedConfig.TLS, true))
}
func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) {
@@ -120,9 +120,9 @@ func TestLoadDaemonCliConfigWithExplicitTLSVerifyFalse(t *testing.T) {
opts.TLSOptions.CAFile = "/tmp/ca.pem"
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.True(t, loadedConfig.TLS)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, loadedConfig.TLS)
}
func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) {
@@ -133,9 +133,9 @@ func TestLoadDaemonCliConfigWithoutTLSVerify(t *testing.T) {
opts.TLSOptions.CAFile = "/tmp/ca.pem"
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.False(t, loadedConfig.TLS)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, !loadedConfig.TLS)
}
func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) {
@@ -144,10 +144,10 @@ func TestLoadDaemonCliConfigWithLogLevel(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.Equal(t, "warn", loadedConfig.LogLevel)
assert.Equal(t, logrus.WarnLevel, logrus.GetLevel())
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, is.Equal("warn", loadedConfig.LogLevel))
assert.Check(t, is.Equal(logrus.WarnLevel, logrus.GetLevel()))
}
func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) {
@@ -157,10 +157,10 @@ func TestLoadDaemonConfigWithEmbeddedOptions(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.Equal(t, "/etc/certs/ca.pem", loadedConfig.CommonTLSOptions.CAFile)
assert.Equal(t, "syslog", loadedConfig.LogConfig.Type)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, is.Equal("/etc/certs/ca.pem", loadedConfig.CommonTLSOptions.CAFile))
assert.Check(t, is.Equal("syslog", loadedConfig.LogConfig.Type))
}
func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) {
@@ -174,10 +174,10 @@ func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Len(t, loadedConfig.AllowNondistributableArtifacts, 1)
assert.Len(t, loadedConfig.Mirrors, 1)
assert.Len(t, loadedConfig.InsecureRegistries, 1)
assert.Check(t, is.Len(loadedConfig.AllowNondistributableArtifacts, 1))
assert.Check(t, is.Len(loadedConfig.Mirrors, 1))
assert.Check(t, is.Len(loadedConfig.InsecureRegistries, 1))
}
@@ -6,9 +6,9 @@ import (
"testing"
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) {
@@ -19,17 +19,17 @@ func TestLoadDaemonCliConfigWithDaemonFlags(t *testing.T) {
opts := defaultOptions(tempFile.Path())
opts.Debug = true
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)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.True(t, loadedConfig.Debug)
assert.Equal(t, "info", loadedConfig.LogLevel)
assert.True(t, loadedConfig.EnableSelinuxSupport)
assert.Equal(t, "json-file", loadedConfig.LogConfig.Type)
assert.Equal(t, "1k", loadedConfig.LogConfig.Config["max-size"])
assert.Check(t, loadedConfig.Debug)
assert.Check(t, is.Equal("info", loadedConfig.LogLevel))
assert.Check(t, loadedConfig.EnableSelinuxSupport)
assert.Check(t, is.Equal("json-file", loadedConfig.LogConfig.Type))
assert.Check(t, is.Equal("1k", loadedConfig.LogConfig.Config["max-size"]))
}
func TestLoadDaemonConfigWithNetwork(t *testing.T) {
@@ -39,11 +39,11 @@ func TestLoadDaemonConfigWithNetwork(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Equal(t, "127.0.0.2", loadedConfig.IP)
assert.Equal(t, "127.0.0.1", loadedConfig.DefaultIP.String())
assert.Check(t, is.Equal("127.0.0.2", loadedConfig.IP))
assert.Check(t, is.Equal("127.0.0.1", loadedConfig.DefaultIP.String()))
}
func TestLoadDaemonConfigWithMapOptions(t *testing.T) {
@@ -56,14 +56,14 @@ func TestLoadDaemonConfigWithMapOptions(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NotNil(t, loadedConfig.ClusterOpts)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.Check(t, loadedConfig.ClusterOpts != nil)
expectedPath := "/var/lib/docker/discovery_certs/ca.pem"
assert.Equal(t, expectedPath, loadedConfig.ClusterOpts["kv.cacertfile"])
assert.NotNil(t, loadedConfig.LogConfig.Config)
assert.Equal(t, "test", loadedConfig.LogConfig.Config["tag"])
assert.Check(t, is.Equal(expectedPath, loadedConfig.ClusterOpts["kv.cacertfile"]))
assert.Check(t, loadedConfig.LogConfig.Config != nil)
assert.Check(t, is.Equal("test", loadedConfig.LogConfig.Config["tag"]))
}
func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) {
@@ -73,17 +73,17 @@ func TestLoadDaemonConfigWithTrueDefaultValues(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.False(t, loadedConfig.EnableUserlandProxy)
assert.Check(t, !loadedConfig.EnableUserlandProxy)
// make sure reloading doesn't generate configuration
// conflicts after normalizing boolean values.
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) {
@@ -92,8 +92,8 @@ func TestLoadDaemonConfigWithTrueDefaultValuesLeaveDefaults(t *testing.T) {
opts := defaultOptions(tempFile.Path())
loadedConfig, err := loadDaemonCliConfig(opts)
require.NoError(t, err)
require.NotNil(t, loadedConfig)
assert.NilError(t, err)
assert.Assert(t, loadedConfig != nil)
assert.True(t, loadedConfig.EnableUserlandProxy)
assert.Check(t, loadedConfig.EnableUserlandProxy)
}
+10 -9
View File
@@ -6,8 +6,9 @@ import (
cliconfig "github.com/docker/docker/cli/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/stretchr/testify/assert"
)
func TestCommonOptionsInstallFlags(t *testing.T) {
@@ -20,10 +21,10 @@ func TestCommonOptionsInstallFlags(t *testing.T) {
"--tlscert=\"/foo/cert\"",
"--tlskey=\"/foo/key\"",
})
assert.NoError(t, err)
assert.Equal(t, "/foo/cafile", opts.TLSOptions.CAFile)
assert.Equal(t, "/foo/cert", opts.TLSOptions.CertFile)
assert.Equal(t, opts.TLSOptions.KeyFile, "/foo/key")
assert.Check(t, err)
assert.Check(t, is.Equal("/foo/cafile", opts.TLSOptions.CAFile))
assert.Check(t, is.Equal("/foo/cert", opts.TLSOptions.CertFile))
assert.Check(t, is.Equal(opts.TLSOptions.KeyFile, "/foo/key"))
}
func defaultPath(filename string) string {
@@ -36,8 +37,8 @@ func TestCommonOptionsInstallFlagsWithDefaults(t *testing.T) {
opts.InstallFlags(flags)
err := flags.Parse([]string{})
assert.NoError(t, err)
assert.Equal(t, defaultPath("ca.pem"), opts.TLSOptions.CAFile)
assert.Equal(t, defaultPath("cert.pem"), opts.TLSOptions.CertFile)
assert.Equal(t, defaultPath("key.pem"), opts.TLSOptions.KeyFile)
assert.Check(t, err)
assert.Check(t, is.Equal(defaultPath("ca.pem"), opts.TLSOptions.CAFile))
assert.Check(t, is.Equal(defaultPath("cert.pem"), opts.TLSOptions.CertFile))
assert.Check(t, is.Equal(defaultPath("key.pem"), opts.TLSOptions.KeyFile))
}
@@ -11,7 +11,7 @@ import (
swarmtypes "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/daemon/logger/jsonfilelog"
"github.com/docker/docker/pkg/signal"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func TestContainerStopSignal(t *testing.T) {
@@ -74,7 +74,7 @@ func TestContainerSecretReferenceDestTarget(t *testing.T) {
func TestContainerLogPathSetForJSONFileLogger(t *testing.T) {
containerRoot, err := ioutil.TempDir("", "TestContainerLogPathSetForJSONFileLogger")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(containerRoot)
c := &Container{
@@ -89,17 +89,17 @@ func TestContainerLogPathSetForJSONFileLogger(t *testing.T) {
}
logger, err := c.StartLogger()
require.NoError(t, err)
assert.NilError(t, err)
defer logger.Close()
expectedLogPath, err := filepath.Abs(filepath.Join(containerRoot, fmt.Sprintf("%s-json.log", c.ID)))
require.NoError(t, err)
require.Equal(t, c.LogPath, expectedLogPath)
assert.NilError(t, err)
assert.Equal(t, c.LogPath, expectedLogPath)
}
func TestContainerLogPathSetForRingLogger(t *testing.T) {
containerRoot, err := ioutil.TempDir("", "TestContainerLogPathSetForRingLogger")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(containerRoot)
c := &Container{
@@ -117,10 +117,10 @@ func TestContainerLogPathSetForRingLogger(t *testing.T) {
}
logger, err := c.StartLogger()
require.NoError(t, err)
assert.NilError(t, err)
defer logger.Close()
expectedLogPath, err := filepath.Abs(filepath.Join(containerRoot, fmt.Sprintf("%s-json.log", c.ID)))
require.NoError(t, err)
require.Equal(t, c.LogPath, expectedLogPath)
assert.NilError(t, err)
assert.Equal(t, c.LogPath, expectedLogPath)
}
+26 -25
View File
@@ -8,8 +8,9 @@ import (
"github.com/docker/docker/api/types"
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/stretchr/testify/assert"
)
var root string
@@ -109,56 +110,56 @@ func TestNames(t *testing.T) {
if err != nil {
t.Fatal(err)
}
assert.NoError(t, db.ReserveName("name1", "containerid1"))
assert.NoError(t, db.ReserveName("name1", "containerid1")) // idempotent
assert.NoError(t, db.ReserveName("name2", "containerid2"))
assert.EqualError(t, db.ReserveName("name2", "containerid3"), ErrNameReserved.Error())
assert.Check(t, db.ReserveName("name1", "containerid1"))
assert.Check(t, db.ReserveName("name1", "containerid1")) // idempotent
assert.Check(t, db.ReserveName("name2", "containerid2"))
assert.Check(t, is.Error(db.ReserveName("name2", "containerid3"), ErrNameReserved.Error()))
// Releasing a name allows the name to point to something else later.
assert.NoError(t, db.ReleaseName("name2"))
assert.NoError(t, db.ReserveName("name2", "containerid3"))
assert.Check(t, db.ReleaseName("name2"))
assert.Check(t, db.ReserveName("name2", "containerid3"))
view := db.Snapshot()
id, err := view.GetID("name1")
assert.NoError(t, err)
assert.Equal(t, "containerid1", id)
assert.Check(t, err)
assert.Check(t, is.Equal("containerid1", id))
id, err = view.GetID("name2")
assert.NoError(t, err)
assert.Equal(t, "containerid3", id)
assert.Check(t, err)
assert.Check(t, is.Equal("containerid3", id))
_, 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.
assert.NoError(t, db.ReleaseName("name2"))
assert.NoError(t, db.ReserveName("name2", "containerid4"))
assert.Check(t, db.ReleaseName("name2"))
assert.Check(t, db.ReserveName("name2", "containerid4"))
id, err = view.GetID("name1")
assert.NoError(t, err)
assert.Equal(t, "containerid1", id)
assert.Check(t, err)
assert.Check(t, is.Equal("containerid1", id))
id, err = view.GetID("name2")
assert.NoError(t, err)
assert.Equal(t, "containerid3", id)
assert.Check(t, err)
assert.Check(t, is.Equal("containerid3", id))
// 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.NoError(t, db.ReserveName("name4", "containerid1"))
assert.Check(t, db.ReserveName("name3", "containerid1"))
assert.Check(t, db.ReserveName("name4", "containerid1"))
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
assert.NoError(t, db.Delete(&Container{ID: "containerid1"}))
assert.Check(t, db.Delete(&Container{ID: "containerid1"}))
// Reusing one of those names should work
assert.NoError(t, db.ReserveName("name1", "containerid4"))
assert.Check(t, db.ReserveName("name1", "containerid4"))
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
@@ -8,7 +8,7 @@ import (
"github.com/docker/docker/api/types/swarm/runtime"
swarmapi "github.com/docker/swarmkit/api"
google_protobuf3 "github.com/gogo/protobuf/types"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func TestServiceConvertFromGRPCRuntimeContainer(t *testing.T) {
@@ -178,12 +178,12 @@ func TestServiceConvertToGRPCIsolation(t *testing.T) {
},
}
res, err := ServiceSpecToGRPC(s)
require.NoError(t, err)
assert.NilError(t, err)
v, ok := res.Task.Runtime.(*swarmapi.TaskSpec_Container)
if !ok {
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)
}
require.Equal(t, c.to, svc.Spec.TaskTemplate.ContainerSpec.Isolation)
assert.Equal(t, c.to, svc.Spec.TaskTemplate.ContainerSpec.Isolation)
})
}
}
@@ -5,7 +5,7 @@ import (
container "github.com/docker/docker/api/types/container"
swarmapi "github.com/docker/swarmkit/api"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func TestIsolationConversion(t *testing.T) {
@@ -31,7 +31,7 @@ func TestIsolationConversion(t *testing.T) {
},
}
config := containerConfig{task: &task}
require.Equal(t, c.to, config.hostConfig().Isolation)
assert.Equal(t, c.to, config.hostConfig().Isolation)
})
}
}
+10 -9
View File
@@ -9,9 +9,10 @@ import (
"github.com/docker/docker/daemon/discovery"
"github.com/docker/docker/internal/testutil"
"github.com/docker/docker/opts"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)
func TestDaemonConfigurationNotFound(t *testing.T) {
@@ -59,7 +60,7 @@ func TestFindConfigurationConflicts(t *testing.T) {
flags := pflag.NewFlagSet("test", pflag.ContinueOnError)
flags.String("authorization-plugins", "", "")
assert.NoError(t, flags.Set("authorization-plugins", "asdf"))
assert.Check(t, flags.Set("authorization-plugins", "asdf"))
testutil.ErrorContains(t,
findConfigurationConflicts(config, flags),
@@ -72,8 +73,8 @@ func TestFindConfigurationConflictsWithNamedOptions(t *testing.T) {
var hosts []string
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.NoError(t, flags.Set("host", "unix:///var/run/docker.sock"))
assert.Check(t, flags.Set("host", "tcp://127.0.0.1:4444"))
assert.Check(t, flags.Set("host", "unix:///var/run/docker.sock"))
testutil.ErrorContains(t, findConfigurationConflicts(config, flags), "hosts")
}
@@ -424,7 +425,7 @@ func TestReloadSetConfigFileNotExist(t *testing.T) {
flags.Set("config-file", configFile)
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")
}
@@ -438,8 +439,8 @@ func TestReloadDefaultConfigNotExist(t *testing.T) {
err := Reload(configFile, flags, func(c *Config) {
reloaded = true
})
assert.Nil(t, err)
assert.True(t, reloaded)
assert.Check(t, err)
assert.Check(t, reloaded)
}
// 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.String("config-file", configFile, "")
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")
}
@@ -484,5 +485,5 @@ func TestReloadWithDuplicateLabels(t *testing.T) {
flags.String("config-file", configFile, "")
flags.StringSlice("labels", lbls, "")
err := Reload(configFile, flags, func(c *Config) {})
assert.NoError(t, err)
assert.Check(t, err)
}
@@ -7,10 +7,10 @@ import (
"github.com/docker/docker/opts"
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/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestGetConflictFreeConfiguration(t *testing.T) {
@@ -39,9 +39,9 @@ func TestGetConflictFreeConfiguration(t *testing.T) {
flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "")
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{
"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) {
@@ -91,17 +91,17 @@ func TestDaemonConfigurationMerge(t *testing.T) {
flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "")
cc, err := MergeDaemonConfigurations(c, flags, file.Path())
require.NoError(t, err)
assert.NilError(t, err)
assert.True(t, cc.Debug)
assert.True(t, cc.AutoRestart)
assert.Check(t, cc.Debug)
assert.Check(t, cc.AutoRestart)
expectedLogConfig := LogConfig{
Type: "syslog",
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{
"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) {
@@ -127,8 +127,8 @@ func TestDaemonConfigurationMergeShmSize(t *testing.T) {
flags.Var(&shmSize, "default-shm-size", "")
cc, err := MergeDaemonConfigurations(c, flags, file.Path())
require.NoError(t, err)
assert.NilError(t, err)
expectedValue := 1 * 1024 * 1024 * 1024
assert.Equal(t, int64(expectedValue), cc.ShmSize.Value())
assert.Check(t, is.Equal(int64(expectedValue), cc.ShmSize.Value()))
}
@@ -7,9 +7,9 @@ import (
"testing"
"github.com/docker/docker/opts"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDaemonConfigurationMerge(t *testing.T) {
@@ -46,15 +46,15 @@ func TestDaemonConfigurationMerge(t *testing.T) {
flags.Var(opts.NewNamedMapOpts("log-opts", nil, nil), "log-opt", "")
cc, err := MergeDaemonConfigurations(c, flags, configFile)
require.NoError(t, err)
assert.NilError(t, err)
assert.True(t, cc.Debug)
assert.True(t, cc.AutoRestart)
assert.Check(t, cc.Debug)
assert.Check(t, cc.AutoRestart)
expectedLogConfig := LogConfig{
Type: "syslog",
Config: map[string]string{"tag": "test_tag"},
}
assert.Equal(t, expectedLogConfig, cc.LogConfig)
assert.Check(t, is.DeepEqual(expectedLogConfig, cc.LogConfig))
}
@@ -9,7 +9,7 @@ import (
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/daemon/config"
"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.
@@ -38,7 +38,7 @@ func TestContainerWarningHostAndPublishPorts(t *testing.T) {
}
d := &Daemon{configStore: cs}
wrns, err := d.verifyContainerSettings("", hostConfig, &containertypes.Config{}, false)
require.NoError(t, err)
require.Equal(t, tc.warnings, wrns)
assert.NilError(t, err)
assert.DeepEqual(t, tc.warnings, wrns)
}
}
+2 -2
View File
@@ -5,7 +5,7 @@ import (
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/errdefs"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
)
// Test case for 35752
@@ -17,5 +17,5 @@ func TestVerifyNetworkingConfig(t *testing.T) {
EndpointsConfig: endpoints,
}
err := verifyNetworkingConfig(nwConfig)
assert.True(t, errdefs.IsInvalidParameter(err))
assert.Check(t, errdefs.IsInvalidParameter(err))
}
@@ -11,8 +11,8 @@ import (
"github.com/docker/docker/oci"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/mount"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
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
spec := oci.DefaultSpec()
err := setMounts(&d, &spec, c, ms)
assert.NoError(t, err)
assert.Check(t, err)
// Check the resulting spec for the correct size
found := false
@@ -149,7 +149,7 @@ func TestTmpfsDevShmSizeOverride(t *testing.T) {
continue
}
t.Logf("%+v\n", m.Options)
assert.Equal(t, "size="+size, o)
assert.Check(t, is.Equal("size="+size, o))
found = true
}
}
@@ -163,7 +163,7 @@ func TestValidateContainerIsolationLinux(t *testing.T) {
d := Daemon{}
_, 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) {
@@ -222,7 +222,7 @@ func TestShouldUnmountRoot(t *testing.T) {
if test.info != nil {
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)))
})
}
})
+4 -3
View File
@@ -19,8 +19,9 @@ import (
"github.com/docker/docker/volume/store"
"github.com/docker/go-connections/nat"
"github.com/docker/libnetwork"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)
//
@@ -312,7 +313,7 @@ func TestValidateContainerIsolation(t *testing.T) {
d := Daemon{}
_, 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) {
@@ -320,6 +321,6 @@ func TestFindNetworkErrorType(t *testing.T) {
_, err := d.FindNetwork("fakeNet")
_, ok := errors.Cause(err).(libnetwork.ErrNoSuchNetwork)
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")
}
}
+3 -3
View File
@@ -17,7 +17,7 @@ import (
"github.com/docker/docker/volume/drivers"
"github.com/docker/docker/volume/local"
"github.com/docker/docker/volume/store"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
type fakeContainerGetter struct {
@@ -290,12 +290,12 @@ func TestMigratePre17Volumes(t *testing.T) {
containerRoot := filepath.Join(rootDir, "containers")
cid := "1234"
err = os.MkdirAll(filepath.Join(containerRoot, cid), 0755)
require.NoError(t, err)
assert.NilError(t, err)
vid := "5678"
vfsPath := filepath.Join(rootDir, "vfs", "dir", vid)
err = os.MkdirAll(vfsPath, 0755)
require.NoError(t, err)
assert.NilError(t, err)
config := []byte(`
{
+2 -2
View File
@@ -10,12 +10,12 @@ import (
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container"
"github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func newDaemonWithTmpRoot(t *testing.T) (*Daemon, func()) {
tmp, err := ioutil.TempDir("", "docker-daemon-unix-test-")
require.NoError(t, err)
assert.NilError(t, err)
d := &Daemon{
repository: tmp,
root: tmp,
@@ -5,8 +5,8 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestDiscoveryOptsErrors(t *testing.T) {
@@ -42,26 +42,26 @@ func TestDiscoveryOptsErrors(t *testing.T) {
for _, testcase := range testcases {
_, _, err := discoveryOpts(testcase.opts)
assert.Error(t, err, testcase.doc)
assert.Check(t, is.ErrorContains(err, ""), testcase.doc)
}
}
func TestDiscoveryOpts(t *testing.T) {
clusterOpts := map[string]string{"discovery.heartbeat": "10", "discovery.ttl": "20"}
heartbeat, ttl, err := discoveryOpts(clusterOpts)
require.NoError(t, err)
assert.Equal(t, 10*time.Second, heartbeat)
assert.Equal(t, 20*time.Second, ttl)
assert.NilError(t, err)
assert.Check(t, is.Equal(10*time.Second, heartbeat))
assert.Check(t, is.Equal(20*time.Second, ttl))
clusterOpts = map[string]string{"discovery.heartbeat": "10"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
require.NoError(t, err)
assert.Equal(t, 10*time.Second, heartbeat)
assert.Equal(t, 10*defaultDiscoveryTTLFactor*time.Second, ttl)
assert.NilError(t, err)
assert.Check(t, is.Equal(10*time.Second, heartbeat))
assert.Check(t, is.Equal(10*defaultDiscoveryTTLFactor*time.Second, ttl))
clusterOpts = map[string]string{"discovery.ttl": "30"}
heartbeat, ttl, err = discoveryOpts(clusterOpts)
require.NoError(t, err)
assert.NilError(t, err)
if ttl != 30*time.Second {
t.Fatalf("TTL - Expected : %v, Actual : %v", 30*time.Second, ttl)
@@ -17,8 +17,8 @@ import (
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/reexec"
"github.com/docker/docker/pkg/stringid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
var (
@@ -189,7 +189,7 @@ func TestCleanupWithNoDirs(t *testing.T) {
defer os.RemoveAll(tmp)
err := d.Cleanup()
assert.NoError(t, err)
assert.Check(t, err)
}
func TestCleanupWithDir(t *testing.T) {
@@ -210,11 +210,11 @@ func TestMountedFalseResponse(t *testing.T) {
defer os.RemoveAll(tmp)
err := d.Create("1", "", nil)
require.NoError(t, err)
assert.NilError(t, err)
response, err := d.mounted(d.getDiffPath("1"))
require.NoError(t, err)
assert.False(t, response)
assert.NilError(t, err)
assert.Check(t, !response)
}
func TestMountedTrueResponse(t *testing.T) {
@@ -223,16 +223,16 @@ func TestMountedTrueResponse(t *testing.T) {
defer d.Cleanup()
err := d.Create("1", "", nil)
require.NoError(t, err)
assert.NilError(t, err)
err = d.Create("2", "1", nil)
require.NoError(t, err)
assert.NilError(t, err)
_, err = d.Get("2", "")
require.NoError(t, err)
assert.NilError(t, err)
response, err := d.mounted(d.pathCache["2"])
require.NoError(t, err)
assert.True(t, response)
assert.NilError(t, err)
assert.Check(t, response)
}
func TestMountWithParent(t *testing.T) {
@@ -567,7 +567,7 @@ func TestStatus(t *testing.T) {
}
status := d.Status()
assert.Len(t, status, 4)
assert.Check(t, is.Len(status, 4))
rootDir := status[0]
dirs := status[2]
@@ -670,18 +670,18 @@ func testMountMoreThan42Layers(t *testing.T, mountPath string) {
current = hash(current)
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, "")
require.NoError(t, err, "current layer %d", i)
assert.NilError(t, err, "current layer %d", i)
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()
if i%10 == 0 {
err := os.Remove(path.Join(point, parent))
require.NoError(t, err, "current layer %d", i)
assert.NilError(t, err, "current layer %d", i)
expected--
}
last = current
@@ -689,10 +689,10 @@ func testMountMoreThan42Layers(t *testing.T, mountPath string) {
// Perform the actual mount for the top most image
point, err := driverGet(d, last, "")
require.NoError(t, err)
assert.NilError(t, err)
files, err := ioutil.ReadDir(point)
require.NoError(t, err)
assert.Len(t, files, expected)
assert.NilError(t, err)
assert.Check(t, is.Len(files, expected))
}
func TestMountMoreThan42Layers(t *testing.T) {
@@ -14,8 +14,8 @@ import (
"github.com/docker/docker/pkg/parsers/kernel"
"github.com/docker/docker/pkg/system"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"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
// 2. That isCopyFileRangeSyscallAvailable() works on "new" kernels
v, err := kernel.GetKernelVersion()
require.NoError(t, err)
assert.NilError(t, err)
copyWithFileRange := true
copyWithFileClone := false
doCopyTest(t, &copyWithFileRange, &copyWithFileClone)
if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: 4, Major: 5, Minor: 0}) < 0 {
assert.False(t, copyWithFileRange)
assert.Check(t, !copyWithFileRange)
} else {
assert.True(t, copyWithFileRange)
assert.Check(t, copyWithFileRange)
}
}
@@ -52,47 +52,47 @@ func TestCopyWithoutRange(t *testing.T) {
func TestCopyDir(t *testing.T) {
srcDir, err := ioutil.TempDir("", "srcDir")
require.NoError(t, err)
assert.NilError(t, err)
populateSrcDir(t, srcDir, 3)
dstDir, err := ioutil.TempDir("", "testdst")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(dstDir)
assert.NoError(t, DirCopy(srcDir, dstDir, Content, false))
require.NoError(t, filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error {
assert.Check(t, DirCopy(srcDir, dstDir, Content, false))
assert.NilError(t, filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error {
if err != nil {
return err
}
// Rebase path
relPath, err := filepath.Rel(srcDir, srcPath)
require.NoError(t, err)
assert.NilError(t, err)
if relPath == "." {
return nil
}
dstPath := filepath.Join(dstDir, relPath)
require.NoError(t, err)
assert.NilError(t, err)
// If we add non-regular dirs and files to the test
// then we need to add more checks here.
dstFileInfo, err := os.Lstat(dstPath)
require.NoError(t, err)
assert.NilError(t, err)
srcFileSys := f.Sys().(*syscall.Stat_t)
dstFileSys := dstFileInfo.Sys().(*syscall.Stat_t)
t.Log(relPath)
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
/// on filesystems that have granular ctimes
assert.Equal(t, srcFileSys.Mode, dstFileSys.Mode)
assert.Equal(t, srcFileSys.Uid, dstFileSys.Uid)
assert.Equal(t, srcFileSys.Gid, dstFileSys.Gid)
assert.Equal(t, srcFileSys.Mtim, dstFileSys.Mtim)
assert.Check(t, is.DeepEqual(srcFileSys.Mode, dstFileSys.Mode))
assert.Check(t, is.DeepEqual(srcFileSys.Uid, dstFileSys.Uid))
assert.Check(t, is.DeepEqual(srcFileSys.Gid, dstFileSys.Gid))
assert.Check(t, is.DeepEqual(srcFileSys.Mtim, dstFileSys.Mtim))
return nil
}))
@@ -115,22 +115,22 @@ func populateSrcDir(t *testing.T, srcDir string, remainingDepth int) {
for i := 0; i < 10; i++ {
dirName := filepath.Join(srcDir, fmt.Sprintf("srcdir-%d", i))
// 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)
require.NoError(t, system.Chtimes(dirName, aTime, mTime))
assert.NilError(t, system.Chtimes(dirName, aTime, mTime))
}
for i := 0; i < 10; i++ {
fileName := filepath.Join(srcDir, fmt.Sprintf("srcfile-%d", i))
// Owner read bit set
require.NoError(t, ioutil.WriteFile(fileName, []byte{}, randomMode(0400)))
require.NoError(t, system.Chtimes(fileName, aTime, mTime))
assert.NilError(t, ioutil.WriteFile(fileName, []byte{}, randomMode(0400)))
assert.NilError(t, system.Chtimes(fileName, aTime, mTime))
}
}
func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) {
dir, err := ioutil.TempDir("", "docker-copy-check")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(dir)
srcFilename := filepath.Join(dir, "srcFilename")
dstFilename := filepath.Join(dir, "dstilename")
@@ -138,42 +138,42 @@ func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) {
r := rand.New(rand.NewSource(0))
buf := make([]byte, 1024)
_, err = r.Read(buf)
require.NoError(t, err)
require.NoError(t, ioutil.WriteFile(srcFilename, buf, 0777))
assert.NilError(t, err)
assert.NilError(t, ioutil.WriteFile(srcFilename, buf, 0777))
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)
require.NoError(t, err)
assert.Equal(t, buf, readBuf)
assert.NilError(t, err)
assert.Check(t, is.DeepEqual(buf, readBuf))
}
func TestCopyHardlink(t *testing.T) {
var srcFile1FileInfo, srcFile2FileInfo, dstFile1FileInfo, dstFile2FileInfo unix.Stat_t
srcDir, err := ioutil.TempDir("", "srcDir")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(srcDir)
dstDir, err := ioutil.TempDir("", "dstDir")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(dstDir)
srcFile1 := filepath.Join(srcDir, "file1")
srcFile2 := filepath.Join(srcDir, "file2")
dstFile1 := filepath.Join(dstDir, "file1")
dstFile2 := filepath.Join(dstDir, "file2")
require.NoError(t, ioutil.WriteFile(srcFile1, []byte{}, 0777))
require.NoError(t, os.Link(srcFile1, srcFile2))
assert.NilError(t, ioutil.WriteFile(srcFile1, []byte{}, 0777))
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))
require.NoError(t, unix.Stat(srcFile2, &srcFile2FileInfo))
require.Equal(t, srcFile1FileInfo.Ino, srcFile2FileInfo.Ino)
assert.NilError(t, unix.Stat(srcFile1, &srcFile1FileInfo))
assert.NilError(t, unix.Stat(srcFile2, &srcFile2FileInfo))
assert.Equal(t, srcFile1FileInfo.Ino, srcFile2FileInfo.Ino)
require.NoError(t, unix.Stat(dstFile1, &dstFile1FileInfo))
require.NoError(t, unix.Stat(dstFile2, &dstFile2FileInfo))
assert.Equal(t, dstFile1FileInfo.Ino, dstFile2FileInfo.Ino)
assert.NilError(t, unix.Stat(dstFile1, &dstFile1FileInfo))
assert.NilError(t, unix.Stat(dstFile2, &dstFile2FileInfo))
assert.Check(t, is.Equal(dstFile1FileInfo.Ino, dstFile2FileInfo.Ino))
}
@@ -6,32 +6,31 @@ import (
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func TestIsEmptyDir(t *testing.T) {
tmp, err := ioutil.TempDir("", "test-is-empty-dir")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(tmp)
d := filepath.Join(tmp, "empty-dir")
err = os.Mkdir(d, 0755)
require.NoError(t, err)
assert.NilError(t, err)
empty := isEmptyDir(d)
assert.True(t, empty)
assert.Check(t, empty)
d = filepath.Join(tmp, "dir-with-subdir")
err = os.MkdirAll(filepath.Join(d, "subdir"), 0755)
require.NoError(t, err)
assert.NilError(t, err)
empty = isEmptyDir(d)
assert.False(t, empty)
assert.Check(t, !empty)
d = filepath.Join(tmp, "dir-with-empty-file")
err = os.Mkdir(d, 0755)
require.NoError(t, err)
assert.NilError(t, err)
_, err = ioutil.TempFile(d, "file")
require.NoError(t, err)
assert.NilError(t, err)
empty = isEmptyDir(d)
assert.False(t, empty)
assert.Check(t, !empty)
}
@@ -9,7 +9,7 @@ import (
contdriver "github.com/containerd/continuity/driver"
"github.com/docker/docker/pkg/stringid"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
// DriverBenchExists benchmarks calls to exist
@@ -251,7 +251,7 @@ func DriverBenchDeepLayerRead(b *testing.B, layerCount int, drivername string, d
}
b.StopTimer()
require.Equal(b, content, c)
assert.DeepEqual(b, content, c)
b.StartTimer()
}
}
@@ -15,9 +15,9 @@ import (
"github.com/docker/docker/daemon/graphdriver"
"github.com/docker/docker/daemon/graphdriver/quota"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/go-units"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
units "github.com/docker/go-units"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/sys/unix"
)
@@ -36,9 +36,9 @@ type Driver struct {
func newDriver(t testing.TB, name string, options []string) *Driver {
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})
if err != nil {
t.Logf("graphdriver: %v\n", err)
@@ -85,10 +85,10 @@ func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...str
defer PutDriver(t)
err := driver.Create("empty", "", nil)
require.NoError(t, err)
assert.NilError(t, err)
defer func() {
require.NoError(t, driver.Remove("empty"))
assert.NilError(t, driver.Remove("empty"))
}()
if !driver.Exists("empty") {
@@ -96,14 +96,14 @@ func DriverTestCreateEmpty(t testing.TB, drivername string, driverOptions ...str
}
dir, err := driver.Get("empty", "")
require.NoError(t, err)
assert.NilError(t, err)
verifyFile(t, dir.Path(), 0755|os.ModeDir, 0, 0)
// Verify that the directory is empty
fis, err := readDir(dir, dir.Path())
require.NoError(t, err)
assert.Len(t, fis, 0)
assert.NilError(t, err)
assert.Check(t, is.Len(fis, 0))
driver.Put("empty")
}
@@ -115,7 +115,7 @@ func DriverTestCreateBase(t testing.TB, drivername string, driverOptions ...stri
createBase(t, driver, "Base")
defer func() {
require.NoError(t, driver.Remove("Base"))
assert.NilError(t, driver.Remove("Base"))
}()
verifyBase(t, driver, "Base")
}
@@ -127,13 +127,13 @@ func DriverTestCreateSnap(t testing.TB, drivername string, driverOptions ...stri
createBase(t, driver, "Base")
defer func() {
require.NoError(t, driver.Remove("Base"))
assert.NilError(t, driver.Remove("Base"))
}()
err := driver.Create("Snap", "Base", nil)
require.NoError(t, err)
assert.NilError(t, err)
defer func() {
require.NoError(t, driver.Remove("Snap"))
assert.NilError(t, driver.Remove("Snap"))
}()
verifyBase(t, driver, "Snap")
@@ -9,25 +9,25 @@ import (
contdriver "github.com/containerd/continuity/driver"
"github.com/docker/docker/daemon/graphdriver"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/sys/unix"
)
func verifyFile(t testing.TB, path string, mode os.FileMode, uid, gid uint32) {
fi, err := os.Stat(path)
require.NoError(t, err)
assert.NilError(t, err)
actual := fi.Mode()
assert.Equal(t, mode&os.ModeType, actual&os.ModeType, path)
assert.Equal(t, mode&os.ModePerm, actual&os.ModePerm, path)
assert.Equal(t, mode&os.ModeSticky, actual&os.ModeSticky, path)
assert.Equal(t, mode&os.ModeSetuid, actual&os.ModeSetuid, path)
assert.Equal(t, mode&os.ModeSetgid, actual&os.ModeSetgid, path)
assert.Check(t, is.Equal(mode&os.ModeType, actual&os.ModeType), path)
assert.Check(t, is.Equal(mode&os.ModePerm, actual&os.ModePerm), path)
assert.Check(t, is.Equal(mode&os.ModeSticky, actual&os.ModeSticky), path)
assert.Check(t, is.Equal(mode&os.ModeSetuid, actual&os.ModeSetuid), path)
assert.Check(t, is.Equal(mode&os.ModeSetgid, actual&os.ModeSetgid), path)
if stat, ok := fi.Sys().(*syscall.Stat_t); ok {
assert.Equal(t, uid, stat.Uid, path)
assert.Equal(t, gid, stat.Gid, path)
assert.Check(t, is.Equal(uid, stat.Uid), 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)
err := driver.CreateReadWrite(name, "", nil)
require.NoError(t, err)
assert.NilError(t, err)
dirFS, err := driver.Get(name, "")
require.NoError(t, err)
assert.NilError(t, err)
defer driver.Put(name)
subdir := dirFS.Join(dirFS.Path(), "a subdir")
require.NoError(t, dirFS.Mkdir(subdir, 0705|os.ModeSticky))
require.NoError(t, dirFS.Lchown(subdir, 1, 2))
assert.NilError(t, dirFS.Mkdir(subdir, 0705|os.ModeSticky))
assert.NilError(t, dirFS.Lchown(subdir, 1, 2))
file := dirFS.Join(dirFS.Path(), "a file")
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) {
dirFS, err := driver.Get(name, "")
require.NoError(t, err)
assert.NilError(t, err)
defer driver.Put(name)
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)
files, err := readDir(dirFS, dirFS.Path())
require.NoError(t, err)
assert.Len(t, files, 2)
assert.NilError(t, err)
assert.Check(t, is.Len(files, 2))
}
@@ -10,9 +10,9 @@ import (
"path/filepath"
"testing"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"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() {
require.NoError(t, unix.Unmount(mountPoint, 0))
assert.NilError(t, unix.Unmount(mountPoint, 0))
}()
backingFsDev, err := makeBackingFsDev(mountPoint)
require.NoError(t, err)
assert.NilError(t, err)
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) {
hasSupport, err := hasQuotaSupport(backingFsDev)
require.NoError(t, err)
assert.False(t, hasSupport)
assert.NilError(t, err)
assert.Check(t, !hasSupport)
}
func testBlockDevQuotaEnabled(t *testing.T, mountPoint, backingFsDev string) {
hasSupport, err := hasQuotaSupport(backingFsDev)
require.NoError(t, err)
assert.True(t, hasSupport)
assert.NilError(t, err)
assert.Check(t, hasSupport)
}
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) {
testDir, err := ioutil.TempDir(mountPoint, "per-test")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(testDir)
ctrl, err := NewControl(testDir)
require.NoError(t, err)
assert.NilError(t, err)
testSubDir, err := ioutil.TempDir(testDir, "quota-test")
require.NoError(t, err)
assert.NilError(t, err)
testFunc(t, ctrl, mountPoint, testDir, testSubDir)
}
}
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")
require.NoError(t, ioutil.WriteFile(smallerThanQuotaFile, make([]byte, testQuotaSize/2), 0644))
require.NoError(t, os.Remove(smallerThanQuotaFile))
assert.NilError(t, ioutil.WriteFile(smallerThanQuotaFile, make([]byte, testQuotaSize/2), 0644))
assert.NilError(t, os.Remove(smallerThanQuotaFile))
}
func testBiggerThanQuota(t *testing.T, ctrl *Control, homeDir, testDir, testSubDir string) {
// Make sure the quota is being enforced
// TODO: When we implement this under EXT4, we need to shed CAP_SYS_RESOURCE, otherwise
// 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")
err := ioutil.WriteFile(biggerThanQuotaFile, make([]byte, testQuotaSize+1), 0644)
require.Error(t, err)
assert.Assert(t, is.ErrorContains(err, ""))
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) {
// 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
require.NoError(t, ctrl.GetQuota(testSubDir, &q))
assert.EqualValues(t, testQuotaSize, q.Size)
assert.NilError(t, ctrl.GetQuota(testSubDir, &q))
assert.Check(t, is.Equal(uint64(testQuotaSize), q.Size))
}
+5 -4
View File
@@ -7,7 +7,8 @@ import (
"github.com/docker/docker/api/types"
"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) {
@@ -43,10 +44,10 @@ func TestParseInitVersion(t *testing.T) {
for _, test := range tests {
ver, err := parseInitVersion(string(test.version))
if test.invalid {
assert.Error(t, err)
assert.Check(t, is.ErrorContains(err, ""))
} else {
assert.NoError(t, err)
assert.Check(t, err)
}
assert.Equal(t, test.result, ver)
assert.Check(t, is.DeepEqual(test.result, ver))
}
}
+4 -4
View File
@@ -7,8 +7,8 @@ import (
"github.com/docker/docker/container"
"github.com/docker/docker/daemon/config"
"github.com/docker/docker/daemon/exec"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestGetInspectData(t *testing.T) {
@@ -25,9 +25,9 @@ func TestGetInspectData(t *testing.T) {
}
_, err := d.getInspectData(c)
assert.Error(t, err)
assert.Check(t, is.ErrorContains(err, ""))
c.Dead = true
_, err = d.getInspectData(c)
assert.NoError(t, err)
assert.Check(t, err)
}
+13 -12
View File
@@ -10,7 +10,8 @@ import (
"github.com/docker/docker/api/types/plugins/logdriver"
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
@@ -88,7 +89,7 @@ func (l *mockLoggingPlugin) ReadLogs(info Info, config ReadConfig) (io.ReadClose
func newMockPluginAdapter(t *testing.T) Logger {
r, w := io.Pipe()
f, err := ioutil.TempFile("", "mock-plugin-adapter")
assert.NoError(t, err)
assert.Check(t, err)
enc := logdriver.NewLogEntryEncoder(w)
a := &pluginAdapterWithRead{
@@ -116,11 +117,11 @@ func TestAdapterReadLogs(t *testing.T) {
}
for _, msg := range testMsg {
m := msg.copy()
assert.NoError(t, l.Log(m))
assert.Check(t, l.Log(m))
}
lr, ok := l.(LogReader)
assert.NotNil(t, ok)
assert.Check(t, ok, "Logger does not implement LogReader")
lw := lr.ReadLogs(ReadConfig{})
@@ -135,7 +136,7 @@ func TestAdapterReadLogs(t *testing.T) {
select {
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):
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()}
assert.NoError(t, l.Log(x.copy()))
assert.Check(t, l.Log(x.copy()))
select {
case msg, ok := <-lw.Msg:
assert.NotNil(t, ok, "message channel unexpectedly closed")
assert.Check(t, ok, "message channel unexpectedly closed")
testMessageEqual(t, &x, msg)
case <-time.After(10 * time.Second):
t.Fatal("timeout reading logs")
@@ -166,15 +167,15 @@ func TestAdapterReadLogs(t *testing.T) {
l.Close()
select {
case msg, ok := <-lw.Msg:
assert.False(t, ok, "expected message channel to be closed")
assert.Nil(t, msg)
assert.Check(t, !ok, "expected message channel to be closed")
assert.Check(t, is.Nil(msg))
case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for logger to close")
}
}
func testMessageEqual(t *testing.T, a, b *Message) {
assert.Equal(t, a.Line, b.Line)
assert.Equal(t, a.Timestamp.UnixNano(), b.Timestamp.UnixNano())
assert.Equal(t, a.Source, b.Source)
assert.Check(t, is.DeepEqual(a.Line, b.Line))
assert.Check(t, is.DeepEqual(a.Timestamp.UnixNano(), b.Timestamp.UnixNano()))
assert.Check(t, is.Equal(a.Source, b.Source))
}
@@ -69,6 +69,8 @@ type logStream struct {
sequenceToken *string
}
var _ logger.SizedLogger = &logStream{}
type api interface {
CreateLogGroup(*cloudwatchlogs.CreateLogGroupInput) (*cloudwatchlogs.CreateLogGroupOutput, error)
CreateLogStream(*cloudwatchlogs.CreateLogStreamInput) (*cloudwatchlogs.CreateLogStreamOutput, error)
@@ -21,7 +21,8 @@ import (
"github.com/docker/docker/daemon/logger"
"github.com/docker/docker/daemon/logger/loggerutils"
"github.com/docker/docker/dockerversion"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
const (
@@ -544,17 +545,17 @@ func TestCollectBatchMultilinePattern(t *testing.T) {
// Verify single multiline event
argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 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, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Check(t, is.Equal(logline+"\n"+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
stream.Close()
// Verify single event
argument = <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 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, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Check(t, is.Equal("xxxx "+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
}
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)
argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 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, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Check(t, is.Equal(logline+"\n"+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
// Log an event 1 second later
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
argument = <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 1, len(argument.LogEvents), "Expected single multiline event")
assert.Equal(t, logline+"\n", *argument.LogEvents[0].Message, "Received incorrect multiline message")
assert.Check(t, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Check(t, is.Equal(logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
stream.Close()
}
@@ -719,9 +720,9 @@ func TestCollectBatchMultilinePatternNegativeEventAge(t *testing.T) {
// Verify single multiline event is flushed with a negative event buffer age
argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 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, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Check(t, is.Equal(1, len(argument.LogEvents)), "Expected single multiline event")
assert.Check(t, is.Equal(logline+"\n"+logline+"\n", *argument.LogEvents[0].Message), "Received incorrect multiline message")
stream.Close()
}
@@ -772,10 +773,10 @@ func TestCollectBatchMultilinePatternMaxEventSize(t *testing.T) {
// We expect a maximum sized event with no new line characters and a
// second short event with a new line character at the end
argument := <-mockClient.putLogEventsArgument
assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
assert.Equal(t, 2, len(argument.LogEvents), "Expected two events")
assert.Equal(t, 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, argument != nil, "Expected non-nil PutLogEventsInput")
assert.Check(t, is.Equal(2, len(argument.LogEvents)), "Expected two events")
assert.Check(t, is.Equal(longline, *argument.LogEvents[0].Message), "Received incorrect multiline message")
assert.Check(t, is.Equal(shortline+"\n", *argument.LogEvents[1].Message), "Received incorrect multiline message")
stream.Close()
}
@@ -1069,8 +1070,8 @@ func TestParseLogOptionsMultilinePattern(t *testing.T) {
}
multilinePattern, err := parseMultilineOptions(info)
assert.Nil(t, err, "Received unexpected error")
assert.True(t, multilinePattern.MatchString("xxxx"), "No multiline pattern match found")
assert.Check(t, err, "Received unexpected error")
assert.Check(t, multilinePattern.MatchString("xxxx"), "No multiline pattern match found")
}
func TestParseLogOptionsDatetimeFormat(t *testing.T) {
@@ -1094,8 +1095,8 @@ func TestParseLogOptionsDatetimeFormat(t *testing.T) {
},
}
multilinePattern, err := parseMultilineOptions(info)
assert.Nil(t, err, "Received unexpected error")
assert.True(t, multilinePattern.MatchString(dt.match), "No multiline pattern match found")
assert.Check(t, err, "Received unexpected error")
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"
err := ValidateLogOpt(cfg)
assert.NotNil(t, err, "Expected an error")
assert.Equal(t, err.Error(), conflictingLogOptionsError, "Received invalid error")
assert.Check(t, err != nil, "Expected an error")
assert.Check(t, is.Equal(err.Error(), conflictingLogOptionsError), "Received invalid error")
}
func TestCreateTagSuccess(t *testing.T) {
@@ -1143,11 +1144,6 @@ func TestCreateTagSuccess(t *testing.T) {
}
}
func TestIsSizedLogger(t *testing.T) {
awslogs := &logStream{}
assert.Implements(t, (*logger.SizedLogger)(nil), awslogs, "awslogs should implement SizedLogger")
}
func BenchmarkUnwrapEvents(b *testing.B) {
events := make([]wrappedEvent, maximumLogEventsPerPut)
for i := 0; i < maximumLogEventsPerPut; i++ {
@@ -1157,11 +1153,10 @@ func BenchmarkUnwrapEvents(b *testing.B) {
}
}
as := assert.New(b)
b.ResetTimer()
for i := 0; i < b.N; i++ {
res := unwrapEvents(events)
as.Len(res, maximumLogEventsPerPut)
assert.Check(b, is.Len(res, maximumLogEventsPerPut))
}
}
@@ -1194,15 +1189,15 @@ func TestNewAWSLogsClientCredentialEndpointDetect(t *testing.T) {
info.Config["awslogs-credentials-endpoint"] = "/creds"
c, err := newAWSLogsClient(info)
assert.NoError(t, err)
assert.Check(t, err)
client := c.(*cloudwatchlogs.CloudWatchLogs)
creds, err := client.Config.Credentials.Get()
assert.NoError(t, err)
assert.Check(t, err)
assert.Equal(t, expectedAccessKeyID, creds.AccessKeyID)
assert.Equal(t, expectedSecretAccessKey, creds.SecretAccessKey)
assert.Check(t, is.Equal(expectedAccessKeyID, creds.AccessKeyID))
assert.Check(t, is.Equal(expectedSecretAccessKey, creds.SecretAccessKey))
}
func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) {
@@ -1224,15 +1219,15 @@ func TestNewAWSLogsClientCredentialEnvironmentVariable(t *testing.T) {
}
c, err := newAWSLogsClient(info)
assert.NoError(t, err)
assert.Check(t, err)
client := c.(*cloudwatchlogs.CloudWatchLogs)
creds, err := client.Config.Credentials.Get()
assert.NoError(t, err)
assert.Check(t, err)
assert.Equal(t, expectedAccessKeyID, creds.AccessKeyID)
assert.Equal(t, expectedSecretAccessKey, creds.SecretAccessKey)
assert.Check(t, is.Equal(expectedAccessKeyID, creds.AccessKeyID))
assert.Check(t, is.Equal(expectedSecretAccessKey, creds.SecretAccessKey))
}
@@ -1253,13 +1248,13 @@ func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "example")
defer os.Remove(tmpfile.Name()) // clean up
assert.NoError(t, err)
assert.Check(t, err)
_, err = tmpfile.Write(content)
assert.NoError(t, err)
assert.Check(t, err)
err = tmpfile.Close()
assert.NoError(t, err)
assert.Check(t, err)
os.Unsetenv("AWS_ACCESS_KEY_ID")
os.Unsetenv("AWS_SECRET_ACCESS_KEY")
@@ -1272,13 +1267,13 @@ func TestNewAWSLogsClientCredentialSharedFile(t *testing.T) {
}
c, err := newAWSLogsClient(info)
assert.NoError(t, err)
assert.Check(t, err)
client := c.(*cloudwatchlogs.CloudWatchLogs)
creds, err := client.Config.Credentials.Get()
assert.NoError(t, err)
assert.Check(t, err)
assert.Equal(t, expectedAccessKeyID, creds.AccessKeyID)
assert.Equal(t, expectedSecretAccessKey, creds.SecretAccessKey)
assert.Check(t, is.Equal(expectedAccessKeyID, creds.AccessKeyID))
assert.Check(t, is.Equal(expectedSecretAccessKey, creds.SecretAccessKey))
}
@@ -13,9 +13,9 @@ import (
"github.com/docker/docker/daemon/logger"
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestJSONFileLogger(t *testing.T) {
@@ -63,7 +63,7 @@ func TestJSONFileLoggerWithTags(t *testing.T) {
cname := "test-container"
tmp, err := ioutil.TempDir("", "docker-logger-")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "container.log")
@@ -76,26 +76,26 @@ func TestJSONFileLoggerWithTags(t *testing.T) {
LogPath: filename,
})
require.NoError(t, err)
assert.NilError(t, err)
defer l.Close()
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"})
require.NoError(t, err)
assert.NilError(t, err)
err = l.Log(&logger.Message{Line: []byte("line3"), Source: "src3"})
require.NoError(t, err)
assert.NilError(t, err)
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"}
{"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"}
`
assert.Equal(t, expected, string(res))
assert.Check(t, is.Equal(expected, string(res)))
}
func BenchmarkJSONFileLoggerLog(b *testing.B) {
@@ -113,7 +113,7 @@ func BenchmarkJSONFileLoggerLog(b *testing.B) {
"second": "label_foo",
},
})
require.NoError(b, err)
assert.NilError(b, err)
defer jsonlogger.Close()
msg := &logger.Message{
@@ -123,7 +123,7 @@ func BenchmarkJSONFileLoggerLog(b *testing.B) {
}
buf := bytes.NewBuffer(nil)
require.NoError(b, marshalMessage(msg, nil, buf))
assert.NilError(b, marshalMessage(msg, nil, buf))
b.SetBytes(int64(buf.Len()))
b.ResetTimer()
@@ -3,12 +3,12 @@ package jsonlog // import "github.com/docker/docker/daemon/logger/jsonfilelog/js
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func TestJSONLogsMarshalJSONBuf(t *testing.T) {
@@ -35,8 +35,17 @@ func TestJSONLogsMarshalJSONBuf(t *testing.T) {
for jsonLog, expression := range logs {
var buf bytes.Buffer
err := jsonLog.MarshalJSONBuf(&buf)
require.NoError(t, err)
assert.Regexp(t, regexp.MustCompile(expression), buf.String())
assert.NoError(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{}))
assert.NilError(t, err)
assert.Assert(t, regexP(buf.String(), expression))
assert.NilError(t, json.Unmarshal(buf.Bytes(), &map[string]interface{}{}))
}
}
func regexP(value string, pattern string) func() (bool, string) {
return func() (bool, string) {
re := regexp.MustCompile(pattern)
msg := fmt.Sprintf("%q did not match pattern %q", value, pattern)
return re.MatchString(value), msg
}
}
@@ -5,8 +5,8 @@ import (
"time"
"github.com/docker/docker/internal/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestFastTimeMarshalJSONWithInvalidYear(t *testing.T) {
@@ -22,14 +22,14 @@ func TestFastTimeMarshalJSONWithInvalidYear(t *testing.T) {
func TestFastTimeMarshalJSON(t *testing.T) {
aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC)
json, err := fastTimeMarshalJSON(aTime)
require.NoError(t, err)
assert.Equal(t, "\"2015-05-29T11:01:02.000000003Z\"", json)
assert.NilError(t, err)
assert.Check(t, is.Equal("\"2015-05-29T11:01:02.000000003Z\"", json))
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)
json, err = fastTimeMarshalJSON(aTime)
require.NoError(t, err)
assert.Equal(t, "\"2015-05-29T11:01:02.000000003+02:00\"", json)
assert.NilError(t, err)
assert.Check(t, is.Equal("\"2015-05-29T11:01:02.000000003+02:00\"", json))
}
@@ -6,8 +6,8 @@ import (
"time"
"github.com/docker/docker/daemon/logger"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/require"
)
func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
@@ -25,7 +25,7 @@ func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
"second": "label_foo",
},
})
require.NoError(b, err)
assert.NilError(b, err)
defer jsonlogger.Close()
msg := &logger.Message{
@@ -35,7 +35,7 @@ func BenchmarkJSONFileLoggerReadLogs(b *testing.B) {
}
buf := bytes.NewBuffer(nil)
require.NoError(b, marshalMessage(msg, nil, buf))
assert.NilError(b, marshalMessage(msg, nil, buf))
b.SetBytes(int64(buf.Len()))
b.ResetTimer()
@@ -11,8 +11,8 @@ import (
"time"
"github.com/docker/docker/daemon/logger"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/env"
"github.com/stretchr/testify/require"
)
// Validate options
@@ -99,19 +99,19 @@ func TestNewWithProxy(t *testing.T) {
},
ContainerID: "containeriid",
})
require.NoError(t, err)
assert.NilError(t, err)
splunkLogger := logger.(*splunkLoggerInline)
proxyFunc := splunkLogger.transport.Proxy
require.NotNil(t, proxyFunc)
assert.Assert(t, proxyFunc != nil)
req, err := http.NewRequest("GET", splunkURL, nil)
require.NoError(t, err)
assert.NilError(t, err)
proxyURL, err := proxyFunc(req)
require.NoError(t, err)
require.NotNil(t, proxyURL)
require.Equal(t, proxy, proxyURL.String())
assert.NilError(t, err)
assert.Assert(t, proxyURL != nil)
assert.Equal(t, proxy, proxyURL.String())
}
// Test default settings
@@ -483,10 +483,10 @@ func TestRawFormat(t *testing.T) {
}
hostname, err := info.Hostname()
require.NoError(t, err)
assert.NilError(t, err)
loggerDriver, err := New(info)
require.NoError(t, err)
assert.NilError(t, err)
if !hec.connectionVerified {
t.Fatal("By default connection should be verified")
@@ -4,15 +4,16 @@ import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
func TestNewParse(t *testing.T) {
tm, err := NewParse("foo", "this is a {{ . }}")
assert.NoError(t, err)
assert.Check(t, err)
var b bytes.Buffer
assert.NoError(t, tm.Execute(&b, "string"))
assert.Check(t, tm.Execute(&b, "string"))
want := "this is a string"
assert.Equal(t, want, b.String())
assert.Check(t, is.Equal(want, b.String()))
}
+8 -8
View File
@@ -8,8 +8,8 @@ import (
"github.com/docker/docker/daemon/config"
"github.com/docker/docker/oci"
"github.com/docker/docker/pkg/idtools"
"github.com/stretchr/testify/assert"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
// 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
ms, err := d.setupMounts(c)
assert.NoError(t, err)
assert.Check(t, err)
ms = append(ms, c.IpcMounts()...)
tmpfsMounts, err := c.TmpfsMounts()
assert.NoError(t, err)
assert.Check(t, err)
ms = append(ms, tmpfsMounts...)
s := oci.DefaultSpec()
err = setMounts(&d, &s, c, ms)
assert.NoError(t, err)
assert.Check(t, err)
}
// 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
// of its code flow, just enough to reproduce the issue.
ms, err := d.setupMounts(c)
assert.NoError(t, err)
assert.Check(t, err)
s := oci.DefaultSpec()
s.Root.Readonly = c.HostConfig.ReadonlyRootfs
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
for _, m := range s.Mounts {
if m.Destination != "/dev/shm" {
continue
}
assert.Equal(t, false, inSlice(m.Options, "ro"))
assert.Check(t, is.Equal(false, inSlice(m.Options, "ro")))
}
}
+3 -2
View File
@@ -11,7 +11,8 @@ import (
_ "github.com/docker/docker/pkg/discovery/memory"
"github.com/docker/docker/registry"
"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) {
@@ -93,7 +94,7 @@ func TestDaemonReloadAllowNondistributableArtifacts(t *testing.T) {
sort.Strings(registries)
sort.Strings(actual)
assert.Equal(t, registries, actual)
assert.Check(t, is.DeepEqual(registries, actual))
}
func TestDaemonReloadMirrors(t *testing.T) {
+15 -15
View File
@@ -7,19 +7,19 @@ import (
"testing"
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// LoadOrCreateTrustKey
func TestLoadOrCreateTrustKeyInvalidKeyFile(t *testing.T) {
tmpKeyFolderPath, err := ioutil.TempDir("", "api-trustkey-test")
require.NoError(t, err)
assert.NilError(t, err)
defer os.RemoveAll(tmpKeyFolderPath)
tmpKeyFile, err := ioutil.TempFile(tmpKeyFolderPath, "keyfile")
require.NoError(t, err)
assert.NilError(t, err)
_, err = loadOrCreateTrustKey(tmpKeyFile.Name())
testutil.ErrorContains(t, err, "Error loading key file")
@@ -33,11 +33,11 @@ func TestLoadOrCreateTrustKeyCreateKeyWhenFileDoesNotExist(t *testing.T) {
tmpKeyFile := tmpKeyFolderPath.Join("keyfile")
key, err := loadOrCreateTrustKey(tmpKeyFile)
require.NoError(t, err)
assert.NotNil(t, key)
assert.NilError(t, err)
assert.Check(t, key != nil)
_, 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) {
@@ -46,27 +46,27 @@ func TestLoadOrCreateTrustKeyCreateKeyWhenDirectoryDoesNotExist(t *testing.T) {
tmpKeyFile := tmpKeyFolderPath.Join("folder/hierarchy/keyfile")
key, err := loadOrCreateTrustKey(tmpKeyFile)
require.NoError(t, err)
assert.NotNil(t, key)
assert.NilError(t, err)
assert.Check(t, key != nil)
_, 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) {
defer os.Remove("keyfile")
key, err := loadOrCreateTrustKey("keyfile")
require.NoError(t, err)
assert.NotNil(t, key)
assert.NilError(t, err)
assert.Check(t, key != nil)
_, 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) {
tmpKeyFile := filepath.Join("testdata", "keyfile")
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"
assert.Contains(t, key.String(), expected)
assert.Check(t, is.Contains(key.String(), expected))
}
@@ -6,7 +6,7 @@ import (
"testing"
"github.com/docker/docker/layer"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
)
func TestV1IDService(t *testing.T) {
@@ -24,7 +24,7 @@ func TestV1IDService(t *testing.T) {
ns := v1IDService.namespace()
require.Equal(t, "v1id", ns)
assert.Equal(t, "v1id", ns)
testVectors := []struct {
registry string
+56 -25
View File
@@ -1,41 +1,72 @@
#!/usr/bin/env bash
set -e
set -e -u -o pipefail
TESTFLAGS=${TESTFLAGS:-""}
# Currently only DockerSuite and DockerNetworkSuite have been adapted for E2E testing
TESTFLAGS_LEGACY=${TESTFLAGS_LEGACY:-""}
TIMEOUT=${TIMEOUT:-60m}
ARCH=$(uname -m)
if [ "$ARCH" == "x86_64" ]; then
ARCH="amd64"
fi
SCRIPTDIR="$(dirname ${BASH_SOURCE[0]})"
export DOCKER_ENGINE_GOARCH=${DOCKER_ENGINE_GOARCH:-${ARCH}}
export DOCKER_ENGINE_GOARCH=${DOCKER_ENGINE_GOARCH:-amd64}
# Set defaults
: ${TESTFLAGS:=}
: ${TESTDEBUG:=}
integration_api_dirs=${TEST_INTEGRATION_DIR:-"$(
find /tests/integration -type d |
grep -vE '(^/tests/integration($|/internal)|/testdata)')"}
run_test_integration() {
run_test_integration_suites
run_test_integration_legacy_suites
[[ "$TESTFLAGS" != *-check.f* ]] && run_test_integration_suites
run_test_integration_legacy_suites
}
run_test_integration_suites() {
local flags="-test.timeout=${TIMEOUT} $TESTFLAGS"
for dir in /tests/integration/*; do
if ! (
cd $dir
echo "Running $PWD"
./test.main $flags
); then exit 1; fi
done
local flags="-test.v -test.timeout=${TIMEOUT:-10m} $TESTFLAGS"
for dir in $integration_api_dirs; do
if ! (
cd $dir
echo "Running $PWD"
test_env ./test.main $flags
); then exit 1; fi
done
}
run_test_integration_legacy_suites() {
(
flags="-check.timeout=${TIMEOUT} -test.timeout=360m $TESTFLAGS_LEGACY"
cd /tests/integration-cli
echo "Running $PWD"
./test.main $flags
)
(
flags="-check.v -check.timeout=${TIMEOUT:-200m} -test.timeout=360m $TESTFLAGS"
cd /tests/integration-cli
echo "Running $PWD"
test_env ./test.main $flags
)
}
bash $SCRIPTDIR/ensure-emptyfs.sh
# use "env -i" to tightly control the environment variables that bleed into the tests
test_env() {
(
set -e +u
[ -n "$TESTDEBUG" ] && set -x
env -i \
DOCKER_API_VERSION="$DOCKER_API_VERSION" \
DOCKER_INTEGRATION_DAEMON_DEST="$DOCKER_INTEGRATION_DAEMON_DEST" \
DOCKER_TLS_VERIFY="$DOCKER_TEST_TLS_VERIFY" \
DOCKER_CERT_PATH="$DOCKER_TEST_CERT_PATH" \
DOCKER_ENGINE_GOARCH="$DOCKER_ENGINE_GOARCH" \
DOCKER_GRAPHDRIVER="$DOCKER_GRAPHDRIVER" \
DOCKER_USERLANDPROXY="$DOCKER_USERLANDPROXY" \
DOCKER_HOST="$DOCKER_HOST" \
DOCKER_REMAP_ROOT="$DOCKER_REMAP_ROOT" \
DOCKER_REMOTE_DAEMON="$DOCKER_REMOTE_DAEMON" \
DOCKERFILE="$DOCKERFILE" \
GOPATH="$GOPATH" \
GOTRACEBACK=all \
HOME="$ABS_DEST/fake-HOME" \
PATH="$PATH" \
TEMP="$TEMP" \
TEST_CLIENT_BINARY="$TEST_CLIENT_BINARY" \
"$@"
)
}
echo "Run integration tests"
sh /scripts/ensure-emptyfs.sh
run_test_integration
+37 -36
View File
@@ -11,16 +11,17 @@ import (
"testing"
"github.com/docker/docker/internal/testutil"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
digest "github.com/opencontainers/go-digest"
"github.com/stretchr/testify/assert"
)
func defaultFSStoreBackend(t *testing.T) (StoreBackend, func()) {
tmpdir, err := ioutil.TempDir("", "images-fs-store")
assert.NoError(t, err)
assert.Check(t, err)
fsBackend, err := NewFSStoreBackend(tmpdir)
assert.NoError(t, err)
assert.Check(t, err)
return fsBackend, func() { os.RemoveAll(tmpdir) }
}
@@ -30,12 +31,12 @@ func TestFSGetInvalidData(t *testing.T) {
defer cleanup()
id, err := store.Set([]byte("foobar"))
assert.NoError(t, err)
assert.Check(t, err)
dgst := digest.Digest(id)
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)
testutil.ErrorContains(t, err, "failed to verify")
@@ -47,7 +48,7 @@ func TestFSInvalidSet(t *testing.T) {
id := digest.FromBytes([]byte("foobar"))
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"))
testutil.ErrorContains(t, err, "failed to write digest data")
@@ -55,7 +56,7 @@ func TestFSInvalidSet(t *testing.T) {
func TestFSInvalidRoot(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "images-fs-store")
assert.NoError(t, err)
assert.Check(t, err)
defer os.RemoveAll(tmpdir)
tcases := []struct {
@@ -70,10 +71,10 @@ func TestFSInvalidRoot(t *testing.T) {
root := filepath.Join(tmpdir, tc.root)
filePath := filepath.Join(tmpdir, tc.invalidFile)
err := os.MkdirAll(filepath.Dir(filePath), 0700)
assert.NoError(t, err)
assert.Check(t, err)
f, err := os.Create(filePath)
assert.NoError(t, err)
assert.Check(t, err)
f.Close()
_, err = NewFSStoreBackend(root)
@@ -89,10 +90,10 @@ func TestFSMetadataGetSet(t *testing.T) {
defer cleanup()
id, err := store.Set([]byte("foo"))
assert.NoError(t, err)
assert.Check(t, err)
id2, err := store.Set([]byte("bar"))
assert.NoError(t, err)
assert.Check(t, err)
tcases := []struct {
id digest.Digest
@@ -106,12 +107,12 @@ func TestFSMetadataGetSet(t *testing.T) {
for _, tc := range tcases {
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)
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")
@@ -130,19 +131,19 @@ func TestFSInvalidWalker(t *testing.T) {
defer cleanup()
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)
assert.NoError(t, err)
assert.Check(t, err)
n := 0
err = store.Walk(func(id digest.Digest) error {
assert.Equal(t, fooID, id)
assert.Check(t, is.Equal(fooID, id))
n++
return nil
})
assert.NoError(t, err)
assert.Equal(t, 1, n)
assert.Check(t, err)
assert.Check(t, is.Equal(1, n))
}
func TestFSGetSet(t *testing.T) {
@@ -159,12 +160,12 @@ func TestFSGetSet(t *testing.T) {
randomInput := make([]byte, 8*1024)
_, err := rand.Read(randomInput)
assert.NoError(t, err)
assert.Check(t, err)
// skipping use of digest pkg because it is used by the implementation
h := sha256.New()
_, err = h.Write(randomInput)
assert.NoError(t, err)
assert.Check(t, err)
tcases = append(tcases, tcase{
input: randomInput,
@@ -173,14 +174,14 @@ func TestFSGetSet(t *testing.T) {
for _, tc := range tcases {
id, err := store.Set([]byte(tc.input))
assert.NoError(t, err)
assert.Equal(t, tc.expected, id)
assert.Check(t, err)
assert.Check(t, is.Equal(tc.expected, id))
}
for _, tc := range tcases {
data, err := store.Get(tc.expected)
assert.NoError(t, err)
assert.Equal(t, tc.input, data)
assert.Check(t, err)
assert.Check(t, is.DeepEqual(tc.input, data))
}
}
@@ -209,22 +210,22 @@ func TestFSDelete(t *testing.T) {
defer cleanup()
id, err := store.Set([]byte("foo"))
assert.NoError(t, err)
assert.Check(t, err)
id2, err := store.Set([]byte("bar"))
assert.NoError(t, err)
assert.Check(t, err)
err = store.Delete(id)
assert.NoError(t, err)
assert.Check(t, err)
_, err = store.Get(id)
testutil.ErrorContains(t, err, "failed to get digest")
_, err = store.Get(id2)
assert.NoError(t, err)
assert.Check(t, err)
err = store.Delete(id2)
assert.NoError(t, err)
assert.Check(t, err)
_, err = store.Get(id2)
testutil.ErrorContains(t, err, "failed to get digest")
@@ -235,10 +236,10 @@ func TestFSWalker(t *testing.T) {
defer cleanup()
id, err := store.Set([]byte("foo"))
assert.NoError(t, err)
assert.Check(t, err)
id2, err := store.Set([]byte("bar"))
assert.NoError(t, err)
assert.Check(t, err)
tcases := make(map[digest.Digest]struct{})
tcases[id] = struct{}{}
@@ -249,9 +250,9 @@ func TestFSWalker(t *testing.T) {
n++
return nil
})
assert.NoError(t, err)
assert.Equal(t, 2, n)
assert.Len(t, tcases, 0)
assert.Check(t, err)
assert.Check(t, is.Equal(2, n))
assert.Check(t, is.Len(tcases, 0))
}
func TestFSWalkerStopOnError(t *testing.T) {
@@ -259,7 +260,7 @@ func TestFSWalkerStopOnError(t *testing.T) {
defer cleanup()
id, err := store.Set([]byte("foo"))
assert.NoError(t, err)
assert.Check(t, err)
tcases := make(map[digest.Digest]struct{})
tcases[id] = struct{}{}
+22 -21
View File
@@ -9,8 +9,9 @@ import (
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/layer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/google/go-cmp/cmp"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
)
const sampleImageJSON = `{
@@ -25,13 +26,13 @@ const sampleImageJSON = `{
func TestNewFromJSON(t *testing.T) {
img, err := NewFromJSON([]byte(sampleImageJSON))
require.NoError(t, err)
assert.Equal(t, sampleImageJSON, string(img.RawJSON()))
assert.NilError(t, err)
assert.Check(t, is.Equal(sampleImageJSON, string(img.RawJSON())))
}
func TestNewFromJSONWithInvalidJSON(t *testing.T) {
_, 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) {
@@ -42,7 +43,7 @@ func TestMarshalKeyOrder(t *testing.T) {
Architecture: "c",
},
})
assert.NoError(t, err)
assert.Check(t, err)
expectedOrder := []string{"architecture", "author", "comment"}
var indexes []int
@@ -71,10 +72,10 @@ func TestImage(t *testing.T) {
computedID: ID(cid),
}
assert.Equal(t, cid, img.ImageID())
assert.Equal(t, cid, img.ID().String())
assert.Equal(t, os, img.OperatingSystem())
assert.Equal(t, config, img.RunConfig())
assert.Check(t, is.Equal(cid, img.ImageID()))
assert.Check(t, is.Equal(cid, img.ID().String()))
assert.Check(t, is.Equal(os, img.OperatingSystem()))
assert.Check(t, is.DeepEqual(config, img.RunConfig()))
}
func TestImageOSNotEmpty(t *testing.T) {
@@ -85,7 +86,7 @@ func TestImageOSNotEmpty(t *testing.T) {
},
OSVersion: "osversion",
}
assert.Equal(t, os, img.OperatingSystem())
assert.Check(t, is.Equal(os, img.OperatingSystem()))
}
func TestNewChildImageFromImageWithRootFS(t *testing.T) {
@@ -109,16 +110,16 @@ func TestNewChildImageFromImageWithRootFS(t *testing.T) {
newImage := NewChildImage(parent, childConfig, "platform")
expectedDiffIDs := []layer.DiffID{layer.DiffID("ba5e"), layer.DiffID("abcdef")}
assert.Equal(t, expectedDiffIDs, newImage.RootFS.DiffIDs)
assert.Equal(t, childConfig.Author, newImage.Author)
assert.Equal(t, childConfig.Config, newImage.Config)
assert.Equal(t, *childConfig.ContainerConfig, newImage.ContainerConfig)
assert.Equal(t, "platform", newImage.OS)
assert.Equal(t, childConfig.Config, newImage.Config)
assert.Check(t, is.DeepEqual(expectedDiffIDs, newImage.RootFS.DiffIDs))
assert.Check(t, is.Equal(childConfig.Author, newImage.Author))
assert.Check(t, is.DeepEqual(childConfig.Config, newImage.Config))
assert.Check(t, is.DeepEqual(*childConfig.ContainerConfig, newImage.ContainerConfig))
assert.Check(t, is.Equal("platform", newImage.OS))
assert.Check(t, is.DeepEqual(childConfig.Config, newImage.Config))
assert.Len(t, newImage.History, 2)
assert.Equal(t, childConfig.Comment, newImage.History[1].Comment)
assert.Check(t, is.Len(newImage.History, 2))
assert.Check(t, is.Equal(childConfig.Comment, newImage.History[1].Comment))
// RootFS should be copied not mutated
assert.NotEqual(t, parent.RootFS.DiffIDs, newImage.RootFS.DiffIDs)
assert.Check(t, !cmp.Equal(parent.RootFS.DiffIDs, newImage.RootFS.DiffIDs),
"RootFS should be copied not mutated")
}
+57 -57
View File
@@ -4,10 +4,10 @@ import (
"runtime"
"testing"
"github.com/docker/docker/internal/testutil"
"github.com/docker/docker/layer"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/assert/cmp"
"github.com/opencontainers/go-digest"
"github.com/stretchr/testify/assert"
)
func TestRestore(t *testing.T) {
@@ -15,57 +15,57 @@ func TestRestore(t *testing.T) {
defer cleanup()
id1, err := fs.Set([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err)
assert.NilError(t, err)
_, err = fs.Set([]byte(`invalid`))
assert.NoError(t, err)
assert.NilError(t, err)
id2, err := fs.Set([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
assert.NoError(t, err)
assert.NilError(t, err)
err = fs.SetMetadata(id2, "parent", []byte(id1))
assert.NoError(t, err)
assert.NilError(t, err)
mlgrMap := make(map[string]LayerGetReleaser)
mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{}
is, err := NewImageStore(fs, mlgrMap)
assert.NoError(t, err)
assert.NilError(t, err)
assert.Len(t, is.Map(), 2)
assert.Check(t, cmp.Len(is.Map(), 2))
img1, err := is.Get(ID(id1))
assert.NoError(t, err)
assert.Equal(t, ID(id1), img1.computedID)
assert.Equal(t, string(id1), img1.computedID.String())
assert.NilError(t, err)
assert.Check(t, cmp.Equal(ID(id1), img1.computedID))
assert.Check(t, cmp.Equal(string(id1), img1.computedID.String()))
img2, err := is.Get(ID(id2))
assert.NoError(t, err)
assert.Equal(t, "abc", img1.Comment)
assert.Equal(t, "def", img2.Comment)
assert.NilError(t, err)
assert.Check(t, cmp.Equal("abc", img1.Comment))
assert.Check(t, cmp.Equal("def", img2.Comment))
_, err = is.GetParent(ID(id1))
testutil.ErrorContains(t, err, "failed to read metadata")
assert.ErrorContains(t, err, "failed to read metadata")
p, err := is.GetParent(ID(id2))
assert.NoError(t, err)
assert.Equal(t, ID(id1), p)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(ID(id1), p))
children := is.Children(ID(id1))
assert.Len(t, children, 1)
assert.Equal(t, ID(id2), children[0])
assert.Len(t, is.Heads(), 1)
assert.Check(t, cmp.Len(children, 1))
assert.Check(t, cmp.Equal(ID(id2), children[0]))
assert.Check(t, cmp.Len(is.Heads(), 1))
sid1, err := is.Search(string(id1)[:10])
assert.NoError(t, err)
assert.Equal(t, ID(id1), sid1)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(ID(id1), sid1))
sid1, err = is.Search(digest.Digest(id1).Hex()[:6])
assert.NoError(t, err)
assert.Equal(t, ID(id1), sid1)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(ID(id1), sid1))
invalidPattern := digest.Digest(id1).Hex()[1:6]
_, err = is.Search(invalidPattern)
testutil.ErrorContains(t, err, "No such image")
assert.ErrorContains(t, err, "No such image")
}
func TestAddDelete(t *testing.T) {
@@ -73,34 +73,34 @@ func TestAddDelete(t *testing.T) {
defer cleanup()
id1, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
assert.NoError(t, err)
assert.Equal(t, ID("sha256:8d25a9c45df515f9d0fe8e4a6b1c64dd3b965a84790ddbcc7954bb9bc89eb993"), id1)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(ID("sha256:8d25a9c45df515f9d0fe8e4a6b1c64dd3b965a84790ddbcc7954bb9bc89eb993"), id1))
img, err := is.Get(id1)
assert.NoError(t, err)
assert.Equal(t, "abc", img.Comment)
assert.NilError(t, err)
assert.Check(t, cmp.Equal("abc", img.Comment))
id2, err := is.Create([]byte(`{"comment": "def", "rootfs": {"type": "layers", "diff_ids": ["2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"]}}`))
assert.NoError(t, err)
assert.NilError(t, err)
err = is.SetParent(id2, id1)
assert.NoError(t, err)
assert.NilError(t, err)
pid1, err := is.GetParent(id2)
assert.NoError(t, err)
assert.Equal(t, pid1, id1)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(pid1, id1))
_, err = is.Delete(id1)
assert.NoError(t, err)
assert.NilError(t, err)
_, err = is.Get(id1)
testutil.ErrorContains(t, err, "failed to get digest")
assert.ErrorContains(t, err, "failed to get digest")
_, err = is.Get(id2)
assert.NoError(t, err)
assert.NilError(t, err)
_, err = is.GetParent(id2)
testutil.ErrorContains(t, err, "failed to read metadata")
assert.ErrorContains(t, err, "failed to read metadata")
}
func TestSearchAfterDelete(t *testing.T) {
@@ -108,17 +108,17 @@ func TestSearchAfterDelete(t *testing.T) {
defer cleanup()
id, err := is.Create([]byte(`{"comment": "abc", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err)
assert.NilError(t, err)
id1, err := is.Search(string(id)[:15])
assert.NoError(t, err)
assert.Equal(t, id1, id)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(id1, id))
_, err = is.Delete(id)
assert.NoError(t, err)
assert.NilError(t, err)
_, err = is.Search(string(id)[:15])
testutil.ErrorContains(t, err, "No such image")
assert.ErrorContains(t, err, "No such image")
}
func TestParentReset(t *testing.T) {
@@ -126,20 +126,20 @@ func TestParentReset(t *testing.T) {
defer cleanup()
id, err := is.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err)
assert.NilError(t, err)
id2, err := is.Create([]byte(`{"comment": "abc2", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err)
assert.NilError(t, err)
id3, err := is.Create([]byte(`{"comment": "abc3", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err)
assert.NilError(t, err)
assert.NoError(t, is.SetParent(id, id2))
assert.Len(t, is.Children(id2), 1)
assert.Check(t, is.SetParent(id, id2))
assert.Check(t, cmp.Len(is.Children(id2), 1))
assert.NoError(t, is.SetParent(id, id3))
assert.Len(t, is.Children(id2), 0)
assert.Len(t, is.Children(id3), 1)
assert.Check(t, is.SetParent(id, id3))
assert.Check(t, cmp.Len(is.Children(id2), 0))
assert.Check(t, cmp.Len(is.Children(id3), 1))
}
func defaultImageStore(t *testing.T) (Store, func()) {
@@ -148,7 +148,7 @@ func defaultImageStore(t *testing.T) (Store, func()) {
mlgrMap := make(map[string]LayerGetReleaser)
mlgrMap[runtime.GOOS] = &mockLayerGetReleaser{}
store, err := NewImageStore(fsBackend, mlgrMap)
assert.NoError(t, err)
assert.NilError(t, err)
return store, cleanup
}
@@ -158,17 +158,17 @@ func TestGetAndSetLastUpdated(t *testing.T) {
defer cleanup()
id, err := store.Create([]byte(`{"comment": "abc1", "rootfs": {"type": "layers"}}`))
assert.NoError(t, err)
assert.NilError(t, err)
updated, err := store.GetLastUpdated(id)
assert.NoError(t, err)
assert.Equal(t, updated.IsZero(), true)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(updated.IsZero(), true))
assert.NoError(t, store.SetLastUpdated(id))
assert.Check(t, store.SetLastUpdated(id))
updated, err = store.GetLastUpdated(id)
assert.NoError(t, err)
assert.Equal(t, updated.IsZero(), false)
assert.NilError(t, err)
assert.Check(t, cmp.Equal(updated.IsZero(), false))
}
type mockLayerGetReleaser struct{}
+38 -55
View File
@@ -13,15 +13,15 @@ import (
"testing"
"time"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build/fakestorage"
"github.com/docker/docker/integration-cli/daemon"
"github.com/docker/docker/integration-cli/environment"
"github.com/docker/docker/integration-cli/fixtures/plugin"
"github.com/docker/docker/integration-cli/registry"
testdaemon "github.com/docker/docker/internal/test/daemon"
ienv "github.com/docker/docker/internal/test/environment"
"github.com/docker/docker/internal/test/fakestorage"
"github.com/docker/docker/internal/test/fixtures/plugin"
"github.com/docker/docker/internal/test/registry"
"github.com/docker/docker/pkg/reexec"
"github.com/go-check/check"
"golang.org/x/net/context"
@@ -29,7 +29,7 @@ import (
const (
// the private registry to use for tests
privateRegistryURL = "127.0.0.1:5000"
privateRegistryURL = registry.DefaultURL
// path to containerd's ctr binary
ctrBinary = "docker-containerd-ctr"
@@ -100,7 +100,7 @@ func (s *DockerSuite) OnTimeout(c *check.C) {
daemonPid := int(rawPid)
if daemonPid > 0 {
daemon.SignalDaemonDump(daemonPid)
testdaemon.SignalDaemonDump(daemonPid)
}
}
@@ -125,11 +125,10 @@ func (s *DockerRegistrySuite) OnTimeout(c *check.C) {
}
func (s *DockerRegistrySuite) SetUpTest(c *check.C) {
testRequires(c, DaemonIsLinux, registry.Hosting, SameHostDaemon)
s.reg = setupRegistry(c, false, "", "")
s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.DaemonInfo.ExperimentalBuild,
})
testRequires(c, DaemonIsLinux, RegistryHosting, SameHostDaemon)
s.reg = registry.NewV2(c)
s.reg.WaitReady(c)
s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
}
func (s *DockerRegistrySuite) TearDownTest(c *check.C) {
@@ -159,11 +158,10 @@ func (s *DockerSchema1RegistrySuite) OnTimeout(c *check.C) {
}
func (s *DockerSchema1RegistrySuite) SetUpTest(c *check.C) {
testRequires(c, DaemonIsLinux, registry.Hosting, NotArm64, SameHostDaemon)
s.reg = setupRegistry(c, true, "", "")
s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.DaemonInfo.ExperimentalBuild,
})
testRequires(c, DaemonIsLinux, RegistryHosting, NotArm64, SameHostDaemon)
s.reg = registry.NewV2(c, registry.Schema1)
s.reg.WaitReady(c)
s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
}
func (s *DockerSchema1RegistrySuite) TearDownTest(c *check.C) {
@@ -193,11 +191,10 @@ func (s *DockerRegistryAuthHtpasswdSuite) OnTimeout(c *check.C) {
}
func (s *DockerRegistryAuthHtpasswdSuite) SetUpTest(c *check.C) {
testRequires(c, DaemonIsLinux, registry.Hosting, SameHostDaemon)
s.reg = setupRegistry(c, false, "htpasswd", "")
s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.DaemonInfo.ExperimentalBuild,
})
testRequires(c, DaemonIsLinux, RegistryHosting, SameHostDaemon)
s.reg = registry.NewV2(c, registry.Htpasswd)
s.reg.WaitReady(c)
s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
}
func (s *DockerRegistryAuthHtpasswdSuite) TearDownTest(c *check.C) {
@@ -229,10 +226,8 @@ func (s *DockerRegistryAuthTokenSuite) OnTimeout(c *check.C) {
}
func (s *DockerRegistryAuthTokenSuite) SetUpTest(c *check.C) {
testRequires(c, DaemonIsLinux, registry.Hosting, SameHostDaemon)
s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.DaemonInfo.ExperimentalBuild,
})
testRequires(c, DaemonIsLinux, RegistryHosting, SameHostDaemon)
s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
}
func (s *DockerRegistryAuthTokenSuite) TearDownTest(c *check.C) {
@@ -251,7 +246,8 @@ func (s *DockerRegistryAuthTokenSuite) setupRegistryWithTokenService(c *check.C,
if s == nil {
c.Fatal("registry suite isn't initialized")
}
s.reg = setupRegistry(c, false, "token", tokenURL)
s.reg = registry.NewV2(c, registry.Token(tokenURL))
s.reg.WaitReady(c)
}
func init() {
@@ -271,9 +267,7 @@ func (s *DockerDaemonSuite) OnTimeout(c *check.C) {
func (s *DockerDaemonSuite) SetUpTest(c *check.C) {
testRequires(c, DaemonIsLinux, SameHostDaemon)
s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.DaemonInfo.ExperimentalBuild,
})
s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution))
}
func (s *DockerDaemonSuite) TearDownTest(c *check.C) {
@@ -285,7 +279,7 @@ func (s *DockerDaemonSuite) TearDownTest(c *check.C) {
}
func (s *DockerDaemonSuite) TearDownSuite(c *check.C) {
filepath.Walk(daemon.SockRoot, func(path string, fi os.FileInfo, err error) error {
filepath.Walk(testdaemon.SockRoot, func(path string, fi os.FileInfo, err error) error {
if err != nil {
// ignore errors here
// not cleaning up sockets is not really an error
@@ -296,7 +290,7 @@ func (s *DockerDaemonSuite) TearDownSuite(c *check.C) {
}
return nil
})
os.RemoveAll(daemon.SockRoot)
os.RemoveAll(testdaemon.SockRoot)
}
const defaultSwarmPort = 2477
@@ -310,7 +304,7 @@ func init() {
type DockerSwarmSuite struct {
server *httptest.Server
ds *DockerSuite
daemons []*daemon.Swarm
daemons []*daemon.Daemon
daemonsLock sync.Mutex // protect access to daemons
portIndex int
}
@@ -327,31 +321,19 @@ func (s *DockerSwarmSuite) SetUpTest(c *check.C) {
testRequires(c, DaemonIsLinux, SameHostDaemon)
}
func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *daemon.Swarm {
d := &daemon.Swarm{
Daemon: daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
Experimental: testEnv.DaemonInfo.ExperimentalBuild,
}),
Port: defaultSwarmPort + s.portIndex,
}
d.ListenAddr = fmt.Sprintf("0.0.0.0:%d", d.Port)
args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"} // avoid networking conflicts
d.StartWithBusybox(c, args...)
func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *daemon.Daemon {
d := daemon.New(c, dockerBinary, dockerdBinary,
testdaemon.WithEnvironment(testEnv.Execution),
testdaemon.WithSwarmPort(defaultSwarmPort+s.portIndex),
)
if joinSwarm {
if len(s.daemons) > 0 {
tokens := s.daemons[0].JoinTokens(c)
token := tokens.Worker
if manager {
token = tokens.Manager
}
c.Assert(d.Join(swarm.JoinRequest{
RemoteAddrs: []string{s.daemons[0].ListenAddr},
JoinToken: token,
}), check.IsNil)
d.StartAndSwarmJoin(c, s.daemons[0].Daemon, manager)
} else {
c.Assert(d.Init(swarm.InitRequest{}), check.IsNil)
d.StartAndSwarmInit(c)
}
} else {
d.StartWithBusybox(c, "--iptables=false", "--swarm-default-advertise-addr=lo")
}
s.portIndex++
@@ -408,8 +390,9 @@ func (ps *DockerPluginSuite) getPluginRepoWithTag() string {
}
func (ps *DockerPluginSuite) SetUpSuite(c *check.C) {
testRequires(c, DaemonIsLinux, registry.Hosting)
ps.registry = setupRegistry(c, false, "", "")
testRequires(c, DaemonIsLinux, RegistryHosting)
ps.registry = registry.NewV2(c)
ps.registry.WaitReady(c)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
@@ -4,7 +4,7 @@ import (
"io"
"strings"
"github.com/docker/docker/integration-cli/cli/build/fakecontext"
"github.com/docker/docker/internal/test/fakecontext"
"github.com/gotestyourself/gotestyourself/icmd"
)
@@ -8,6 +8,7 @@ import (
"github.com/docker/docker/integration-cli/daemon"
"github.com/docker/docker/integration-cli/environment"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/icmd"
"github.com/pkg/errors"
)
@@ -24,6 +25,7 @@ func SetTestEnvironment(env *environment.Execution) {
type CmdOperator func(*icmd.Cmd) func()
type testingT interface {
assert.TestingT
Fatal(args ...interface{})
Fatalf(string, ...interface{})
}
@@ -1,37 +1,21 @@
package daemon // import "github.com/docker/docker/integration-cli/daemon"
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/request"
"github.com/docker/docker/opts"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/go-connections/sockets"
"github.com/docker/go-connections/tlsconfig"
"github.com/docker/docker/internal/test/daemon"
"github.com/go-check/check"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/gotestyourself/gotestyourself/icmd"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
)
type testingT interface {
require.TestingT
assert.TestingT
logT
Fatalf(string, ...interface{})
}
@@ -40,537 +24,24 @@ type logT interface {
Logf(string, ...interface{})
}
// SockRoot holds the path of the default docker integration daemon socket
var SockRoot = filepath.Join(os.TempDir(), "docker-integration")
var errDaemonNotStarted = errors.New("daemon not started")
// Daemon represents a Docker daemon for the testing framework.
type Daemon struct {
GlobalFlags []string
Root string
Folder string
Wait chan error
UseDefaultHost bool
UseDefaultTLSHost bool
id string
logFile *os.File
stdin io.WriteCloser
stdout, stderr io.ReadCloser
cmd *exec.Cmd
storageDriver string
userlandProxy bool
execRoot string
experimental bool
dockerBinary string
dockerdBinary string
log logT
}
// Config holds docker daemon integration configuration
type Config struct {
Experimental bool
}
type clientConfig struct {
transport *http.Transport
scheme string
addr string
*daemon.Daemon
dockerBinary string
}
// New returns a Daemon instance to be used for testing.
// This will create a directory such as d123456789 in the folder specified by $DOCKER_INTEGRATION_DAEMON_DEST or $DEST.
// The daemon will not automatically start.
func New(t testingT, dockerBinary string, dockerdBinary string, config Config) *Daemon {
dest := os.Getenv("DOCKER_INTEGRATION_DAEMON_DEST")
if dest == "" {
dest = os.Getenv("DEST")
}
if dest == "" {
t.Fatalf("Please set the DOCKER_INTEGRATION_DAEMON_DEST or the DEST environment variable")
}
if err := os.MkdirAll(SockRoot, 0700); err != nil {
t.Fatalf("could not create daemon socket root")
}
id := fmt.Sprintf("d%s", stringid.TruncateID(stringid.GenerateRandomID()))
dir := filepath.Join(dest, id)
daemonFolder, err := filepath.Abs(dir)
if err != nil {
t.Fatalf("Could not make %q an absolute path", dir)
}
daemonRoot := filepath.Join(daemonFolder, "root")
if err := os.MkdirAll(daemonRoot, 0755); err != nil {
t.Fatalf("Could not create daemon root %q", dir)
}
userlandProxy := true
if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" {
if val, err := strconv.ParseBool(env); err != nil {
userlandProxy = val
}
}
func New(t testingT, dockerBinary string, dockerdBinary string, ops ...func(*daemon.Daemon)) *Daemon {
ops = append(ops, daemon.WithDockerdBinary(dockerdBinary))
d := daemon.New(t, ops...)
return &Daemon{
id: id,
Folder: daemonFolder,
Root: daemonRoot,
storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"),
userlandProxy: userlandProxy,
execRoot: filepath.Join(os.TempDir(), "docker-execroot", id),
dockerBinary: dockerBinary,
dockerdBinary: dockerdBinary,
experimental: config.Experimental,
log: t,
Daemon: d,
dockerBinary: dockerBinary,
}
}
// RootDir returns the root directory of the daemon.
func (d *Daemon) RootDir() string {
return d.Root
}
// ID returns the generated id of the daemon
func (d *Daemon) ID() string {
return d.id
}
// StorageDriver returns the configured storage driver of the daemon
func (d *Daemon) StorageDriver() string {
return d.storageDriver
}
// CleanupExecRoot cleans the daemon exec root (network namespaces, ...)
func (d *Daemon) CleanupExecRoot(c *check.C) {
cleanupExecRoot(c, d.execRoot)
}
func (d *Daemon) getClientConfig() (*clientConfig, error) {
var (
transport *http.Transport
scheme string
addr string
proto string
)
if d.UseDefaultTLSHost {
option := &tlsconfig.Options{
CAFile: "fixtures/https/ca.pem",
CertFile: "fixtures/https/client-cert.pem",
KeyFile: "fixtures/https/client-key.pem",
}
tlsConfig, err := tlsconfig.Client(*option)
if err != nil {
return nil, err
}
transport = &http.Transport{
TLSClientConfig: tlsConfig,
}
addr = fmt.Sprintf("%s:%d", opts.DefaultHTTPHost, opts.DefaultTLSHTTPPort)
scheme = "https"
proto = "tcp"
} else if d.UseDefaultHost {
addr = opts.DefaultUnixSocket
proto = "unix"
scheme = "http"
transport = &http.Transport{}
} else {
addr = d.sockPath()
proto = "unix"
scheme = "http"
transport = &http.Transport{}
}
if err := sockets.ConfigureTransport(transport, proto, addr); err != nil {
return nil, err
}
transport.DisableKeepAlives = true
return &clientConfig{
transport: transport,
scheme: scheme,
addr: addr,
}, nil
}
// Start starts the daemon and return once it is ready to receive requests.
func (d *Daemon) Start(t testingT, args ...string) {
if err := d.StartWithError(args...); err != nil {
t.Fatalf("Error starting daemon with arguments: %v", args)
}
}
// StartWithError starts the daemon and return once it is ready to receive requests.
// It returns an error in case it couldn't start.
func (d *Daemon) StartWithError(args ...string) error {
logFile, err := os.OpenFile(filepath.Join(d.Folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return errors.Wrapf(err, "[%s] Could not create %s/docker.log", d.id, d.Folder)
}
return d.StartWithLogFile(logFile, args...)
}
// StartWithLogFile will start the daemon and attach its streams to a given file.
func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error {
dockerdBinary, err := exec.LookPath(d.dockerdBinary)
if err != nil {
return errors.Wrapf(err, "[%s] could not find docker binary in $PATH", d.id)
}
args := append(d.GlobalFlags,
"--containerd", "/var/run/docker/containerd/docker-containerd.sock",
"--data-root", d.Root,
"--exec-root", d.execRoot,
"--pidfile", fmt.Sprintf("%s/docker.pid", d.Folder),
fmt.Sprintf("--userland-proxy=%t", d.userlandProxy),
)
if d.experimental {
args = append(args, "--experimental", "--init")
}
if !(d.UseDefaultHost || d.UseDefaultTLSHost) {
args = append(args, []string{"--host", d.Sock()}...)
}
if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
args = append(args, []string{"--userns-remap", root}...)
}
// If we don't explicitly set the log-level or debug flag(-D) then
// turn on debug mode
foundLog := false
foundSd := false
for _, a := range providedArgs {
if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") || strings.Contains(a, "--debug") {
foundLog = true
}
if strings.Contains(a, "--storage-driver") {
foundSd = true
}
}
if !foundLog {
args = append(args, "--debug")
}
if d.storageDriver != "" && !foundSd {
args = append(args, "--storage-driver", d.storageDriver)
}
args = append(args, providedArgs...)
d.cmd = exec.Command(dockerdBinary, args...)
d.cmd.Env = append(os.Environ(), "DOCKER_SERVICE_PREFER_OFFLINE_IMAGE=1")
d.cmd.Stdout = out
d.cmd.Stderr = out
d.logFile = out
if err := d.cmd.Start(); err != nil {
return errors.Errorf("[%s] could not start daemon container: %v", d.id, err)
}
wait := make(chan error)
go func() {
wait <- d.cmd.Wait()
d.log.Logf("[%s] exiting daemon", d.id)
close(wait)
}()
d.Wait = wait
tick := time.Tick(500 * time.Millisecond)
// make sure daemon is ready to receive requests
startTime := time.Now().Unix()
for {
d.log.Logf("[%s] waiting for daemon to start", d.id)
if time.Now().Unix()-startTime > 5 {
// After 5 seconds, give up
return errors.Errorf("[%s] Daemon exited and never started", d.id)
}
select {
case <-time.After(2 * time.Second):
return errors.Errorf("[%s] timeout: daemon does not respond", d.id)
case <-tick:
clientConfig, err := d.getClientConfig()
if err != nil {
return err
}
client := &http.Client{
Transport: clientConfig.transport,
}
req, err := http.NewRequest("GET", "/_ping", nil)
if err != nil {
return errors.Wrapf(err, "[%s] could not create new request", d.id)
}
req.URL.Host = clientConfig.addr
req.URL.Scheme = clientConfig.scheme
resp, err := client.Do(req)
if err != nil {
continue
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
d.log.Logf("[%s] received status != 200 OK: %s\n", d.id, resp.Status)
}
d.log.Logf("[%s] daemon started\n", d.id)
d.Root, err = d.queryRootDir()
if err != nil {
return errors.Errorf("[%s] error querying daemon for root directory: %v", d.id, err)
}
return nil
case <-d.Wait:
return errors.Errorf("[%s] Daemon exited during startup", d.id)
}
}
}
// StartWithBusybox will first start the daemon with Daemon.Start()
// then save the busybox image from the main daemon and load it into this Daemon instance.
func (d *Daemon) StartWithBusybox(t testingT, arg ...string) {
d.Start(t, arg...)
d.LoadBusybox(t)
}
// Kill will send a SIGKILL to the daemon
func (d *Daemon) Kill() error {
if d.cmd == nil || d.Wait == nil {
return errDaemonNotStarted
}
defer func() {
d.logFile.Close()
d.cmd = nil
}()
if err := d.cmd.Process.Kill(); err != nil {
return err
}
return os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder))
}
// Pid returns the pid of the daemon
func (d *Daemon) Pid() int {
return d.cmd.Process.Pid
}
// Interrupt stops the daemon by sending it an Interrupt signal
func (d *Daemon) Interrupt() error {
return d.Signal(os.Interrupt)
}
// Signal sends the specified signal to the daemon if running
func (d *Daemon) Signal(signal os.Signal) error {
if d.cmd == nil || d.Wait == nil {
return errDaemonNotStarted
}
return d.cmd.Process.Signal(signal)
}
// DumpStackAndQuit sends SIGQUIT to the daemon, which triggers it to dump its
// stack to its log file and exit
// This is used primarily for gathering debug information on test timeout
func (d *Daemon) DumpStackAndQuit() {
if d.cmd == nil || d.cmd.Process == nil {
return
}
SignalDaemonDump(d.cmd.Process.Pid)
}
// Stop will send a SIGINT every second and wait for the daemon to stop.
// If it times out, a SIGKILL is sent.
// Stop will not delete the daemon directory. If a purged daemon is needed,
// instantiate a new one with NewDaemon.
// If an error occurs while starting the daemon, the test will fail.
func (d *Daemon) Stop(t testingT) {
err := d.StopWithError()
if err != nil {
if err != errDaemonNotStarted {
t.Fatalf("Error while stopping the daemon %s : %v", d.id, err)
} else {
t.Logf("Daemon %s is not started", d.id)
}
}
}
// StopWithError will send a SIGINT every second and wait for the daemon to stop.
// If it timeouts, a SIGKILL is sent.
// Stop will not delete the daemon directory. If a purged daemon is needed,
// instantiate a new one with NewDaemon.
func (d *Daemon) StopWithError() error {
if d.cmd == nil || d.Wait == nil {
return errDaemonNotStarted
}
defer func() {
d.logFile.Close()
d.cmd = nil
}()
i := 1
tick := time.Tick(time.Second)
if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
if strings.Contains(err.Error(), "os: process already finished") {
return errDaemonNotStarted
}
return errors.Errorf("could not send signal: %v", err)
}
out1:
for {
select {
case err := <-d.Wait:
return err
case <-time.After(20 * time.Second):
// time for stopping jobs and run onShutdown hooks
d.log.Logf("[%s] daemon started", d.id)
break out1
}
}
out2:
for {
select {
case err := <-d.Wait:
return err
case <-tick:
i++
if i > 5 {
d.log.Logf("tried to interrupt daemon for %d times, now try to kill it", i)
break out2
}
d.log.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid)
if err := d.cmd.Process.Signal(os.Interrupt); err != nil {
return errors.Errorf("could not send signal: %v", err)
}
}
}
if err := d.cmd.Process.Kill(); err != nil {
d.log.Logf("Could not kill daemon: %v", err)
return err
}
d.cmd.Wait()
return os.Remove(fmt.Sprintf("%s/docker.pid", d.Folder))
}
// Restart will restart the daemon by first stopping it and the starting it.
// If an error occurs while starting the daemon, the test will fail.
func (d *Daemon) Restart(t testingT, args ...string) {
d.Stop(t)
d.handleUserns()
d.Start(t, args...)
}
// RestartWithError will restart the daemon by first stopping it and then starting it.
func (d *Daemon) RestartWithError(arg ...string) error {
if err := d.StopWithError(); err != nil {
return err
}
d.handleUserns()
return d.StartWithError(arg...)
}
func (d *Daemon) handleUserns() {
// in the case of tests running a user namespace-enabled daemon, we have resolved
// d.Root to be the actual final path of the graph dir after the "uid.gid" of
// remapped root is added--we need to subtract it from the path before calling
// start or else we will continue making subdirectories rather than truly restarting
// with the same location/root:
if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
d.Root = filepath.Dir(d.Root)
}
}
// LoadBusybox image into the daemon
func (d *Daemon) LoadBusybox(t testingT) {
clientHost, err := client.NewEnvClient()
require.NoError(t, err, "failed to create client")
defer clientHost.Close()
ctx := context.Background()
reader, err := clientHost.ImageSave(ctx, []string{"busybox:latest"})
require.NoError(t, err, "failed to download busybox")
defer reader.Close()
client, err := d.NewClient()
require.NoError(t, err, "failed to create client")
defer client.Close()
resp, err := client.ImageLoad(ctx, reader, true)
require.NoError(t, err, "failed to load busybox")
defer resp.Body.Close()
}
func (d *Daemon) queryRootDir() (string, error) {
// update daemon root by asking /info endpoint (to support user
// namespaced daemon with root remapped uid.gid directory)
clientConfig, err := d.getClientConfig()
if err != nil {
return "", err
}
client := &http.Client{
Transport: clientConfig.transport,
}
req, err := http.NewRequest("GET", "/info", nil)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.URL.Host = clientConfig.addr
req.URL.Scheme = clientConfig.scheme
resp, err := client.Do(req)
if err != nil {
return "", err
}
body := ioutils.NewReadCloserWrapper(resp.Body, func() error {
return resp.Body.Close()
})
type Info struct {
DockerRootDir string
}
var b []byte
var i Info
b, err = request.ReadBody(body)
if err == nil && resp.StatusCode == http.StatusOK {
// read the docker root dir
if err = json.Unmarshal(b, &i); err == nil {
return i.DockerRootDir, nil
}
}
return "", err
}
// Sock returns the socket path of the daemon
func (d *Daemon) Sock() string {
return fmt.Sprintf("unix://" + d.sockPath())
}
func (d *Daemon) sockPath() string {
return filepath.Join(SockRoot, d.id+".sock")
}
// WaitRun waits for a container to be running for 10s
func (d *Daemon) WaitRun(contID string) error {
args := []string{"--host", d.Sock()}
return WaitInspectWithArgs(d.dockerBinary, contID, "{{.State.Running}}", "true", 10*time.Second, args...)
}
// Info returns the info struct for this daemon
func (d *Daemon) Info(t require.TestingT) types.Info {
apiclient, err := client.NewClientWithOpts(client.WithHost((d.Sock())))
require.NoError(t, err)
info, err := apiclient.Info(context.Background())
require.NoError(t, err)
return info
}
// Cmd executes a docker CLI command against this daemon.
// Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version
func (d *Daemon) Cmd(args ...string) (string, error) {
@@ -594,11 +65,6 @@ func (d *Daemon) PrependHostArg(args []string) []string {
return append([]string{"--host", d.Sock()}, args...)
}
// LogFileName returns the path the daemon's log file
func (d *Daemon) LogFileName() string {
return d.logFile.Name()
}
// GetIDByName returns the ID of an object (container, volume, …) given its name
func (d *Daemon) GetIDByName(name string) (string, error) {
return d.inspectFieldWithError(name, "Id")
@@ -616,11 +82,6 @@ func (d *Daemon) ActiveContainers() (ids []string) {
return
}
// ReadLogFile returns the content of the daemon log file
func (d *Daemon) ReadLogFile() ([]byte, error) {
return ioutil.ReadFile(d.logFile.Name())
}
// InspectField returns the field filter by 'filter'
func (d *Daemon) InspectField(name, filter string) (string, error) {
return d.inspectFilter(name, filter)
@@ -672,59 +133,25 @@ func (d *Daemon) CheckActiveContainerCount(c *check.C) (interface{}, check.Comme
return len(strings.Split(strings.TrimSpace(out), "\n")), check.Commentf("output: %q", string(out))
}
// ReloadConfig asks the daemon to reload its configuration
func (d *Daemon) ReloadConfig() error {
if d.cmd == nil || d.cmd.Process == nil {
return errors.New("daemon is not running")
}
errCh := make(chan error)
started := make(chan struct{})
go func() {
_, body, err := request.DoOnHost(d.Sock(), "/events", request.Method(http.MethodGet))
close(started)
if err != nil {
errCh <- err
}
defer body.Close()
dec := json.NewDecoder(body)
for {
var e events.Message
if err := dec.Decode(&e); err != nil {
errCh <- err
return
}
if e.Type != events.DaemonEventType {
continue
}
if e.Action != "reload" {
continue
}
close(errCh) // notify that we are done
return
}
}()
<-started
if err := signalDaemonReload(d.cmd.Process.Pid); err != nil {
return errors.Errorf("error signaling daemon reload: %v", err)
}
select {
case err := <-errCh:
if err != nil {
return errors.Errorf("error waiting for daemon reload event: %v", err)
}
case <-time.After(30 * time.Second):
return errors.New("timeout waiting for daemon reload event")
}
return nil
// WaitRun waits for a container to be running for 10s
func (d *Daemon) WaitRun(contID string) error {
args := []string{"--host", d.Sock()}
return WaitInspectWithArgs(d.dockerBinary, contID, "{{.State.Running}}", "true", 10*time.Second, args...)
}
// NewClient creates new client based on daemon's socket path
func (d *Daemon) NewClient() (*client.Client, error) {
return client.NewClientWithOpts(
client.FromEnv,
client.WithHost(d.Sock()))
// CmdRetryOutOfSequence tries the specified command against the current daemon for 10 times
func (d *Daemon) CmdRetryOutOfSequence(args ...string) (string, error) {
for i := 0; ; i++ {
out, err := d.Cmd(args...)
if err != nil {
if strings.Contains(out, "update out of sequence") {
if i < 10 {
continue
}
}
}
return out, err
}
}
// WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
@@ -3,7 +3,6 @@ package daemon // import "github.com/docker/docker/integration-cli/daemon"
import (
"fmt"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
@@ -11,179 +10,13 @@ import (
"github.com/docker/docker/client"
"github.com/docker/docker/integration-cli/checker"
"github.com/go-check/check"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
"golang.org/x/net/context"
)
// Swarm is a test daemon with helpers for participating in a swarm.
type Swarm struct {
*Daemon
swarm.Info
Port int
ListenAddr string
}
// Init initializes a new swarm cluster.
func (d *Swarm) Init(req swarm.InitRequest) error {
if req.ListenAddr == "" {
req.ListenAddr = d.ListenAddr
}
cli, err := d.NewClient()
if err != nil {
return fmt.Errorf("initializing swarm: failed to create client %v", err)
}
defer cli.Close()
_, err = cli.SwarmInit(context.Background(), req)
if err != nil {
return fmt.Errorf("initializing swarm: %v", err)
}
info, err := d.SwarmInfo()
if err != nil {
return err
}
d.Info = info
return nil
}
// Join joins a daemon to an existing cluster.
func (d *Swarm) Join(req swarm.JoinRequest) error {
if req.ListenAddr == "" {
req.ListenAddr = d.ListenAddr
}
cli, err := d.NewClient()
if err != nil {
return fmt.Errorf("joining swarm: failed to create client %v", err)
}
defer cli.Close()
err = cli.SwarmJoin(context.Background(), req)
if err != nil {
return fmt.Errorf("joining swarm: %v", err)
}
info, err := d.SwarmInfo()
if err != nil {
return err
}
d.Info = info
return nil
}
// Leave forces daemon to leave current cluster.
func (d *Swarm) Leave(force bool) error {
cli, err := d.NewClient()
if err != nil {
return fmt.Errorf("leaving swarm: failed to create client %v", err)
}
defer cli.Close()
err = cli.SwarmLeave(context.Background(), force)
if err != nil {
err = fmt.Errorf("leaving swarm: %v", err)
}
return err
}
// SwarmInfo returns the swarm information of the daemon
func (d *Swarm) SwarmInfo() (swarm.Info, error) {
cli, err := d.NewClient()
if err != nil {
return swarm.Info{}, fmt.Errorf("get swarm info: %v", err)
}
info, err := cli.Info(context.Background())
if err != nil {
return swarm.Info{}, fmt.Errorf("get swarm info: %v", err)
}
return info.Swarm, nil
}
// Unlock tries to unlock a locked swarm
func (d *Swarm) Unlock(req swarm.UnlockRequest) error {
cli, err := d.NewClient()
if err != nil {
return fmt.Errorf("unlocking swarm: failed to create client %v", err)
}
defer cli.Close()
err = cli.SwarmUnlock(context.Background(), req)
if err != nil {
err = errors.Wrap(err, "unlocking swarm")
}
return err
}
// ServiceConstructor defines a swarm service constructor function
type ServiceConstructor func(*swarm.Service)
// NodeConstructor defines a swarm node constructor
type NodeConstructor func(*swarm.Node)
// SecretConstructor defines a swarm secret constructor
type SecretConstructor func(*swarm.Secret)
// ConfigConstructor defines a swarm config constructor
type ConfigConstructor func(*swarm.Config)
// SpecConstructor defines a swarm spec constructor
type SpecConstructor func(*swarm.Spec)
// CreateServiceWithOptions creates a swarm service given the specified service constructors
// and auth config
func (d *Swarm) CreateServiceWithOptions(c *check.C, opts types.ServiceCreateOptions, f ...ServiceConstructor) string {
var service swarm.Service
for _, fn := range f {
fn(&service)
}
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
res, err := cli.ServiceCreate(ctx, service.Spec, opts)
c.Assert(err, checker.IsNil)
return res.ID
}
// CreateService creates a swarm service given the specified service constructor
func (d *Swarm) CreateService(c *check.C, f ...ServiceConstructor) string {
return d.CreateServiceWithOptions(c, types.ServiceCreateOptions{}, f...)
}
// GetService returns the swarm service corresponding to the specified id
func (d *Swarm) GetService(c *check.C, id string) *swarm.Service {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
service, _, err := cli.ServiceInspectWithRaw(context.Background(), id, types.ServiceInspectOptions{})
c.Assert(err, checker.IsNil)
return &service
}
// GetServiceTasks returns the swarm tasks for the specified service
func (d *Swarm) GetServiceTasks(c *check.C, service string) []swarm.Task {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
filterArgs := filters.NewArgs()
filterArgs.Add("desired-state", "running")
filterArgs.Add("service", service)
options := types.TaskListOptions{
Filters: filterArgs,
}
tasks, err := cli.TaskList(context.Background(), options)
c.Assert(err, checker.IsNil)
return tasks
}
// CheckServiceTasksInState returns the number of tasks with a matching state,
// and optional message substring.
func (d *Swarm) CheckServiceTasksInState(service string, state swarm.TaskState, message string) func(*check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckServiceTasksInState(service string, state swarm.TaskState, message string) func(*check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) {
tasks := d.GetServiceTasks(c, service)
var count int
@@ -200,7 +33,7 @@ func (d *Swarm) CheckServiceTasksInState(service string, state swarm.TaskState,
// CheckServiceTasksInStateWithError returns the number of tasks with a matching state,
// and optional message substring.
func (d *Swarm) CheckServiceTasksInStateWithError(service string, state swarm.TaskState, errorMessage string) func(*check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckServiceTasksInStateWithError(service string, state swarm.TaskState, errorMessage string) func(*check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) {
tasks := d.GetServiceTasks(c, service)
var count int
@@ -216,12 +49,12 @@ func (d *Swarm) CheckServiceTasksInStateWithError(service string, state swarm.Ta
}
// CheckServiceRunningTasks returns the number of running tasks for the specified service
func (d *Swarm) CheckServiceRunningTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckServiceRunningTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
return d.CheckServiceTasksInState(service, swarm.TaskStateRunning, "")
}
// CheckServiceUpdateState returns the current update state for the specified service
func (d *Swarm) CheckServiceUpdateState(service string) func(*check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckServiceUpdateState(service string) func(*check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) {
service := d.GetService(c, service)
if service.UpdateStatus == nil {
@@ -232,35 +65,35 @@ func (d *Swarm) CheckServiceUpdateState(service string) func(*check.C) (interfac
}
// CheckPluginRunning returns the runtime state of the plugin
func (d *Swarm) CheckPluginRunning(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckPluginRunning(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) {
apiclient, err := d.NewClient()
require.NoError(c, err)
assert.NilError(c, err)
resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin)
if client.IsErrNotFound(err) {
return false, check.Commentf("%v", err)
}
require.NoError(c, err)
assert.NilError(c, err)
return resp.Enabled, check.Commentf("%+v", resp)
}
}
// CheckPluginImage returns the runtime state of the plugin
func (d *Swarm) CheckPluginImage(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckPluginImage(plugin string) func(c *check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) {
apiclient, err := d.NewClient()
require.NoError(c, err)
assert.NilError(c, err)
resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin)
if client.IsErrNotFound(err) {
return false, check.Commentf("%v", err)
}
require.NoError(c, err)
assert.NilError(c, err)
return resp.PluginReference, check.Commentf("%+v", resp)
}
}
// CheckServiceTasks returns the number of tasks for the specified service
func (d *Swarm) CheckServiceTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckServiceTasks(service string) func(*check.C) (interface{}, check.CommentInterface) {
return func(c *check.C) (interface{}, check.CommentInterface) {
tasks := d.GetServiceTasks(c, service)
return len(tasks), nil
@@ -268,7 +101,7 @@ func (d *Swarm) CheckServiceTasks(service string) func(*check.C) (interface{}, c
}
// CheckRunningTaskNetworks returns the number of times each network is referenced from a task.
func (d *Swarm) CheckRunningTaskNetworks(c *check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckRunningTaskNetworks(c *check.C) (interface{}, check.CommentInterface) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
@@ -293,7 +126,7 @@ func (d *Swarm) CheckRunningTaskNetworks(c *check.C) (interface{}, check.Comment
}
// CheckRunningTaskImages returns the times each image is running as a task.
func (d *Swarm) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
@@ -318,7 +151,7 @@ func (d *Swarm) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentIn
}
// CheckNodeReadyCount returns the number of ready node on the swarm
func (d *Swarm) CheckNodeReadyCount(c *check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckNodeReadyCount(c *check.C) (interface{}, check.CommentInterface) {
nodes := d.ListNodes(c)
var readyCount int
for _, node := range nodes {
@@ -329,303 +162,21 @@ func (d *Swarm) CheckNodeReadyCount(c *check.C) (interface{}, check.CommentInter
return readyCount, nil
}
// GetTask returns the swarm task identified by the specified id
func (d *Swarm) GetTask(c *check.C, id string) swarm.Task {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
task, _, err := cli.TaskInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
return task
}
// UpdateService updates a swarm service with the specified service constructor
func (d *Swarm) UpdateService(c *check.C, service *swarm.Service, f ...ServiceConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
for _, fn := range f {
fn(service)
}
_, err = cli.ServiceUpdate(context.Background(), service.ID, service.Version, service.Spec, types.ServiceUpdateOptions{})
c.Assert(err, checker.IsNil)
}
// RemoveService removes the specified service
func (d *Swarm) RemoveService(c *check.C, id string) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
err = cli.ServiceRemove(context.Background(), id)
c.Assert(err, checker.IsNil)
}
// GetNode returns a swarm node identified by the specified id
func (d *Swarm) GetNode(c *check.C, id string) *swarm.Node {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
node, _, err := cli.NodeInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
c.Assert(node.ID, checker.Equals, id)
return &node
}
// RemoveNode removes the specified node
func (d *Swarm) RemoveNode(c *check.C, id string, force bool) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
options := types.NodeRemoveOptions{
Force: force,
}
err = cli.NodeRemove(context.Background(), id, options)
c.Assert(err, checker.IsNil)
}
// UpdateNode updates a swarm node with the specified node constructor
func (d *Swarm) UpdateNode(c *check.C, id string, f ...NodeConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
for i := 0; ; i++ {
node := d.GetNode(c, id)
for _, fn := range f {
fn(node)
}
err = cli.NodeUpdate(context.Background(), node.ID, node.Version, node.Spec)
if i < 10 && err != nil && strings.Contains(err.Error(), "update out of sequence") {
time.Sleep(100 * time.Millisecond)
continue
}
c.Assert(err, checker.IsNil)
return
}
}
// ListNodes returns the list of the current swarm nodes
func (d *Swarm) ListNodes(c *check.C) []swarm.Node {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
nodes, err := cli.NodeList(context.Background(), types.NodeListOptions{})
c.Assert(err, checker.IsNil)
return nodes
}
// ListServices returns the list of the current swarm services
func (d *Swarm) ListServices(c *check.C) []swarm.Service {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
services, err := cli.ServiceList(context.Background(), types.ServiceListOptions{})
c.Assert(err, checker.IsNil)
return services
}
// CreateSecret creates a secret given the specified spec
func (d *Swarm) CreateSecret(c *check.C, secretSpec swarm.SecretSpec) string {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
scr, err := cli.SecretCreate(context.Background(), secretSpec)
c.Assert(err, checker.IsNil)
return scr.ID
}
// ListSecrets returns the list of the current swarm secrets
func (d *Swarm) ListSecrets(c *check.C) []swarm.Secret {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
secrets, err := cli.SecretList(context.Background(), types.SecretListOptions{})
c.Assert(err, checker.IsNil)
return secrets
}
// GetSecret returns a swarm secret identified by the specified id
func (d *Swarm) GetSecret(c *check.C, id string) *swarm.Secret {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
secret, _, err := cli.SecretInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
return &secret
}
// DeleteSecret removes the swarm secret identified by the specified id
func (d *Swarm) DeleteSecret(c *check.C, id string) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
err = cli.SecretRemove(context.Background(), id)
c.Assert(err, checker.IsNil)
}
// UpdateSecret updates the swarm secret identified by the specified id
// Currently, only label update is supported.
func (d *Swarm) UpdateSecret(c *check.C, id string, f ...SecretConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
secret := d.GetSecret(c, id)
for _, fn := range f {
fn(secret)
}
err = cli.SecretUpdate(context.Background(), secret.ID, secret.Version, secret.Spec)
c.Assert(err, checker.IsNil)
}
// CreateConfig creates a config given the specified spec
func (d *Swarm) CreateConfig(c *check.C, configSpec swarm.ConfigSpec) string {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
scr, err := cli.ConfigCreate(context.Background(), configSpec)
c.Assert(err, checker.IsNil)
return scr.ID
}
// ListConfigs returns the list of the current swarm configs
func (d *Swarm) ListConfigs(c *check.C) []swarm.Config {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
configs, err := cli.ConfigList(context.Background(), types.ConfigListOptions{})
c.Assert(err, checker.IsNil)
return configs
}
// GetConfig returns a swarm config identified by the specified id
func (d *Swarm) GetConfig(c *check.C, id string) *swarm.Config {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
config, _, err := cli.ConfigInspectWithRaw(context.Background(), id)
c.Assert(err, checker.IsNil)
return &config
}
// DeleteConfig removes the swarm config identified by the specified id
func (d *Swarm) DeleteConfig(c *check.C, id string) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
err = cli.ConfigRemove(context.Background(), id)
c.Assert(err, checker.IsNil)
}
// UpdateConfig updates the swarm config identified by the specified id
// Currently, only label update is supported.
func (d *Swarm) UpdateConfig(c *check.C, id string, f ...ConfigConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
config := d.GetConfig(c, id)
for _, fn := range f {
fn(config)
}
err = cli.ConfigUpdate(context.Background(), config.ID, config.Version, config.Spec)
c.Assert(err, checker.IsNil)
}
// GetSwarm returns the current swarm object
func (d *Swarm) GetSwarm(c *check.C) swarm.Swarm {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
sw, err := cli.SwarmInspect(context.Background())
c.Assert(err, checker.IsNil)
return sw
}
// UpdateSwarm updates the current swarm object with the specified spec constructors
func (d *Swarm) UpdateSwarm(c *check.C, f ...SpecConstructor) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
sw := d.GetSwarm(c)
for _, fn := range f {
fn(&sw.Spec)
}
err = cli.SwarmUpdate(context.Background(), sw.Version, sw.Spec, swarm.UpdateFlags{})
c.Assert(err, checker.IsNil)
}
// RotateTokens update the swarm to rotate tokens
func (d *Swarm) RotateTokens(c *check.C) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
sw, err := cli.SwarmInspect(context.Background())
c.Assert(err, checker.IsNil)
flags := swarm.UpdateFlags{
RotateManagerToken: true,
RotateWorkerToken: true,
}
err = cli.SwarmUpdate(context.Background(), sw.Version, sw.Spec, flags)
c.Assert(err, checker.IsNil)
}
// JoinTokens returns the current swarm join tokens
func (d *Swarm) JoinTokens(c *check.C) swarm.JoinTokens {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
sw, err := cli.SwarmInspect(context.Background())
c.Assert(err, checker.IsNil)
return sw.JoinTokens
}
// CheckLocalNodeState returns the current swarm node state
func (d *Swarm) CheckLocalNodeState(c *check.C) (interface{}, check.CommentInterface) {
info, err := d.SwarmInfo()
c.Assert(err, checker.IsNil)
func (d *Daemon) CheckLocalNodeState(c *check.C) (interface{}, check.CommentInterface) {
info := d.SwarmInfo(c)
return info.LocalNodeState, nil
}
// CheckControlAvailable returns the current swarm control available
func (d *Swarm) CheckControlAvailable(c *check.C) (interface{}, check.CommentInterface) {
info, err := d.SwarmInfo()
c.Assert(err, checker.IsNil)
func (d *Daemon) CheckControlAvailable(c *check.C) (interface{}, check.CommentInterface) {
info := d.SwarmInfo(c)
c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive)
return info.ControlAvailable, nil
}
// CheckLeader returns whether there is a leader on the swarm or not
func (d *Swarm) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
func (d *Daemon) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
@@ -644,18 +195,3 @@ func (d *Swarm) CheckLeader(c *check.C) (interface{}, check.CommentInterface) {
}
return fmt.Errorf("no leader"), check.Commentf("could not find leader")
}
// CmdRetryOutOfSequence tries the specified command against the current daemon for 10 times
func (d *Swarm) CmdRetryOutOfSequence(args ...string) (string, error) {
for i := 0; ; i++ {
out, err := d.Cmd(args...)
if err != nil {
if strings.Contains(out, "update out of sequence") {
if i < 10 {
continue
}
}
}
return out, err
}
}
@@ -5,11 +5,11 @@ import (
"github.com/go-check/check"
)
func (s *DockerSwarmSuite) getDaemon(c *check.C, nodeID string) *daemon.Swarm {
func (s *DockerSwarmSuite) getDaemon(c *check.C, nodeID string) *daemon.Daemon {
s.daemonsLock.Lock()
defer s.daemonsLock.Unlock()
for _, d := range s.daemons {
if d.NodeID == nodeID {
if d.NodeID() == nodeID {
return d
}
}
@@ -13,17 +13,14 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/cli/build/fakecontext"
"github.com/docker/docker/integration-cli/cli/build/fakegit"
"github.com/docker/docker/integration-cli/cli/build/fakestorage"
"github.com/docker/docker/integration-cli/request"
"github.com/docker/docker/internal/test/fakecontext"
"github.com/docker/docker/internal/test/fakegit"
"github.com/docker/docker/internal/test/fakestorage"
"github.com/go-check/check"
"github.com/moby/buildkit/session"
"github.com/moby/buildkit/session/filesync"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/gotestyourself/gotestyourself/assert"
is "github.com/gotestyourself/gotestyourself/assert/cmp"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
func (s *DockerSuite) TestBuildAPIDockerFileRemote(c *check.C) {
@@ -296,12 +293,12 @@ func (s *DockerSuite) TestBuildOnBuildCache(c *check.C) {
"/build",
request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar"))
require.NoError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode)
assert.NilError(c, err)
assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(out), "Successfully built")
assert.NilError(c, err)
assert.Check(c, is.Contains(string(out), "Successfully built"))
return out
}
@@ -316,15 +313,15 @@ func (s *DockerSuite) TestBuildOnBuildCache(c *check.C) {
out := build(dockerfile)
imageIDs := getImageIDsFromBuild(c, out)
assert.Len(c, imageIDs, 2)
assert.Check(c, is.Len(imageIDs, 2))
parentID, childID := imageIDs[0], imageIDs[1]
client := testEnv.APIClient()
// check parentID is correct
image, _, err := client.ImageInspectWithRaw(context.Background(), childID)
require.NoError(c, err)
assert.Equal(c, parentID, image.Parent)
assert.NilError(c, err)
assert.Check(c, is.Equal(parentID, image.Parent))
}
func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
@@ -333,12 +330,12 @@ func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
// tag the image to upload it to the private registry
err := client.ImageTag(context.TODO(), "busybox", repoName)
assert.Nil(c, err)
assert.Check(c, err)
// push the image to the registry
rc, err := client.ImagePush(context.TODO(), repoName, types.ImagePushOptions{RegistryAuth: "{}"})
assert.Nil(c, err)
assert.Check(c, err)
_, err = io.Copy(ioutil.Discard, rc)
assert.Nil(c, err)
assert.Check(c, err)
dockerfile := fmt.Sprintf(`
FROM %s AS foo
@@ -356,12 +353,12 @@ func (s *DockerRegistrySuite) TestBuildCopyFromForcePull(c *check.C) {
"/build?pull=1",
request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar"))
require.NoError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode)
assert.NilError(c, err)
assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(out), "Successfully built")
assert.NilError(c, err)
assert.Check(c, is.Contains(string(out), "Successfully built"))
}
func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
@@ -374,11 +371,11 @@ func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
Mode: 0600,
Typeflag: tar.TypeReg,
})
require.NoError(c, err)
assert.NilError(c, err)
_, err = tw.Write(dt)
require.NoError(c, err)
assert.NilError(c, err)
err = tw.Close()
require.NoError(c, err)
assert.NilError(c, err)
server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{
"test.tar": buffer,
@@ -400,12 +397,12 @@ func (s *DockerSuite) TestBuildAddRemoteNoDecompress(c *check.C) {
"/build",
request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar"))
require.NoError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode)
assert.NilError(c, err)
assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(out), "Successfully built")
assert.NilError(c, err)
assert.Check(c, is.Contains(string(out), "Successfully built"))
}
func (s *DockerSuite) TestBuildChownOnCopy(c *check.C) {
@@ -433,8 +430,8 @@ func (s *DockerSuite) TestBuildChownOnCopy(c *check.C) {
c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(out), "Successfully built")
assert.NilError(c, err)
assert.Check(c, is.Contains(string(out), "Successfully built"))
}
func (s *DockerSuite) TestBuildCopyCacheOnFileChange(c *check.C) {
@@ -454,11 +451,11 @@ COPY file /file`
request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar"))
require.NoError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode)
assert.NilError(c, err)
assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.NilError(c, err)
ids := getImageIDsFromBuild(c, out)
return ids[len(ids)-1]
@@ -493,11 +490,11 @@ ADD file /file`
request.RawContent(ctx.AsTarReader(c)),
request.ContentType("application/x-tar"))
require.NoError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode)
assert.NilError(c, err)
assert.Check(c, is.DeepEqual(http.StatusOK, res.StatusCode))
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.NilError(c, err)
ids := getImageIDsFromBuild(c, out)
return ids[len(ids)-1]
@@ -515,106 +512,6 @@ ADD file /file`
}
}
func (s *DockerSuite) TestBuildWithSession(c *check.C) {
testRequires(c, ExperimentalDaemon)
dockerfile := `
FROM busybox
COPY file /
RUN cat /file
`
fctx := fakecontext.New(c, "",
fakecontext.WithFile("file", "some content"),
)
defer fctx.Close()
out := testBuildWithSession(c, fctx.Dir, dockerfile)
assert.Contains(c, out, "some content")
fctx.Add("second", "contentcontent")
dockerfile += `
COPY second /
RUN cat /second
`
out = testBuildWithSession(c, fctx.Dir, dockerfile)
assert.Equal(c, strings.Count(out, "Using cache"), 2)
assert.Contains(c, out, "contentcontent")
client := testEnv.APIClient()
du, err := client.DiskUsage(context.TODO())
assert.Nil(c, err)
assert.True(c, du.BuilderSize > 10)
out = testBuildWithSession(c, fctx.Dir, dockerfile)
assert.Equal(c, strings.Count(out, "Using cache"), 4)
du2, err := client.DiskUsage(context.TODO())
assert.Nil(c, err)
assert.Equal(c, du.BuilderSize, du2.BuilderSize)
// rebuild with regular tar, confirm cache still applies
fctx.Add("Dockerfile", dockerfile)
res, body, err := request.Post(
"/build",
request.RawContent(fctx.AsTarReader(c)),
request.ContentType("application/x-tar"))
require.NoError(c, err)
assert.Equal(c, http.StatusOK, res.StatusCode)
outBytes, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(outBytes), "Successfully built")
assert.Equal(c, strings.Count(string(outBytes), "Using cache"), 4)
_, err = client.BuildCachePrune(context.TODO())
assert.Nil(c, err)
du, err = client.DiskUsage(context.TODO())
assert.Nil(c, err)
assert.Equal(c, du.BuilderSize, int64(0))
}
func testBuildWithSession(c *check.C, dir, dockerfile string) (outStr string) {
client := testEnv.APIClient()
sess, err := session.NewSession("foo1", "foo")
assert.Nil(c, err)
fsProvider := filesync.NewFSSyncProvider([]filesync.SyncedDir{
{Dir: dir},
})
sess.Allow(fsProvider)
g, ctx := errgroup.WithContext(context.Background())
g.Go(func() error {
return sess.Run(ctx, client.DialSession)
})
g.Go(func() error {
res, body, err := request.Post("/build?remote=client-session&session="+sess.ID(), func(req *http.Request) error {
req.Body = ioutil.NopCloser(strings.NewReader(dockerfile))
return nil
})
if err != nil {
return err
}
assert.Equal(c, res.StatusCode, http.StatusOK)
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(out), "Successfully built")
sess.Close()
outStr = string(out)
return nil
})
err = g.Wait()
assert.Nil(c, err)
return
}
func (s *DockerSuite) TestBuildScratchCopy(c *check.C) {
testRequires(c, DaemonIsLinux)
dockerfile := `FROM scratch
@@ -633,8 +530,8 @@ ENV foo bar`
c.Assert(res.StatusCode, checker.Equals, http.StatusOK)
out, err := request.ReadBody(body)
require.NoError(c, err)
assert.Contains(c, string(out), "Successfully built")
assert.NilError(c, err)
assert.Check(c, is.Contains(string(out), "Successfully built"))
}
type buildLine struct {
@@ -651,7 +548,7 @@ func getImageIDsFromBuild(c *check.C, output []byte) []string {
continue
}
entry := buildLine{}
require.NoError(c, json.Unmarshal(line, &entry))
assert.NilError(c, json.Unmarshal(line, &entry))
if entry.Aux.ID != "" {
ids = append(ids, entry.Aux.ID)
}

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