diff --git a/cli/internal/util_test.go b/cli/internal/util_test.go index bb4402673c..7461fa0af0 100644 --- a/cli/internal/util_test.go +++ b/cli/internal/util_test.go @@ -14,21 +14,20 @@ package internal -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestParseKeyPair(t *testing.T) { s := []string{"FOO=bar", "BAR=", "BAZ=qux=quux", "INVALID"} p := ParseKeyPair(s) - if p["FOO"] != "bar" { - t.Errorf("Wanted %q, got %q.", "bar", p["FOO"]) - } - if p["BAZ"] != "qux=quux" { - t.Errorf("Wanted %q, got %q.", "qux=quux", p["BAZ"]) - } - if _, exists := p["BAR"]; !exists { - t.Error("Missing a key with no value. Keys with empty values are also valid.") - } - if _, exists := p["INVALID"]; exists { - t.Error("Keys without an equal sign suffix are invalid.") - } + assert.Equal(t, "bar", p["FOO"]) + assert.Equal(t, "qux=quux", p["BAZ"]) + val, exists := p["BAR"] + assert.Empty(t, val) + assert.True(t, exists, "missing a key with no value, keys with empty values are also valid") + _, exists = p["INVALID"] + assert.False(t, exists, "keys without an equal sign suffix are invalid") } diff --git a/cmd/agent/config_test.go b/cmd/agent/config_test.go index 5ec38c2c13..fa21ca6b1b 100644 --- a/cmd/agent/config_test.go +++ b/cmd/agent/config_test.go @@ -28,14 +28,14 @@ func TestReadAgentIDFileNotExists(t *testing.T) { func TestReadAgentIDFileExists(t *testing.T) { tmpF, errTmpF := os.CreateTemp("", "tmp_") if !assert.NoError(t, errTmpF) { - t.FailNow() + return } defer os.Remove(tmpF.Name()) // there is an existing config errWrite := os.WriteFile(tmpF.Name(), []byte(`{"agent_id":3}`), 0o644) if !assert.NoError(t, errWrite) { - t.FailNow() + return } // read existing config @@ -50,7 +50,7 @@ func TestReadAgentIDFileExists(t *testing.T) { tmpF2, errTmpF := os.CreateTemp("", "tmp_") if !assert.NoError(t, errTmpF) { - t.FailNow() + return } defer os.Remove(tmpF2.Name()) diff --git a/cmd/agent/health_test.go b/cmd/agent/health_test.go index 04d297cf54..463928f762 100644 --- a/cmd/agent/health_test.go +++ b/cmd/agent/health_test.go @@ -18,6 +18,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/agent" ) @@ -27,35 +29,23 @@ func TestHealthy(t *testing.T) { s.Add("1", time.Hour, "octocat/hello-world", "42") - if got, want := s.Metadata["1"].ID, "1"; got != want { - t.Errorf("got ID %s, want %s", got, want) - } - if got, want := s.Metadata["1"].Timeout, time.Hour; got != want { - t.Errorf("got duration %v, want %v", got, want) - } - if got, want := s.Metadata["1"].Repo, "octocat/hello-world"; got != want { - t.Errorf("got repository name %s, want %s", got, want) - } + assert.Equal(t, "1", s.Metadata["1"].ID) + assert.Equal(t, time.Hour, s.Metadata["1"].Timeout) + assert.Equal(t, "octocat/hello-world", s.Metadata["1"].Repo) s.Metadata["1"] = agent.Info{ Timeout: time.Hour, Started: time.Now().UTC(), } - if s.Healthy() == false { - t.Error("want healthy status when timeout not exceeded, got false") - } + assert.True(t, s.Healthy(), "want healthy status when timeout not exceeded, got false") s.Metadata["1"] = agent.Info{ Started: time.Now().UTC().Add(-(time.Minute * 30)), } - if s.Healthy() == false { - t.Error("want healthy status when timeout+buffer not exceeded, got false") - } + assert.True(t, s.Healthy(), "want healthy status when timeout+buffer not exceeded, got false") s.Metadata["1"] = agent.Info{ Started: time.Now().UTC().Add(-(time.Hour + time.Minute)), } - if s.Healthy() == true { - t.Error("want unhealthy status when timeout+buffer not exceeded, got true") - } + assert.False(t, s.Healthy(), "want unhealthy status when timeout+buffer not exceeded, got true") } diff --git a/pipeline/backend/docker/convert_test.go b/pipeline/backend/docker/convert_test.go index 6c97bcf2e6..e3540e7146 100644 --- a/pipeline/backend/docker/convert_test.go +++ b/pipeline/backend/docker/convert_test.go @@ -86,9 +86,7 @@ func TestSplitVolumeParts(t *testing.T) { for _, test := range testdata { results, err := splitVolumeParts(test.from) if test.success != (err == nil) { - if reflect.DeepEqual(results, test.to) != test.success { - t.Errorf("Expect %q matches %q is %v", test.from, results, test.to) - } + assert.Equal(t, test.success, reflect.DeepEqual(results, test.to)) } } } diff --git a/pipeline/error_test.go b/pipeline/error_test.go index 536895e8dd..95a264f2e6 100644 --- a/pipeline/error_test.go +++ b/pipeline/error_test.go @@ -16,6 +16,8 @@ package pipeline import ( "testing" + + "github.com/stretchr/testify/assert" ) func TestExitError(t *testing.T) { @@ -23,18 +25,12 @@ func TestExitError(t *testing.T) { UUID: "14534321", Code: 255, } - got, want := err.Error(), "uuid=14534321: exit code 255" - if got != want { - t.Errorf("Want error message %q, got %q", want, got) - } + assert.Equal(t, "uuid=14534321: exit code 255", err.Error()) } func TestOomError(t *testing.T) { err := OomError{ UUID: "14534321", } - got, want := err.Error(), "uuid=14534321: received oom kill" - if got != want { - t.Errorf("Want error message %q, got %q", want, got) - } + assert.Equal(t, "uuid=14534321: received oom kill", err.Error()) } diff --git a/pipeline/errors/error_test.go b/pipeline/errors/error_test.go index 50bdf9d34d..b6b328e7ef 100644 --- a/pipeline/errors/error_test.go +++ b/pipeline/errors/error_test.go @@ -151,8 +151,6 @@ func TestHasBlockingErrors(t *testing.T) { } for _, test := range tests { - if pipeline_errors.HasBlockingErrors(test.err) != test.expected { - t.Error("Should only return true if there are blocking errors") - } + assert.Equal(t, test.expected, pipeline_errors.HasBlockingErrors(test.err)) } } diff --git a/pipeline/frontend/yaml/compiler/option_test.go b/pipeline/frontend/yaml/compiler/option_test.go index a485dbdeb4..77b26638b3 100644 --- a/pipeline/frontend/yaml/compiler/option_test.go +++ b/pipeline/frontend/yaml/compiler/option_test.go @@ -15,9 +15,10 @@ package compiler import ( - "reflect" "testing" + "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/pipeline/frontend/metadata" ) @@ -28,12 +29,8 @@ func TestWithWorkspace(t *testing.T) { "src/github.com/octocat/hello-world", ), ) - if compiler.base != "/pipeline" { - t.Errorf("WithWorkspace must set the base directory") - } - if compiler.path != "src/github.com/octocat/hello-world" { - t.Errorf("WithWorkspace must set the path directory") - } + assert.Equal(t, "/pipeline", compiler.base) + assert.Equal(t, "src/github.com/octocat/hello-world", compiler.path) } func TestWithEscalated(t *testing.T) { @@ -43,9 +40,8 @@ func TestWithEscalated(t *testing.T) { "docker-dev", ), ) - if compiler.escalated[0] != "docker" || compiler.escalated[1] != "docker-dev" { - t.Errorf("WithEscalated must whitelist privileged images") - } + assert.Equal(t, "docker", compiler.escalated[0]) + assert.Equal(t, "docker-dev", compiler.escalated[1]) } func TestWithVolumes(t *testing.T) { @@ -55,9 +51,8 @@ func TestWithVolumes(t *testing.T) { "/foo:/foo", ), ) - if compiler.volumes[0] != "/tmp:/tmp" || compiler.volumes[1] != "/foo:/foo" { - t.Errorf("TestWithVolumes must set default volumes") - } + assert.Equal(t, "/tmp:/tmp", compiler.volumes[0]) + assert.Equal(t, "/foo:/foo", compiler.volumes[1]) } func TestWithNetworks(t *testing.T) { @@ -67,9 +62,8 @@ func TestWithNetworks(t *testing.T) { "overlay_bar", ), ) - if compiler.networks[0] != "overlay_1" || compiler.networks[1] != "overlay_bar" { - t.Errorf("TestWithNetworks must set networks from parameters") - } + assert.Equal(t, "overlay_1", compiler.networks[0]) + assert.Equal(t, "overlay_bar", compiler.networks[1]) } func TestWithResourceLimit(t *testing.T) { @@ -83,30 +77,16 @@ func TestWithResourceLimit(t *testing.T) { "0,2-5", ), ) - if compiler.reslimit.MemSwapLimit != 1 { - t.Errorf("TestWithResourceLimit must set MemSwapLimit from parameters") - } - if compiler.reslimit.MemLimit != 2 { - t.Errorf("TestWithResourceLimit must set MemLimit from parameters") - } - if compiler.reslimit.ShmSize != 3 { - t.Errorf("TestWithResourceLimit must set ShmSize from parameters") - } - if compiler.reslimit.CPUQuota != 4 { - t.Errorf("TestWithResourceLimit must set CPUQuota from parameters") - } - if compiler.reslimit.CPUShares != 5 { - t.Errorf("TestWithResourceLimit must set CPUShares from parameters") - } - if compiler.reslimit.CPUSet != "0,2-5" { - t.Errorf("TestWithResourceLimit must set CPUSet from parameters") - } + assert.EqualValues(t, 1, compiler.reslimit.MemSwapLimit) + assert.EqualValues(t, 2, compiler.reslimit.MemLimit) + assert.EqualValues(t, 3, compiler.reslimit.ShmSize) + assert.EqualValues(t, 4, compiler.reslimit.CPUQuota) + assert.EqualValues(t, 5, compiler.reslimit.CPUShares) + assert.Equal(t, "0,2-5", compiler.reslimit.CPUSet) } func TestWithPrefix(t *testing.T) { - if New(WithPrefix("someprefix_")).prefix != "someprefix_" { - t.Errorf("WithPrefix must set the prefix") - } + assert.Equal(t, "someprefix_", New(WithPrefix("someprefix_")).prefix) } func TestWithMetadata(t *testing.T) { @@ -122,28 +102,16 @@ func TestWithMetadata(t *testing.T) { compiler := New( WithMetadata(metadata), ) - if !reflect.DeepEqual(compiler.metadata, metadata) { - t.Errorf("WithMetadata must set compiler the metadata") - } - if compiler.env["CI_REPO_NAME"] != metadata.Repo.Name { - t.Errorf("WithMetadata must set CI_REPO_NAME") - } - if compiler.env["CI_REPO_URL"] != metadata.Repo.ForgeURL { - t.Errorf("WithMetadata must set CI_REPO_URL") - } - if compiler.env["CI_REPO_CLONE_URL"] != metadata.Repo.CloneURL { - t.Errorf("WithMetadata must set CI_REPO_CLONE_URL") - } + assert.Equal(t, metadata, compiler.metadata) + assert.Equal(t, metadata.Repo.Name, compiler.env["CI_REPO_NAME"]) + assert.Equal(t, metadata.Repo.ForgeURL, compiler.env["CI_REPO_URL"]) + assert.Equal(t, metadata.Repo.CloneURL, compiler.env["CI_REPO_CLONE_URL"]) } func TestWithLocal(t *testing.T) { - if New(WithLocal(true)).local == false { - t.Errorf("WithLocal true must enable the local flag") - } - if New(WithLocal(false)).local == true { - t.Errorf("WithLocal false must disable the local flag") - } + assert.True(t, New(WithLocal(true)).local) + assert.False(t, New(WithLocal(false)).local) } func TestWithNetrc(t *testing.T) { @@ -154,15 +122,9 @@ func TestWithNetrc(t *testing.T) { "github.com", ), ) - if compiler.cloneEnv["CI_NETRC_USERNAME"] != "octocat" { - t.Errorf("WithNetrc should set CI_NETRC_USERNAME") - } - if compiler.cloneEnv["CI_NETRC_PASSWORD"] != "password" { - t.Errorf("WithNetrc should set CI_NETRC_PASSWORD") - } - if compiler.cloneEnv["CI_NETRC_MACHINE"] != "github.com" { - t.Errorf("WithNetrc should set CI_NETRC_MACHINE") - } + assert.Equal(t, "octocat", compiler.cloneEnv["CI_NETRC_USERNAME"]) + assert.Equal(t, "password", compiler.cloneEnv["CI_NETRC_PASSWORD"]) + assert.Equal(t, "github.com", compiler.cloneEnv["CI_NETRC_MACHINE"]) } func TestWithProxy(t *testing.T) { @@ -187,9 +149,7 @@ func TestWithProxy(t *testing.T) { }), ) for key, value := range testdata { - if compiler.env[key] != value { - t.Errorf("WithProxy should set %s=%s", key, value) - } + assert.Equal(t, value, compiler.env[key]) } } @@ -202,12 +162,8 @@ func TestWithEnviron(t *testing.T) { }, ), ) - if compiler.env["RACK_ENV"] != "development" { - t.Errorf("WithEnviron should set RACK_ENV") - } - if compiler.env["SHOW"] != "true" { - t.Errorf("WithEnviron should set SHOW") - } + assert.Equal(t, "development", compiler.env["RACK_ENV"]) + assert.Equal(t, "true", compiler.env["SHOW"]) } func TestWithVolumeCacher(t *testing.T) { @@ -215,21 +171,15 @@ func TestWithVolumeCacher(t *testing.T) { WithVolumeCacher("/cache"), ) cacher, ok := compiler.cacher.(*volumeCacher) - if !ok { - t.Errorf("Expected volume cacher configured") - } - if got, want := cacher.base, "/cache"; got != want { - t.Errorf("Expected volume cacher with base %s, got %s", want, got) - } + assert.True(t, ok) + assert.Equal(t, "/cache", cacher.base) } func TestWithDefaultCloneImage(t *testing.T) { compiler := New( WithDefaultCloneImage("not-an-image"), ) - if compiler.defaultCloneImage != "not-an-image" { - t.Errorf("Expected default clone image 'not-an-image' not found") - } + assert.Equal(t, "not-an-image", compiler.defaultCloneImage) } func TestWithS3Cacher(t *testing.T) { @@ -237,19 +187,9 @@ func TestWithS3Cacher(t *testing.T) { WithS3Cacher("some-access-key", "some-secret-key", "some-region", "some-bucket"), ) cacher, ok := compiler.cacher.(*s3Cacher) - if !ok { - t.Errorf("Expected s3 cacher configured") - } - if got, want := cacher.bucket, "some-bucket"; got != want { - t.Errorf("Expected s3 cacher with bucket %s, got %s", want, got) - } - if got, want := cacher.access, "some-access-key"; got != want { - t.Errorf("Expected s3 cacher with access key %s, got %s", want, got) - } - if got, want := cacher.region, "some-region"; got != want { - t.Errorf("Expected s3 cacher with region %s, got %s", want, got) - } - if got, want := cacher.secret, "some-secret-key"; got != want { - t.Errorf("Expected s3 cacher with secret key %s, got %s", want, got) - } + assert.True(t, ok) + assert.Equal(t, "some-bucket", cacher.bucket) + assert.Equal(t, "some-access-key", cacher.access) + assert.Equal(t, "some-region", cacher.region) + assert.Equal(t, "some-secret-key", cacher.secret) } diff --git a/pipeline/frontend/yaml/constraint/constraint_test.go b/pipeline/frontend/yaml/constraint/constraint_test.go index 3b0fa24a44..834e7f6bc6 100644 --- a/pipeline/frontend/yaml/constraint/constraint_test.go +++ b/pipeline/frontend/yaml/constraint/constraint_test.go @@ -158,10 +158,7 @@ func TestConstraint(t *testing.T) { } for _, test := range testdata { c := parseConstraint(t, test.conf) - got, want := c.Match(test.with), test.want - if got != want { - t.Errorf("Expect %q matches %q is %v", test.with, test.conf, want) - } + assert.Equal(t, test.want, c.Match(test.with)) } } @@ -266,10 +263,7 @@ func TestConstraintList(t *testing.T) { } for _, test := range testdata { c := parseConstraintPath(t, test.conf) - got, want := c.Match(test.with, test.message), test.want - if got != want { - t.Errorf("Expect %q matches %q should be %v got %v", test.with, test.conf, want, got) - } + assert.Equal(t, test.want, c.Match(test.with, test.message)) } } @@ -546,12 +540,8 @@ func TestConstraints(t *testing.T) { assert.NoError(t, err) c := parseConstraints(t, conf) got, err := c.Match(test.with, false, test.env) - if err != nil { - t.Errorf("Match returned error: %v", err) - } - if got != test.want { - t.Errorf("Expect %+v matches %q is %v", test.with, test.conf, test.want) - } + assert.NoError(t, err) + assert.Equal(t, test.want, got) }) } } diff --git a/pipeline/frontend/yaml/linter/linter_test.go b/pipeline/frontend/yaml/linter/linter_test.go index 1deef4c85c..50bc4092b4 100644 --- a/pipeline/frontend/yaml/linter/linter_test.go +++ b/pipeline/frontend/yaml/linter/linter_test.go @@ -83,17 +83,13 @@ steps: for _, testd := range testdatas { t.Run(testd.Title, func(t *testing.T) { conf, err := yaml.ParseString(testd.Data) - if err != nil { - t.Fatalf("Cannot unmarshal yaml %q. Error: %s", testd.Title, err) - } + assert.NoError(t, err) - if err := linter.New(linter.WithTrusted(true)).Lint([]*linter.WorkflowConfig{{ + assert.NoError(t, linter.New(linter.WithTrusted(true)).Lint([]*linter.WorkflowConfig{{ File: testd.Title, RawConfig: testd.Data, Workflow: conf, - }}); err != nil { - t.Errorf("Expected lint returns no errors, got %q", err) - } + }}), "expected lint returns no errors") }) } } @@ -156,18 +152,14 @@ func TestLintErrors(t *testing.T) { for _, test := range testdata { conf, err := yaml.ParseString(test.from) - if err != nil { - t.Fatalf("Cannot unmarshal yaml %q. Error: %s", test.from, err) - } + assert.NoError(t, err) lerr := linter.New().Lint([]*linter.WorkflowConfig{{ File: test.from, RawConfig: test.from, Workflow: conf, }}) - if lerr == nil { - t.Errorf("Expected lint error for configuration %q", test.from) - } + assert.Error(t, lerr, "expected lint error for configuration", test.from) lerrors := errors.GetPipelineErrors(lerr) found := false diff --git a/pipeline/frontend/yaml/parse_test.go b/pipeline/frontend/yaml/parse_test.go index ea679411be..5402cd03c5 100644 --- a/pipeline/frontend/yaml/parse_test.go +++ b/pipeline/frontend/yaml/parse_test.go @@ -166,12 +166,12 @@ pipeline: workflow1, err := ParseString(sampleYamlPipelineLegacy) if !assert.NoError(t, err) { - t.Fail() + return } workflow2, err := ParseString(sampleYamlPipelineLegacyIgnore) if !assert.NoError(t, err) { - t.Fail() + return } assert.EqualValues(t, workflow1, workflow2) diff --git a/pipeline/frontend/yaml/utils/image_test.go b/pipeline/frontend/yaml/utils/image_test.go index ff9affe090..17fab45d5b 100644 --- a/pipeline/frontend/yaml/utils/image_test.go +++ b/pipeline/frontend/yaml/utils/image_test.go @@ -16,6 +16,8 @@ package utils import ( "testing" + + "github.com/stretchr/testify/assert" ) func Test_trimImage(t *testing.T) { @@ -66,10 +68,7 @@ func Test_trimImage(t *testing.T) { }, } for _, test := range testdata { - got, want := trimImage(test.from), test.want - if got != want { - t.Errorf("Want image %q trimmed to %q, got %q", test.from, want, got) - } + assert.Equal(t, test.want, trimImage(test.from)) } } @@ -121,10 +120,7 @@ func Test_expandImage(t *testing.T) { }, } for _, test := range testdata { - got, want := expandImage(test.from), test.want - if got != want { - t.Errorf("Want image %q expanded to %q, got %q", test.from, want, got) - } + assert.Equal(t, test.want, expandImage(test.from)) } } @@ -205,10 +201,7 @@ func Test_matchImage(t *testing.T) { }, } for _, test := range testdata { - got, want := MatchImage(test.from, test.to), test.want - if got != want { - t.Errorf("Want image %q matching %q is %v", test.from, test.to, want) - } + assert.Equal(t, test.want, MatchImage(test.from, test.to)) } } @@ -264,9 +257,6 @@ func Test_matchHostname(t *testing.T) { }, } for _, test := range testdata { - got, want := MatchHostname(test.image, test.hostname), test.want - if got != want { - t.Errorf("Want image %q matching hostname %q is %v", test.image, test.hostname, want) - } + assert.Equal(t, test.want, MatchHostname(test.image, test.hostname)) } } diff --git a/pipeline/rpc/log_entry_test.go b/pipeline/rpc/log_entry_test.go index a60c4650e5..a76fc62446 100644 --- a/pipeline/rpc/log_entry_test.go +++ b/pipeline/rpc/log_entry_test.go @@ -16,6 +16,8 @@ package rpc import ( "testing" + + "github.com/stretchr/testify/assert" ) func TestLogEntry(t *testing.T) { @@ -25,8 +27,5 @@ func TestLogEntry(t *testing.T) { Line: 1, Data: "starting redis server", } - got, want := line.String(), "[e9ea76a5-44a1-4059-9c4a-6956c478b26d:L1:60s] starting redis server" - if got != want { - t.Errorf("Wanted line string %q, got %q", want, got) - } + assert.Equal(t, "[e9ea76a5-44a1-4059-9c4a-6956c478b26d:L1:60s] starting redis server", line.String()) } diff --git a/server/api/helper_test.go b/server/api/helper_test.go index 485451ccec..50721f9b3b 100644 --- a/server/api/helper_test.go +++ b/server/api/helper_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" "go.woodpecker-ci.org/woodpecker/v2/server/pipeline" ) @@ -34,8 +35,6 @@ func TestHandlePipelineError(t *testing.T) { c, _ := gin.CreateTestContext(r) handlePipelineErr(c, tt.err) c.Writer.WriteHeaderNow() // require written header - if r.Code != tt.code { - t.Errorf("status code: %d - expected: %d", r.Code, tt.code) - } + assert.Equal(t, tt.code, r.Code) } } diff --git a/server/forge/common/utils_test.go b/server/forge/common/utils_test.go index dd33be01ff..1599029120 100644 --- a/server/forge/common/utils_test.go +++ b/server/forge/common/utils_test.go @@ -17,16 +17,13 @@ package common_test import ( "testing" + "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/server/forge/common" ) func Test_Netrc(t *testing.T) { host, err := common.ExtractHostFromCloneURL("https://git.example.com/foo/bar.git") - if err != nil { - t.Fatal(err) - } - - if host != "git.example.com" { - t.Errorf("Expected host to be git.example.com, got %s", host) - } + assert.NoError(t, err) + assert.Equal(t, "git.example.com", host) } diff --git a/server/forge/gitlab/gitlab_test.go b/server/forge/gitlab/gitlab_test.go index 11b865975d..e6ee0f77c0 100644 --- a/server/forge/gitlab/gitlab_test.go +++ b/server/forge/gitlab/gitlab_test.go @@ -30,11 +30,8 @@ import ( "go.woodpecker-ci.org/woodpecker/v2/server/model" ) -func load(t *testing.T, config string) *GitLab { - _url, err := url.Parse(config) - if err != nil { - t.FailNow() - } +func load(config string) *GitLab { + _url, _ := url.Parse(config) params := _url.Query() _url.RawQuery = "" @@ -58,7 +55,7 @@ func Test_GitLab(t *testing.T) { env := server.URL + "?client_id=test&client_secret=test" - client := load(t, env) + client := load(env) user := model.User{ Login: "test_user", diff --git a/server/grpc/rpc_test.go b/server/grpc/rpc_test.go index 9c23cb9fec..1fd850b8a5 100644 --- a/server/grpc/rpc_test.go +++ b/server/grpc/rpc_test.go @@ -20,9 +20,10 @@ import ( "github.com/franela/goblin" "github.com/stretchr/testify/assert" + "google.golang.org/grpc/metadata" + "go.woodpecker-ci.org/woodpecker/v2/server/model" mocks_store "go.woodpecker-ci.org/woodpecker/v2/server/store/mocks" - "google.golang.org/grpc/metadata" ) func TestRegisterAgent(t *testing.T) { @@ -59,7 +60,7 @@ func TestRegisterAgent(t *testing.T) { capacity := int32(2) agentID, err := rpc.RegisterAgent(ctx, "platform", "backend", "version", capacity) if !assert.NoError(t, err) { - t.Fail() + return } assert.EqualValues(t, 1337, agentID) @@ -99,7 +100,7 @@ func TestRegisterAgent(t *testing.T) { capacity := int32(2) agentID, err := rpc.RegisterAgent(ctx, "platform", "backend", "version", capacity) if !assert.NoError(t, err) { - t.Fail() + return } assert.EqualValues(t, 1337, agentID) diff --git a/server/model/user_test.go b/server/model/user_test.go index 22a5a321f2..c92e9361fe 100644 --- a/server/model/user_test.go +++ b/server/model/user_test.go @@ -15,8 +15,9 @@ package model import ( - "errors" "testing" + + "github.com/stretchr/testify/assert" ) func TestUserValidate(t *testing.T) { @@ -60,8 +61,6 @@ func TestUserValidate(t *testing.T) { for _, test := range tests { err := test.user.Validate() - if !errors.Is(err, test.err) { - t.Errorf("Want user validation error %s, got %s", test.err, err) - } + assert.ErrorIs(t, err, test.err) } } diff --git a/server/pipeline/pipelineStatus_test.go b/server/pipeline/pipelineStatus_test.go index ff0c6b8689..05d906fc39 100644 --- a/server/pipeline/pipelineStatus_test.go +++ b/server/pipeline/pipelineStatus_test.go @@ -20,6 +20,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/server/model" ) @@ -33,12 +35,8 @@ func TestUpdateToStatusRunning(t *testing.T) { t.Parallel() pipeline, _ := UpdateToStatusRunning(&mockUpdatePipelineStore{}, model.Pipeline{}, int64(1)) - - if model.StatusRunning != pipeline.Status { - t.Errorf("Pipeline status not equals '%s' != '%s'", model.StatusRunning, pipeline.Status) - } else if int64(1) != pipeline.Started { - t.Errorf("Pipeline started not equals 1 != %d", pipeline.Started) - } + assert.Equal(t, model.StatusRunning, pipeline.Status) + assert.EqualValues(t, 1, pipeline.Started) } func TestUpdateToStatusPending(t *testing.T) { @@ -48,14 +46,9 @@ func TestUpdateToStatusPending(t *testing.T) { pipeline, _ := UpdateToStatusPending(&mockUpdatePipelineStore{}, model.Pipeline{}, "Reviewer") - switch { - case model.StatusPending != pipeline.Status: - t.Errorf("Pipeline status not equals '%s' != '%s'", model.StatusPending, pipeline.Status) - case pipeline.Reviewer != "Reviewer": - t.Errorf("Reviewer not equals 'Reviewer' != '%s'", pipeline.Reviewer) - case now > pipeline.Reviewed: - t.Errorf("Reviewed not updated %d !< %d", now, pipeline.Reviewed) - } + assert.Equal(t, model.StatusPending, pipeline.Status) + assert.Equal(t, "Reviewer", pipeline.Reviewer) + assert.LessOrEqual(t, now, pipeline.Reviewed) } func TestUpdateToStatusDeclined(t *testing.T) { @@ -65,14 +58,9 @@ func TestUpdateToStatusDeclined(t *testing.T) { pipeline, _ := UpdateToStatusDeclined(&mockUpdatePipelineStore{}, model.Pipeline{}, "Reviewer") - switch { - case model.StatusDeclined != pipeline.Status: - t.Errorf("Pipeline status not equals '%s' != '%s'", model.StatusDeclined, pipeline.Status) - case pipeline.Reviewer != "Reviewer": - t.Errorf("Reviewer not equals 'Reviewer' != '%s'", pipeline.Reviewer) - case now > pipeline.Reviewed: - t.Errorf("Reviewed not updated %d !< %d", now, pipeline.Reviewed) - } + assert.Equal(t, model.StatusDeclined, pipeline.Status) + assert.Equal(t, "Reviewer", pipeline.Reviewer) + assert.LessOrEqual(t, now, pipeline.Reviewed) } func TestUpdateToStatusToDone(t *testing.T) { @@ -80,11 +68,8 @@ func TestUpdateToStatusToDone(t *testing.T) { pipeline, _ := UpdateStatusToDone(&mockUpdatePipelineStore{}, model.Pipeline{}, "status", int64(1)) - if pipeline.Status != "status" { - t.Errorf("Pipeline status not equals 'status' != '%s'", pipeline.Status) - } else if int64(1) != pipeline.Finished { - t.Errorf("Pipeline finished not equals 1 != %d", pipeline.Finished) - } + assert.Equal(t, model.StatusValue("status"), pipeline.Status) + assert.EqualValues(t, 1, pipeline.Finished) } func TestUpdateToStatusError(t *testing.T) { @@ -94,18 +79,12 @@ func TestUpdateToStatusError(t *testing.T) { pipeline, _ := UpdateToStatusError(&mockUpdatePipelineStore{}, model.Pipeline{}, errors.New("this is an error")) - switch { - case len(pipeline.Errors) != 1: - t.Errorf("Expected one error, got %d", len(pipeline.Errors)) - case pipeline.Errors[0].Error() != "[generic] this is an error": - t.Errorf("Pipeline error not equals '[generic] this is an error' != '%s'", pipeline.Errors[0].Error()) - case model.StatusError != pipeline.Status: - t.Errorf("Pipeline status not equals '%s' != '%s'", model.StatusError, pipeline.Status) - case now > pipeline.Started: - t.Errorf("Started not updated %d !< %d", now, pipeline.Started) - case pipeline.Started != pipeline.Finished: - t.Errorf("Pipeline started and finished not equals %d != %d", pipeline.Started, pipeline.Finished) - } + assert.Len(t, pipeline.Errors, 1) + assert.Equal(t, "[generic] this is an error", pipeline.Errors[0].Error()) + assert.Equal(t, model.StatusError, pipeline.Status) + assert.Equal(t, pipeline.Started, pipeline.Finished) + assert.LessOrEqual(t, now, pipeline.Started) + assert.Equal(t, pipeline.Started, pipeline.Finished) } func TestUpdateToStatusKilled(t *testing.T) { @@ -115,9 +94,6 @@ func TestUpdateToStatusKilled(t *testing.T) { pipeline, _ := UpdateToStatusKilled(&mockUpdatePipelineStore{}, model.Pipeline{}) - if model.StatusKilled != pipeline.Status { - t.Errorf("Pipeline status not equals '%s' != '%s'", model.StatusKilled, pipeline.Status) - } else if now > pipeline.Finished { - t.Errorf("Finished not updated %d !< %d", now, pipeline.Finished) - } + assert.Equal(t, model.StatusKilled, pipeline.Status) + assert.LessOrEqual(t, now, pipeline.Finished) } diff --git a/server/pipeline/step_status_test.go b/server/pipeline/step_status_test.go index 0f43f19d42..f786ca5cce 100644 --- a/server/pipeline/step_status_test.go +++ b/server/pipeline/step_status_test.go @@ -141,11 +141,8 @@ func TestUpdateStepStatusExitedWithCode(t *testing.T) { err := UpdateStepStatus(&mockUpdateStepStore{}, step, state) assert.NoError(t, err) - if step.State != model.StatusFailure { - t.Errorf("Step status not equals '%s' != '%s'", model.StatusFailure, step.State) - } else if step.ExitCode != 1 { - t.Errorf("Step exit code not equals 1 != %d", step.ExitCode) - } + assert.Equal(t, model.StatusFailure, step.State) + assert.Equal(t, 1, step.ExitCode) } func TestUpdateStepPToStatusStarted(t *testing.T) { @@ -154,11 +151,8 @@ func TestUpdateStepPToStatusStarted(t *testing.T) { state := rpc.State{Started: int64(42)} step, _ := UpdateStepToStatusStarted(&mockUpdateStepStore{}, model.Step{}, state) - if step.State != model.StatusRunning { - t.Errorf("Step status not equals '%s' != '%s'", model.StatusRunning, step.State) - } else if step.Started != int64(42) { - t.Errorf("Step started not equals 42 != %d", step.Started) - } + assert.Equal(t, model.StatusRunning, step.State) + assert.EqualValues(t, 42, step.Started) } func TestUpdateStepToStatusSkipped(t *testing.T) { @@ -166,11 +160,8 @@ func TestUpdateStepToStatusSkipped(t *testing.T) { step, _ := UpdateStepToStatusSkipped(&mockUpdateStepStore{}, model.Step{}, int64(1)) - if step.State != model.StatusSkipped { - t.Errorf("Step status not equals '%s' != '%s'", model.StatusSkipped, step.State) - } else if step.Stopped != int64(0) { - t.Errorf("Step stopped not equals 0 != %d", step.Stopped) - } + assert.Equal(t, model.StatusSkipped, step.State) + assert.EqualValues(t, 0, step.Stopped) } func TestUpdateStepToStatusSkippedButStarted(t *testing.T) { @@ -182,11 +173,8 @@ func TestUpdateStepToStatusSkippedButStarted(t *testing.T) { step, _ = UpdateStepToStatusSkipped(&mockUpdateStepStore{}, *step, int64(1)) - if step.State != model.StatusSuccess { - t.Errorf("Step status not equals '%s' != '%s'", model.StatusSuccess, step.State) - } else if step.Stopped != int64(1) { - t.Errorf("Step stopped not equals 1 != %d", step.Stopped) - } + assert.Equal(t, model.StatusSuccess, step.State) + assert.EqualValues(t, 1, step.Stopped) } func TestUpdateStepStatusToDoneSkipped(t *testing.T) { @@ -198,16 +186,10 @@ func TestUpdateStepStatusToDoneSkipped(t *testing.T) { step, _ := UpdateStepStatusToDone(&mockUpdateStepStore{}, model.Step{}, state) - switch { - case step.State != model.StatusSkipped: - t.Errorf("Step status not equals '%s' != '%s'", model.StatusSkipped, step.State) - case step.Stopped != int64(34): - t.Errorf("Step stopped not equals 34 != %d", step.Stopped) - case step.Error != "": - t.Errorf("Step error not equals '' != '%s'", step.Error) - case step.ExitCode != 0: - t.Errorf("Step exit code not equals 0 != %d", step.ExitCode) - } + assert.Equal(t, model.StatusSkipped, step.State) + assert.EqualValues(t, 34, step.Stopped) + assert.Empty(t, step.Error) + assert.Equal(t, 0, step.ExitCode) } func TestUpdateStepStatusToDoneSuccess(t *testing.T) { @@ -220,16 +202,10 @@ func TestUpdateStepStatusToDoneSuccess(t *testing.T) { step, _ := UpdateStepStatusToDone(&mockUpdateStepStore{}, model.Step{}, state) - switch { - case step.State != model.StatusSuccess: - t.Errorf("Step status not equals '%s' != '%s'", model.StatusSuccess, step.State) - case step.Stopped != int64(34): - t.Errorf("Step stopped not equals 34 != %d", step.Stopped) - case step.Error != "": - t.Errorf("Step error not equals '' != '%s'", step.Error) - case step.ExitCode != 0: - t.Errorf("Step exit code not equals 0 != %d", step.ExitCode) - } + assert.Equal(t, model.StatusSuccess, step.State) + assert.EqualValues(t, 34, step.Stopped) + assert.Empty(t, step.Error) + assert.Equal(t, 0, step.ExitCode) } func TestUpdateStepStatusToDoneFailureWithError(t *testing.T) { @@ -239,9 +215,7 @@ func TestUpdateStepStatusToDoneFailureWithError(t *testing.T) { step, _ := UpdateStepStatusToDone(&mockUpdateStepStore{}, model.Step{}, state) - if step.State != model.StatusFailure { - t.Errorf("Step status not equals '%s' != '%s'", model.StatusFailure, step.State) - } + assert.Equal(t, model.StatusFailure, step.State) } func TestUpdateStepStatusToDoneFailureWithExitCode(t *testing.T) { @@ -251,9 +225,7 @@ func TestUpdateStepStatusToDoneFailureWithExitCode(t *testing.T) { step, _ := UpdateStepStatusToDone(&mockUpdateStepStore{}, model.Step{}, state) - if step.State != model.StatusFailure { - t.Errorf("Step status not equals '%s' != '%s'", model.StatusFailure, step.State) - } + assert.Equal(t, model.StatusFailure, step.State) } func TestUpdateStepToStatusKilledStarted(t *testing.T) { @@ -263,16 +235,10 @@ func TestUpdateStepToStatusKilledStarted(t *testing.T) { step, _ := UpdateStepToStatusKilled(&mockUpdateStepStore{}, model.Step{}) - switch { - case step.State != model.StatusKilled: - t.Errorf("Step status not equals '%s' != '%s'", model.StatusKilled, step.State) - case step.Stopped < now: - t.Errorf("Step stopped not equals %d < %d", now, step.Stopped) - case step.Started != step.Stopped: - t.Errorf("Step started not equals %d != %d", step.Stopped, step.Started) - case step.ExitCode != 137: - t.Errorf("Step exit code not equals 137 != %d", step.ExitCode) - } + assert.Equal(t, model.StatusKilled, step.State) + assert.LessOrEqual(t, now, step.Stopped) + assert.Equal(t, step.Stopped, step.Started) + assert.Equal(t, 137, step.ExitCode) } func TestUpdateStepToStatusKilledNotStarted(t *testing.T) { @@ -280,7 +246,5 @@ func TestUpdateStepToStatusKilledNotStarted(t *testing.T) { step, _ := UpdateStepToStatusKilled(&mockUpdateStepStore{}, model.Step{Started: int64(1)}) - if step.Started != int64(1) { - t.Errorf("Step started not equals 1 != %d", step.Started) - } + assert.EqualValues(t, 1, step.Started) } diff --git a/server/plugins/utils/http_test.go b/server/plugins/utils/http_test.go index 4426e82ffa..723a20a6a4 100644 --- a/server/plugins/utils/http_test.go +++ b/server/plugins/utils/http_test.go @@ -24,6 +24,7 @@ import ( "github.com/go-ap/httpsig" "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/server/plugins/utils" ) @@ -32,7 +33,7 @@ func TestSign(t *testing.T) { pubEd25519Key, privEd25519Key, err := ed25519.GenerateKey(rand.Reader) if !assert.NoError(t, err) { - t.FailNow() + return } body := []byte("{\"foo\":\"bar\"}") @@ -49,7 +50,7 @@ func TestSign(t *testing.T) { t.Fatal(err) } - VerifyHandler := func(w http.ResponseWriter, r *http.Request) { + verifyHandler := func(w http.ResponseWriter, r *http.Request) { keystore := httpsig.NewMemoryKeyStore() keystore.SetKey(pubKeyID, pubEd25519Key) @@ -57,24 +58,16 @@ func TestSign(t *testing.T) { verifier.SetRequiredHeaders([]string{"(request-target)", "date"}) keyID, err := verifier.Verify(r) - if err != nil { - t.Fatal(err) - } - - if keyID != pubKeyID { - t.Fatalf("expected key ID %q, got %q", pubKeyID, keyID) - } + assert.NoError(t, err) + assert.Equal(t, pubKeyID, keyID) w.WriteHeader(http.StatusOK) } rr := httptest.NewRecorder() - handler := http.HandlerFunc(VerifyHandler) + handler := http.HandlerFunc(verifyHandler) handler.ServeHTTP(rr, req) - if status := rr.Code; status != http.StatusOK { - t.Errorf("handler returned wrong status code: got %v want %v", - status, http.StatusOK) - } + assert.Equal(t, http.StatusOK, rr.Code) } diff --git a/server/queue/fifo_test.go b/server/queue/fifo_test.go index 49d191e3ad..e9c07d131c 100644 --- a/server/queue/fifo_test.go +++ b/server/queue/fifo_test.go @@ -16,13 +16,13 @@ package queue import ( "context" - "errors" "fmt" "sync" "testing" "time" "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/server/model" ) @@ -34,37 +34,20 @@ func TestFifo(t *testing.T) { q := New(context.Background()) assert.NoError(t, q.Push(noContext, want)) info := q.Info(noContext) - if len(info.Pending) != 1 { - t.Errorf("expect task in pending queue") - return - } + assert.Len(t, info.Pending, 1, "expect task in pending queue") - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != want { - t.Errorf("expect task returned form queue") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, want, got) info = q.Info(noContext) - if len(info.Pending) != 0 { - t.Errorf("expect task removed from pending queue") - return - } - if len(info.Running) != 1 { - t.Errorf("expect task in running queue") - return - } + assert.Len(t, info.Pending, 0, "expect task removed from pending queue") + assert.Len(t, info.Running, 1, "expect task in running queue") assert.NoError(t, q.Done(noContext, got.ID, model.StatusSuccess)) info = q.Info(noContext) - if len(info.Pending) != 0 { - t.Errorf("expect task removed from pending queue") - return - } - if len(info.Running) != 0 { - t.Errorf("expect task removed from running queue") - return - } + assert.Len(t, info.Pending, 0, "expect task removed from pending queue") + assert.Len(t, info.Running, 0, "expect task removed from running queue") } func TestFifoExpire(t *testing.T) { @@ -74,22 +57,14 @@ func TestFifoExpire(t *testing.T) { q.extension = 0 assert.NoError(t, q.Push(noContext, want)) info := q.Info(noContext) - if len(info.Pending) != 1 { - t.Errorf("expect task in pending queue") - return - } + assert.Len(t, info.Pending, 1, "expect task in pending queue") - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != want { - t.Errorf("expect task returned form queue") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, want, got) q.process() - if len(info.Pending) != 1 { - t.Errorf("expect task re-added to pending queue") - return - } + assert.Len(t, info.Pending, 1, "expect task re-added to pending queue") } func TestFifoWait(t *testing.T) { @@ -98,11 +73,9 @@ func TestFifoWait(t *testing.T) { q, _ := New(context.Background()).(*fifo) assert.NoError(t, q.Push(noContext, want)) - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != want { - t.Errorf("expect task returned form queue") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, want, got) var wg sync.WaitGroup wg.Add(1) @@ -122,19 +95,13 @@ func TestFifoEvict(t *testing.T) { q := New(context.Background()) assert.NoError(t, q.Push(noContext, t1)) info := q.Info(noContext) - if len(info.Pending) != 1 { - t.Errorf("expect task in pending queue") - } - if err := q.Evict(noContext, t1.ID); err != nil { - t.Errorf("expect task evicted from queue") - } + assert.Len(t, info.Pending, 1, "expect task in pending queue") + err := q.Evict(noContext, t1.ID) + assert.NoError(t, err) info = q.Info(noContext) - if len(info.Pending) != 0 { - t.Errorf("expect pending queue has zero items") - } - if err := q.Evict(noContext, t1.ID); !errors.Is(err, ErrNotFound) { - t.Errorf("expect not found error when evicting item not in queue, got %s", err) - } + assert.Len(t, info.Pending, 0) + err = q.Evict(noContext, t1.ID) + assert.ErrorIs(t, err, ErrNotFound) } func TestFifoDependencies(t *testing.T) { @@ -151,19 +118,15 @@ func TestFifoDependencies(t *testing.T) { q, _ := New(context.Background()).(*fifo) assert.NoError(t, q.PushAtOnce(noContext, []*model.Task{task2, task1})) - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task1 { - t.Errorf("expect task1 returned from queue as task2 depends on it") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task1, got) assert.NoError(t, q.Done(noContext, got.ID, model.StatusSuccess)) - got, _ = q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task2 { - t.Errorf("expect task2 returned from queue") - return - } + got, err = q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task2, got) } func TestFifoErrors(t *testing.T) { @@ -187,35 +150,21 @@ func TestFifoErrors(t *testing.T) { q, _ := New(context.Background()).(*fifo) assert.NoError(t, q.PushAtOnce(noContext, []*model.Task{task2, task3, task1})) - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task1 { - t.Errorf("expect task1 returned from queue as task2 depends on it") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task1, got) assert.NoError(t, q.Error(noContext, got.ID, fmt.Errorf("exitcode 1, there was an error"))) - got, _ = q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task2 { - t.Errorf("expect task2 returned from queue") - return - } - - if got.ShouldRun() { - t.Errorf("expect task2 should not run, since task1 failed") - return - } - - got, _ = q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task3 { - t.Errorf("expect task3 returned from queue") - return - } + got, err = q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task2, got) + assert.False(t, got.ShouldRun()) - if !got.ShouldRun() { - t.Errorf("expect task3 should run, task1 failed, but task3 runs on failure too") - return - } + got, err = q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task3, got) + assert.True(t, got.ShouldRun()) } func TestFifoErrors2(t *testing.T) { @@ -237,11 +186,9 @@ func TestFifoErrors2(t *testing.T) { assert.NoError(t, q.PushAtOnce(noContext, []*model.Task{task2, task3, task1})) for i := 0; i < 2; i++ { - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task1 && got != task2 { - t.Errorf("expect task1 or task2 returned from queue as task3 depends on them") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.False(t, got != task1 && got != task2, "expect task1 or task2 returned from queue as task3 depends on them") if got != task1 { assert.NoError(t, q.Done(noContext, got.ID, model.StatusSuccess)) @@ -251,16 +198,10 @@ func TestFifoErrors2(t *testing.T) { } } - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task3 { - t.Errorf("expect task3 returned from queue") - return - } - - if got.ShouldRun() { - t.Errorf("expect task3 should not run, task1 succeeded but task2 failed") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task3, got) + assert.False(t, got.ShouldRun()) } func TestFifoErrorsMultiThread(t *testing.T) { @@ -289,7 +230,8 @@ func TestFifoErrorsMultiThread(t *testing.T) { go func(i int) { for { fmt.Printf("Worker %d started\n", i) - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) obtainedWorkCh <- got } }(i) @@ -305,10 +247,7 @@ func TestFifoErrorsMultiThread(t *testing.T) { switch { case !task1Processed: - if got != task1 { - t.Errorf("expect task1 returned from queue as task2 and task3 depends on it") - return - } + assert.Equal(t, task1, got) task1Processed = true assert.NoError(t, q.Error(noContext, got.ID, fmt.Errorf("exitcode 1, there was an error"))) go func() { @@ -319,10 +258,7 @@ func TestFifoErrorsMultiThread(t *testing.T) { } }() case !task2Processed: - if got != task2 { - t.Errorf("expect task2 returned from queue") - return - } + assert.Equal(t, task2, got) task2Processed = true assert.NoError(t, q.Done(noContext, got.ID, model.StatusSuccess)) go func() { @@ -333,15 +269,8 @@ func TestFifoErrorsMultiThread(t *testing.T) { } }() default: - if got != task3 { - t.Errorf("expect task3 returned from queue") - return - } - - if got.ShouldRun() { - t.Errorf("expect task3 should not run, task1 succeeded but task2 failed") - return - } + assert.Equal(t, task3, got) + assert.False(t, got.ShouldRun(), "expect task3 should not run, task1 succeeded but task2 failed") return } @@ -374,33 +303,21 @@ func TestFifoTransitiveErrors(t *testing.T) { q, _ := New(context.Background()).(*fifo) assert.NoError(t, q.PushAtOnce(noContext, []*model.Task{task2, task3, task1})) - got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task1 { - t.Errorf("expect task1 returned from queue as task2 depends on it") - return - } + got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task1, got) assert.NoError(t, q.Error(noContext, got.ID, fmt.Errorf("exitcode 1, there was an error"))) - got, _ = q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task2 { - t.Errorf("expect task2 returned from queue") - return - } - if got.ShouldRun() { - t.Errorf("expect task2 should not run, since task1 failed") - return - } + got, err = q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task2, got) + assert.False(t, got.ShouldRun(), "expect task2 should not run, since task1 failed") assert.NoError(t, q.Done(noContext, got.ID, model.StatusSkipped)) - got, _ = q.Poll(noContext, 1, func(*model.Task) bool { return true }) - if got != task3 { - t.Errorf("expect task3 returned from queue") - return - } - if got.ShouldRun() { - t.Errorf("expect task3 should not run, task1 failed, thus task2 was skipped, task3 should be skipped too") - return - } + got, err = q.Poll(noContext, 1, func(*model.Task) bool { return true }) + assert.NoError(t, err) + assert.Equal(t, task3, got) + assert.False(t, got.ShouldRun(), "expect task3 should not run, task1 failed, thus task2 was skipped, task3 should be skipped too") } func TestFifoCancel(t *testing.T) { @@ -430,10 +347,7 @@ func TestFifoCancel(t *testing.T) { assert.NoError(t, q.Error(noContext, task3.ID, fmt.Errorf("canceled"))) info := q.Info(noContext) - if len(info.Pending) != 0 { - t.Errorf("All pipelines should be canceled") - return - } + assert.Len(t, info.Pending, 0, "all pipelines should be canceled") } func TestFifoPause(t *testing.T) { @@ -458,9 +372,7 @@ func TestFifoPause(t *testing.T) { wg.Wait() t1 := time.Now() - if t1.Sub(t0) < 20*time.Millisecond { - t.Errorf("Should have waited til resume") - } + assert.Greater(t, t1.Sub(t0), 20*time.Millisecond, "should have waited til resume") q.Pause() assert.NoError(t, q.Push(noContext, task1)) @@ -505,9 +417,7 @@ func TestWaitingVsPending(t *testing.T) { got, _ := q.Poll(noContext, 1, func(*model.Task) bool { return true }) info := q.Info(noContext) - if info.Stats.WaitingOnDeps != 2 { - t.Errorf("2 should wait on deps") - } + assert.Equal(t, 2, info.Stats.WaitingOnDeps) assert.NoError(t, q.Error(noContext, got.ID, fmt.Errorf("exitcode 1, there was an error"))) got, err := q.Poll(noContext, 1, func(*model.Task) bool { return true }) @@ -515,12 +425,8 @@ func TestWaitingVsPending(t *testing.T) { assert.EqualValues(t, task2, got) info = q.Info(noContext) - if info.Stats.WaitingOnDeps != 0 { - t.Errorf("0 should wait on deps") - } - if info.Stats.Pending != 1 { - t.Errorf("1 should wait for worker") - } + assert.Equal(t, 0, info.Stats.WaitingOnDeps) + assert.Equal(t, 1, info.Stats.Pending) } func TestShouldRun(t *testing.T) { @@ -532,10 +438,7 @@ func TestShouldRun(t *testing.T) { }, RunOn: []string{"failure"}, } - if task.ShouldRun() { - t.Errorf("expect task to not run, it runs on failure only") - return - } + assert.False(t, task.ShouldRun(), "expect task to not run, it runs on failure only") task = &model.Task{ ID: "2", @@ -545,10 +448,7 @@ func TestShouldRun(t *testing.T) { }, RunOn: []string{"failure", "success"}, } - if !task.ShouldRun() { - t.Errorf("expect task to run") - return - } + assert.True(t, task.ShouldRun()) task = &model.Task{ ID: "2", @@ -557,10 +457,7 @@ func TestShouldRun(t *testing.T) { "1": model.StatusFailure, }, } - if task.ShouldRun() { - t.Errorf("expect task to not run") - return - } + assert.False(t, task.ShouldRun()) task = &model.Task{ ID: "2", @@ -570,10 +467,7 @@ func TestShouldRun(t *testing.T) { }, RunOn: []string{"success"}, } - if !task.ShouldRun() { - t.Errorf("expect task to run") - return - } + assert.True(t, task.ShouldRun()) task = &model.Task{ ID: "2", @@ -583,10 +477,7 @@ func TestShouldRun(t *testing.T) { }, RunOn: []string{"failure"}, } - if !task.ShouldRun() { - t.Errorf("expect task to run") - return - } + assert.True(t, task.ShouldRun()) task = &model.Task{ ID: "2", @@ -595,10 +486,7 @@ func TestShouldRun(t *testing.T) { "1": model.StatusSkipped, }, } - if task.ShouldRun() { - t.Errorf("model.Tasked should not run if dependency is skipped") - return - } + assert.False(t, task.ShouldRun(), "task should not run if dependency is skipped") task = &model.Task{ ID: "2", @@ -608,8 +496,5 @@ func TestShouldRun(t *testing.T) { }, RunOn: []string{"failure"}, } - if !task.ShouldRun() { - t.Errorf("On Failure tasks should run on skipped deps, something failed higher up the chain") - return - } + assert.True(t, task.ShouldRun(), "on failure, tasks should run on skipped deps, something failed higher up the chain") } diff --git a/server/store/datastore/agent_test.go b/server/store/datastore/agent_test.go index d314df6f35..992412128f 100644 --- a/server/store/datastore/agent_test.go +++ b/server/store/datastore/agent_test.go @@ -35,11 +35,8 @@ func TestAgentFindByToken(t *testing.T) { assert.NoError(t, err) _agent, err := store.AgentFindByToken(agent.Token) - if err != nil { - t.Error(err) - return - } - assert.Equal(t, int64(1), _agent.ID) + assert.NoError(t, err) + assert.EqualValues(t, 1, _agent.ID) _agent, err = store.AgentFindByToken("") assert.ErrorIs(t, err, ErrNoTokenProvided) diff --git a/server/store/datastore/config_test.go b/server/store/datastore/config_test.go index 32e7d21cb9..97bc25afba 100644 --- a/server/store/datastore/config_test.go +++ b/server/store/datastore/config_test.go @@ -37,10 +37,7 @@ func TestConfig(t *testing.T) { Owner: "bradrydzewski", Name: "test", } - if err := store.CreateRepo(repo); err != nil { - t.Errorf("Unexpected error: insert repo: %s", err) - return - } + assert.NoError(t, store.CreateRepo(repo)) config := &model.Config{ RepoID: repo.ID, @@ -48,60 +45,33 @@ func TestConfig(t *testing.T) { Hash: hash, Name: "default", } - if err := store.ConfigCreate(config); err != nil { - t.Errorf("Unexpected error: insert config: %s", err) - return - } + assert.NoError(t, store.ConfigCreate(config)) pipeline := &model.Pipeline{ RepoID: repo.ID, Status: model.StatusRunning, Commit: "85f8c029b902ed9400bc600bac301a0aadb144ac", } - if err := store.CreatePipeline(pipeline); err != nil { - t.Errorf("Unexpected error: insert pipeline: %s", err) - return - } + assert.NoError(t, store.CreatePipeline(pipeline)) - if err := store.PipelineConfigCreate( + assert.NoError(t, store.PipelineConfigCreate( &model.PipelineConfig{ ConfigID: config.ID, PipelineID: pipeline.ID, }, - ); err != nil { - t.Errorf("Unexpected error: insert pipeline config: %s", err) - return - } + )) config, err := store.ConfigFindIdentical(repo.ID, hash) - if err != nil { - t.Error(err) - return - } - if got, want := config.ID, int64(1); got != want { - t.Errorf("Want config id %d, got %d", want, got) - } - if got, want := config.RepoID, repo.ID; got != want { - t.Errorf("Want config repo id %d, got %d", want, got) - } - if got, want := string(config.Data), data; got != want { - t.Errorf("Want config data %s, got %s", want, got) - } - if got, want := config.Hash, hash; got != want { - t.Errorf("Want config hash %s, got %s", want, got) - } - if got, want := config.Name, "default"; got != want { - t.Errorf("Want config name %s, got %s", want, got) - } + assert.NoError(t, err) + assert.EqualValues(t, 1, config.ID) + assert.Equal(t, repo.ID, config.RepoID) + assert.Equal(t, data, string(config.Data)) + assert.Equal(t, hash, config.Hash) + assert.Equal(t, "default", config.Name) loaded, err := store.ConfigsForPipeline(pipeline.ID) - if err != nil { - t.Errorf("Want config by id, got error %q", err) - return - } - if got, want := loaded[0].ID, config.ID; got != want { - t.Errorf("Want config by id %d, got %d", want, got) - } + assert.NoError(t, err) + assert.Equal(t, config.ID, loaded[0].ID) } func TestConfigApproved(t *testing.T) { @@ -114,10 +84,7 @@ func TestConfigApproved(t *testing.T) { Owner: "bradrydzewski", Name: "test", } - if err := store.CreateRepo(repo); err != nil { - t.Errorf("Unexpected error: insert repo: %s", err) - return - } + assert.NoError(t, store.CreateRepo(repo)) var ( data = "pipeline: [ { image: golang, commands: [ go build, go test ] } ]" @@ -139,40 +106,25 @@ func TestConfigApproved(t *testing.T) { } ) - if err := store.CreatePipeline(pipelineBlocked); err != nil { - t.Errorf("Unexpected error: insert pipeline: %s", err) - return - } - if err := store.CreatePipeline(pipelinePending); err != nil { - t.Errorf("Unexpected error: insert pipeline: %s", err) - return - } + assert.NoError(t, store.CreatePipeline(pipelineBlocked)) + assert.NoError(t, store.CreatePipeline(pipelinePending)) conf := &model.Config{ RepoID: repo.ID, Data: []byte(data), Hash: hash, } - if err := store.ConfigCreate(conf); err != nil { - t.Errorf("Unexpected error: insert config: %s", err) - return - } + assert.NoError(t, store.ConfigCreate(conf)) pipelineConfig := &model.PipelineConfig{ ConfigID: conf.ID, PipelineID: pipelineBlocked.ID, } - if err := store.PipelineConfigCreate(pipelineConfig); err != nil { - t.Errorf("Unexpected error: insert pipeline_config: %s", err) - return - } + assert.NoError(t, store.PipelineConfigCreate(pipelineConfig)) approved, err := store.ConfigFindApproved(conf) if !assert.NoError(t, err) { return } - if approved != false { - t.Errorf("Want config not approved, when blocked or pending.") - return - } + assert.False(t, approved, "want config not approved when blocked or pending.") assert.NoError(t, store.CreatePipeline(pipelineRunning)) conf2 := &model.Config{ @@ -180,23 +132,16 @@ func TestConfigApproved(t *testing.T) { Data: []byte(data), Hash: "xxx", } - if err := store.ConfigCreate(conf2); err != nil { - t.Errorf("Unexpected error: insert config: %s", err) - return - } + assert.NoError(t, store.ConfigCreate(conf2)) pipelineConfig2 := &model.PipelineConfig{ ConfigID: conf2.ID, PipelineID: pipelineRunning.ID, } - if err := store.PipelineConfigCreate(pipelineConfig2); err != nil { - t.Errorf("Unexpected error: insert config: %s", err) - return - } + assert.NoError(t, store.PipelineConfigCreate(pipelineConfig2)) - if approved, err := store.ConfigFindApproved(conf2); approved != true || err != nil { - t.Errorf("Want config approved, when running. %v", err) - return - } + approved, err = store.ConfigFindApproved(conf2) + assert.NoError(t, err) + assert.True(t, approved) } func TestConfigIndexes(t *testing.T) { @@ -208,25 +153,20 @@ func TestConfigIndexes(t *testing.T) { hash = "8d8647c9aa90d893bfb79dddbe901f03e258588121e5202632f8ae5738590b26" ) - if err := store.ConfigCreate( + assert.NoError(t, store.ConfigCreate( &model.Config{ RepoID: 2, Data: []byte(data), Hash: hash, }, - ); err != nil { - t.Errorf("Unexpected error: insert config: %s", err) - return - } + )) // fail due to duplicate sha - if err := store.ConfigCreate( + assert.Error(t, store.ConfigCreate( &model.Config{ RepoID: 2, Data: []byte(data), Hash: hash, }, - ); err == nil { - t.Errorf("Unexpected error: duplicate sha") - } + )) } diff --git a/server/store/datastore/feed_test.go b/server/store/datastore/feed_test.go index 333c68b3ad..7d44eda746 100644 --- a/server/store/datastore/feed_test.go +++ b/server/store/datastore/feed_test.go @@ -54,13 +54,8 @@ func TestGetPipelineQueue(t *testing.T) { assert.NoError(t, store.CreatePipeline(pipeline1)) feed, err := store.GetPipelineQueue() - if err != nil { - t.Errorf("Unexpected error: repository list with latest pipeline: %s", err) - return - } - if got, want := len(feed), 1; got != want { - t.Errorf("Want %d repositories, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, feed, 1) } func TestUserFeed(t *testing.T) { @@ -105,13 +100,8 @@ func TestUserFeed(t *testing.T) { assert.NoError(t, store.CreatePipeline(pipeline1)) feed, err := store.UserFeed(user) - if err != nil { - t.Errorf("Unexpected error: repository list with latest pipeline: %s", err) - return - } - if got, want := len(feed), 1; got != want { - t.Errorf("Want %d repositories, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, feed, 1) } func TestRepoListLatest(t *testing.T) { @@ -182,23 +172,10 @@ func TestRepoListLatest(t *testing.T) { assert.NoError(t, store.CreatePipeline(pipeline4)) pipelines, err := store.RepoListLatest(user) - if err != nil { - t.Errorf("Unexpected error: repository list with latest pipeline: %s", err) - return - } - if got, want := len(pipelines), 2; got != want { - t.Errorf("Want %d repositories, got %d", want, got) - } - if got, want := pipelines[0].Status, string(model.StatusRunning); want != got { - t.Errorf("Want repository status %s, got %s", want, got) - } - if got, want := pipelines[0].RepoID, repo1.ID; want != got { - t.Errorf("Want repository id %d, got %d", want, got) - } - if got, want := pipelines[1].Status, string(model.StatusKilled); want != got { - t.Errorf("Want repository status %s, got %s", want, got) - } - if got, want := pipelines[1].RepoID, repo2.ID; want != got { - t.Errorf("Want repository id %d, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, pipelines, 2) + assert.EqualValues(t, model.StatusRunning, pipelines[0].Status) + assert.Equal(t, repo1.ID, pipelines[0].RepoID) + assert.EqualValues(t, model.StatusKilled, pipelines[1].Status) + assert.Equal(t, repo2.ID, pipelines[1].RepoID) } diff --git a/server/store/datastore/permission_test.go b/server/store/datastore/permission_test.go index 924124c58a..46c1f96519 100644 --- a/server/store/datastore/permission_test.go +++ b/server/store/datastore/permission_test.go @@ -46,25 +46,13 @@ func TestPermFind(t *testing.T) { Admin: false, }, ) - if err != nil { - t.Error(err) - return - } + assert.NoError(t, err) perm, err := store.PermFind(user, repo) - if err != nil { - t.Error(err) - return - } - if got, want := perm.Pull, true; got != want { - t.Errorf("Wanted pull %v, got %v", want, got) - } - if got, want := perm.Push, false; got != want { - t.Errorf("Wanted push %v, got %v", want, got) - } - if got, want := perm.Admin, false; got != want { - t.Errorf("Wanted admin %v, got %v", want, got) - } + assert.NoError(t, err) + assert.True(t, perm.Pull) + assert.False(t, perm.Push) + assert.False(t, perm.Admin) } func TestPermUpsert(t *testing.T) { @@ -91,25 +79,13 @@ func TestPermUpsert(t *testing.T) { Admin: false, }, ) - if err != nil { - t.Error(err) - return - } + assert.NoError(t, err) perm, err := store.PermFind(user, repo) - if err != nil { - t.Error(err) - return - } - if got, want := perm.Pull, true; got != want { - t.Errorf("Wanted pull %v, got %v", want, got) - } - if got, want := perm.Push, false; got != want { - t.Errorf("Wanted push %v, got %v", want, got) - } - if got, want := perm.Admin, false; got != want { - t.Errorf("Wanted admin %v, got %v", want, got) - } + assert.NoError(t, err) + assert.True(t, perm.Pull) + assert.False(t, perm.Push) + assert.False(t, perm.Admin) // // this will attempt to replace the existing permissions @@ -126,25 +102,13 @@ func TestPermUpsert(t *testing.T) { Admin: true, }, ) - if err != nil { - t.Error(err) - return - } + assert.NoError(t, err) perm, err = store.PermFind(user, repo) - if err != nil { - t.Error(err) - return - } - if got, want := perm.Pull, true; got != want { - t.Errorf("Wanted pull %v, got %v", want, got) - } - if got, want := perm.Push, true; got != want { - t.Errorf("Wanted push %v, got %v", want, got) - } - if got, want := perm.Admin, true; got != want { - t.Errorf("Wanted admin %v, got %v", want, got) - } + assert.NoError(t, err) + assert.True(t, perm.Pull) + assert.True(t, perm.Push) + assert.True(t, perm.Admin) } func TestPermDelete(t *testing.T) { @@ -171,24 +135,12 @@ func TestPermDelete(t *testing.T) { Admin: false, }, ) - if err != nil { - t.Errorf("Unexpected error: insert perm: %s", err) - return - } + assert.NoError(t, err) perm, err := store.PermFind(user, repo) - if err != nil { - t.Errorf("Unexpected error: select perm: %s", err) - return - } + assert.NoError(t, err) err = store.PermDelete(perm) - if err != nil { - t.Errorf("Unexpected error: delete perm: %s", err) - return - } + assert.NoError(t, err) _, err = store.PermFind(user, repo) - if err == nil { - t.Errorf("Expect error: sql.ErrNoRows") - return - } + assert.Error(t, err) } diff --git a/server/store/datastore/redirection_test.go b/server/store/datastore/redirection_test.go index 2fc4c53d17..a4d4c18def 100644 --- a/server/store/datastore/redirection_test.go +++ b/server/store/datastore/redirection_test.go @@ -31,10 +31,7 @@ func TestGetRedirection(t *testing.T) { RepoID: 1, FullName: "foo/bar", } - if err := store.CreateRedirection(redirection); err != nil { - t.Errorf("Unexpected error: insert redirection: %s", err) - return - } + assert.NoError(t, store.CreateRedirection(redirection)) redirectionFromStore, err := store.GetRedirection("foo/bar") assert.NoError(t, err) assert.NotNil(t, redirectionFromStore) @@ -62,24 +59,11 @@ func TestHasRedirectionForRepo(t *testing.T) { RepoID: 1, FullName: "foo/bar", } - if err := store.CreateRedirection(redirection); err != nil { - t.Errorf("Unexpected error: insert redirection: %s", err) - return - } + assert.NoError(t, store.CreateRedirection(redirection)) has, err := store.HasRedirectionForRepo(1, "foo/bar") - if err != nil { - t.Error(err) - return - } - if !has { - t.Errorf("Expected a redirection for %s", redirection.FullName) - } + assert.NoError(t, err) + assert.True(t, has) has, err = store.HasRedirectionForRepo(1, "foo/baz") - if err != nil { - t.Error(err) - return - } - if has { - t.Errorf("Expected not finding a redirection for %s", redirection.FullName) - } + assert.NoError(t, err) + assert.False(t, has) } diff --git a/server/store/datastore/registry_test.go b/server/store/datastore/registry_test.go index 06c84259be..a4e9e07ffa 100644 --- a/server/store/datastore/registry_test.go +++ b/server/store/datastore/registry_test.go @@ -35,34 +35,16 @@ func TestRegistryFind(t *testing.T) { Email: "foo@bar.com", Token: "12345", }) - if err != nil { - t.Errorf("Unexpected error: insert registry: %s", err) - return - } + assert.NoError(t, err) registry, err := store.RegistryFind(&model.Repo{ID: 1}, "index.docker.io") - if err != nil { - t.Error(err) - return - } - if got, want := registry.RepoID, int64(1); got != want { - t.Errorf("Want repo id %d, got %d", want, got) - } - if got, want := registry.Address, "index.docker.io"; got != want { - t.Errorf("Want registry address %s, got %s", want, got) - } - if got, want := registry.Username, "foo"; got != want { - t.Errorf("Want registry username %s, got %s", want, got) - } - if got, want := registry.Password, "bar"; got != want { - t.Errorf("Want registry password %s, got %s", want, got) - } - if got, want := registry.Email, "foo@bar.com"; got != want { - t.Errorf("Want registry email %s, got %s", want, got) - } - if got, want := registry.Token, "12345"; got != want { - t.Errorf("Want registry token %s, got %s", want, got) - } + assert.NoError(t, err) + assert.EqualValues(t, 1, registry.RepoID) + assert.Equal(t, "index.docker.io", registry.Address) + assert.Equal(t, "foo", registry.Username) + assert.Equal(t, "bar", registry.Password) + assert.Equal(t, "foo@bar.com", registry.Email) + assert.Equal(t, "12345", registry.Token) } func TestRegistryList(t *testing.T) { @@ -83,13 +65,8 @@ func TestRegistryList(t *testing.T) { })) list, err := store.RegistryList(&model.Repo{ID: 1}, &model.ListOptions{Page: 1, PerPage: 50}) - if err != nil { - t.Error(err) - return - } - if got, want := len(list), 2; got != want { - t.Errorf("Want %d registries, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, list, 2) } func TestRegistryUpdate(t *testing.T) { @@ -102,48 +79,32 @@ func TestRegistryUpdate(t *testing.T) { Username: "foo", Password: "bar", } - if err := store.RegistryCreate(registry); err != nil { - t.Errorf("Unexpected error: insert registry: %s", err) - return - } + assert.NoError(t, store.RegistryCreate(registry)) registry.Password = "qux" - if err := store.RegistryUpdate(registry); err != nil { - t.Errorf("Unexpected error: update registry: %s", err) - return - } + assert.NoError(t, store.RegistryUpdate(registry)) updated, err := store.RegistryFind(&model.Repo{ID: 1}, "index.docker.io") - if err != nil { - t.Error(err) - return - } - if got, want := updated.Password, "qux"; got != want { - t.Errorf("Want registry password %s, got %s", want, got) - } + assert.NoError(t, err) + assert.Equal(t, "qux", updated.Password) } func TestRegistryIndexes(t *testing.T) { store, closer := newTestStore(t, new(model.Registry)) defer closer() - if err := store.RegistryCreate(&model.Registry{ + assert.NoError(t, store.RegistryCreate(&model.Registry{ RepoID: 1, Address: "index.docker.io", Username: "foo", Password: "bar", - }); err != nil { - t.Errorf("Unexpected error: insert registry: %s", err) - return - } + })) // fail due to duplicate addr - if err := store.RegistryCreate(&model.Registry{ + assert.Error(t, store.RegistryCreate(&model.Registry{ RepoID: 1, Address: "index.docker.io", Username: "baz", Password: "qux", - }); err == nil { - t.Errorf("Unexpected error: duplicate address") - } + })) } func TestRegistryDelete(t *testing.T) { @@ -157,7 +118,7 @@ func TestRegistryDelete(t *testing.T) { Password: "bar", } if !assert.NoError(t, store.RegistryCreate(reg1)) { - t.FailNow() + return } assert.NoError(t, store.RegistryDelete(&model.Repo{ID: 1}, "index.docker.io")) diff --git a/server/store/datastore/repo_test.go b/server/store/datastore/repo_test.go index 1a05613b4e..2dcdb80937 100644 --- a/server/store/datastore/repo_test.go +++ b/server/store/datastore/repo_test.go @@ -201,19 +201,10 @@ func TestRepoList(t *testing.T) { } repos, err := store.RepoList(user, false, false) - if err != nil { - t.Error(err) - return - } - if got, want := len(repos), 2; got != want { - t.Errorf("Want %d repositories, got %d", want, got) - } - if got, want := repos[0].ID, repo1.ID; got != want { - t.Errorf("Want repository id %d, got %d", want, got) - } - if got, want := repos[1].ID, repo2.ID; got != want { - t.Errorf("Want repository id %d, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, repos, 2) + assert.Equal(t, repo1.ID, repos[0].ID) + assert.Equal(t, repo2.ID, repos[1].ID) } func TestOwnedRepoList(t *testing.T) { @@ -266,19 +257,10 @@ func TestOwnedRepoList(t *testing.T) { } repos, err := store.RepoList(user, true, false) - if err != nil { - t.Error(err) - return - } - if got, want := len(repos), 2; got != want { - t.Errorf("Want %d repositories, got %d", want, got) - } - if got, want := repos[0].ID, repo1.ID; got != want { - t.Errorf("Want repository id %d, got %d", want, got) - } - if got, want := repos[1].ID, repo2.ID; got != want { - t.Errorf("Want repository id %d, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, repos, 2) + assert.Equal(t, repo1.ID, repos[0].ID) + assert.Equal(t, repo2.ID, repos[1].ID) } func TestRepoCount(t *testing.T) { @@ -307,10 +289,9 @@ func TestRepoCount(t *testing.T) { assert.NoError(t, store.CreateRepo(repo2)) assert.NoError(t, store.CreateRepo(repo3)) - count, _ := store.GetRepoCount() - if got, want := count, int64(2); got != want { - t.Errorf("Want %d repositories, got %d", want, got) - } + count, err := store.GetRepoCount() + assert.NoError(t, err) + assert.EqualValues(t, 2, count) } func TestRepoCrud(t *testing.T) { diff --git a/server/store/datastore/secret_test.go b/server/store/datastore/secret_test.go index 78d92eabad..88171ea9c3 100644 --- a/server/store/datastore/secret_test.go +++ b/server/store/datastore/secret_test.go @@ -34,37 +34,17 @@ func TestSecretFind(t *testing.T) { Images: []string{"golang", "node"}, Events: []model.WebhookEvent{"push", "tag"}, }) - if err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, err) secret, err := store.SecretFind(&model.Repo{ID: 1}, "password") - if err != nil { - t.Error(err) - return - } - if got, want := secret.RepoID, int64(1); got != want { - t.Errorf("Want repo id %d, got %d", want, got) - } - if got, want := secret.Name, "password"; got != want { - t.Errorf("Want secret name %s, got %s", want, got) - } - if got, want := secret.Value, "correct-horse-battery-staple"; got != want { - t.Errorf("Want secret value %s, got %s", want, got) - } - if got, want := secret.Events[0], model.EventPush; got != want { - t.Errorf("Want secret event %s, got %s", want, got) - } - if got, want := secret.Events[1], model.EventTag; got != want { - t.Errorf("Want secret event %s, got %s", want, got) - } - if got, want := secret.Images[0], "golang"; got != want { - t.Errorf("Want secret image %s, got %s", want, got) - } - if got, want := secret.Images[1], "node"; got != want { - t.Errorf("Want secret image %s, got %s", want, got) - } + assert.NoError(t, err) + assert.EqualValues(t, 1, secret.RepoID) + assert.Equal(t, "password", secret.Name) + assert.Equal(t, "correct-horse-battery-staple", secret.Value) + assert.Equal(t, model.EventPush, secret.Events[0]) + assert.Equal(t, model.EventTag, secret.Events[1]) + assert.Equal(t, "golang", secret.Images[0]) + assert.Equal(t, "node", secret.Images[1]) } func TestSecretList(t *testing.T) { @@ -109,24 +89,13 @@ func TestSecretUpdate(t *testing.T) { Name: "foo", Value: "baz", } - if err := store.SecretCreate(secret); err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, store.SecretCreate(secret)) secret.Value = "qux" assert.EqualValues(t, 1, secret.ID) - if err := store.SecretUpdate(secret); err != nil { - t.Errorf("Unexpected error: update secret: %s", err) - return - } + assert.NoError(t, store.SecretUpdate(secret)) updated, err := store.SecretFind(&model.Repo{ID: 1}, "foo") - if err != nil { - t.Error(err) - return - } - if got, want := updated.Value, "qux"; got != want { - t.Errorf("Want secret value %s, got %s", want, got) - } + assert.NoError(t, err) + assert.Equal(t, "qux", updated.Value) } func TestSecretDelete(t *testing.T) { @@ -138,43 +107,29 @@ func TestSecretDelete(t *testing.T) { Name: "foo", Value: "baz", } - if err := store.SecretCreate(secret); err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, store.SecretCreate(secret)) - if err := store.SecretDelete(secret); err != nil { - t.Errorf("Unexpected error: delete secret: %s", err) - return - } + assert.NoError(t, store.SecretDelete(secret)) _, err := store.SecretFind(&model.Repo{ID: 1}, "foo") - if err == nil { - t.Errorf("Expect error: sql.ErrNoRows") - return - } + assert.Error(t, err) } func TestSecretIndexes(t *testing.T) { store, closer := newTestStore(t, new(model.Secret)) defer closer() - if err := store.SecretCreate(&model.Secret{ + assert.NoError(t, store.SecretCreate(&model.Secret{ RepoID: 1, Name: "foo", Value: "bar", - }); err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + })) // fail due to duplicate name - if err := store.SecretCreate(&model.Secret{ + assert.Error(t, store.SecretCreate(&model.Secret{ RepoID: 1, Name: "foo", Value: "baz", - }); err == nil { - t.Errorf("Unexpected error: duplicate name") - } + })) } func createTestSecrets(t *testing.T, store *storage) { @@ -210,37 +165,17 @@ func TestOrgSecretFind(t *testing.T) { Images: []string{"golang", "node"}, Events: []model.WebhookEvent{"push", "tag"}, }) - if err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, err) secret, err := store.OrgSecretFind(12, "password") - if err != nil { - t.Error(err) - return - } - if got, want := secret.OrgID, int64(12); got != want { - t.Errorf("Want org_id %d, got %d", want, got) - } - if got, want := secret.Name, "password"; got != want { - t.Errorf("Want secret name %s, got %s", want, got) - } - if got, want := secret.Value, "correct-horse-battery-staple"; got != want { - t.Errorf("Want secret value %s, got %s", want, got) - } - if got, want := secret.Events[0], model.EventPush; got != want { - t.Errorf("Want secret event %s, got %s", want, got) - } - if got, want := secret.Events[1], model.EventTag; got != want { - t.Errorf("Want secret event %s, got %s", want, got) - } - if got, want := secret.Images[0], "golang"; got != want { - t.Errorf("Want secret image %s, got %s", want, got) - } - if got, want := secret.Images[1], "node"; got != want { - t.Errorf("Want secret image %s, got %s", want, got) - } + assert.NoError(t, err) + assert.EqualValues(t, 12, secret.OrgID) + assert.Equal(t, "password", secret.Name) + assert.Equal(t, "correct-horse-battery-staple", secret.Value) + assert.Equal(t, model.EventPush, secret.Events[0]) + assert.Equal(t, model.EventTag, secret.Events[1]) + assert.Equal(t, "golang", secret.Images[0]) + assert.Equal(t, "node", secret.Images[1]) } func TestOrgSecretList(t *testing.T) { @@ -266,34 +201,16 @@ func TestGlobalSecretFind(t *testing.T) { Images: []string{"golang", "node"}, Events: []model.WebhookEvent{"push", "tag"}, }) - if err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, err) secret, err := store.GlobalSecretFind("password") - if err != nil { - t.Error(err) - return - } - if got, want := secret.Name, "password"; got != want { - t.Errorf("Want secret name %s, got %s", want, got) - } - if got, want := secret.Value, "correct-horse-battery-staple"; got != want { - t.Errorf("Want secret value %s, got %s", want, got) - } - if got, want := secret.Events[0], model.EventPush; got != want { - t.Errorf("Want secret event %s, got %s", want, got) - } - if got, want := secret.Events[1], model.EventTag; got != want { - t.Errorf("Want secret event %s, got %s", want, got) - } - if got, want := secret.Images[0], "golang"; got != want { - t.Errorf("Want secret image %s, got %s", want, got) - } - if got, want := secret.Images[1], "node"; got != want { - t.Errorf("Want secret image %s, got %s", want, got) - } + assert.NoError(t, err) + assert.Equal(t, "password", secret.Name) + assert.Equal(t, "correct-horse-battery-staple", secret.Value) + assert.Equal(t, model.EventPush, secret.Events[0]) + assert.Equal(t, model.EventTag, secret.Events[1]) + assert.Equal(t, "golang", secret.Images[0]) + assert.Equal(t, "node", secret.Images[1]) } func TestGlobalSecretList(t *testing.T) { diff --git a/server/store/datastore/server_config_test.go b/server/store/datastore/server_config_test.go index ac13d1c147..dbbeddde97 100644 --- a/server/store/datastore/server_config_test.go +++ b/server/store/datastore/server_config_test.go @@ -17,6 +17,8 @@ package datastore import ( "testing" + "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/server/model" ) @@ -28,46 +30,20 @@ func TestServerConfigGetSet(t *testing.T) { Key: "test", Value: "wonderland", } - if err := store.ServerConfigSet(serverConfig.Key, serverConfig.Value); err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, store.ServerConfigSet(serverConfig.Key, serverConfig.Value)) value, err := store.ServerConfigGet(serverConfig.Key) - if err != nil { - t.Errorf("Unexpected error: delete secret: %s", err) - return - } - - if value != serverConfig.Value { - t.Errorf("Want server-config value %s, got %s", serverConfig.Value, value) - return - } + assert.NoError(t, err) + assert.Equal(t, serverConfig.Value, value) serverConfig.Value = "new-wonderland" - if err := store.ServerConfigSet(serverConfig.Key, serverConfig.Value); err != nil { - t.Errorf("Unexpected error: insert secret: %s", err) - return - } + assert.NoError(t, store.ServerConfigSet(serverConfig.Key, serverConfig.Value)) value, err = store.ServerConfigGet(serverConfig.Key) - if err != nil { - t.Errorf("Unexpected error: delete secret: %s", err) - return - } - - if value != serverConfig.Value { - t.Errorf("Want server-config value %s, got %s", serverConfig.Value, value) - return - } + assert.NoError(t, err) + assert.Equal(t, serverConfig.Value, value) value, err = store.ServerConfigGet("config_not_exist") - if err == nil { - t.Errorf("Unexpected: no error on missing config: %v", err) - return - } - if value != "" { - t.Errorf("Unexpected: got value on missing config: %s", value) - return - } + assert.Error(t, err) + assert.Empty(t, value) } diff --git a/server/store/datastore/step_test.go b/server/store/datastore/step_test.go index 5238ab415a..74840d2e22 100644 --- a/server/store/datastore/step_test.go +++ b/server/store/datastore/step_test.go @@ -76,23 +76,12 @@ func TestStepChild(t *testing.T) { State: "success", }, }) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, err) _ = sess.Commit() step, err := store.StepChild(&model.Pipeline{ID: 1}, 1, "build") - if err != nil { - t.Error(err) - return - } - - if got, want := step.PID, 2; got != want { - t.Errorf("Want step pid %d, got %d", want, got) - } - if got, want := step.Name, "build"; got != want { - t.Errorf("Want step name %s, got %s", want, got) - } + assert.NoError(t, err) + assert.Equal(t, 2, step.PID) + assert.Equal(t, "build", step.Name) } func TestStepList(t *testing.T) { @@ -124,19 +113,12 @@ func TestStepList(t *testing.T) { State: "success", }, }) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, err) + _ = sess.Commit() steps, err := store.StepList(&model.Pipeline{ID: 1}) - if err != nil { - t.Error(err) - return - } - if got, want := len(steps), 2; got != want { - t.Errorf("Want %d steps, got %d", want, got) - } + assert.NoError(t, err) + assert.Len(t, steps, 2) } func TestStepUpdate(t *testing.T) { @@ -154,24 +136,13 @@ func TestStepUpdate(t *testing.T) { ExitCode: 255, } sess := store.engine.NewSession() - if err := store.stepCreate(sess, []*model.Step{step}); err != nil { - t.Errorf("Unexpected error: insert step: %s", err) - return - } + assert.NoError(t, store.stepCreate(sess, []*model.Step{step})) _ = sess.Commit() step.State = "running" - if err := store.StepUpdate(step); err != nil { - t.Errorf("Unexpected error: update step: %s", err) - return - } + assert.NoError(t, store.StepUpdate(step)) updated, err := store.StepFind(&model.Pipeline{ID: 1}, 1) - if err != nil { - t.Error(err) - return - } - if got, want := updated.State, model.StatusRunning; got != want { - t.Errorf("Want step name %s, got %s", want, got) - } + assert.NoError(t, err) + assert.Equal(t, model.StatusRunning, updated.State) } func TestStepIndexes(t *testing.T) { @@ -181,7 +152,7 @@ func TestStepIndexes(t *testing.T) { sess := store.engine.NewSession() defer sess.Close() - if err := store.stepCreate(sess, []*model.Step{ + assert.NoError(t, store.stepCreate(sess, []*model.Step{ { UUID: "4db7e5fc-5312-4d02-9e14-b51b9e3242cc", PipelineID: 1, @@ -190,13 +161,10 @@ func TestStepIndexes(t *testing.T) { State: "running", Name: "build", }, - }); err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + })) // fail due to duplicate pid - if err := store.stepCreate(sess, []*model.Step{ + assert.Error(t, store.stepCreate(sess, []*model.Step{ { UUID: "c1f33a9e-2a02-4579-95ec-90255d785a12", PipelineID: 1, @@ -205,9 +173,7 @@ func TestStepIndexes(t *testing.T) { State: "success", Name: "clone", }, - }); err == nil { - t.Errorf("Unexpected error: duplicate pid") - } + })) } func TestStepByUUID(t *testing.T) { diff --git a/server/store/datastore/task_test.go b/server/store/datastore/task_test.go index ff93f42b58..61e16bb81f 100644 --- a/server/store/datastore/task_test.go +++ b/server/store/datastore/task_test.go @@ -34,25 +34,15 @@ func TestTaskList(t *testing.T) { })) list, err := store.TaskList() - if err != nil { - t.Error(err) - return - } + assert.NoError(t, err) assert.Len(t, list, 1, "Expected one task in list") assert.Equal(t, "some_random_id", list[0].ID) assert.Equal(t, "foo", string(list[0].Data)) assert.EqualValues(t, map[string]model.StatusValue{"test": "dep"}, list[0].DepStatus) - err = store.TaskDelete("some_random_id") - if err != nil { - t.Error(err) - return - } + assert.NoError(t, store.TaskDelete("some_random_id")) list, err = store.TaskList() - if err != nil { - t.Error(err) - return - } + assert.NoError(t, err) assert.Len(t, list, 0, "Want empty task list after delete") } diff --git a/server/store/datastore/workflow_test.go b/server/store/datastore/workflow_test.go index 57af85f2d0..b0a6e2b68b 100644 --- a/server/store/datastore/workflow_test.go +++ b/server/store/datastore/workflow_test.go @@ -18,6 +18,8 @@ package datastore import ( "testing" + "github.com/stretchr/testify/assert" + "go.woodpecker-ci.org/woodpecker/v2/server/model" ) @@ -47,27 +49,12 @@ func TestWorkflowLoad(t *testing.T) { }, }, } - err := store.WorkflowsCreate([]*model.Workflow{wf}) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, store.WorkflowsCreate([]*model.Workflow{wf})) workflowGet, err := store.WorkflowLoad(1) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } - - if got, want := workflowGet.PipelineID, int64(1); got != want { - t.Errorf("Want pipeline id %d, got %d", want, got) - } - if got, want := workflowGet.PID, 1; got != want { - t.Errorf("Want workflow pid %d, got %d", want, got) - } - // children are not loaded - if got, want := len(workflowGet.Children), 0; got != want { - t.Errorf("Want children len %d, got %d", want, got) - } + assert.NoError(t, err) + assert.EqualValues(t, 1, workflowGet.PipelineID) + assert.Equal(t, 1, workflowGet.PID) + assert.Len(t, workflowGet.Children, 0) } func TestWorkflowGetTree(t *testing.T) { @@ -96,36 +83,16 @@ func TestWorkflowGetTree(t *testing.T) { }, }, } - err := store.WorkflowsCreate([]*model.Workflow{wf}) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, store.WorkflowsCreate([]*model.Workflow{wf})) workflowsGet, err := store.WorkflowGetTree(&model.Pipeline{ID: 1}) - if err != nil { - t.Error(err) - return - } - - if got, want := len(workflowsGet), 1; got != want { - t.Errorf("Want workflow len %d, got %d", want, got) - return - } + assert.NoError(t, err) + assert.Len(t, workflowsGet, 1) workflowGet := workflowsGet[0] - if got, want := workflowGet.Name, "woodpecker"; got != want { - t.Errorf("Want workflow name %s, got %s", want, got) - } - if got, want := len(workflowGet.Children), 2; got != want { - t.Errorf("Want children len %d, got %d", want, got) - return - } - if got, want := workflowGet.Children[0].PID, 2; got != want { - t.Errorf("Want children len %d, got %d", want, got) - } - if got, want := workflowGet.Children[1].PID, 3; got != want { - t.Errorf("Want children len %d, got %d", want, got) - } + assert.Equal(t, "woodpecker", workflowGet.Name) + assert.Len(t, workflowGet.Children, 2) + assert.Equal(t, 2, workflowGet.Children[0].PID) + assert.Equal(t, 3, workflowGet.Children[1].PID) } func TestWorkflowUpdate(t *testing.T) { @@ -138,34 +105,16 @@ func TestWorkflowUpdate(t *testing.T) { Name: "woodpecker", State: "pending", } - err := store.WorkflowsCreate([]*model.Workflow{wf}) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, store.WorkflowsCreate([]*model.Workflow{wf})) workflowGet, err := store.WorkflowLoad(1) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, err) - if got, want := workflowGet.State, model.StatusValue("pending"); got != want { - t.Errorf("Want workflow state %s, got %s", want, got) - } + assert.Equal(t, model.StatusValue("pending"), workflowGet.State) wf.State = "success" - err = store.WorkflowUpdate(wf) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } + assert.NoError(t, store.WorkflowUpdate(wf)) workflowGet, err = store.WorkflowLoad(1) - if err != nil { - t.Errorf("Unexpected error: insert steps: %s", err) - return - } - if got, want := workflowGet.State, model.StatusValue("success"); got != want { - t.Errorf("Want workflow state %s, got %s", want, got) - } + assert.NoError(t, err) + assert.Equal(t, model.StatusValue("success"), workflowGet.State) } diff --git a/woodpecker-go/woodpecker/client_test.go b/woodpecker-go/woodpecker/client_test.go index 51013c7499..15d6ab8768 100644 --- a/woodpecker-go/woodpecker/client_test.go +++ b/woodpecker-go/woodpecker/client_test.go @@ -21,6 +21,8 @@ import ( "net/http/httptest" "strings" "testing" + + "github.com/stretchr/testify/assert" ) func Test_QueueInfo(t *testing.T) { @@ -57,9 +59,8 @@ func Test_QueueInfo(t *testing.T) { client := NewClient(ts.URL, http.DefaultClient) info, err := client.QueueInfo() - if info.Stats.Workers != 3 { - t.Errorf("Unexpected worker count: %v, %v", info, err) - } + assert.NoError(t, err) + assert.Equal(t, 3, info.Stats.Workers) } func Test_LogLevel(t *testing.T) { @@ -67,16 +68,16 @@ func Test_LogLevel(t *testing.T) { fixtureHandler := func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { var ll LogLevel - if err := json.NewDecoder(r.Body).Decode(&ll); err != nil { - t.Logf("could not decode json: %v\n", err) - t.FailNow() + if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&ll)) { + return } logLevel = ll.Level } - fmt.Fprintf(w, `{ + _, err := fmt.Fprintf(w, `{ "log-level": "%s" }`, logLevel) + assert.NoError(t, err) } ts := httptest.NewServer(http.HandlerFunc(fixtureHandler)) @@ -85,24 +86,10 @@ func Test_LogLevel(t *testing.T) { client := NewClient(ts.URL, http.DefaultClient) curLvl, err := client.LogLevel() - if err != nil { - t.Logf("could not get current log level: %v", err) - t.FailNow() - } - - if !strings.EqualFold(curLvl.Level, logLevel) { - t.Logf("log level is not correct\n\tExpected: %s\n\t Got: %s\n", logLevel, curLvl.Level) - t.FailNow() - } + assert.NoError(t, err) + assert.True(t, strings.EqualFold(curLvl.Level, logLevel)) newLvl, err := client.SetLogLevel(&LogLevel{Level: "trace"}) - if err != nil { - t.Logf("could not set log level: %v", err) - t.FailNow() - } - - if !strings.EqualFold(newLvl.Level, logLevel) { - t.Logf("log level is not correct\n\tExpected: %s\n\t Got: %s\n", logLevel, newLvl.Level) - t.FailNow() - } + assert.NoError(t, err) + assert.True(t, strings.EqualFold(newLvl.Level, logLevel)) }