Use testify

Signed-off-by: Maksym Pavlenko <pavlenko.maksym@gmail.com>
This commit is contained in:
Maksym Pavlenko 2022-04-01 18:17:58 -07:00
parent 9766107a53
commit 871b6b6a9f
30 changed files with 356 additions and 362 deletions

View File

@ -32,9 +32,7 @@ import (
"testing" "testing"
"github.com/containerd/fifo" "github.com/containerd/fifo"
"github.com/google/go-cmp/cmp/cmpopts" "github.com/stretchr/testify/assert"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
) )
func assertHasPrefix(t *testing.T, s, prefix string) { func assertHasPrefix(t *testing.T, s, prefix string) {
@ -52,7 +50,7 @@ func TestNewFIFOSetInDir(t *testing.T) {
root := t.TempDir() root := t.TempDir()
fifos, err := NewFIFOSetInDir(root, "theid", true) fifos, err := NewFIFOSetInDir(root, "theid", true)
assert.NilError(t, err) assert.NoError(t, err)
dir := filepath.Dir(fifos.Stdin) dir := filepath.Dir(fifos.Stdin)
assertHasPrefix(t, dir, root) assertHasPrefix(t, dir, root)
@ -64,20 +62,19 @@ func TestNewFIFOSetInDir(t *testing.T) {
Terminal: true, Terminal: true,
}, },
} }
assert.Assert(t, is.DeepEqual(fifos, expected, cmpFIFOSet))
assert.Equal(t, fifos.Config, expected.Config)
files, err := os.ReadDir(root) files, err := os.ReadDir(root)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Len(files, 1)) assert.Len(t, files, 1)
assert.NilError(t, fifos.Close()) assert.Nil(t, fifos.Close())
files, err = os.ReadDir(root) files, err = os.ReadDir(root)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Len(files, 0)) assert.Len(t, files, 0)
} }
var cmpFIFOSet = cmpopts.IgnoreUnexported(FIFOSet{})
func TestNewAttach(t *testing.T) { func TestNewAttach(t *testing.T) {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
t.Skip("setupFIFOProducers not yet implemented on windows") t.Skip("setupFIFOProducers not yet implemented on windows")
@ -97,25 +94,25 @@ func TestNewAttach(t *testing.T) {
attacher := NewAttach(withBytesBuffers) attacher := NewAttach(withBytesBuffers)
fifos, err := NewFIFOSetInDir("", "theid", false) fifos, err := NewFIFOSetInDir("", "theid", false)
assert.NilError(t, err) assert.NoError(t, err)
attachedFifos, err := attacher(fifos) attachedFifos, err := attacher(fifos)
assert.NilError(t, err) assert.NoError(t, err)
defer attachedFifos.Close() defer attachedFifos.Close()
producers := setupFIFOProducers(t, attachedFifos.Config()) producers := setupFIFOProducers(t, attachedFifos.Config())
initProducers(t, producers, expectedStdout, expectedStderr) initProducers(t, producers, expectedStdout, expectedStderr)
actualStdin, err := io.ReadAll(producers.Stdin) actualStdin, err := io.ReadAll(producers.Stdin)
assert.NilError(t, err) assert.NoError(t, err)
attachedFifos.Wait() attachedFifos.Wait()
attachedFifos.Cancel() attachedFifos.Cancel()
assert.NilError(t, attachedFifos.Close()) assert.Nil(t, attachedFifos.Close())
assert.Check(t, is.Equal(expectedStdout, stdout.String())) assert.Equal(t, expectedStdout, stdout.String())
assert.Check(t, is.Equal(expectedStderr, stderr.String())) assert.Equal(t, expectedStderr, stderr.String())
assert.Check(t, is.Equal(expectedStdin, string(actualStdin))) assert.Equal(t, expectedStdin, string(actualStdin))
} }
type producers struct { type producers struct {
@ -132,41 +129,41 @@ func setupFIFOProducers(t *testing.T, fifos Config) producers {
) )
pipes.Stdin, err = fifo.OpenFifo(ctx, fifos.Stdin, syscall.O_RDONLY, 0) pipes.Stdin, err = fifo.OpenFifo(ctx, fifos.Stdin, syscall.O_RDONLY, 0)
assert.NilError(t, err) assert.NoError(t, err)
pipes.Stdout, err = fifo.OpenFifo(ctx, fifos.Stdout, syscall.O_WRONLY, 0) pipes.Stdout, err = fifo.OpenFifo(ctx, fifos.Stdout, syscall.O_WRONLY, 0)
assert.NilError(t, err) assert.NoError(t, err)
pipes.Stderr, err = fifo.OpenFifo(ctx, fifos.Stderr, syscall.O_WRONLY, 0) pipes.Stderr, err = fifo.OpenFifo(ctx, fifos.Stderr, syscall.O_WRONLY, 0)
assert.NilError(t, err) assert.NoError(t, err)
return pipes return pipes
} }
func initProducers(t *testing.T, producers producers, stdout, stderr string) { func initProducers(t *testing.T, producers producers, stdout, stderr string) {
_, err := producers.Stdout.Write([]byte(stdout)) _, err := producers.Stdout.Write([]byte(stdout))
assert.NilError(t, err) assert.NoError(t, err)
assert.NilError(t, producers.Stdout.Close()) assert.Nil(t, producers.Stdout.Close())
_, err = producers.Stderr.Write([]byte(stderr)) _, err = producers.Stderr.Write([]byte(stderr))
assert.NilError(t, err) assert.NoError(t, err)
assert.NilError(t, producers.Stderr.Close()) assert.Nil(t, producers.Stderr.Close())
} }
func TestBinaryIOArgs(t *testing.T) { func TestBinaryIOArgs(t *testing.T) {
res, err := BinaryIO("/file.bin", map[string]string{"id": "1"})("") res, err := BinaryIO("/file.bin", map[string]string{"id": "1"})("")
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, "binary:///file.bin?id=1", res.Config().Stdout) assert.Equal(t, "binary:///file.bin?id=1", res.Config().Stdout)
assert.Equal(t, "binary:///file.bin?id=1", res.Config().Stderr) assert.Equal(t, "binary:///file.bin?id=1", res.Config().Stderr)
} }
func TestBinaryIOAbsolutePath(t *testing.T) { func TestBinaryIOAbsolutePath(t *testing.T) {
res, err := BinaryIO("/full/path/bin", nil)("!") res, err := BinaryIO("/full/path/bin", nil)("!")
assert.NilError(t, err) assert.NoError(t, err)
// Test parse back // Test parse back
parsed, err := url.Parse(res.Config().Stdout) parsed, err := url.Parse(res.Config().Stdout)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, "binary", parsed.Scheme) assert.Equal(t, "binary", parsed.Scheme)
assert.Equal(t, "/full/path/bin", parsed.Path) assert.Equal(t, "/full/path/bin", parsed.Path)
} }
@ -178,13 +175,13 @@ func TestBinaryIOFailOnRelativePath(t *testing.T) {
func TestLogFileAbsolutePath(t *testing.T) { func TestLogFileAbsolutePath(t *testing.T) {
res, err := LogFile("/full/path/file.txt")("!") res, err := LogFile("/full/path/file.txt")("!")
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, "file:///full/path/file.txt", res.Config().Stdout) assert.Equal(t, "file:///full/path/file.txt", res.Config().Stdout)
assert.Equal(t, "file:///full/path/file.txt", res.Config().Stderr) assert.Equal(t, "file:///full/path/file.txt", res.Config().Stderr)
// Test parse back // Test parse back
parsed, err := url.Parse(res.Config().Stdout) parsed, err := url.Parse(res.Config().Stdout)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, "file", parsed.Scheme) assert.Equal(t, "file", parsed.Scheme)
assert.Equal(t, "/full/path/file.txt", parsed.Path) assert.Equal(t, "/full/path/file.txt", parsed.Path)
} }

View File

@ -24,7 +24,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestOpenFifos(t *testing.T) { func TestOpenFifos(t *testing.T) {
@ -53,7 +53,7 @@ func TestOpenFifos(t *testing.T) {
} }
for _, scenario := range scenarios { for _, scenario := range scenarios {
_, err := openFifos(context.Background(), scenario) _, err := openFifos(context.Background(), scenario)
assert.Assert(t, err != nil, scenario) assert.Error(t, err, scenario)
} }
} }

View File

@ -19,7 +19,7 @@ package cio
import ( import (
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestNewFifoSetInDir_NoTerminal(t *testing.T) { func TestNewFifoSetInDir_NoTerminal(t *testing.T) {
@ -28,10 +28,10 @@ func TestNewFifoSetInDir_NoTerminal(t *testing.T) {
t.Fatalf("NewFifoSetInDir failed with: %v", err) t.Fatalf("NewFifoSetInDir failed with: %v", err)
} }
assert.Assert(t, !set.Terminal, "FIFOSet.Terminal should be false") assert.True(t, !set.Terminal, "FIFOSet.Terminal should be false")
assert.Assert(t, set.Stdin != "", "FIFOSet.Stdin should be set") assert.NotEmpty(t, set.Stdin, "FIFOSet.Stdin should be set")
assert.Assert(t, set.Stdout != "", "FIFOSet.Stdout should be set") assert.NotEmpty(t, set.Stdout, "FIFOSet.Stdout should be set")
assert.Assert(t, set.Stderr != "", "FIFOSet.Stderr should be set") assert.NotEmpty(t, set.Stderr, "FIFOSet.Stderr should be set")
} }
func TestNewFifoSetInDir_Terminal(t *testing.T) { func TestNewFifoSetInDir_Terminal(t *testing.T) {
@ -40,8 +40,8 @@ func TestNewFifoSetInDir_Terminal(t *testing.T) {
t.Fatalf("NewFifoSetInDir failed with: %v", err) t.Fatalf("NewFifoSetInDir failed with: %v", err)
} }
assert.Assert(t, set.Terminal, "FIFOSet.Terminal should be false") assert.True(t, set.Terminal, "FIFOSet.Terminal should be true")
assert.Assert(t, set.Stdin != "", "FIFOSet.Stdin should be set") assert.NotEmpty(t, set.Stdin, "FIFOSet.Stdin should be set")
assert.Assert(t, set.Stdout != "", "FIFOSet.Stdout should be set") assert.NotEmpty(t, set.Stdout, "FIFOSet.Stdout should be set")
assert.Assert(t, set.Stderr == "", "FIFOSet.Stderr should not be set") assert.Empty(t, set.Stderr, "FIFOSet.Stderr should not be set")
} }

View File

@ -26,8 +26,7 @@ import (
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
is "gotest.tools/v3/assert/cmp"
) )
type copySource struct { type copySource struct {
@ -81,9 +80,9 @@ func TestCopy(t *testing.T) {
testcase.source.size, testcase.source.size,
testcase.source.digest) testcase.source.digest)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Equal(testcase.source.digest, testcase.writer.committedDigest)) assert.Equal(t, testcase.source.digest, testcase.writer.committedDigest)
assert.Check(t, is.Equal(testcase.expected, testcase.writer.String())) assert.Equal(t, testcase.expected, testcase.writer.String())
}) })
} }
} }

View File

