update thrift, opencensus, others (#893)

* update thrift, opencensus, others

* stats: update to opencensus 0.6.0 view api
This commit is contained in:
Reed Allman
2018-03-26 15:43:49 -07:00
committed by GitHub
parent 0ce5c4500b
commit 8af605cf3d
1266 changed files with 122191 additions and 28775 deletions

View File

@@ -3,7 +3,7 @@
#
# KEEP THIS FILE SORTED. Order is important. Last match takes precedence.
builder/** @dnephin @tonistiigi
builder/** @tonistiigi
client/** @dnephin
contrib/mkimage/** @tianon
daemon/graphdriver/devmapper/** @rhvgoyal
@@ -12,10 +12,9 @@ daemon/graphdriver/overlay/** @dmcgowan
daemon/graphdriver/overlay2/** @dmcgowan
daemon/graphdriver/windows/** @johnstep @jhowardmsft
daemon/logger/awslogs/** @samuelkarp
hack/** @dnephin @tianon
hack/** @tianon
hack/integration-cli-on-swarm/** @AkihiroSuda
integration-cli/** @dnephin @vdemeester
integration/** @dnephin @vdemeester
pkg/testutil/** @dnephin
integration-cli/** @vdemeester
integration/** @vdemeester
plugin/** @cpuguy83
project/** @thaJeztah

View File

@@ -44,9 +44,7 @@ FROM base AS criu
# Install CRIU for checkpoint/restore support
ENV CRIU_VERSION 3.6
# Install dependancy packages specific to criu
RUN case $(uname -m) in \
x86_64) \
apt-get update && apt-get install -y \
RUN apt-get update && apt-get install -y \
libnet-dev \
libprotobuf-c0-dev \
libprotobuf-dev \
@@ -59,13 +57,7 @@ RUN case $(uname -m) in \
&& curl -sSL https://github.com/checkpoint-restore/criu/archive/v${CRIU_VERSION}.tar.gz | tar -C /usr/src/criu/ -xz --strip-components=1 \
&& cd /usr/src/criu \
&& make \
&& make PREFIX=/opt/criu install-criu ;\
;; \
armv7l|aarch64|ppc64le|s390x) \
mkdir -p /opt/criu; \
;; \
esac
&& make PREFIX=/opt/criu install-criu
FROM base AS registry
# Install two versions of the registry. The first is an older version that
@@ -80,8 +72,8 @@ RUN set -x \
&& (cd "$GOPATH/src/github.com/docker/distribution" && git checkout -q "$REGISTRY_COMMIT") \
&& GOPATH="$GOPATH/src/github.com/docker/distribution/Godeps/_workspace:$GOPATH" \
go build -buildmode=pie -o /usr/local/bin/registry-v2 github.com/docker/distribution/cmd/registry \
&& case $(uname -m) in \
x86_64|ppc64le|s390x) \
&& case $(dpkg --print-architecture) in \
amd64|ppc64*|s390x) \
(cd "$GOPATH/src/github.com/docker/distribution" && git checkout -q "$REGISTRY_COMMIT_SCHEMA1"); \
GOPATH="$GOPATH/src/github.com/docker/distribution/Godeps/_workspace:$GOPATH"; \
go build -buildmode=pie -o /usr/local/bin/registry-v2-schema1 github.com/docker/distribution/cmd/registry; \
@@ -91,21 +83,6 @@ RUN set -x \
FROM base AS notary
# Install notary and notary-server
ENV NOTARY_VERSION v0.5.0
RUN set -x \
&& export GOPATH="$(mktemp -d)" \
&& git clone https://github.com/docker/notary.git "$GOPATH/src/github.com/docker/notary" \
&& (cd "$GOPATH/src/github.com/docker/notary" && git checkout -q "$NOTARY_VERSION") \
&& GOPATH="$GOPATH/src/github.com/docker/notary/vendor:$GOPATH" \
go build -buildmode=pie -o /usr/local/bin/notary-server github.com/docker/notary/cmd/notary-server \
&& GOPATH="$GOPATH/src/github.com/docker/notary/vendor:$GOPATH" \
go build -buildmode=pie -o /usr/local/bin/notary github.com/docker/notary/cmd/notary \
&& rm -rf "$GOPATH"
FROM base AS docker-py
# Get the "docker-py" source so we can run their integration tests
ENV DOCKER_PY_COMMIT 8b246db271a85d6541dc458838627e89c683e42f
@@ -248,7 +225,6 @@ COPY --from=containerd /opt/containerd/ /usr/local/bin/
COPY --from=proxy /opt/proxy/ /usr/local/bin/
COPY --from=dockercli /opt/dockercli /usr/local/cli
COPY --from=registry /usr/local/bin/registry* /usr/local/bin/
COPY --from=notary /usr/local/bin/notary* /usr/local/bin/
COPY --from=criu /opt/criu/ /usr/local/
COPY --from=docker-py /docker-py /docker-py
# TODO: This is for the docker-py tests, which shouldn't really be needed for

View File

@@ -71,18 +71,15 @@
# - close an issue or pull request when it's inappropriate or off-topic
people = [
"aboch",
"alexellis",
"andrewhsu",
"anonymuse",
"chanwit",
"ehazlett",
"fntlnz",
"gianarb",
"mgoelzer",
"programmerq",
"rheinwein",
"ripcurld0",
"ripcurld",
"thajeztah"
]
@@ -242,11 +239,6 @@
Email = "aaron.lehmann@docker.com"
GitHub = "aaronlehmann"
[people.aboch]
Name = "Alessandro Boch"
Email = "aboch@docker.com"
GitHub = "aboch"
[people.alexellis]
Name = "Alex Ellis"
Email = "alexellis2@gmail.com"
@@ -382,11 +374,6 @@
Email = "madhu@docker.com"
GitHub = "mavenugo"
[people.mgoelzer]
Name = "Mike Goelzer"
Email = "mike.goelzer@docker.com"
GitHub = "mgoelzer"
[people.mhbauer]
Name = "Morgan Bauer"
Email = "mbauer@us.ibm.com"
@@ -422,10 +409,10 @@
Email = "laura@codeship.com"
GitHub = "rheinwein"
[people.ripcurld0]
[people.ripcurld]
Name = "Boaz Shuster"
Email = "ripcurld.github@gmail.com"
GitHub = "ripcurld0"
GitHub = "ripcurld"
[people.runcom]
Name = "Antonio Murdaca"

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.

View File

@@ -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))
}
}

View File

@@ -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))
}

View File

@@ -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)
}
}

View File

@@ -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"))
}

View File

@@ -5,7 +5,6 @@ import (
"fmt"
"io"
"io/ioutil"
"runtime"
"strings"
"time"
@@ -104,18 +103,12 @@ func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (
source = src
}
os := runtime.GOOS
optionsPlatform := system.ParsePlatform(config.Options.Platform)
if dockerfile.OS != "" {
if optionsPlatform.OS != "" && optionsPlatform.OS != dockerfile.OS {
return nil, fmt.Errorf("invalid platform")
}
os = dockerfile.OS
} else if optionsPlatform.OS != "" {
os = optionsPlatform.OS
os := ""
apiPlatform := system.ParsePlatform(config.Options.Platform)
if apiPlatform.OS != "" {
os = apiPlatform.OS
}
config.Options.Platform = os
dockerfile.OS = os
builderOptions := builderOptions{
Options: config.Options,

View File

@@ -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))
}
}

View File

@@ -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))
}
}

View File

@@ -145,14 +145,17 @@ func (d *dispatchRequest) getImageMount(imageRefOrID string) (*imageMount, error
imageRefOrID = stage.Image
localOnly = true
}
return d.builder.imageSources.Get(imageRefOrID, localOnly)
return d.builder.imageSources.Get(imageRefOrID, localOnly, d.state.operatingSystem)
}
// FROM imagename[:tag | @digest] [AS build-stage-name]
// FROM [--platform=platform] imagename[:tag | @digest] [AS build-stage-name]
//
func initializeStage(d dispatchRequest, cmd *instructions.Stage) error {
d.builder.imageProber.Reset()
image, err := d.getFromImage(d.shlex, cmd.BaseName)
if err := system.ValidatePlatform(&cmd.Platform); err != nil {
return err
}
image, err := d.getFromImage(d.shlex, cmd.BaseName, cmd.Platform.OS)
if err != nil {
return err
}
@@ -210,20 +213,41 @@ func (d *dispatchRequest) getExpandedImageName(shlex *shell.Lex, name string) (s
}
return name, nil
}
func (d *dispatchRequest) getImageOrStage(name string) (builder.Image, error) {
// getOsFromFlagsAndStage calculates the operating system if we need to pull an image.
// stagePlatform contains the value supplied by optional `--platform=` on
// a current FROM statement. b.builder.options.Platform contains the operating
// system part of the optional flag passed in the API call (or CLI flag
// through `docker build --platform=...`). Precedence is for an explicit
// platform indication in the FROM statement.
func (d *dispatchRequest) getOsFromFlagsAndStage(stageOS string) string {
switch {
case stageOS != "":
return stageOS
case d.builder.options.Platform != "":
// Note this is API "platform", but by this point, as the daemon is not
// multi-arch aware yet, it is guaranteed to only hold the OS part here.
return d.builder.options.Platform
default:
return runtime.GOOS
}
}
func (d *dispatchRequest) getImageOrStage(name string, stageOS string) (builder.Image, error) {
var localOnly bool
if im, ok := d.stages.getByName(name); ok {
name = im.Image
localOnly = true
}
os := d.getOsFromFlagsAndStage(stageOS)
// Windows cannot support a container with no base image unless it is LCOW.
if name == api.NoBaseImageSpecifier {
imageImage := &image.Image{}
imageImage.OS = runtime.GOOS
if runtime.GOOS == "windows" {
optionsOS := system.ParsePlatform(d.builder.options.Platform).OS
switch optionsOS {
switch os {
case "windows", "":
return nil, errors.New("Windows does not support FROM scratch")
case "linux":
@@ -232,23 +256,23 @@ func (d *dispatchRequest) getImageOrStage(name string) (builder.Image, error) {
}
imageImage.OS = "linux"
default:
return nil, errors.Errorf("operating system %q is not supported", optionsOS)
return nil, errors.Errorf("operating system %q is not supported", os)
}
}
return builder.Image(imageImage), nil
}
imageMount, err := d.builder.imageSources.Get(name, localOnly)
imageMount, err := d.builder.imageSources.Get(name, localOnly, os)
if err != nil {
return nil, err
}
return imageMount.Image(), nil
}
func (d *dispatchRequest) getFromImage(shlex *shell.Lex, name string) (builder.Image, error) {
func (d *dispatchRequest) getFromImage(shlex *shell.Lex, name string, stageOS string) (builder.Image, error) {
name, err := d.getExpandedImageName(shlex, name)
if err != nil {
return nil, err
}
return d.getImageOrStage(name)
return d.getImageOrStage(name, stageOS)
}
func dispatchOnbuild(d dispatchRequest, c *instructions.OnbuildCommand) error {
@@ -264,8 +288,7 @@ func dispatchOnbuild(d dispatchRequest, c *instructions.OnbuildCommand) error {
func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
runConfig := d.state.runConfig
var err error
baseImageOS := system.ParsePlatform(d.state.operatingSystem).OS
runConfig.WorkingDir, err = normalizeWorkdir(baseImageOS, runConfig.WorkingDir, c.Path)
runConfig.WorkingDir, err = normalizeWorkdir(d.state.operatingSystem, runConfig.WorkingDir, c.Path)
if err != nil {
return err
}
@@ -281,7 +304,7 @@ func dispatchWorkdir(d dispatchRequest, c *instructions.WorkdirCommand) error {
}
comment := "WORKDIR " + runConfig.WorkingDir
runConfigWithCommentCmd := copyRunConfig(runConfig, withCmdCommentString(comment, baseImageOS))
runConfigWithCommentCmd := copyRunConfig(runConfig, withCmdCommentString(comment, d.state.operatingSystem))
containerID, err := d.builder.probeAndCreate(d.state, runConfigWithCommentCmd)
if err != nil || containerID == "" {
return err
@@ -397,8 +420,7 @@ func prependEnvOnCmd(buildArgs *buildArgs, buildArgVars []string, cmd strslice.S
//
func dispatchCmd(d dispatchRequest, c *instructions.CmdCommand) error {
runConfig := d.state.runConfig
optionsOS := system.ParsePlatform(d.builder.options.Platform).OS
cmd := resolveCmdLine(c.ShellDependantCmdLine, runConfig, optionsOS)
cmd := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem)
runConfig.Cmd = cmd
// set config as already being escaped, this prevents double escaping on windows
runConfig.ArgsEscaped = true
@@ -441,8 +463,7 @@ func dispatchHealthcheck(d dispatchRequest, c *instructions.HealthCheckCommand)
//
func dispatchEntrypoint(d dispatchRequest, c *instructions.EntrypointCommand) error {
runConfig := d.state.runConfig
optionsOS := system.ParsePlatform(d.builder.options.Platform).OS
cmd := resolveCmdLine(c.ShellDependantCmdLine, runConfig, optionsOS)
cmd := resolveCmdLine(c.ShellDependantCmdLine, runConfig, d.state.operatingSystem)
runConfig.Entrypoint = cmd
if !d.state.cmdSet {
runConfig.Cmd = nil

View File

@@ -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,13 +201,14 @@ 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) {
b := newBuilderWithMockBackend()
sb := newDispatchRequest(b, '`', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults())
sb.state.baseImage = &mockImage{}
workingDir := "/app"
if runtime.GOOS == "windows" {
workingDir = "C:\\app"
@@ -217,13 +218,14 @@ 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) {
b := newBuilderWithMockBackend()
sb := newDispatchRequest(b, '`', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults())
sb.state.baseImage = &mockImage{}
command := "./executable"
cmd := &instructions.CmdCommand{
@@ -233,7 +235,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 +244,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 +257,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,15 +274,16 @@ 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) {
b := newBuilderWithMockBackend()
sb := newDispatchRequest(b, '`', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults())
sb.state.baseImage = &mockImage{}
entrypointCmd := "/usr/sbin/nginx"
cmd := &instructions.EntrypointCommand{
@@ -290,8 +293,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 +302,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 +314,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 +332,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 +346,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) {
@@ -356,14 +359,15 @@ func TestStopSignal(t *testing.T) {
}
b := newBuilderWithMockBackend()
sb := newDispatchRequest(b, '`', nil, newBuildArgs(make(map[string]*string)), newStagesBuildResults())
sb.state.baseImage = &mockImage{}
signal := "SIGKILL"
cmd := &instructions.StopSignalCommand{
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 +378,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 +392,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 +407,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 +426,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 +445,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 +467,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))
}

View File

@@ -37,8 +37,7 @@ import (
func dispatch(d dispatchRequest, cmd instructions.Command) (err error) {
if c, ok := cmd.(instructions.PlatformSpecific); ok {
optionsOS := system.ParsePlatform(d.builder.options.Platform).OS
err := c.CheckPlatform(optionsOS)
err := c.CheckPlatform(d.state.operatingSystem)
if err != nil {
return errdefs.InvalidParameter(err)
}

View File

@@ -6,13 +6,12 @@ import (
"github.com/docker/docker/api/types/backend"
"github.com/docker/docker/builder"
dockerimage "github.com/docker/docker/image"
"github.com/docker/docker/pkg/system"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
)
type getAndMountFunc func(string, bool) (builder.Image, builder.ROLayer, error)
type getAndMountFunc func(string, bool, string) (builder.Image, builder.ROLayer, error)
// imageSources mounts images and provides a cache for mounted images. It tracks
// all images so they can be unmounted at the end of the build.
@@ -23,7 +22,7 @@ type imageSources struct {
}
func newImageSources(ctx context.Context, options builderOptions) *imageSources {
getAndMount := func(idOrRef string, localOnly bool) (builder.Image, builder.ROLayer, error) {
getAndMount := func(idOrRef string, localOnly bool, osForPull string) (builder.Image, builder.ROLayer, error) {
pullOption := backend.PullOptionNoPull
if !localOnly {
if options.Options.PullParent {
@@ -32,12 +31,11 @@ func newImageSources(ctx context.Context, options builderOptions) *imageSources
pullOption = backend.PullOptionPreferLocal
}
}
optionsPlatform := system.ParsePlatform(options.Options.Platform)
return options.Backend.GetImageAndReleasableLayer(ctx, idOrRef, backend.GetImageAndLayerOptions{
PullOption: pullOption,
AuthConfig: options.Options.AuthConfigs,
Output: options.ProgressWriter.Output,
OS: optionsPlatform.OS,
OS: osForPull,
})
}
@@ -47,12 +45,12 @@ func newImageSources(ctx context.Context, options builderOptions) *imageSources
}
}
func (m *imageSources) Get(idOrRef string, localOnly bool) (*imageMount, error) {
func (m *imageSources) Get(idOrRef string, localOnly bool, osForPull string) (*imageMount, error) {
if im, ok := m.byImageID[idOrRef]; ok {
return im, nil
}
image, layer, err := m.getImage(idOrRef, localOnly)
image, layer, err := m.getImage(idOrRef, localOnly, osForPull)
if err != nil {
return nil, err
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/strslice"
specs "github.com/opencontainers/image-spec/specs-go/v1"
)
// KeyValuePair represent an arbitrary named value (useful in slice instead of map[string] string to preserve ordering)
@@ -361,6 +362,7 @@ type Stage struct {
Commands []Command
BaseName string
SourceCode string
Platform specs.Platform
}
// AddCommand to the stage

View File

@@ -12,6 +12,7 @@ import (
"github.com/docker/docker/api/types/strslice"
"github.com/docker/docker/builder/dockerfile/command"
"github.com/docker/docker/builder/dockerfile/parser"
"github.com/docker/docker/pkg/system"
"github.com/pkg/errors"
)
@@ -271,16 +272,17 @@ func parseFrom(req parseRequest) (*Stage, error) {
return nil, err
}
flPlatform := req.flags.AddString("platform", "")
if err := req.flags.Parse(); err != nil {
return nil, err
}
code := strings.TrimSpace(req.original)
return &Stage{
BaseName: req.args[0],
Name: stageName,
SourceCode: code,
Commands: []Command{},
Platform: *system.ParsePlatform(flPlatform.Value),
}, nil
}

View File

@@ -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) {
@@ -196,5 +196,4 @@ func TestErrorCases(t *testing.T) {
_, err = ParseInstruction(n)
testutil.ErrorContains(t, err, c.expectedError)
}
}

View File

@@ -83,8 +83,7 @@ func (b *Builder) commit(dispatchState *dispatchState, comment string) error {
return errors.New("Please provide a source image with `from` prior to commit")
}
optionsPlatform := system.ParsePlatform(b.options.Platform)
runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, optionsPlatform.OS))
runConfigWithCommentCmd := copyRunConfig(dispatchState.runConfig, withCmdComment(comment, dispatchState.operatingSystem))
hit, err := b.probeCache(dispatchState, runConfigWithCommentCmd)
if err != nil || hit {
return err
@@ -164,16 +163,15 @@ func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error
commentStr := fmt.Sprintf("%s %s%s in %s ", inst.cmdName, chownComment, srcHash, inst.dest)
// TODO: should this have been using origPaths instead of srcHash in the comment?
optionsPlatform := system.ParsePlatform(b.options.Platform)
runConfigWithCommentCmd := copyRunConfig(
state.runConfig,
withCmdCommentString(commentStr, optionsPlatform.OS))
withCmdCommentString(commentStr, state.operatingSystem))
hit, err := b.probeCache(state, runConfigWithCommentCmd)
if err != nil || hit {
return err
}
imageMount, err := b.imageSources.Get(state.imageID, true)
imageMount, err := b.imageSources.Get(state.imageID, true, state.operatingSystem)
if err != nil {
return errors.Wrapf(err, "failed to get destination image %q", state.imageID)
}
@@ -184,7 +182,7 @@ func (b *Builder) performCopy(state *dispatchState, inst copyInstruction) error
}
defer rwLayer.Release()
destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, rwLayer, b.options.Platform)
destInfo, err := createDestInfo(state.runConfig.WorkingDir, inst, rwLayer, state.operatingSystem)
if err != nil {
return err
}

View File

@@ -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")
})
}
}

View File

@@ -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))
}

View File

@@ -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)
}

View File

@@ -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")
}

View File

@@ -7,13 +7,11 @@ import (
"fmt"
"io"
"regexp"
"runtime"
"strconv"
"strings"
"unicode"
"github.com/docker/docker/builder/dockerfile/command"
"github.com/docker/docker/pkg/system"
"github.com/pkg/errors"
)
@@ -81,11 +79,10 @@ func (node *Node) AddChild(child *Node, startLine, endLine int) {
}
var (
dispatch map[string]func(string, *Directive) (*Node, map[string]bool, error)
tokenWhitespace = regexp.MustCompile(`[\t\v\f\r ]+`)
tokenEscapeCommand = regexp.MustCompile(`^#[ \t]*escape[ \t]*=[ \t]*(?P<escapechar>.).*$`)
tokenPlatformCommand = regexp.MustCompile(`^#[ \t]*platform[ \t]*=[ \t]*(?P<platform>.*)$`)
tokenComment = regexp.MustCompile(`^#.*$`)
dispatch map[string]func(string, *Directive) (*Node, map[string]bool, error)
tokenWhitespace = regexp.MustCompile(`[\t\v\f\r ]+`)
tokenEscapeCommand = regexp.MustCompile(`^#[ \t]*escape[ \t]*=[ \t]*(?P<escapechar>.).*$`)
tokenComment = regexp.MustCompile(`^#.*$`)
)
// DefaultEscapeToken is the default escape token
@@ -95,11 +92,9 @@ const DefaultEscapeToken = '\\'
// parsing directives.
type Directive struct {
escapeToken rune // Current escape token
platformToken string // Current platform token
lineContinuationRegex *regexp.Regexp // Current line continuation regex
processingComplete bool // Whether we are done looking for directives
escapeSeen bool // Whether the escape directive has been seen
platformSeen bool // Whether the platform directive has been seen
}
// setEscapeToken sets the default token for escaping characters in a Dockerfile.
@@ -112,25 +107,9 @@ func (d *Directive) setEscapeToken(s string) error {
return nil
}
// setPlatformToken sets the default platform for pulling images in a Dockerfile.
func (d *Directive) setPlatformToken(s string) error {
s = strings.ToLower(s)
valid := []string{runtime.GOOS}
if system.LCOWSupported() {
valid = append(valid, "linux")
}
for _, item := range valid {
if s == item {
d.platformToken = s
return nil
}
}
return fmt.Errorf("invalid PLATFORM '%s'. Must be one of %v", s, valid)
}
// possibleParserDirective looks for one or more parser directives '# escapeToken=<char>' and
// '# platform=<string>'. Parser directives must precede any builder instruction
// or other comments, and cannot be repeated.
// possibleParserDirective looks for parser directives, eg '# escapeToken=<char>'.
// Parser directives must precede any builder instruction or other comments,
// and cannot be repeated.
func (d *Directive) possibleParserDirective(line string) error {
if d.processingComplete {
return nil
@@ -149,22 +128,6 @@ func (d *Directive) possibleParserDirective(line string) error {
}
}
// Only recognise a platform token if LCOW is supported
if system.LCOWSupported() {
tpcMatch := tokenPlatformCommand.FindStringSubmatch(strings.ToLower(line))
if len(tpcMatch) != 0 {
for i, n := range tokenPlatformCommand.SubexpNames() {
if n == "platform" {
if d.platformSeen {
return errors.New("only one platform parser directive can be used")
}
d.platformSeen = true
return d.setPlatformToken(tpcMatch[i])
}
}
}
}
d.processingComplete = true
return nil
}
@@ -237,10 +200,7 @@ func newNodeFromLine(line string, directive *Directive) (*Node, error) {
type Result struct {
AST *Node
EscapeToken rune
// TODO @jhowardmsft - see https://github.com/moby/moby/issues/34617
// This next field will be removed in a future update for LCOW support.
OS string
Warnings []string
Warnings []string
}
// PrintWarnings to the writer
@@ -320,7 +280,6 @@ func Parse(rwc io.Reader) (*Result, error) {
AST: root,
Warnings: warnings,
EscapeToken: d.escapeToken,
OS: d.platformToken,
}, handleScannerError(scanner.Err())
}

View File

@@ -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"))
}

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"
)
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))
}
}
}

View File

@@ -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 {

View File

@@ -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)))
}
}

View File

@@ -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))
}

View File

@@ -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)
}

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))
}
}
}

View File

@@ -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) {

View File

@@ -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) {

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) {

View File

@@ -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) {

View File

@@ -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) {

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 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))
}
}

View File

@@ -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)
}

View File

@@ -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) {

View File

@@ -188,8 +188,14 @@ func (cli *Client) setupHijackConn(req *http.Request, proto string) (net.Conn, e
c, br := clientconn.Hijack()
if br.Buffered() > 0 {
// If there is buffered content, wrap the connection
c = &hijackedConn{c, br}
// If there is buffered content, wrap the connection. We return an
// object that implements CloseWrite iff the underlying connection
// implements it.
if _, ok := c.(types.CloseWriter); ok {
c = &hijackedConnCloseWriter{&hijackedConn{c, br}}
} else {
c = &hijackedConn{c, br}
}
} else {
br.Reset(nil)
}
@@ -197,6 +203,10 @@ func (cli *Client) setupHijackConn(req *http.Request, proto string) (net.Conn, e
return c, nil
}
// hijackedConn wraps a net.Conn and is returned by setupHijackConn in the case
// that a) there was already buffered data in the http layer when Hijack() was
// called, and b) the underlying net.Conn does *not* implement CloseWrite().
// hijackedConn does not implement CloseWrite() either.
type hijackedConn struct {
net.Conn
r *bufio.Reader
@@ -205,3 +215,18 @@ type hijackedConn struct {
func (c *hijackedConn) Read(b []byte) (int, error) {
return c.r.Read(b)
}
// hijackedConnCloseWriter is a hijackedConn which additionally implements
// CloseWrite(). It is returned by setupHijackConn in the case that a) there
// was already buffered data in the http layer when Hijack() was called, and b)
// the underlying net.Conn *does* implement CloseWrite().
type hijackedConnCloseWriter struct {
*hijackedConn
}
var _ types.CloseWriter = &hijackedConnCloseWriter{}
func (c *hijackedConnCloseWriter) CloseWrite() error {
conn := c.Conn.(types.CloseWriter)
return conn.CloseWrite()
}

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))
}
}

View File

@@ -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) {

View File

@@ -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"))
}

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"
)
@@ -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))
}
}

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))
}

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)
}
}

View File

@@ -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) {

View File

@@ -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) {

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) {

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -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))
}

View File

@@ -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))
}

View File

@@ -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()))
}

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))
}

View File

@@ -104,10 +104,6 @@ func allocateDaemonPort(addr string) error {
return nil
}
// notifyShutdown is called after the daemon shuts down but before the process exits.
func notifyShutdown(err error) {
}
func wrapListeners(proto string, ls []net.Listener) []net.Listener {
switch proto {
case "unix":

View File

@@ -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)
}

View File

@@ -3,7 +3,6 @@ package main
import (
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/docker/docker/cli"
@@ -25,6 +24,10 @@ func newDaemonCommand() *cobra.Command {
SilenceErrors: true,
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if opts.version {
showVersion()
return nil
}
opts.flags = cmd.Flags()
return runDaemon(opts)
},
@@ -41,45 +44,6 @@ func newDaemonCommand() *cobra.Command {
return cmd
}
func runDaemon(opts *daemonOptions) error {
if opts.version {
showVersion()
return nil
}
daemonCli := NewDaemonCli()
// Windows specific settings as these are not defaulted.
if runtime.GOOS == "windows" {
if opts.daemonConfig.Pidfile == "" {
opts.daemonConfig.Pidfile = filepath.Join(opts.daemonConfig.Root, "docker.pid")
}
if opts.configFile == "" {
opts.configFile = filepath.Join(opts.daemonConfig.Root, `config\daemon.json`)
}
}
// On Windows, this may be launching as a service or with an option to
// register the service.
stop, runAsService, err := initService(daemonCli)
if err != nil {
logrus.Fatal(err)
}
if stop {
return nil
}
// If Windows SCM manages the service - no need for PID files
if runAsService {
opts.daemonConfig.Pidfile = ""
}
err = daemonCli.start(opts)
notifyShutdown(err)
return err
}
func showVersion() {
fmt.Printf("Docker version %s, build %s\n", dockerversion.Version, dockerversion.GitCommit)
}

View File

@@ -0,0 +1,8 @@
// +build !windows
package main
func runDaemon(opts *daemonOptions) error {
daemonCli := NewDaemonCli()
return daemonCli.start(opts)
}

View File

@@ -1,5 +1,38 @@
package main
import (
"path/filepath"
_ "github.com/docker/docker/autogen/winresources/dockerd"
"github.com/sirupsen/logrus"
)
func runDaemon(opts *daemonOptions) error {
daemonCli := NewDaemonCli()
// On Windows, this may be launching as a service or with an option to
// register the service.
stop, runAsService, err := initService(daemonCli)
if err != nil {
logrus.Fatal(err)
}
if stop {
return nil
}
// Windows specific settings as these are not defaulted.
if opts.configFile == "" {
opts.configFile = filepath.Join(opts.daemonConfig.Root, `config\daemon.json`)
}
if runAsService {
// If Windows SCM manages the service - no need for PID files
opts.daemonConfig.Pidfile = ""
} else if opts.daemonConfig.Pidfile == "" {
opts.daemonConfig.Pidfile = filepath.Join(opts.daemonConfig.Root, "docker.pid")
}
err = daemonCli.start(opts)
notifyShutdown(err)
return err
}

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))
}

View File

@@ -6,9 +6,5 @@ import (
"github.com/spf13/pflag"
)
func initService(daemonCli *DaemonCli) (bool, bool, error) {
return false, false, nil
}
func installServiceFlags(flags *pflag.FlagSet) {
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/system"
"github.com/pkg/errors"
)
// ResolvePath resolves the given path in the container to a resource on the
@@ -13,6 +14,9 @@ import (
// the absolute path to the resource relative to the container's rootfs, and
// an error if the path points to outside the container's rootfs.
func (container *Container) ResolvePath(path string) (resolvedPath, absPath string, err error) {
if container.BaseFS == nil {
return "", "", errors.New("ResolvePath: BaseFS of container " + container.ID + " is unexpectedly nil")
}
// Check if a drive letter supplied, it must be the system drive. No-op except on Windows
path, err = system.CheckSystemDriveAndRemoveDriveLetter(path, container.BaseFS)
if err != nil {
@@ -45,6 +49,9 @@ func (container *Container) ResolvePath(path string) (resolvedPath, absPath stri
// resolved to a path on the host corresponding to the given absolute path
// inside the container.
func (container *Container) StatPath(resolvedPath, absPath string) (stat *types.ContainerPathStat, err error) {
if container.BaseFS == nil {
return nil, errors.New("StatPath: BaseFS of container " + container.ID + " is unexpectedly nil")
}
driver := container.BaseFS
lstat, err := driver.Lstat(resolvedPath)

View File

@@ -311,6 +311,9 @@ func (container *Container) SetupWorkingDirectory(rootIDs idtools.IDPair) error
// symlinking to a different path) between using this method and using the
// path. See symlink.FollowSymlinkInScope for more details.
func (container *Container) GetResourcePath(path string) (string, error) {
if container.BaseFS == nil {
return "", errors.New("GetResourcePath: BaseFS of container " + container.ID + " is unexpectedly nil")
}
// IMPORTANT - These are paths on the OS where the daemon is running, hence
// any filepath operations must be done in an OS agnostic way.
r, e := container.BaseFS.ResolveScopedPath(path, false)

View File

@@ -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)
}

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

View File

@@ -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)
})
}
}

View File

@@ -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)
})
}
}

View File

@@ -124,8 +124,11 @@ func (n *nodeRunner) start(conf nodeStartConfig) error {
n.cluster.config.Backend,
n.cluster.config.PluginBackend,
n.cluster.config.ImageBackend),
HeartbeatTick: 1,
ElectionTick: 3,
HeartbeatTick: 1,
// Recommended value in etcd/raft is 10 x (HeartbeatTick).
// Lower values were seen to have caused instability because of
// frequent leader elections when running on flakey networks.
ElectionTick: 10,
UnlockKey: conf.lockKey,
AutoLockManagers: conf.autolock,
PluginGetter: n.cluster.config.Backend.PluginGetter(),

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)
}

View File

@@ -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()))
}

View File

@@ -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))
}

View File

@@ -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)
}
}

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))
}

View File

@@ -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)))
})
}
})

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")
}
}

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(`
{

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,

View File

@@ -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)

View File

@@ -270,7 +270,7 @@ func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.R
case <-attachErr:
// TERM signal worked
}
return fmt.Errorf("context cancelled")
return ctx.Err()
case err := <-attachErr:
if err != nil {
if _, ok := err.(term.EscapeError); !ok {

View File

@@ -34,6 +34,8 @@ func (daemon *Daemon) execSetPlatformOpt(c *container.Container, ec *exec.Config
if c.AppArmorProfile != "" {
appArmorProfile = c.AppArmorProfile
} else if c.HostConfig.Privileged {
// `docker exec --privileged` does not currently disable AppArmor
// profiles. Privileged configuration of the container is inherited
appArmorProfile = "unconfined"
} else {
appArmorProfile = "docker-default"
@@ -50,6 +52,7 @@ func (daemon *Daemon) execSetPlatformOpt(c *container.Container, ec *exec.Config
return err
}
}
p.ApparmorProfile = appArmorProfile
}
daemon.setRlimits(&specs.Spec{Process: p}, c)
return nil

View File

@@ -0,0 +1,53 @@
// +build linux
package daemon
import (
"testing"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container"
"github.com/docker/docker/daemon/exec"
"github.com/gotestyourself/gotestyourself/assert"
"github.com/opencontainers/runc/libcontainer/apparmor"
"github.com/opencontainers/runtime-spec/specs-go"
)
func TestExecSetPlatformOpt(t *testing.T) {
if !apparmor.IsEnabled() {
t.Skip("requires AppArmor to be enabled")
}
d := &Daemon{}
c := &container.Container{AppArmorProfile: "my-custom-profile"}
ec := &exec.Config{}
p := &specs.Process{}
err := d.execSetPlatformOpt(c, ec, p)
assert.NilError(t, err)
assert.Equal(t, "my-custom-profile", p.ApparmorProfile)
}
// TestExecSetPlatformOptPrivileged verifies that `docker exec --privileged`
// does not disable AppArmor profiles. Exec currently inherits the `Privileged`
// configuration of the container. See https://github.com/moby/moby/pull/31773#discussion_r105586900
//
// This behavior may change in future, but test for the behavior to prevent it
// from being changed accidentally.
func TestExecSetPlatformOptPrivileged(t *testing.T) {
if !apparmor.IsEnabled() {
t.Skip("requires AppArmor to be enabled")
}
d := &Daemon{}
c := &container.Container{AppArmorProfile: "my-custom-profile"}
ec := &exec.Config{Privileged: true}
p := &specs.Process{}
err := d.execSetPlatformOpt(c, ec, p)
assert.NilError(t, err)
assert.Equal(t, "my-custom-profile", p.ApparmorProfile)
c.HostConfig = &containertypes.HostConfig{Privileged: true}
err = d.execSetPlatformOpt(c, ec, p)
assert.NilError(t, err)
assert.Equal(t, "unconfined", p.ApparmorProfile)
}

View File

@@ -61,12 +61,12 @@ func (daemon *Daemon) containerExport(container *container.Container) (arch io.R
}
}()
_, err = rwlayer.Mount(container.GetMountLabel())
basefs, err := rwlayer.Mount(container.GetMountLabel())
if err != nil {
return nil, err
}
archive, err := archivePath(container.BaseFS, container.BaseFS.Path(), &archive.TarOptions{
archive, err := archivePath(basefs, basefs.Path(), &archive.TarOptions{
Compression: archive.Uncompressed,
UIDMaps: daemon.idMappings.UIDs(),
GIDMaps: daemon.idMappings.GIDs(),

View File

@@ -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) {

View File

@@ -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))
}

View File

@@ -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)
}

View File

@@ -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()
}
}

View File

@@ -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")

View File

@@ -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))
}

View File

@@ -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))
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/docker/distribution/reference"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/layer"
"github.com/docker/docker/pkg/system"
)
// ImageHistory returns a slice of ImageHistory structures for the specified image
@@ -31,7 +32,9 @@ func (i *ImageService) ImageHistory(name string) ([]*image.HistoryResponseItem,
if len(img.RootFS.DiffIDs) <= layerCounter {
return nil, fmt.Errorf("too many non-empty layers in History section")
}
if !system.IsOSSupported(img.OperatingSystem()) {
return nil, system.ErrNotSupportedOperatingSystem
}
rootFS.Append(img.RootFS.DiffIDs[layerCounter])
l, err := i.layerStores[img.OperatingSystem()].Get(rootFS.ChainID())
if err != nil {

View File

@@ -271,7 +271,9 @@ func (i *ImageService) SquashImage(id, parent string) (string, error) {
rootFS := image.NewRootFS()
parentImg = &image.Image{RootFS: rootFS}
}
if !system.IsOSSupported(img.OperatingSystem()) {
return "", errors.Wrap(err, system.ErrNotSupportedOperatingSystem.Error())
}
l, err := i.layerStores[img.OperatingSystem()].Get(img.RootFS.ChainID())
if err != nil {
return "", errors.Wrap(err, "error getting image layer")

View File

@@ -77,7 +77,7 @@ type ImageService struct {
// CountImages returns the number of images stored by ImageService
// called from info.go
func (i *ImageService) CountImages() int {
return len(i.imageStore.Map())
return i.imageStore.Len()
}
// Children returns the children image.IDs for a parent image.

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))
}
}

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)
}

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))
}

View File

@@ -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)

View File

@@ -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))
}

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