@ -19,14 +19,16 @@ package local
import ( import (
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestTryLock(t *testing.T) { func TestTryLock(t *testing.T) {
err := tryLock("testref") err := tryLock("testref")
assert.NilError(t, err) assert.NoError(t, err)
defer unlock("testref") defer unlock("testref")
err = tryLock("testref") err = tryLock("testref")
assert.ErrorContains(t, err, "ref testref locked for ") require.NotNil(t, err)
assert.Contains(t, err.Error(), "ref testref locked for ")
} }

View File

@ -39,7 +39,7 @@ import (
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
type memoryLabelStore struct { type memoryLabelStore struct {
@ -351,7 +351,7 @@ func checkWrite(ctx context.Context, t checker, cs content.Store, dgst digest.Di
func TestWriterTruncateRecoversFromIncompleteWrite(t *testing.T) { func TestWriterTruncateRecoversFromIncompleteWrite(t *testing.T) {
cs, err := NewStore(t.TempDir()) cs, err := NewStore(t.TempDir())
assert.NilError(t, err) assert.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@ -362,26 +362,26 @@ func TestWriterTruncateRecoversFromIncompleteWrite(t *testing.T) {
setupIncompleteWrite(ctx, t, cs, ref, total) setupIncompleteWrite(ctx, t, cs, ref, total)
writer, err := cs.Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{Size: total})) writer, err := cs.Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{Size: total}))
assert.NilError(t, err) assert.NoError(t, err)
assert.NilError(t, writer.Truncate(0)) assert.Nil(t, writer.Truncate(0))
_, err = writer.Write(contentB) _, err = writer.Write(contentB)
assert.NilError(t, err) assert.NoError(t, err)
dgst := digest.FromBytes(contentB) dgst := digest.FromBytes(contentB)
err = writer.Commit(ctx, total, dgst) err = writer.Commit(ctx, total, dgst)
assert.NilError(t, err) assert.NoError(t, err)
} }
func setupIncompleteWrite(ctx context.Context, t *testing.T, cs content.Store, ref string, total int64) { func setupIncompleteWrite(ctx context.Context, t *testing.T, cs content.Store, ref string, total int64) {
writer, err := cs.Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{Size: total})) writer, err := cs.Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{Size: total}))
assert.NilError(t, err) assert.NoError(t, err)
_, err = writer.Write([]byte("bad data")) _, err = writer.Write([]byte("bad data"))
assert.NilError(t, err) assert.NoError(t, err)
assert.NilError(t, writer.Close()) assert.Nil(t, writer.Close())
} }
func TestWriteReadEmptyFileTimestamp(t *testing.T) { func TestWriteReadEmptyFileTimestamp(t *testing.T) {

View File

@ -32,9 +32,9 @@ import (
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/log/logtest" "github.com/containerd/containerd/log/logtest"
"github.com/containerd/containerd/pkg/testutil" "github.com/containerd/containerd/pkg/testutil"
digest "github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
const ( const (
@ -271,7 +271,7 @@ func checkResumeWriter(ctx context.Context, t *testing.T, cs content.Store) {
} }
checkStatus(t, w1, expected, dgstFirst, preStart, postStart, preUpdate, postUpdate) checkStatus(t, w1, expected, dgstFirst, preStart, postStart, preUpdate, postUpdate)
assert.NilError(t, w1.Close(), "close first writer") assert.Nil(t, w1.Close(), "close first writer")
w2, err := cs.Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{Size: 256, Digest: dgst})) w2, err := cs.Writer(ctx, content.WithRef(ref), content.WithDescriptor(ocispec.Descriptor{Size: 256, Digest: dgst}))
if err != nil { if err != nil {
@ -295,7 +295,7 @@ func checkResumeWriter(ctx context.Context, t *testing.T, cs content.Store) {
} }
postCommit := time.Now() postCommit := time.Now()
assert.NilError(t, w2.Close(), "close second writer") assert.Nil(t, w2.Close(), "close second writer")
info := content.Info{ info := content.Info{
Digest: dgst, Digest: dgst,
Size: 256, Size: 256,

View File

@ -6,7 +6,7 @@ package apparmor
import ( import (
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestCleanProfileName(t *testing.T) { func TestCleanProfileName(t *testing.T) {

View File

@ -23,7 +23,7 @@ import (
"time" "time"
"github.com/containerd/containerd/gc" "github.com/containerd/containerd/gc"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestPauseThreshold(t *testing.T) { func TestPauseThreshold(t *testing.T) {

View File

@ -26,7 +26,7 @@ import (
"github.com/containerd/containerd/pkg/ttrpcutil" "github.com/containerd/containerd/pkg/ttrpcutil"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
"github.com/gogo/protobuf/types" "github.com/gogo/protobuf/types"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestClientTTRPC_New(t *testing.T) { func TestClientTTRPC_New(t *testing.T) {
@ -34,10 +34,10 @@ func TestClientTTRPC_New(t *testing.T) {
t.Skip() t.Skip()
} }
client, err := ttrpcutil.NewClient(address + ".ttrpc") client, err := ttrpcutil.NewClient(address + ".ttrpc")
assert.NilError(t, err) assert.NoError(t, err)
err = client.Close() err = client.Close()
assert.NilError(t, err) assert.NoError(t, err)
} }
func TestClientTTRPC_Reconnect(t *testing.T) { func TestClientTTRPC_Reconnect(t *testing.T) {
@ -45,13 +45,13 @@ func TestClientTTRPC_Reconnect(t *testing.T) {
t.Skip() t.Skip()
} }
client, err := ttrpcutil.NewClient(address + ".ttrpc") client, err := ttrpcutil.NewClient(address + ".ttrpc")
assert.NilError(t, err) assert.NoError(t, err)
err = client.Reconnect() err = client.Reconnect()
assert.NilError(t, err) assert.NoError(t, err)
service, err := client.EventsService() service, err := client.EventsService()
assert.NilError(t, err) assert.NoError(t, err)
// Send test request to make sure its alive after reconnect // Send test request to make sure its alive after reconnect
_, err = service.Forward(context.Background(), &v1.ForwardRequest{ _, err = service.Forward(context.Background(), &v1.ForwardRequest{
@ -62,10 +62,10 @@ func TestClientTTRPC_Reconnect(t *testing.T) {
Event: &types.Any{}, Event: &types.Any{},
}, },
}) })
assert.NilError(t, err) assert.NoError(t, err)
err = client.Close() err = client.Close()
assert.NilError(t, err) assert.NoError(t, err)
} }
func TestClientTTRPC_Close(t *testing.T) { func TestClientTTRPC_Close(t *testing.T) {
@ -73,17 +73,17 @@ func TestClientTTRPC_Close(t *testing.T) {
t.Skip() t.Skip()
} }
client, err := ttrpcutil.NewClient(address + ".ttrpc") client, err := ttrpcutil.NewClient(address + ".ttrpc")
assert.NilError(t, err) assert.NoError(t, err)
service, err := client.EventsService() service, err := client.EventsService()
assert.NilError(t, err) assert.NoError(t, err)
err = client.Close() err = client.Close()
assert.NilError(t, err) assert.NoError(t, err)
_, err = service.Forward(context.Background(), &v1.ForwardRequest{Envelope: &v1.Envelope{}}) _, err = service.Forward(context.Background(), &v1.ForwardRequest{Envelope: &v1.Envelope{}})
assert.Equal(t, err, ttrpc.ErrClosed) assert.Equal(t, err, ttrpc.ErrClosed)
err = client.Close() err = client.Close()
assert.NilError(t, err) assert.NoError(t, err)
} }

View File

@ -25,7 +25,7 @@ import (
"github.com/containerd/containerd/images/converter/uncompress" "github.com/containerd/containerd/images/converter/uncompress"
"github.com/containerd/containerd/platforms" "github.com/containerd/containerd/platforms"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
// TestConvert creates an image from testImage, with the following conversion: // TestConvert creates an image from testImage, with the following conversion:
@ -72,7 +72,7 @@ func TestConvert(t *testing.T) {
} }
// Assert that the image does not have any extra arch. // Assert that the image does not have any extra arch.
assert.Equal(t, 1, len(plats)) assert.Equal(t, 1, len(plats))
assert.Check(t, defPlat.Match(plats[0])) assert.True(t, defPlat.Match(plats[0]))
// Assert that the media type is converted to OCI and also uncompressed // Assert that the media type is converted to OCI and also uncompressed
mani, err := images.Manifest(ctx, cs, dstImg.Target, defPlat) mani, err := images.Manifest(ctx, cs, dstImg.Target, defPlat)

View File

@ -16,8 +16,8 @@ require (
github.com/opencontainers/image-spec v1.0.3-0.20220303224323-02efb9a75ee1 github.com/opencontainers/image-spec v1.0.3-0.20220303224323-02efb9a75ee1
github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417
github.com/sirupsen/logrus v1.8.1 github.com/sirupsen/logrus v1.8.1
github.com/stretchr/testify v1.7.0
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e
gotest.tools/v3 v3.0.3
) )
replace ( replace (

View File

@ -1068,10 +1068,8 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0=
gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8= gotest.tools/v3 v3.0.3/go.mod h1:Z7Lb0S5l+klDB31fvDQX8ss/FlKDxtlFlw3Oa8Ymbl8=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@ -20,7 +20,7 @@ import (
"context" "context"
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestLoggerContext(t *testing.T) { func TestLoggerContext(t *testing.T) {
@ -28,5 +28,5 @@ func TestLoggerContext(t *testing.T) {
ctx = WithLogger(ctx, G(ctx).WithField("test", "one")) ctx = WithLogger(ctx, G(ctx).WithField("test", "one"))
assert.Equal(t, GetLogger(ctx).Data["test"], "one") assert.Equal(t, GetLogger(ctx).Data["test"], "one")
assert.Equal(t, G(ctx), GetLogger(ctx)) // these should be the same. assert.Same(t, G(ctx), GetLogger(ctx)) // these should be the same.
} }

View File

@ -34,9 +34,9 @@ import (
"github.com/containerd/typeurl" "github.com/containerd/typeurl"
"github.com/gogo/protobuf/types" "github.com/gogo/protobuf/types"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-spec/specs-go"
"github.com/stretchr/testify/assert"
bolt "go.etcd.io/bbolt" bolt "go.etcd.io/bbolt"
"gotest.tools/v3/assert"
) )
func init() { func init() {
@ -724,7 +724,8 @@ func checkContainersEqual(t *testing.T, a, b *containers.Container, format strin
return true return true
}), }),
) )
assert.DeepEqual(t, a, b, opt)
assert.True(t, cmp.Equal(a, b, opt))
} }
func testEnv(t *testing.T) (context.Context, *bolt.DB, func()) { func testEnv(t *testing.T) (context.Context, *bolt.DB, func()) {

View File

@ -27,14 +27,14 @@ import (
// so we use continuity/testutil instead. // so we use continuity/testutil instead.
"github.com/containerd/continuity/testutil" "github.com/containerd/continuity/testutil"
"github.com/containerd/continuity/testutil/loopback" "github.com/containerd/continuity/testutil/loopback"
"github.com/stretchr/testify/assert"
exec "golang.org/x/sys/execabs" exec "golang.org/x/sys/execabs"
"gotest.tools/v3/assert"
) )
func checkLookup(t *testing.T, fsType, mntPoint, dir string) { func checkLookup(t *testing.T, fsType, mntPoint, dir string) {
t.Helper() t.Helper()
info, err := Lookup(dir) info, err := Lookup(dir)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, fsType, info.FSType) assert.Equal(t, fsType, info.FSType)
assert.Equal(t, mntPoint, info.Mountpoint) assert.Equal(t, mntPoint, info.Mountpoint)
} }
@ -61,7 +61,7 @@ func testLookup(t *testing.T, fsType string) {
testutil.Unmount(t, mnt) testutil.Unmount(t, mnt)
loop.Close() loop.Close()
}() }()
assert.Check(t, strings.HasPrefix(loop.Device, "/dev/loop")) assert.True(t, strings.HasPrefix(loop.Device, "/dev/loop"))
checkLookup(t, fsType, mnt, mnt) checkLookup(t, fsType, mnt, mnt)
newMnt := t.TempDir() newMnt := t.TempDir()
@ -105,11 +105,11 @@ func TestLookupWithOverlay(t *testing.T) {
testdir := filepath.Join(overlay, "testdir") testdir := filepath.Join(overlay, "testdir")
err := os.Mkdir(testdir, 0777) err := os.Mkdir(testdir, 0777)
assert.NilError(t, err) assert.NoError(t, err)
testfile := filepath.Join(overlay, "testfile") testfile := filepath.Join(overlay, "testfile")
_, err = os.Create(testfile) _, err = os.Create(testfile)
assert.NilError(t, err) assert.NoError(t, err)
checkLookup(t, "overlay", overlay, testdir) checkLookup(t, "overlay", overlay, testdir)
checkLookup(t, "overlay", overlay, testfile) checkLookup(t, "overlay", overlay, testfile)

View File

@ -25,14 +25,14 @@ import (
"testing" "testing"
"github.com/containerd/containerd/mount" "github.com/containerd/containerd/mount"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
// Unmount unmounts a given mountPoint and sets t.Error if it fails // Unmount unmounts a given mountPoint and sets t.Error if it fails
func Unmount(t testing.TB, mountPoint string) { func Unmount(t testing.TB, mountPoint string) {
t.Log("unmount", mountPoint) t.Log("unmount", mountPoint)
err := mount.UnmountAll(mountPoint, umountflags) err := mount.UnmountAll(mountPoint, umountflags)
assert.NilError(t, err) assert.NoError(t, err)
} }
// RequiresRoot skips tests that require root, unless the test.root flag has // RequiresRoot skips tests that require root, unless the test.root flag has

View File

@ -27,7 +27,7 @@ import (
"net/url" "net/url"
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
) )
func TestFetcherOpen(t *testing.T) { func TestFetcherOpen(t *testing.T) {

View File

@ -21,8 +21,7 @@ import (
"testing" "testing"
"github.com/containerd/containerd/reference" "github.com/containerd/containerd/reference"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
"gotest.tools/v3/assert/cmp"
) )
func TestRepositoryScope(t *testing.T) { func TestRepositoryScope(t *testing.T) {
@ -51,7 +50,7 @@ func TestRepositoryScope(t *testing.T) {
for _, x := range testCases { for _, x := range testCases {
t.Run(x.refspec.String(), func(t *testing.T) { t.Run(x.refspec.String(), func(t *testing.T) {
actual, err := RepositoryScope(x.refspec, x.push) actual, err := RepositoryScope(x.refspec, x.push)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, x.expected, actual) assert.Equal(t, x.expected, actual)
}) })
} }
@ -97,7 +96,7 @@ func TestGetTokenScopes(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
ctx := context.WithValue(context.TODO(), tokenScopesKey{}, tc.scopesInCtx) ctx := context.WithValue(context.TODO(), tokenScopesKey{}, tc.scopesInCtx)
actual := GetTokenScopes(ctx, tc.commonScopes) actual := GetTokenScopes(ctx, tc.commonScopes)
assert.DeepEqual(t, tc.expected, actual) assert.Equal(t, tc.expected, actual)
} }
} }
@ -107,7 +106,5 @@ func TestCustomScope(t *testing.T) {
ctx = ContextWithAppendPullRepositoryScope(ctx, "foo/bar") ctx = ContextWithAppendPullRepositoryScope(ctx, "foo/bar")
scopes := GetTokenScopes(ctx, []string{}) scopes := GetTokenScopes(ctx, []string{})
assert.Assert(t, cmp.Len(scopes, 2)) assert.Equal(t, []string{"repository:foo/bar:pull", scope}, scopes)
assert.Check(t, cmp.Equal(scopes[0], "repository:foo/bar:pull"))
assert.Check(t, cmp.Equal(scopes[1], scope))
} }

View File

@ -22,7 +22,7 @@ import (
"sort" "sort"
"testing" "testing"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
"github.com/containerd/containerd/plugin" "github.com/containerd/containerd/plugin"
) )
@ -48,16 +48,16 @@ func TestMergeConfigs(t *testing.T) {
} }
err := mergeConfig(a, b) err := mergeConfig(a, b)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, a.Version, 2) assert.Equal(t, 2, a.Version)
assert.Equal(t, a.Root, "new_root") assert.Equal(t, "new_root", a.Root)
assert.Equal(t, a.State, "old_state") assert.Equal(t, "old_state", a.State)
assert.Equal(t, a.OOMScore, 2) assert.Equal(t, 2, a.OOMScore)
assert.DeepEqual(t, a.RequiredPlugins, []string{"old_plugin", "new_plugin1", "new_plugin2"}) assert.Equal(t, []string{"old_plugin", "new_plugin1", "new_plugin2"}, a.RequiredPlugins)
assert.DeepEqual(t, a.DisabledPlugins, []string{"old_plugin"}) assert.Equal(t, []string{"old_plugin"}, a.DisabledPlugins)
assert.DeepEqual(t, a.Timeouts, map[string]string{"a": "1", "b": "2"}) assert.Equal(t, map[string]string{"a": "1", "b": "2"}, a.Timeouts)
assert.DeepEqual(t, a.StreamProcessors, map[string]StreamProcessor{"1": {Path: "3"}, "2": {Path: "5"}}) assert.Equal(t, map[string]StreamProcessor{"1": {Path: "3"}, "2": {Path: "5"}}, a.StreamProcessors)
} }
func TestResolveImports(t *testing.T) { func TestResolveImports(t *testing.T) {
@ -65,7 +65,7 @@ func TestResolveImports(t *testing.T) {
for _, filename := range []string{"config_1.toml", "config_2.toml", "test.toml"} { for _, filename := range []string{"config_1.toml", "config_2.toml", "test.toml"} {
err := os.WriteFile(filepath.Join(tempDir, filename), []byte(""), 0600) err := os.WriteFile(filepath.Join(tempDir, filename), []byte(""), 0600)
assert.NilError(t, err) assert.NoError(t, err)
} }
imports, err := resolveImports(filepath.Join(tempDir, "root.toml"), []string{ imports, err := resolveImports(filepath.Join(tempDir, "root.toml"), []string{
@ -73,9 +73,9 @@ func TestResolveImports(t *testing.T) {
filepath.Join(tempDir, "./test.toml"), // Path clean up filepath.Join(tempDir, "./test.toml"), // Path clean up
"current.toml", // Resolve current working dir "current.toml", // Resolve current working dir
}) })
assert.NilError(t, err) assert.NoError(t, err)
assert.DeepEqual(t, imports, []string{ assert.Equal(t, imports, []string{
filepath.Join(tempDir, "config_1.toml"), filepath.Join(tempDir, "config_1.toml"),
filepath.Join(tempDir, "config_2.toml"), filepath.Join(tempDir, "config_2.toml"),
filepath.Join(tempDir, "test.toml"), filepath.Join(tempDir, "test.toml"),
@ -97,14 +97,14 @@ root = "/var/lib/containerd"
path := filepath.Join(tempDir, "config.toml") path := filepath.Join(tempDir, "config.toml")
err := os.WriteFile(path, []byte(data), 0600) err := os.WriteFile(path, []byte(data), 0600)
assert.NilError(t, err) assert.NoError(t, err)
var out Config var out Config
err = LoadConfig(path, &out) err = LoadConfig(path, &out)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, out.Version) assert.Equal(t, 2, out.Version)
assert.Equal(t, "/var/lib/containerd", out.Root) assert.Equal(t, "/var/lib/containerd", out.Root)
assert.DeepEqual(t, map[string]StreamProcessor{ assert.Equal(t, map[string]StreamProcessor{
"io.containerd.processor.v1.pigz": { "io.containerd.processor.v1.pigz": {
Accepts: []string{"application/vnd.docker.image.rootfs.diff.tar.gzip"}, Accepts: []string{"application/vnd.docker.image.rootfs.diff.tar.gzip"},
Path: "unpigz", Path: "unpigz",
@ -126,18 +126,18 @@ disabled_plugins = ["io.containerd.v1.xyz"]
tempDir := t.TempDir() tempDir := t.TempDir()
err := os.WriteFile(filepath.Join(tempDir, "data1.toml"), []byte(data1), 0600) err := os.WriteFile(filepath.Join(tempDir, "data1.toml"), []byte(data1), 0600)
assert.NilError(t, err) assert.NoError(t, err)
err = os.WriteFile(filepath.Join(tempDir, "data2.toml"), []byte(data2), 0600) err = os.WriteFile(filepath.Join(tempDir, "data2.toml"), []byte(data2), 0600)
assert.NilError(t, err) assert.NoError(t, err)
var out Config var out Config
err = LoadConfig(filepath.Join(tempDir, "data1.toml"), &out) err = LoadConfig(filepath.Join(tempDir, "data1.toml"), &out)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, out.Version) assert.Equal(t, 2, out.Version)
assert.Equal(t, "/var/lib/containerd", out.Root) assert.Equal(t, "/var/lib/containerd", out.Root)
assert.DeepEqual(t, []string{"io.containerd.v1.xyz"}, out.DisabledPlugins) assert.Equal(t, []string{"io.containerd.v1.xyz"}, out.DisabledPlugins)
} }
func TestLoadConfigWithCircularImports(t *testing.T) { func TestLoadConfigWithCircularImports(t *testing.T) {
@ -154,21 +154,21 @@ imports = ["data1.toml", "data2.toml"]
tempDir := t.TempDir() tempDir := t.TempDir()
err := os.WriteFile(filepath.Join(tempDir, "data1.toml"), []byte(data1), 0600) err := os.WriteFile(filepath.Join(tempDir, "data1.toml"), []byte(data1), 0600)
assert.NilError(t, err) assert.NoError(t, err)
err = os.WriteFile(filepath.Join(tempDir, "data2.toml"), []byte(data2), 0600) err = os.WriteFile(filepath.Join(tempDir, "data2.toml"), []byte(data2), 0600)
assert.NilError(t, err) assert.NoError(t, err)
var out Config var out Config
err = LoadConfig(filepath.Join(tempDir, "data1.toml"), &out) err = LoadConfig(filepath.Join(tempDir, "data1.toml"), &out)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, out.Version) assert.Equal(t, 2, out.Version)
assert.Equal(t, "/var/lib/containerd", out.Root) assert.Equal(t, "/var/lib/containerd", out.Root)
assert.DeepEqual(t, []string{"io.containerd.v1.xyz"}, out.DisabledPlugins) assert.Equal(t, []string{"io.containerd.v1.xyz"}, out.DisabledPlugins)
sort.Strings(out.Imports) sort.Strings(out.Imports)
assert.DeepEqual(t, []string{ assert.Equal(t, []string{
filepath.Join(tempDir, "data1.toml"), filepath.Join(tempDir, "data1.toml"),
filepath.Join(tempDir, "data2.toml"), filepath.Join(tempDir, "data2.toml"),
}, out.Imports) }, out.Imports)
@ -185,15 +185,15 @@ version = 2
path := filepath.Join(tempDir, "config.toml") path := filepath.Join(tempDir, "config.toml")
err := os.WriteFile(path, []byte(data), 0600) err := os.WriteFile(path, []byte(data), 0600)
assert.NilError(t, err) assert.NoError(t, err)
var out Config var out Config
err = LoadConfig(path, &out) err = LoadConfig(path, &out)
assert.NilError(t, err) assert.NoError(t, err)
pluginConfig := map[string]interface{}{} pluginConfig := map[string]interface{}{}
_, err = out.Decode(&plugin.Registration{Type: "io.containerd.runtime.v1", ID: "linux", Config: &pluginConfig}) _, err = out.Decode(&plugin.Registration{Type: "io.containerd.runtime.v1", ID: "linux", Config: &pluginConfig})
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, true, pluginConfig["shim_debug"]) assert.Equal(t, true, pluginConfig["shim_debug"])
} }
@ -207,14 +207,14 @@ func TestDecodePluginInV1Config(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml") path := filepath.Join(t.TempDir(), "config.toml")
err := os.WriteFile(path, []byte(data), 0600) err := os.WriteFile(path, []byte(data), 0600)
assert.NilError(t, err) assert.NoError(t, err)
var out Config var out Config
err = LoadConfig(path, &out) err = LoadConfig(path, &out)
assert.NilError(t, err) assert.NoError(t, err)
pluginConfig := map[string]interface{}{} pluginConfig := map[string]interface{}{}
_, err = out.Decode(&plugin.Registration{ID: "linux", Config: &pluginConfig}) _, err = out.Decode(&plugin.Registration{ID: "linux", Config: &pluginConfig})
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, true, pluginConfig["shim_debug"]) assert.Equal(t, true, pluginConfig["shim_debug"])
} }

View File

@ -20,8 +20,7 @@ import (
"testing" "testing"
srvconfig "github.com/containerd/containerd/services/server/config" srvconfig "github.com/containerd/containerd/services/server/config"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
is "gotest.tools/v3/assert/cmp"
) )
func TestCreateTopLevelDirectoriesErrorsWithSamePathForRootAndState(t *testing.T) { func TestCreateTopLevelDirectoriesErrorsWithSamePathForRootAndState(t *testing.T) {
@ -30,7 +29,7 @@ func TestCreateTopLevelDirectoriesErrorsWithSamePathForRootAndState(t *testing.T
Root: path, Root: path,
State: path, State: path,
}) })
assert.Check(t, is.Error(err, "root and state must be different paths")) assert.EqualError(t, err, "root and state must be different paths")
} }
func TestCreateTopLevelDirectoriesWithEmptyStatePath(t *testing.T) { func TestCreateTopLevelDirectoriesWithEmptyStatePath(t *testing.T) {
@ -40,7 +39,7 @@ func TestCreateTopLevelDirectoriesWithEmptyStatePath(t *testing.T) {
Root: rootPath, Root: rootPath,
State: statePath, State: statePath,
}) })
assert.Check(t, is.Error(err, "state must be specified")) assert.EqualError(t, err, "state must be specified")
} }
func TestCreateTopLevelDirectoriesWithEmptyRootPath(t *testing.T) { func TestCreateTopLevelDirectoriesWithEmptyRootPath(t *testing.T) {
@ -50,5 +49,5 @@ func TestCreateTopLevelDirectoriesWithEmptyRootPath(t *testing.T) {
Root: rootPath, Root: rootPath,
State: statePath, State: statePath,
}) })
assert.Check(t, is.Error(err, "root must be specified")) assert.EqualError(t, err, "root must be specified")
} }

View File

@ -32,7 +32,7 @@ import (
"github.com/containerd/continuity/fs/fstest" "github.com/containerd/continuity/fs/fstest"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
"github.com/containerd/containerd/mount" "github.com/containerd/containerd/mount"
"github.com/containerd/containerd/snapshots" "github.com/containerd/containerd/snapshots"
@ -64,14 +64,14 @@ func BenchmarkNative(b *testing.B) {
} }
snapshotter, err := native.NewSnapshotter(nativeRootPath) snapshotter, err := native.NewSnapshotter(nativeRootPath)
assert.NilError(b, err) assert.Nil(b, err)
defer func() { defer func() {
err = snapshotter.Close() err = snapshotter.Close()
assert.NilError(b, err) assert.Nil(b, err)
err = os.RemoveAll(nativeRootPath) err = os.RemoveAll(nativeRootPath)
assert.NilError(b, err) assert.Nil(b, err)
}() }()
benchmarkSnapshotter(b, snapshotter) benchmarkSnapshotter(b, snapshotter)
@ -83,14 +83,14 @@ func BenchmarkOverlay(b *testing.B) {
} }
snapshotter, err := overlay.NewSnapshotter(overlayRootPath) snapshotter, err := overlay.NewSnapshotter(overlayRootPath)
assert.NilError(b, err, "failed to create overlay snapshotter") assert.Nil(b, err, "failed to create overlay snapshotter")
defer func() { defer func() {
err = snapshotter.Close() err = snapshotter.Close()
assert.NilError(b, err) assert.Nil(b, err)
err = os.RemoveAll(overlayRootPath) err = os.RemoveAll(overlayRootPath)
assert.NilError(b, err) assert.Nil(b, err)
}() }()
benchmarkSnapshotter(b, snapshotter) benchmarkSnapshotter(b, snapshotter)
@ -114,17 +114,17 @@ func BenchmarkDeviceMapper(b *testing.B) {
ctx := context.Background() ctx := context.Background()
snapshotter, err := devmapper.NewSnapshotter(ctx, config) snapshotter, err := devmapper.NewSnapshotter(ctx, config)
assert.NilError(b, err) assert.Nil(b, err)
defer func() { defer func() {
err := snapshotter.ResetPool(ctx) err := snapshotter.ResetPool(ctx)
assert.NilError(b, err) assert.Nil(b, err)
err = snapshotter.Close() err = snapshotter.Close()
assert.NilError(b, err) assert.Nil(b, err)
err = os.RemoveAll(dmRootPath) err = os.RemoveAll(dmRootPath)
assert.NilError(b, err) assert.Nil(b, err)
}() }()
benchmarkSnapshotter(b, snapshotter) benchmarkSnapshotter(b, snapshotter)
@ -184,19 +184,19 @@ func benchmarkSnapshotter(b *testing.B, snapshotter snapshots.Snapshotter) {
timer = time.Now() timer = time.Now()
mounts, err := snapshotter.Prepare(ctx, current, parent) mounts, err := snapshotter.Prepare(ctx, current, parent)
assert.NilError(b, err) assert.Nil(b, err)
prepareDuration += time.Since(timer) prepareDuration += time.Since(timer)
timer = time.Now() timer = time.Now()
err = mount.WithTempMount(ctx, mounts, layers[l].Apply) err = mount.WithTempMount(ctx, mounts, layers[l].Apply)
assert.NilError(b, err) assert.Nil(b, err)
writeDuration += time.Since(timer) writeDuration += time.Since(timer)
parent = fmt.Sprintf("committed-%d", atomic.AddInt64(&layerIndex, 1)) parent = fmt.Sprintf("committed-%d", atomic.AddInt64(&layerIndex, 1))
timer = time.Now() timer = time.Now()
err = snapshotter.Commit(ctx, parent, current) err = snapshotter.Commit(ctx, parent, current)
assert.NilError(b, err) assert.Nil(b, err)
commitDuration += time.Since(timer) commitDuration += time.Since(timer)
} }
} }

View File

@ -25,8 +25,7 @@ import (
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/pelletier/go-toml" "github.com/pelletier/go-toml"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
is "gotest.tools/v3/assert/cmp"
) )
func TestLoadConfig(t *testing.T) { func TestLoadConfig(t *testing.T) {
@ -37,28 +36,27 @@ func TestLoadConfig(t *testing.T) {
} }
file, err := os.CreateTemp("", "devmapper-config-") file, err := os.CreateTemp("", "devmapper-config-")
assert.NilError(t, err) assert.NoError(t, err)
encoder := toml.NewEncoder(file) encoder := toml.NewEncoder(file)
err = encoder.Encode(&expected) err = encoder.Encode(&expected)
assert.NilError(t, err) assert.NoError(t, err)
defer func() { defer func() {
err := file.Close() err := file.Close()
assert.NilError(t, err) assert.NoError(t, err)
err = os.Remove(file.Name()) err = os.Remove(file.Name())
assert.NilError(t, err) assert.NoError(t, err)
}() }()
loaded, err := LoadConfig(file.Name()) loaded, err := LoadConfig(file.Name())
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, loaded.RootPath, expected.RootPath) assert.Equal(t, loaded.RootPath, expected.RootPath)
assert.Equal(t, loaded.PoolName, expected.PoolName) assert.Equal(t, loaded.PoolName, expected.PoolName)
assert.Equal(t, loaded.BaseImageSize, expected.BaseImageSize) assert.Equal(t, loaded.BaseImageSize, expected.BaseImageSize)
assert.True(t, loaded.BaseImageSizeBytes == 128*1024*1024)
assert.Assert(t, loaded.BaseImageSizeBytes == 128*1024*1024)
} }
func TestLoadConfigInvalidPath(t *testing.T) { func TestLoadConfigInvalidPath(t *testing.T) {
@ -66,7 +64,7 @@ func TestLoadConfigInvalidPath(t *testing.T) {
assert.Equal(t, os.ErrNotExist, err) assert.Equal(t, os.ErrNotExist, err)
_, err = LoadConfig("/dev/null") _, err = LoadConfig("/dev/null")
assert.Assert(t, err != nil) assert.NotNil(t, err)
} }
func TestParseInvalidData(t *testing.T) { func TestParseInvalidData(t *testing.T) {
@ -81,15 +79,15 @@ func TestParseInvalidData(t *testing.T) {
func TestFieldValidation(t *testing.T) { func TestFieldValidation(t *testing.T) {
config := &Config{} config := &Config{}
err := config.Validate() err := config.Validate()
assert.Assert(t, err != nil) assert.NotNil(t, err)
multErr := (err).(*multierror.Error) multErr := (err).(*multierror.Error)
assert.Assert(t, is.Len(multErr.Errors, 4)) assert.Len(t, multErr.Errors, 4)
assert.Assert(t, multErr.Errors[0] != nil, "pool_name is empty") assert.NotNil(t, multErr.Errors[0], "pool_name is empty")
assert.Assert(t, multErr.Errors[1] != nil, "root_path is empty") assert.NotNil(t, multErr.Errors[1], "root_path is empty")
assert.Assert(t, multErr.Errors[2] != nil, "base_image_size is empty") assert.NotNil(t, multErr.Errors[2], "base_image_size is empty")
assert.Assert(t, multErr.Errors[3] != nil, "filesystem type cannot be empty") assert.NotNil(t, multErr.Errors[3], "filesystem type cannot be empty")
} }
func TestExistingPoolFieldValidation(t *testing.T) { func TestExistingPoolFieldValidation(t *testing.T) {
@ -101,5 +99,5 @@ func TestExistingPoolFieldValidation(t *testing.T) {
} }
err := config.Validate() err := config.Validate()
assert.NilError(t, err) assert.NoError(t, err)
} }

View File

@ -24,13 +24,11 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/docker/go-units"
"golang.org/x/sys/unix"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"github.com/containerd/containerd/mount" "github.com/containerd/containerd/mount"
"github.com/containerd/containerd/pkg/testutil" "github.com/containerd/containerd/pkg/testutil"
"github.com/docker/go-units"
"github.com/stretchr/testify/assert"
"golang.org/x/sys/unix"
) )
const ( const (
@ -50,23 +48,23 @@ func TestDMSetup(t *testing.T) {
defer func() { defer func() {
err := mount.DetachLoopDevice(loopDataDevice, loopMetaDevice) err := mount.DetachLoopDevice(loopDataDevice, loopMetaDevice)
assert.NilError(t, err, "failed to detach loop devices for data image: %s and meta image: %s", dataImage, metaImage) assert.Nil(t, err, "failed to detach loop devices for data image: %s and meta image: %s", dataImage, metaImage)
}() }()
t.Run("CreatePool", func(t *testing.T) { t.Run("CreatePool", func(t *testing.T) {
err := CreatePool(testPoolName, loopDataDevice, loopMetaDevice, 128) err := CreatePool(testPoolName, loopDataDevice, loopMetaDevice, 128)
assert.NilError(t, err, "failed to create thin-pool with %s %s", loopDataDevice, loopMetaDevice) assert.Nil(t, err, "failed to create thin-pool with %s %s", loopDataDevice, loopMetaDevice)
table, err := Table(testPoolName) table, err := Table(testPoolName)
t.Logf("table: %s", table) t.Logf("table: %s", table)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, strings.HasPrefix(table, "0 32768 thin-pool")) assert.True(t, strings.HasPrefix(table, "0 32768 thin-pool"))
assert.Assert(t, strings.HasSuffix(table, "128 32768 1 skip_block_zeroing")) assert.True(t, strings.HasSuffix(table, "128 32768 1 skip_block_zeroing"))
}) })
t.Run("ReloadPool", func(t *testing.T) { t.Run("ReloadPool", func(t *testing.T) {
err := ReloadPool(testPoolName, loopDataDevice, loopMetaDevice, 256) err := ReloadPool(testPoolName, loopDataDevice, loopMetaDevice, 256)
assert.NilError(t, err, "failed to reload thin-pool") assert.Nil(t, err, "failed to reload thin-pool")
}) })
t.Run("CreateDevice", testCreateDevice) t.Run("CreateDevice", testCreateDevice)
@ -82,7 +80,7 @@ func TestDMSetup(t *testing.T) {
t.Run("RemovePool", func(t *testing.T) { t.Run("RemovePool", func(t *testing.T) {
err := RemoveDevice(testPoolName, RemoveWithForce, RemoveWithRetries) err := RemoveDevice(testPoolName, RemoveWithForce, RemoveWithRetries)
assert.NilError(t, err, "failed to remove thin-pool") assert.Nil(t, err, "failed to remove thin-pool")
}) })
t.Run("Version", testVersion) t.Run("Version", testVersion)
@ -90,116 +88,116 @@ func TestDMSetup(t *testing.T) {
func testCreateDevice(t *testing.T) { func testCreateDevice(t *testing.T) {
err := CreateDevice(testPoolName, deviceID) err := CreateDevice(testPoolName, deviceID)
assert.NilError(t, err, "failed to create test device") assert.Nil(t, err, "failed to create test device")
err = CreateDevice(testPoolName, deviceID) err = CreateDevice(testPoolName, deviceID)
assert.Assert(t, err == unix.EEXIST) assert.True(t, err == unix.EEXIST)
infos, err := Info(testPoolName) infos, err := Info(testPoolName)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, is.Len(infos, 1), "got unexpected number of device infos") assert.Len(t, infos, 1, "got unexpected number of device infos")
} }
func testCreateSnapshot(t *testing.T) { func testCreateSnapshot(t *testing.T) {
err := CreateSnapshot(testPoolName, snapshotID, deviceID) err := CreateSnapshot(testPoolName, snapshotID, deviceID)
assert.NilError(t, err) assert.NoError(t, err)
} }
func testDeleteSnapshot(t *testing.T) { func testDeleteSnapshot(t *testing.T) {
err := DeleteDevice(testPoolName, snapshotID) err := DeleteDevice(testPoolName, snapshotID)
assert.NilError(t, err, "failed to send delete message") assert.Nil(t, err, "failed to send delete message")
err = DeleteDevice(testPoolName, snapshotID) err = DeleteDevice(testPoolName, snapshotID)
assert.Assert(t, err == unix.ENODATA) assert.Equal(t, err, unix.ENODATA)
} }
func testActivateDevice(t *testing.T) { func testActivateDevice(t *testing.T) {
err := ActivateDevice(testPoolName, testDeviceName, 1, 1024, "") err := ActivateDevice(testPoolName, testDeviceName, 1, 1024, "")
assert.NilError(t, err, "failed to activate device") assert.Nil(t, err, "failed to activate device")
err = ActivateDevice(testPoolName, testDeviceName, 1, 1024, "") err = ActivateDevice(testPoolName, testDeviceName, 1, 1024, "")
assert.Equal(t, err, unix.EBUSY) assert.Equal(t, err, unix.EBUSY)
if _, err := os.Stat("/dev/mapper/" + testDeviceName); err != nil && !os.IsExist(err) { if _, err := os.Stat("/dev/mapper/" + testDeviceName); err != nil && !os.IsExist(err) {
assert.NilError(t, err, "failed to stat device") assert.Nil(t, err, "failed to stat device")
} }
list, err := Info(testPoolName) list, err := Info(testPoolName)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, is.Len(list, 1)) assert.Len(t, list, 1)
info := list[0] info := list[0]
assert.Equal(t, testPoolName, info.Name) assert.Equal(t, testPoolName, info.Name)
assert.Assert(t, info.TableLive) assert.True(t, info.TableLive)
} }
func testDeviceStatus(t *testing.T) { func testDeviceStatus(t *testing.T) {
status, err := Status(testDeviceName) status, err := Status(testDeviceName)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(0), status.Offset) assert.Equal(t, int64(0), status.Offset)
assert.Equal(t, int64(2), status.Length) assert.Equal(t, int64(2), status.Length)
assert.Equal(t, "thin", status.Target) assert.Equal(t, "thin", status.Target)
assert.DeepEqual(t, status.Params, []string{"0", "-"}) assert.Equal(t, status.Params, []string{"0", "-"})
} }
func testSuspendResumeDevice(t *testing.T) { func testSuspendResumeDevice(t *testing.T) {
err := SuspendDevice(testDeviceName) err := SuspendDevice(testDeviceName)
assert.NilError(t, err) assert.NoError(t, err)
err = SuspendDevice(testDeviceName) err = SuspendDevice(testDeviceName)
assert.NilError(t, err) assert.NoError(t, err)
list, err := Info(testDeviceName) list, err := Info(testDeviceName)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, is.Len(list, 1)) assert.Len(t, list, 1)
info := list[0] info := list[0]
assert.Assert(t, info.Suspended) assert.True(t, info.Suspended)
err = ResumeDevice(testDeviceName) err = ResumeDevice(testDeviceName)
assert.NilError(t, err) assert.NoError(t, err)
err = ResumeDevice(testDeviceName) err = ResumeDevice(testDeviceName)
assert.NilError(t, err) assert.NoError(t, err)
} }
func testDiscardBlocks(t *testing.T) { func testDiscardBlocks(t *testing.T) {
err := DiscardBlocks(testDeviceName) err := DiscardBlocks(testDeviceName)
assert.NilError(t, err, "failed to discard blocks") assert.Nil(t, err, "failed to discard blocks")
} }
func testRemoveDevice(t *testing.T) { func testRemoveDevice(t *testing.T) {
err := RemoveDevice(testPoolName) err := RemoveDevice(testPoolName)
assert.Assert(t, err == unix.EBUSY, "removing thin-pool with dependencies shouldn't be allowed") assert.Equal(t, err, unix.EBUSY, "removing thin-pool with dependencies shouldn't be allowed")
err = RemoveDevice(testDeviceName, RemoveWithRetries) err = RemoveDevice(testDeviceName, RemoveWithRetries)
assert.NilError(t, err, "failed to remove thin-device") assert.Nil(t, err, "failed to remove thin-device")
} }
func testVersion(t *testing.T) { func testVersion(t *testing.T) {
version, err := Version() version, err := Version()
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, version != "") assert.NotEmpty(t, version)
} }
func createLoopbackDevice(t *testing.T, dir string) (string, string) { func createLoopbackDevice(t *testing.T, dir string) (string, string) {
file, err := os.CreateTemp(dir, "dmsetup-tests-") file, err := os.CreateTemp(dir, "dmsetup-tests-")
assert.NilError(t, err) assert.NoError(t, err)
size, err := units.RAMInBytes("16Mb") size, err := units.RAMInBytes("16Mb")
assert.NilError(t, err) assert.NoError(t, err)
err = file.Truncate(size) err = file.Truncate(size)
assert.NilError(t, err) assert.NoError(t, err)
err = file.Close() err = file.Close()
assert.NilError(t, err) assert.NoError(t, err)
imagePath := file.Name() imagePath := file.Name()
loopDevice, err := mount.AttachLoopDevice(imagePath) loopDevice, err := mount.AttachLoopDevice(imagePath)
assert.NilError(t, err) assert.NoError(t, err)
return imagePath, loopDevice return imagePath, loopDevice
} }

View File

@ -26,9 +26,8 @@ import (
"strconv" "strconv"
"testing" "testing"
"github.com/stretchr/testify/assert"
"go.etcd.io/bbolt" "go.etcd.io/bbolt"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
) )
var ( var (
@ -47,16 +46,16 @@ func TestPoolMetadata_AddDevice(t *testing.T) {
} }
err := store.AddDevice(testCtx, expected) err := store.AddDevice(testCtx, expected)
assert.NilError(t, err) assert.NoError(t, err)
result, err := store.GetDevice(testCtx, "test2") result, err := store.GetDevice(testCtx, "test2")
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, expected.Name, result.Name) assert.Equal(t, expected.Name, result.Name)
assert.Equal(t, expected.ParentName, result.ParentName) assert.Equal(t, expected.ParentName, result.ParentName)
assert.Equal(t, expected.Size, result.Size) assert.Equal(t, expected.Size, result.Size)
assert.Equal(t, expected.State, result.State) assert.Equal(t, expected.State, result.State)
assert.Assert(t, result.DeviceID != 0) assert.NotZero(t, result.DeviceID, 0)
assert.Equal(t, expected.DeviceID, result.DeviceID) assert.Equal(t, expected.DeviceID, result.DeviceID)
} }
@ -65,7 +64,7 @@ func TestPoolMetadata_AddDeviceRollback(t *testing.T) {
defer cleanupStore(t, store) defer cleanupStore(t, store)
err := store.AddDevice(testCtx, &DeviceInfo{Name: ""}) err := store.AddDevice(testCtx, &DeviceInfo{Name: ""})
assert.Assert(t, err != nil) assert.True(t, err != nil)
_, err = store.GetDevice(testCtx, "") _, err = store.GetDevice(testCtx, "")
assert.Equal(t, ErrNotFound, err) assert.Equal(t, ErrNotFound, err)
@ -76,10 +75,10 @@ func TestPoolMetadata_AddDeviceDuplicate(t *testing.T) {
defer cleanupStore(t, store) defer cleanupStore(t, store)
err := store.AddDevice(testCtx, &DeviceInfo{Name: "test"}) err := store.AddDevice(testCtx, &DeviceInfo{Name: "test"})
assert.NilError(t, err) assert.NoError(t, err)
err = store.AddDevice(testCtx, &DeviceInfo{Name: "test"}) err = store.AddDevice(testCtx, &DeviceInfo{Name: "test"})
assert.Assert(t, errors.Is(err, ErrAlreadyExists)) assert.True(t, errors.Is(err, ErrAlreadyExists))
} }
func TestPoolMetadata_ReuseDeviceID(t *testing.T) { func TestPoolMetadata_ReuseDeviceID(t *testing.T) {
@ -88,21 +87,21 @@ func TestPoolMetadata_ReuseDeviceID(t *testing.T) {
info1 := &DeviceInfo{Name: "test1"} info1 := &DeviceInfo{Name: "test1"}
err := store.AddDevice(testCtx, info1) err := store.AddDevice(testCtx, info1)
assert.NilError(t, err) assert.NoError(t, err)
info2 := &DeviceInfo{Name: "test2"} info2 := &DeviceInfo{Name: "test2"}
err = store.AddDevice(testCtx, info2) err = store.AddDevice(testCtx, info2)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, info1.DeviceID != info2.DeviceID) assert.NotEqual(t, info1.DeviceID, info2.DeviceID)
assert.Assert(t, info1.DeviceID != 0) assert.NotZero(t, info1.DeviceID)
err = store.RemoveDevice(testCtx, info2.Name) err = store.RemoveDevice(testCtx, info2.Name)
assert.NilError(t, err) assert.NoError(t, err)
info3 := &DeviceInfo{Name: "test3"} info3 := &DeviceInfo{Name: "test3"}
err = store.AddDevice(testCtx, info3) err = store.AddDevice(testCtx, info3)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, info2.DeviceID, info3.DeviceID) assert.Equal(t, info2.DeviceID, info3.DeviceID)
} }
@ -112,10 +111,10 @@ func TestPoolMetadata_RemoveDevice(t *testing.T) {
defer cleanupStore(t, store) defer cleanupStore(t, store)
err := store.AddDevice(testCtx, &DeviceInfo{Name: "test"}) err := store.AddDevice(testCtx, &DeviceInfo{Name: "test"})
assert.NilError(t, err) assert.NoError(t, err)
err = store.RemoveDevice(testCtx, "test") err = store.RemoveDevice(testCtx, "test")
assert.NilError(t, err) assert.NoError(t, err)
_, err = store.GetDevice(testCtx, "test") _, err = store.GetDevice(testCtx, "test")
assert.Equal(t, ErrNotFound, err) assert.Equal(t, ErrNotFound, err)
@ -133,7 +132,7 @@ func TestPoolMetadata_UpdateDevice(t *testing.T) {
} }
err := store.AddDevice(testCtx, oldInfo) err := store.AddDevice(testCtx, oldInfo)
assert.NilError(t, err) assert.NoError(t, err)
err = store.UpdateDevice(testCtx, oldInfo.Name, func(info *DeviceInfo) error { err = store.UpdateDevice(testCtx, oldInfo.Name, func(info *DeviceInfo) error {
info.ParentName = "test5" info.ParentName = "test5"
@ -142,14 +141,14 @@ func TestPoolMetadata_UpdateDevice(t *testing.T) {
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
newInfo, err := store.GetDevice(testCtx, "test1") newInfo, err := store.GetDevice(testCtx, "test1")
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, "test1", newInfo.Name) assert.Equal(t, "test1", newInfo.Name)
assert.Equal(t, "test5", newInfo.ParentName) assert.Equal(t, "test5", newInfo.ParentName)
assert.Assert(t, newInfo.Size == 6) assert.EqualValues(t, newInfo.Size, 6)
assert.Equal(t, Created, newInfo.State) assert.Equal(t, Created, newInfo.State)
} }
@ -159,15 +158,15 @@ func TestPoolMetadata_MarkFaulty(t *testing.T) {
info := &DeviceInfo{Name: "test"} info := &DeviceInfo{Name: "test"}
err := store.AddDevice(testCtx, info) err := store.AddDevice(testCtx, info)
assert.NilError(t, err) assert.NoError(t, err)
err = store.MarkFaulty(testCtx, "test") err = store.MarkFaulty(testCtx, "test")
assert.NilError(t, err) assert.NoError(t, err)
saved, err := store.GetDevice(testCtx, info.Name) saved, err := store.GetDevice(testCtx, info.Name)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, saved.State, Faulty) assert.Equal(t, saved.State, Faulty)
assert.Assert(t, saved.DeviceID > 0) assert.True(t, saved.DeviceID > 0)
// Make sure a device ID marked as faulty as well // Make sure a device ID marked as faulty as well
err = store.db.View(func(tx *bbolt.Tx) error { err = store.db.View(func(tx *bbolt.Tx) error {
@ -177,7 +176,7 @@ func TestPoolMetadata_MarkFaulty(t *testing.T) {
assert.Equal(t, value[0], byte(deviceFaulty)) assert.Equal(t, value[0], byte(deviceFaulty))
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
} }
func TestPoolMetadata_WalkDevices(t *testing.T) { func TestPoolMetadata_WalkDevices(t *testing.T) {
@ -185,10 +184,10 @@ func TestPoolMetadata_WalkDevices(t *testing.T) {
defer cleanupStore(t, store) defer cleanupStore(t, store)
err := store.AddDevice(testCtx, &DeviceInfo{Name: "device1", DeviceID: 1, State: Created}) err := store.AddDevice(testCtx, &DeviceInfo{Name: "device1", DeviceID: 1, State: Created})
assert.NilError(t, err) assert.NoError(t, err)
err = store.AddDevice(testCtx, &DeviceInfo{Name: "device2", DeviceID: 2, State: Faulty}) err = store.AddDevice(testCtx, &DeviceInfo{Name: "device2", DeviceID: 2, State: Faulty})
assert.NilError(t, err) assert.NoError(t, err)
called := 0 called := 0
err = store.WalkDevices(testCtx, func(info *DeviceInfo) error { err = store.WalkDevices(testCtx, func(info *DeviceInfo) error {
@ -208,7 +207,7 @@ func TestPoolMetadata_WalkDevices(t *testing.T) {
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, called, 2) assert.Equal(t, called, 2)
} }
@ -217,14 +216,14 @@ func TestPoolMetadata_GetDeviceNames(t *testing.T) {
defer cleanupStore(t, store) defer cleanupStore(t, store)
err := store.AddDevice(testCtx, &DeviceInfo{Name: "test1"}) err := store.AddDevice(testCtx, &DeviceInfo{Name: "test1"})
assert.NilError(t, err) assert.NoError(t, err)
err = store.AddDevice(testCtx, &DeviceInfo{Name: "test2"}) err = store.AddDevice(testCtx, &DeviceInfo{Name: "test2"})
assert.NilError(t, err) assert.NoError(t, err)
names, err := store.GetDeviceNames(testCtx) names, err := store.GetDeviceNames(testCtx)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, is.Len(names, 2)) assert.Len(t, names, 2)
assert.Equal(t, "test1", names[0]) assert.Equal(t, "test1", names[0])
assert.Equal(t, "test2", names[1]) assert.Equal(t, "test2", names[1])
@ -233,12 +232,12 @@ func TestPoolMetadata_GetDeviceNames(t *testing.T) {
func createStore(t *testing.T) (store *PoolMetadata) { func createStore(t *testing.T) (store *PoolMetadata) {
path := filepath.Join(t.TempDir(), "test.db") path := filepath.Join(t.TempDir(), "test.db")
metadata, err := NewPoolMetadata(path) metadata, err := NewPoolMetadata(path)
assert.NilError(t, err) assert.NoError(t, err)
return metadata return metadata
} }
func cleanupStore(t *testing.T, store *PoolMetadata) { func cleanupStore(t *testing.T, store *PoolMetadata) {
err := store.Close() err := store.Close()
assert.NilError(t, err, "failed to close metadata store") assert.Nil(t, err, "failed to close metadata store")
} }

View File

@ -32,8 +32,8 @@ import (
"github.com/containerd/containerd/snapshots/devmapper/dmsetup" "github.com/containerd/containerd/snapshots/devmapper/dmsetup"
"github.com/docker/go-units" "github.com/docker/go-units"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
exec "golang.org/x/sys/execabs" exec "golang.org/x/sys/execabs"
"gotest.tools/v3/assert"
) )
const ( const (
@ -68,12 +68,12 @@ func TestPoolDevice(t *testing.T) {
poolName := fmt.Sprintf("test-pool-device-%d", time.Now().Nanosecond()) poolName := fmt.Sprintf("test-pool-device-%d", time.Now().Nanosecond())
err := dmsetup.CreatePool(poolName, loopDataDevice, loopMetaDevice, 64*1024/dmsetup.SectorSize) err := dmsetup.CreatePool(poolName, loopDataDevice, loopMetaDevice, 64*1024/dmsetup.SectorSize)
assert.NilError(t, err, "failed to create pool %q", poolName) assert.Nil(t, err, "failed to create pool %q", poolName)
defer func() { defer func() {
// Detach loop devices and remove images // Detach loop devices and remove images
err := mount.DetachLoopDevice(loopDataDevice, loopMetaDevice) err := mount.DetachLoopDevice(loopDataDevice, loopMetaDevice)
assert.NilError(t, err) assert.NoError(t, err)
}() }()
config := &Config{ config := &Config{
@ -85,12 +85,12 @@ func TestPoolDevice(t *testing.T) {
} }
pool, err := NewPoolDevice(ctx, config) pool, err := NewPoolDevice(ctx, config)
assert.NilError(t, err, "can't create device pool") assert.Nil(t, err, "can't create device pool")
assert.Assert(t, pool != nil) assert.True(t, pool != nil)
defer func() { defer func() {
err := pool.RemovePool(ctx) err := pool.RemovePool(ctx)
assert.NilError(t, err, "can't close device pool") assert.Nil(t, err, "can't close device pool")
}() }()
// Create thin devices // Create thin devices
@ -108,7 +108,7 @@ func TestPoolDevice(t *testing.T) {
// Write v1 test file on 'thin-1' device // Write v1 test file on 'thin-1' device
thin1TestFilePath := filepath.Join(thin1MountPath, "TEST") thin1TestFilePath := filepath.Join(thin1MountPath, "TEST")
err := os.WriteFile(thin1TestFilePath, []byte("test file (v1)"), 0700) err := os.WriteFile(thin1TestFilePath, []byte("test file (v1)"), 0700)
assert.NilError(t, err, "failed to write test file v1 on '%s' volume", thinDevice1) assert.Nil(t, err, "failed to write test file v1 on '%s' volume", thinDevice1)
return nil return nil
}) })
@ -122,24 +122,24 @@ func TestPoolDevice(t *testing.T) {
err = mount.WithTempMount(ctx, getMounts(thinDevice1), func(thin1MountPath string) error { err = mount.WithTempMount(ctx, getMounts(thinDevice1), func(thin1MountPath string) error {
thin1TestFilePath := filepath.Join(thin1MountPath, "TEST") thin1TestFilePath := filepath.Join(thin1MountPath, "TEST")
err = os.WriteFile(thin1TestFilePath, []byte("test file (v2)"), 0700) err = os.WriteFile(thin1TestFilePath, []byte("test file (v2)"), 0700)
assert.NilError(t, err, "failed to write test file v2 on 'thin-1' volume after taking snapshot") assert.Nil(t, err, "failed to write test file v2 on 'thin-1' volume after taking snapshot")
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
// Mount 'snap-1' and make sure TEST file is v1 // Mount 'snap-1' and make sure TEST file is v1
err = mount.WithTempMount(ctx, getMounts(snapDevice1), func(snap1MountPath string) error { err = mount.WithTempMount(ctx, getMounts(snapDevice1), func(snap1MountPath string) error {
// Read test file from snapshot device and make sure it's v1 // Read test file from snapshot device and make sure it's v1
fileData, err := os.ReadFile(filepath.Join(snap1MountPath, "TEST")) fileData, err := os.ReadFile(filepath.Join(snap1MountPath, "TEST"))
assert.NilError(t, err, "couldn't read test file from '%s' device", snapDevice1) assert.Nil(t, err, "couldn't read test file from '%s' device", snapDevice1)
assert.Equal(t, "test file (v1)", string(fileData), "test file content is invalid on snapshot") assert.Equal(t, "test file (v1)", string(fileData), "test file content is invalid on snapshot")
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
t.Run("DeactivateDevice", func(t *testing.T) { t.Run("DeactivateDevice", func(t *testing.T) {
testDeactivateThinDevice(t, pool) testDeactivateThinDevice(t, pool)
@ -157,17 +157,17 @@ func TestPoolDevice(t *testing.T) {
snapDevice := "snap2" snapDevice := "snap2"
err := pool.CreateSnapshotDevice(ctx, thinDevice1, snapDevice, device1Size) err := pool.CreateSnapshotDevice(ctx, thinDevice1, snapDevice, device1Size)
assert.NilError(t, err) assert.NoError(t, err)
info, err := pool.metadata.GetDevice(ctx, snapDevice) info, err := pool.metadata.GetDevice(ctx, snapDevice)
assert.NilError(t, err) assert.NoError(t, err)
// Simulate a case that the device cannot be activated. // Simulate a case that the device cannot be activated.
err = pool.DeactivateDevice(ctx, info.Name, false, false) err = pool.DeactivateDevice(ctx, info.Name, false, false)
assert.NilError(t, err) assert.NoError(t, err)
err = pool.rollbackActivate(ctx, info, err) err = pool.rollbackActivate(ctx, info, err)
assert.NilError(t, err) assert.NoError(t, err)
}) })
} }
@ -176,16 +176,16 @@ func TestPoolDeviceMarkFaulty(t *testing.T) {
defer cleanupStore(t, store) defer cleanupStore(t, store)
err := store.AddDevice(testCtx, &DeviceInfo{Name: "1", State: Unknown}) err := store.AddDevice(testCtx, &DeviceInfo{Name: "1", State: Unknown})
assert.NilError(t, err) assert.NoError(t, err)
// Note: do not use 'Activated' here because pool.ensureDeviceStates() will // Note: do not use 'Activated' here because pool.ensureDeviceStates() will
// try to activate the real dm device, which will fail on a faked device. // try to activate the real dm device, which will fail on a faked device.
err = store.AddDevice(testCtx, &DeviceInfo{Name: "2", State: Deactivated}) err = store.AddDevice(testCtx, &DeviceInfo{Name: "2", State: Deactivated})
assert.NilError(t, err) assert.NoError(t, err)
pool := &PoolDevice{metadata: store} pool := &PoolDevice{metadata: store}
err = pool.ensureDeviceStates(testCtx) err = pool.ensureDeviceStates(testCtx)
assert.NilError(t, err) assert.NoError(t, err)
called := 0 called := 0
err = pool.metadata.WalkDevices(testCtx, func(info *DeviceInfo) error { err = pool.metadata.WalkDevices(testCtx, func(info *DeviceInfo) error {
@ -204,7 +204,7 @@ func TestPoolDeviceMarkFaulty(t *testing.T) {
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, 2, called) assert.Equal(t, 2, called)
} }
@ -212,24 +212,24 @@ func testCreateThinDevice(t *testing.T, pool *PoolDevice) {
ctx := context.Background() ctx := context.Background()
err := pool.CreateThinDevice(ctx, thinDevice1, device1Size) err := pool.CreateThinDevice(ctx, thinDevice1, device1Size)
assert.NilError(t, err, "can't create first thin device") assert.Nil(t, err, "can't create first thin device")
err = pool.CreateThinDevice(ctx, thinDevice1, device1Size) err = pool.CreateThinDevice(ctx, thinDevice1, device1Size)
assert.Assert(t, err != nil, "device pool allows duplicated device names") assert.True(t, err != nil, "device pool allows duplicated device names")
err = pool.CreateThinDevice(ctx, thinDevice2, device2Size) err = pool.CreateThinDevice(ctx, thinDevice2, device2Size)
assert.NilError(t, err, "can't create second thin device") assert.Nil(t, err, "can't create second thin device")
deviceInfo1, err := pool.metadata.GetDevice(ctx, thinDevice1) deviceInfo1, err := pool.metadata.GetDevice(ctx, thinDevice1)
assert.NilError(t, err) assert.NoError(t, err)
deviceInfo2, err := pool.metadata.GetDevice(ctx, thinDevice2) deviceInfo2, err := pool.metadata.GetDevice(ctx, thinDevice2)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, deviceInfo1.DeviceID != deviceInfo2.DeviceID, "assigned device ids should be different") assert.True(t, deviceInfo1.DeviceID != deviceInfo2.DeviceID, "assigned device ids should be different")
usage, err := pool.GetUsage(thinDevice1) usage, err := pool.GetUsage(thinDevice1)
assert.NilError(t, err) assert.NoError(t, err)
assert.Equal(t, usage, int64(0)) assert.Equal(t, usage, int64(0))
} }
@ -242,16 +242,16 @@ func testMakeFileSystem(t *testing.T, pool *PoolDevice) {
} }
output, err := exec.Command("mkfs.ext4", args...).CombinedOutput() output, err := exec.Command("mkfs.ext4", args...).CombinedOutput()
assert.NilError(t, err, "failed to make filesystem on '%s': %s", thinDevice1, string(output)) assert.Nil(t, err, "failed to make filesystem on '%s': %s", thinDevice1, string(output))
usage, err := pool.GetUsage(thinDevice1) usage, err := pool.GetUsage(thinDevice1)
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, usage > 0) assert.True(t, usage > 0)
} }
func testCreateSnapshot(t *testing.T, pool *PoolDevice) { func testCreateSnapshot(t *testing.T, pool *PoolDevice) {
err := pool.CreateSnapshotDevice(context.Background(), thinDevice1, snapDevice1, device1Size) err := pool.CreateSnapshotDevice(context.Background(), thinDevice1, snapDevice1, device1Size)
assert.NilError(t, err, "failed to create snapshot from '%s' volume", thinDevice1) assert.Nil(t, err, "failed to create snapshot from '%s' volume", thinDevice1)
} }
func testDeactivateThinDevice(t *testing.T, pool *PoolDevice) { func testDeactivateThinDevice(t *testing.T, pool *PoolDevice) {
@ -261,21 +261,21 @@ func testDeactivateThinDevice(t *testing.T, pool *PoolDevice) {
} }
for _, deviceName := range deviceList { for _, deviceName := range deviceList {
assert.Assert(t, pool.IsActivated(deviceName)) assert.True(t, pool.IsActivated(deviceName))
err := pool.DeactivateDevice(context.Background(), deviceName, false, true) err := pool.DeactivateDevice(context.Background(), deviceName, false, true)
assert.NilError(t, err, "failed to remove '%s'", deviceName) assert.Nil(t, err, "failed to remove '%s'", deviceName)
assert.Assert(t, !pool.IsActivated(deviceName)) assert.False(t, pool.IsActivated(deviceName))
} }
} }
func testRemoveThinDevice(t *testing.T, pool *PoolDevice) { func testRemoveThinDevice(t *testing.T, pool *PoolDevice) {
err := pool.RemoveDevice(testCtx, thinDevice1) err := pool.RemoveDevice(testCtx, thinDevice1)
assert.NilError(t, err, "should delete thin device from pool") assert.Nil(t, err, "should delete thin device from pool")
err = pool.RemoveDevice(testCtx, thinDevice2) err = pool.RemoveDevice(testCtx, thinDevice2)
assert.NilError(t, err, "should delete thin device from pool") assert.Nil(t, err, "should delete thin device from pool")
} }
func getMounts(thinDeviceName string) []mount.Mount { func getMounts(thinDeviceName string) []mount.Mount {
@ -289,21 +289,21 @@ func getMounts(thinDeviceName string) []mount.Mount {
func createLoopbackDevice(t *testing.T, dir string) (string, string) { func createLoopbackDevice(t *testing.T, dir string) (string, string) {
file, err := os.CreateTemp(dir, testsPrefix) file, err := os.CreateTemp(dir, testsPrefix)
assert.NilError(t, err) assert.NoError(t, err)
size, err := units.RAMInBytes("128Mb") size, err := units.RAMInBytes("128Mb")
assert.NilError(t, err) assert.NoError(t, err)
err = file.Truncate(size) err = file.Truncate(size)
assert.NilError(t, err) assert.NoError(t, err)
err = file.Close() err = file.Close()
assert.NilError(t, err) assert.NoError(t, err)
imagePath := file.Name() imagePath := file.Name()
loopDevice, err := mount.AttachLoopDevice(imagePath) loopDevice, err := mount.AttachLoopDevice(imagePath)
assert.NilError(t, err) assert.NoError(t, err)
return imagePath, loopDevice return imagePath, loopDevice
} }

View File

@ -29,7 +29,7 @@ import (
"github.com/containerd/continuity/fs/fstest" "github.com/containerd/continuity/fs/fstest"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
"github.com/containerd/containerd/mount" "github.com/containerd/containerd/mount"
"github.com/containerd/containerd/namespaces" "github.com/containerd/containerd/namespaces"
@ -61,7 +61,7 @@ func TestSnapshotterSuite(t *testing.T) {
t.Run("DevMapperUsage", func(t *testing.T) { t.Run("DevMapperUsage", func(t *testing.T) {
snapshotter, closer, err := snapshotterFn(ctx, t.TempDir()) snapshotter, closer, err := snapshotterFn(ctx, t.TempDir())
assert.NilError(t, err) assert.NoError(t, err)
defer closer() defer closer()
testUsage(t, snapshotter) testUsage(t, snapshotter)
@ -75,16 +75,16 @@ func testUsage(t *testing.T, snapshotter snapshots.Snapshotter) {
// Create empty base layer // Create empty base layer
_, err := snapshotter.Prepare(ctx, "prepare-1", "") _, err := snapshotter.Prepare(ctx, "prepare-1", "")
assert.NilError(t, err) assert.NoError(t, err)
emptyLayerUsage, err := snapshotter.Usage(ctx, "prepare-1") emptyLayerUsage, err := snapshotter.Usage(ctx, "prepare-1")
assert.NilError(t, err) assert.NoError(t, err)
// Should be > 0 as just written file system also consumes blocks // Should be > 0 as just written file system also consumes blocks
assert.Assert(t, emptyLayerUsage.Size > 0) assert.Greater(t, emptyLayerUsage.Size, int64(0))
err = snapshotter.Commit(ctx, "layer-1", "prepare-1") err = snapshotter.Commit(ctx, "layer-1", "prepare-1")
assert.NilError(t, err) assert.NoError(t, err)
// Create child layer with 1MB file // Create child layer with 1MB file
@ -94,19 +94,19 @@ func testUsage(t *testing.T, snapshotter snapshots.Snapshotter) {
) )
mounts, err := snapshotter.Prepare(ctx, "prepare-2", "layer-1") mounts, err := snapshotter.Prepare(ctx, "prepare-2", "layer-1")
assert.NilError(t, err) assert.NoError(t, err)
err = mount.WithTempMount(ctx, mounts, baseApplier.Apply) err = mount.WithTempMount(ctx, mounts, baseApplier.Apply)
assert.NilError(t, err) assert.NoError(t, err)
err = snapshotter.Commit(ctx, "layer-2", "prepare-2") err = snapshotter.Commit(ctx, "layer-2", "prepare-2")
assert.NilError(t, err) assert.NoError(t, err)
layer2Usage, err := snapshotter.Usage(ctx, "layer-2") layer2Usage, err := snapshotter.Usage(ctx, "layer-2")
assert.NilError(t, err) assert.NoError(t, err)
// Should be at least 1 MB + fs metadata // Should be at least 1 MB + fs metadata
assert.Check(t, layer2Usage.Size >= sizeBytes, assert.GreaterOrEqual(t, layer2Usage.Size, sizeBytes,
"%d > %d", layer2Usage.Size, sizeBytes) "%d > %d", layer2Usage.Size, sizeBytes)
} }
@ -114,26 +114,26 @@ func TestMkfsExt4(t *testing.T) {
ctx := context.Background() ctx := context.Background()
// We test the default setting which is lazy init is disabled // We test the default setting which is lazy init is disabled
err := mkfs(ctx, "ext4", "nodiscard,lazy_itable_init=0,lazy_journal_init=0", "") err := mkfs(ctx, "ext4", "nodiscard,lazy_itable_init=0,lazy_journal_init=0", "")
assert.ErrorContains(t, err, `mkfs.ext4 couldn't initialize ""`) assert.Contains(t, err.Error(), `mkfs.ext4 couldn't initialize ""`)
} }
func TestMkfsExt4NonDefault(t *testing.T) { func TestMkfsExt4NonDefault(t *testing.T) {
ctx := context.Background() ctx := context.Background()
// We test a non default setting where we enable lazy init for ext4 // We test a non default setting where we enable lazy init for ext4
err := mkfs(ctx, "ext4", "nodiscard", "") err := mkfs(ctx, "ext4", "nodiscard", "")
assert.ErrorContains(t, err, `mkfs.ext4 couldn't initialize ""`) assert.Contains(t, err.Error(), `mkfs.ext4 couldn't initialize ""`)
} }
func TestMkfsXfs(t *testing.T) { func TestMkfsXfs(t *testing.T) {
ctx := context.Background() ctx := context.Background()
err := mkfs(ctx, "xfs", "", "") err := mkfs(ctx, "xfs", "", "")
assert.ErrorContains(t, err, `mkfs.xfs couldn't initialize ""`) assert.Contains(t, err.Error(), `mkfs.xfs couldn't initialize ""`)
} }
func TestMkfsXfsNonDefault(t *testing.T) { func TestMkfsXfsNonDefault(t *testing.T) {
ctx := context.Background() ctx := context.Background()
err := mkfs(ctx, "xfs", "noquota", "") err := mkfs(ctx, "xfs", "noquota", "")
assert.ErrorContains(t, err, `mkfs.xfs couldn't initialize ""`) assert.Contains(t, err.Error(), `mkfs.xfs couldn't initialize ""`)
} }
func TestMultipleXfsMounts(t *testing.T) { func TestMultipleXfsMounts(t *testing.T) {
@ -152,7 +152,7 @@ func TestMultipleXfsMounts(t *testing.T) {
FileSystemType: "xfs", FileSystemType: "xfs",
} }
snapshotter, closer, err := createSnapshotter(ctx, t, config) snapshotter, closer, err := createSnapshotter(ctx, t, config)
assert.NilError(t, err) assert.NoError(t, err)
defer closer() defer closer()
var ( var (
@ -162,27 +162,27 @@ func TestMultipleXfsMounts(t *testing.T) {
// Create base layer // Create base layer
mounts, err := snapshotter.Prepare(ctx, "prepare-1", "") mounts, err := snapshotter.Prepare(ctx, "prepare-1", "")
assert.NilError(t, err) assert.NoError(t, err)
root1 := t.TempDir() root1 := t.TempDir()
defer func() { defer func() {
mount.UnmountAll(root1, 0) mount.UnmountAll(root1, 0)
}() }()
err = mount.All(mounts, root1) err = mount.All(mounts, root1)
assert.NilError(t, err) assert.NoError(t, err)
baseApplier.Apply(root1) baseApplier.Apply(root1)
snapshotter.Commit(ctx, "layer-1", "prepare-1") snapshotter.Commit(ctx, "layer-1", "prepare-1")
// Create one child layer // Create one child layer
mounts, err = snapshotter.Prepare(ctx, "prepare-2", "layer-1") mounts, err = snapshotter.Prepare(ctx, "prepare-2", "layer-1")
assert.NilError(t, err) assert.NoError(t, err)
root2 := t.TempDir() root2 := t.TempDir()
defer func() { defer func() {
mount.UnmountAll(root2, 0) mount.UnmountAll(root2, 0)
}() }()
err = mount.All(mounts, root2) err = mount.All(mounts, root2)
assert.NilError(t, err) assert.NoError(t, err)
} }
func createSnapshotter(ctx context.Context, t *testing.T, config *Config) (snapshots.Snapshotter, func() error, error) { func createSnapshotter(ctx context.Context, t *testing.T, config *Config) (snapshots.Snapshotter, func() error, error) {
@ -191,7 +191,7 @@ func createSnapshotter(ctx context.Context, t *testing.T, config *Config) (snaps
_, loopMetaDevice := createLoopbackDevice(t, config.RootPath) _, loopMetaDevice := createLoopbackDevice(t, config.RootPath)
err := dmsetup.CreatePool(config.PoolName, loopDataDevice, loopMetaDevice, 64*1024/dmsetup.SectorSize) err := dmsetup.CreatePool(config.PoolName, loopDataDevice, loopMetaDevice, 64*1024/dmsetup.SectorSize)
assert.NilError(t, err, "failed to create pool %q", config.PoolName) assert.Nil(t, err, "failed to create pool %q", config.PoolName)
snap, err := NewSnapshotter(ctx, config) snap, err := NewSnapshotter(ctx, config)
if err != nil { if err != nil {

View File

@ -26,8 +26,7 @@ import (
"github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/snapshots" "github.com/containerd/containerd/snapshots"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
is "gotest.tools/v3/assert/cmp"
) )
type testFunc func(context.Context, *testing.T, *MetaStore) type testFunc func(context.Context, *testing.T, *MetaStore)
@ -214,29 +213,29 @@ var baseInfo = map[string]snapshots.Info{
func assertNotExist(t *testing.T, err error) { func assertNotExist(t *testing.T, err error) {
t.Helper() t.Helper()
assert.Assert(t, errdefs.IsNotFound(err), "got %+v", err) assert.True(t, errdefs.IsNotFound(err), "got %+v", err)
} }
func assertNotActive(t *testing.T, err error) { func assertNotActive(t *testing.T, err error) {
t.Helper() t.Helper()
assert.Assert(t, errdefs.IsFailedPrecondition(err), "got %+v", err) assert.True(t, errdefs.IsFailedPrecondition(err), "got %+v", err)
} }
func assertNotCommitted(t *testing.T, err error) { func assertNotCommitted(t *testing.T, err error) {
t.Helper() t.Helper()
assert.Assert(t, errdefs.IsInvalidArgument(err), "got %+v", err) assert.True(t, errdefs.IsInvalidArgument(err), "got %+v", err)
} }
func assertExist(t *testing.T, err error) { func assertExist(t *testing.T, err error) {
t.Helper() t.Helper()
assert.Assert(t, errdefs.IsAlreadyExists(err), "got %+v", err) assert.True(t, errdefs.IsAlreadyExists(err), "got %+v", err)
} }
func testGetInfo(ctx context.Context, t *testing.T, _ *MetaStore) { func testGetInfo(ctx context.Context, t *testing.T, _ *MetaStore) {
for key, expected := range baseInfo { for key, expected := range baseInfo {
_, info, _, err := GetInfo(ctx, key) _, info, _, err := GetInfo(ctx, key)
assert.NilError(t, err, "on key %v", key) assert.Nil(t, err, "on key %v", key)
assert.Check(t, is.DeepEqual(expected, info, cmpSnapshotInfo), "on key %v", key) assert.Truef(t, cmp.Equal(expected, info, cmpSnapshotInfo), "on key %v", key)
} }
} }
@ -276,8 +275,8 @@ func testWalk(ctx context.Context, t *testing.T, _ *MetaStore) {
found[info.Name] = info found[info.Name] = info
return nil return nil
}) })
assert.NilError(t, err) assert.NoError(t, err)
assert.Assert(t, is.DeepEqual(baseInfo, found, cmpSnapshotInfo)) assert.True(t, cmp.Equal(baseInfo, found, cmpSnapshotInfo))
} }
func testGetSnapshot(ctx context.Context, t *testing.T, ms *MetaStore) { func testGetSnapshot(ctx context.Context, t *testing.T, ms *MetaStore) {
@ -326,8 +325,8 @@ func testGetSnapshot(ctx context.Context, t *testing.T, ms *MetaStore) {
test := func(ctx context.Context, t *testing.T, ms *MetaStore) { test := func(ctx context.Context, t *testing.T, ms *MetaStore) {
for key, expected := range snapshotMap { for key, expected := range snapshotMap {
s, err := GetSnapshot(ctx, key) s, err := GetSnapshot(ctx, key)
assert.NilError(t, err, "failed to get snapshot %s", key) assert.Nil(t, err, "failed to get snapshot %s", key)
assert.Check(t, is.DeepEqual(expected, s), "on key %s", key) assert.Equalf(t, expected, s, "on key %s", key)
} }
} }

View File

@ -35,8 +35,7 @@ import (
"github.com/containerd/containerd/pkg/testutil" "github.com/containerd/containerd/pkg/testutil"
"github.com/containerd/containerd/snapshots" "github.com/containerd/containerd/snapshots"
"github.com/containerd/continuity/fs/fstest" "github.com/containerd/continuity/fs/fstest"
"gotest.tools/v3/assert" "github.com/stretchr/testify/assert"
is "gotest.tools/v3/assert/cmp"
) )
// SnapshotterFunc is used in SnapshotterSuite // SnapshotterFunc is used in SnapshotterSuite
@ -173,8 +172,8 @@ func checkSnapshotterBasic(ctx context.Context, t *testing.T, snapshotter snapsh
t.Fatalf("failure reason: %+v", err) t.Fatalf("failure reason: %+v", err)
} }
assert.Check(t, is.Equal("", si.Parent)) assert.Empty(t, si.Parent)
assert.Check(t, is.Equal(snapshots.KindCommitted, si.Kind)) assert.Equal(t, snapshots.KindCommitted, si.Kind)
_, err = snapshotter.Stat(ctx, preparing) _, err = snapshotter.Stat(ctx, preparing)
if err == nil { if err == nil {
@ -209,8 +208,8 @@ func checkSnapshotterBasic(ctx context.Context, t *testing.T, snapshotter snapsh
t.Fatal(err) t.Fatal(err)
} }
assert.Check(t, is.Equal(committed, ni.Parent)) assert.Equal(t, committed, ni.Parent)
assert.Check(t, is.Equal(snapshots.KindActive, ni.Kind)) assert.Equal(t, snapshots.KindActive, ni.Kind)
nextCommitted := filepath.Join(work, "committed-next") nextCommitted := filepath.Join(work, "committed-next")
if err := snapshotter.Commit(ctx, nextCommitted, next, opt); err != nil { if err := snapshotter.Commit(ctx, nextCommitted, next, opt); err != nil {
@ -222,8 +221,8 @@ func checkSnapshotterBasic(ctx context.Context, t *testing.T, snapshotter snapsh
t.Fatalf("failure reason: %+v", err) t.Fatalf("failure reason: %+v", err)
} }
assert.Check(t, is.Equal(committed, si2.Parent)) assert.Equal(t, committed, si2.Parent)
assert.Check(t, is.Equal(snapshots.KindCommitted, si2.Kind)) assert.Equal(t, snapshots.KindCommitted, si2.Kind)
_, err = snapshotter.Stat(ctx, next) _, err = snapshotter.Stat(ctx, next)
if err == nil { if err == nil {
@ -235,7 +234,7 @@ func checkSnapshotterBasic(ctx context.Context, t *testing.T, snapshotter snapsh
si2.Name: si2, si2.Name: si2,
} }
walked := map[string]snapshots.Info{} // walk is not ordered walked := map[string]snapshots.Info{} // walk is not ordered
assert.NilError(t, snapshotter.Walk(ctx, func(ctx context.Context, si snapshots.Info) error { assert.Nil(t, snapshotter.Walk(ctx, func(ctx context.Context, si snapshots.Info) error {
walked[si.Name] = si walked[si.Name] = si
return nil return nil
})) }))
@ -246,7 +245,7 @@ func checkSnapshotterBasic(ctx context.Context, t *testing.T, snapshotter snapsh
t.Errorf("Missing stat for %v", ek) t.Errorf("Missing stat for %v", ek)
continue continue
} }
assert.Check(t, is.DeepEqual(ev, av)) assert.Equal(t, ev, av)
} }
nextnext := filepath.Join(work, "nextnextlayer") nextnext := filepath.Join(work, "nextnextlayer")
@ -269,10 +268,16 @@ func checkSnapshotterBasic(ctx context.Context, t *testing.T, snapshotter snapsh
} }
testutil.Unmount(t, nextnext) testutil.Unmount(t, nextnext)
assert.NilError(t, snapshotter.Remove(ctx, nextnext)) assert.Nil(t, snapshotter.Remove(ctx, nextnext))
assert.Assert(t, is.ErrorContains(snapshotter.Remove(ctx, committed), "remove"))
assert.NilError(t, snapshotter.Remove(ctx, nextCommitted)) err = snapshotter.Remove(ctx, committed)
assert.NilError(t, snapshotter.Remove(ctx, committed)) assert.NotNil(t, err)
if err != nil {
assert.Contains(t, err.Error(), "remove")
}
assert.Nil(t, snapshotter.Remove(ctx, nextCommitted))
assert.Nil(t, snapshotter.Remove(ctx, committed))
} }
// Create a New Layer on top of base layer with Prepare, Stat on new layer, should return Active layer. // Create a New Layer on top of base layer with Prepare, Stat on new layer, should return Active layer.
@ -304,9 +309,9 @@ func checkSnapshotterStatActive(ctx context.Context, t *testing.T, snapshotter s
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
assert.Check(t, is.Equal(si.Name, preparing)) assert.Equal(t, si.Name, preparing)
assert.Check(t, is.Equal(snapshots.KindActive, si.Kind)) assert.Equal(t, snapshots.KindActive, si.Kind)
assert.Check(t, is.Equal("", si.Parent)) assert.Equal(t, "", si.Parent)
} }
// Commit a New Layer on top of base layer with Prepare & Commit , Stat on new layer, should return Committed layer. // Commit a New Layer on top of base layer with Prepare & Commit , Stat on new layer, should return Committed layer.
@ -343,9 +348,9 @@ func checkSnapshotterStatCommitted(ctx context.Context, t *testing.T, snapshotte
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
assert.Check(t, is.Equal(si.Name, committed)) assert.Equal(t, si.Name, committed)
assert.Check(t, is.Equal(snapshots.KindCommitted, si.Kind)) assert.Equal(t, snapshots.KindCommitted, si.Kind)
assert.Check(t, is.Equal("", si.Parent)) assert.Equal(t, "", si.Parent)
} }
@ -418,9 +423,9 @@ func checkSnapshotterTransitivity(ctx context.Context, t *testing.T, snapshotter
} }
// Test the transivity // Test the transivity
assert.Check(t, is.Equal("", siA.Parent)) assert.Equal(t, "", siA.Parent)
assert.Check(t, is.Equal(snapA, siB.Parent)) assert.Equal(t, snapA, siB.Parent)
assert.Check(t, is.Equal("", siParentB.Parent)) assert.Equal(t, "", siParentB.Parent)
} }
@ -450,7 +455,7 @@ func checkSnapshotterPrepareView(ctx context.Context, t *testing.T, snapshotter
} }
_, err = snapshotter.View(ctx, newLayer, snapA, opt) _, err = snapshotter.View(ctx, newLayer, snapA, opt)
assert.Check(t, err != nil) assert.True(t, err != nil)
// Two Prepare with same key // Two Prepare with same key
prepLayer := filepath.Join(work, "prepLayer") prepLayer := filepath.Join(work, "prepLayer")
@ -464,7 +469,7 @@ func checkSnapshotterPrepareView(ctx context.Context, t *testing.T, snapshotter
} }
_, err = snapshotter.Prepare(ctx, prepLayer, snapA, opt) _, err = snapshotter.Prepare(ctx, prepLayer, snapA, opt)
assert.Check(t, err != nil) assert.True(t, err != nil)
// Two View with same key // Two View with same key
viewLayer := filepath.Join(work, "viewLayer") viewLayer := filepath.Join(work, "viewLayer")
@ -478,7 +483,7 @@ func checkSnapshotterPrepareView(ctx context.Context, t *testing.T, snapshotter
} }
_, err = snapshotter.View(ctx, viewLayer, snapA, opt) _, err = snapshotter.View(ctx, viewLayer, snapA, opt)
assert.Check(t, err != nil) assert.True(t, err != nil)
} }
@ -809,8 +814,8 @@ func checkSnapshotterViewReadonly(ctx context.Context, t *testing.T, snapshotter
t.Fatalf("write to %q should fail (EROFS) but did not fail", testfile) t.Fatalf("write to %q should fail (EROFS) but did not fail", testfile)
} }
testutil.Unmount(t, viewMountPoint) testutil.Unmount(t, viewMountPoint)
assert.NilError(t, snapshotter.Remove(ctx, view)) assert.Nil(t, snapshotter.Remove(ctx, view))
assert.NilError(t, snapshotter.Remove(ctx, committed)) assert.Nil(t, snapshotter.Remove(ctx, committed))
} }
// Move files from base layer to new location in intermediate layer. // Move files from base layer to new location in intermediate layer.

View File

@ -24,16 +24,16 @@ import (
"time" "time"
"github.com/containerd/containerd/pkg/userns" "github.com/containerd/containerd/pkg/userns"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
exec "golang.org/x/sys/execabs" exec "golang.org/x/sys/execabs"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
) )
func TestSetPositiveOomScoreAdjustment(t *testing.T) { func TestSetPositiveOomScoreAdjustment(t *testing.T) {
// Setting a *positive* OOM score adjust does not require privileged // Setting a *positive* OOM score adjust does not require privileged
_, adjustment, err := adjustOom(123) _, adjustment, err := adjustOom(123)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Equal(adjustment, 123)) assert.EqualValues(t, adjustment, 123)
} }
func TestSetNegativeOomScoreAdjustmentWhenPrivileged(t *testing.T) { func TestSetNegativeOomScoreAdjustmentWhenPrivileged(t *testing.T) {
@ -43,8 +43,8 @@ func TestSetNegativeOomScoreAdjustmentWhenPrivileged(t *testing.T) {
} }
_, adjustment, err := adjustOom(-123) _, adjustment, err := adjustOom(-123)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Equal(adjustment, -123)) assert.EqualValues(t, adjustment, -123)
} }
func TestSetNegativeOomScoreAdjustmentWhenUnprivilegedHasNoEffect(t *testing.T) { func TestSetNegativeOomScoreAdjustmentWhenUnprivilegedHasNoEffect(t *testing.T) {
@ -54,31 +54,33 @@ func TestSetNegativeOomScoreAdjustmentWhenUnprivilegedHasNoEffect(t *testing.T)
} }
initial, adjustment, err := adjustOom(-123) initial, adjustment, err := adjustOom(-123)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Equal(adjustment, initial)) assert.EqualValues(t, adjustment, initial)
} }
func TestSetOOMScoreBoundaries(t *testing.T) { func TestSetOOMScoreBoundaries(t *testing.T) {
err := SetOOMScore(0, OOMScoreAdjMax+1) err := SetOOMScore(0, OOMScoreAdjMax+1)
assert.ErrorContains(t, err, fmt.Sprintf("value out of range (%d): OOM score must be between", OOMScoreAdjMax+1)) require.NotNil(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("value out of range (%d): OOM score must be between", OOMScoreAdjMax+1))
err = SetOOMScore(0, OOMScoreAdjMin-1) err = SetOOMScore(0, OOMScoreAdjMin-1)
assert.ErrorContains(t, err, fmt.Sprintf("value out of range (%d): OOM score must be between", OOMScoreAdjMin-1)) require.NotNil(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("value out of range (%d): OOM score must be between", OOMScoreAdjMin-1))
_, adjustment, err := adjustOom(OOMScoreAdjMax) _, adjustment, err := adjustOom(OOMScoreAdjMax)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Equal(adjustment, OOMScoreAdjMax)) assert.EqualValues(t, adjustment, OOMScoreAdjMax)
score, err := GetOOMScoreAdj(os.Getpid()) score, err := GetOOMScoreAdj(os.Getpid())
assert.NilError(t, err) assert.NoError(t, err)
if score == OOMScoreAdjMin { if score == OOMScoreAdjMin {
// We won't be able to set the score lower than the parent process. This // We won't be able to set the score lower than the parent process. This
// could also be tested if the parent process does not have a oom-score-adj // could also be tested if the parent process does not have a oom-score-adj
// set, but GetOOMScoreAdj does not distinguish between "not set" and // set, but GetOOMScoreAdj does not distinguish between "not set" and
// "score is set, but zero". // "score is set, but zero".
_, adjustment, err = adjustOom(OOMScoreAdjMin) _, adjustment, err = adjustOom(OOMScoreAdjMin)
assert.NilError(t, err) assert.NoError(t, err)
assert.Check(t, is.Equal(adjustment, OOMScoreAdjMin)) assert.EqualValues(t, adjustment, OOMScoreAdjMin)
} }
} }