Merge pull request #3885 from thaJeztah/rename_table_tests

assorted test updates
This commit is contained in:
Milos Gajdos 2023-05-09 13:58:29 +01:00 committed by GitHub
commit c9b844e533
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 424 additions and 383 deletions

View file

@ -22,7 +22,7 @@ func TestWithRequest(t *testing.T) {
req.Header.Set("User-Agent", "test/0.1") req.Header.Set("User-Agent", "test/0.1")
ctx := WithRequest(Background(), &req) ctx := WithRequest(Background(), &req)
for _, testcase := range []struct { for _, tc := range []struct {
key string key string
expected interface{} expected interface{}
}{ }{
@ -61,18 +61,18 @@ func TestWithRequest(t *testing.T) {
key: "http.request.startedat", key: "http.request.startedat",
}, },
} { } {
v := ctx.Value(testcase.key) v := ctx.Value(tc.key)
if v == nil { if v == nil {
t.Fatalf("value not found for %q", testcase.key) t.Fatalf("value not found for %q", tc.key)
} }
if testcase.expected != nil && v != testcase.expected { if tc.expected != nil && v != tc.expected {
t.Fatalf("%s: %v != %v", testcase.key, v, testcase.expected) t.Fatalf("%s: %v != %v", tc.key, v, tc.expected)
} }
// Key specific checks! // Key specific checks!
switch testcase.key { switch tc.key {
case "http.request.id": case "http.request.id":
if _, ok := v.(string); !ok { if _, ok := v.(string); !ok {
t.Fatalf("request id not a string: %v", v) t.Fatalf("request id not a string: %v", v)
@ -195,7 +195,7 @@ func TestWithVars(t *testing.T) {
} }
ctx := WithVars(Background(), &req) ctx := WithVars(Background(), &req)
for _, testcase := range []struct { for _, tc := range []struct {
key string key string
expected interface{} expected interface{}
}{ }{
@ -212,10 +212,10 @@ func TestWithVars(t *testing.T) {
expected: "qwer", expected: "qwer",
}, },
} { } {
v := ctx.Value(testcase.key) v := ctx.Value(tc.key)
if !reflect.DeepEqual(v, testcase.expected) { if !reflect.DeepEqual(v, tc.expected) {
t.Fatalf("%q: %v != %v", testcase.key, v, testcase.expected) t.Fatalf("%q: %v != %v", tc.key, v, tc.expected)
} }
} }
} }

View file

@ -1,7 +1,6 @@
package context package context
import ( import (
"context"
"runtime" "runtime"
"testing" "testing"
"time" "time"
@ -9,6 +8,7 @@ import (
// TestWithTrace ensures that tracing has the expected values in the context. // TestWithTrace ensures that tracing has the expected values in the context.
func TestWithTrace(t *testing.T) { func TestWithTrace(t *testing.T) {
t.Parallel()
pc, file, _, _ := runtime.Caller(0) // get current caller. pc, file, _, _ := runtime.Caller(0) // get current caller.
f := runtime.FuncForPC(pc) f := runtime.FuncForPC(pc)
@ -36,12 +36,29 @@ func TestWithTrace(t *testing.T) {
ctx, done := WithTrace(Background()) ctx, done := WithTrace(Background())
defer done("this will be emitted at end of test") defer done("this will be emitted at end of test")
checkContextForValues(ctx, t, append(base, valueTestCase{ tests := append(base, valueTestCase{
key: "trace.func", key: "trace.func",
expected: f.Name(), expected: f.Name(),
})) })
for _, tc := range tests {
tc := tc
t.Run(tc.key, func(t *testing.T) {
t.Parallel()
v := ctx.Value(tc.key)
if tc.notnilorempty {
if v == nil || v == "" {
t.Fatalf("value was nil or empty: %#v", v)
}
return
}
traced := func() { if v != tc.expected {
t.Fatalf("unexpected value: %v != %v", v, tc.expected)
}
})
}
tracedFn := func() {
parentID := ctx.Value("trace.id") // ensure the parent trace id is correct. parentID := ctx.Value("trace.id") // ensure the parent trace id is correct.
pc, _, _, _ := runtime.Caller(0) // get current caller. pc, _, _, _ := runtime.Caller(0) // get current caller.
@ -49,15 +66,32 @@ func TestWithTrace(t *testing.T) {
ctx, done := WithTrace(ctx) ctx, done := WithTrace(ctx)
defer done("this should be subordinate to the other trace") defer done("this should be subordinate to the other trace")
time.Sleep(time.Second) time.Sleep(time.Second)
checkContextForValues(ctx, t, append(base, valueTestCase{ tests := append(base, valueTestCase{
key: "trace.func", key: "trace.func",
expected: f.Name(), expected: f.Name(),
}, valueTestCase{ }, valueTestCase{
key: "trace.parent.id", key: "trace.parent.id",
expected: parentID, expected: parentID,
})) })
for _, tc := range tests {
tc := tc
t.Run(tc.key, func(t *testing.T) {
t.Parallel()
v := ctx.Value(tc.key)
if tc.notnilorempty {
if v == nil || v == "" {
t.Fatalf("value was nil or empty: %#v", v)
} }
traced() return
}
if v != tc.expected {
t.Fatalf("unexpected value: %v != %v", v, tc.expected)
}
})
}
}
tracedFn()
time.Sleep(time.Second) time.Sleep(time.Second)
} }
@ -67,19 +101,3 @@ type valueTestCase struct {
expected interface{} expected interface{}
notnilorempty bool // just check not empty/not nil notnilorempty bool // just check not empty/not nil
} }
func checkContextForValues(ctx context.Context, t *testing.T, values []valueTestCase) {
for _, testcase := range values {
v := ctx.Value(testcase.key)
if testcase.notnilorempty {
if v == nil || v == "" {
t.Fatalf("value was nil or empty for %q: %#v", testcase.key, v)
}
continue
}
if v != testcase.expected {
t.Fatalf("unexpected value for key %q: %v != %v", testcase.key, v, testcase.expected)
}
}
}

View file

@ -73,49 +73,49 @@ func TestIgnoredSink(t *testing.T) {
expected events.Event expected events.Event
} }
cases := []testcase{ tests := []testcase{
{nil, nil, blob}, {expected: blob},
{[]string{"other"}, []string{"other"}, blob}, {ignoreMediaTypes: []string{"other"}, ignoreActions: []string{"other"}, expected: blob},
{[]string{"blob", "manifest"}, []string{"other"}, nil}, {ignoreMediaTypes: []string{"blob", "manifest"}, ignoreActions: []string{"other"}},
{[]string{"other"}, []string{"pull"}, blob}, {ignoreMediaTypes: []string{"other"}, ignoreActions: []string{"pull"}, expected: blob},
{[]string{"other"}, []string{"pull", "push"}, nil}, {ignoreMediaTypes: []string{"other"}, ignoreActions: []string{"pull", "push"}},
} }
for _, c := range cases { for _, tc := range tests {
ts := &testSink{} ts := &testSink{}
s := newIgnoredSink(ts, c.ignoreMediaTypes, c.ignoreActions) s := newIgnoredSink(ts, tc.ignoreMediaTypes, tc.ignoreActions)
if err := s.Write(blob); err != nil { if err := s.Write(blob); err != nil {
t.Fatalf("error writing event: %v", err) t.Fatalf("error writing event: %v", err)
} }
ts.mu.Lock() ts.mu.Lock()
if !reflect.DeepEqual(ts.event, c.expected) { if !reflect.DeepEqual(ts.event, tc.expected) {
t.Fatalf("unexpected event: %#v != %#v", ts.event, c.expected) t.Fatalf("unexpected event: %#v != %#v", ts.event, tc.expected)
} }
ts.mu.Unlock() ts.mu.Unlock()
} }
cases = []testcase{ tests = []testcase{
{nil, nil, manifest}, {expected: manifest},
{[]string{"other"}, []string{"other"}, manifest}, {ignoreMediaTypes: []string{"other"}, ignoreActions: []string{"other"}, expected: manifest},
{[]string{"blob"}, []string{"other"}, manifest}, {ignoreMediaTypes: []string{"blob"}, ignoreActions: []string{"other"}, expected: manifest},
{[]string{"blob", "manifest"}, []string{"other"}, nil}, {ignoreMediaTypes: []string{"blob", "manifest"}, ignoreActions: []string{"other"}},
{[]string{"other"}, []string{"push"}, manifest}, {ignoreMediaTypes: []string{"other"}, ignoreActions: []string{"push"}, expected: manifest},
{[]string{"other"}, []string{"pull", "push"}, nil}, {ignoreMediaTypes: []string{"other"}, ignoreActions: []string{"pull", "push"}},
} }
for _, c := range cases { for _, tc := range tests {
ts := &testSink{} ts := &testSink{}
s := newIgnoredSink(ts, c.ignoreMediaTypes, c.ignoreActions) s := newIgnoredSink(ts, tc.ignoreMediaTypes, tc.ignoreActions)
if err := s.Write(manifest); err != nil { if err := s.Write(manifest); err != nil {
t.Fatalf("error writing event: %v", err) t.Fatalf("error writing event: %v", err)
} }
ts.mu.Lock() ts.mu.Lock()
if !reflect.DeepEqual(ts.event, c.expected) { if !reflect.DeepEqual(ts.event, tc.expected) {
t.Fatalf("unexpected event: %#v != %#v", ts.event, c.expected) t.Fatalf("unexpected event: %#v != %#v", ts.event, tc.expected)
} }
ts.mu.Unlock() ts.mu.Unlock()
} }

View file

@ -146,7 +146,7 @@ func TestParseRepositoryInfo(t *testing.T) {
RemoteName, FamiliarName, FullName, AmbiguousName, Domain string RemoteName, FamiliarName, FullName, AmbiguousName, Domain string
} }
tcases := []tcase{ tests := []tcase{
{ {
RemoteName: "fooo/bar", RemoteName: "fooo/bar",
FamiliarName: "fooo/bar", FamiliarName: "fooo/bar",
@ -261,7 +261,7 @@ func TestParseRepositoryInfo(t *testing.T) {
}, },
} }
for i, tc := range tcases { for i, tc := range tests {
tc := tc tc := tc
refStrings := []string{tc.FamiliarName, tc.FullName} refStrings := []string{tc.FamiliarName, tc.FullName}
if tc.AmbiguousName != "" { if tc.AmbiguousName != "" {
@ -367,7 +367,7 @@ func equalReference(r1, r2 Reference) bool {
func TestParseAnyReference(t *testing.T) { func TestParseAnyReference(t *testing.T) {
t.Parallel() t.Parallel()
tcases := []struct { tests := []struct {
Reference string Reference string
Equivalent string Equivalent string
Expected Reference Expected Reference
@ -432,33 +432,37 @@ func TestParseAnyReference(t *testing.T) {
}, },
} }
for _, tcase := range tcases { for _, tc := range tests {
tc := tc
t.Run(tc.Reference, func(t *testing.T) {
t.Parallel()
var ref Reference var ref Reference
var err error var err error
ref, err = ParseAnyReference(tcase.Reference) ref, err = ParseAnyReference(tc.Reference)
if err != nil { if err != nil {
t.Fatalf("Error parsing reference %s: %v", tcase.Reference, err) t.Fatalf("Error parsing reference %s: %v", tc.Reference, err)
} }
if ref.String() != tcase.Equivalent { if ref.String() != tc.Equivalent {
t.Fatalf("Unexpected string: %s, expected %s", ref.String(), tcase.Equivalent) t.Fatalf("Unexpected string: %s, expected %s", ref.String(), tc.Equivalent)
} }
expected := tcase.Expected expected := tc.Expected
if expected == nil { if expected == nil {
expected, err = Parse(tcase.Equivalent) expected, err = Parse(tc.Equivalent)
if err != nil { if err != nil {
t.Fatalf("Error parsing reference %s: %v", tcase.Equivalent, err) t.Fatalf("Error parsing reference %s: %v", tc.Equivalent, err)
} }
} }
if !equalReference(ref, expected) { if !equalReference(ref, expected) {
t.Errorf("Unexpected reference %#v, expected %#v", ref, expected) t.Errorf("Unexpected reference %#v, expected %#v", ref, expected)
} }
})
} }
} }
func TestNormalizedSplitHostname(t *testing.T) { func TestNormalizedSplitHostname(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
input string input string
domain string domain string
name string name string
@ -519,23 +523,22 @@ func TestNormalizedSplitHostname(t *testing.T) {
name: "library/foo/bar", name: "library/foo/bar",
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
failf := func(format string, v ...interface{}) { tc := tc
t.Logf(strconv.Quote(testcase.input)+": "+format, v...) t.Run(tc.input, func(t *testing.T) {
t.Fail() t.Parallel()
} named, err := ParseNormalizedNamed(tc.input)
named, err := ParseNormalizedNamed(testcase.input)
if err != nil { if err != nil {
failf("error parsing name: %s", err) t.Errorf("error parsing name: %s", err)
} }
domain, name := SplitHostname(named) domain, name := SplitHostname(named)
if domain != testcase.domain { if domain != tc.domain {
failf("unexpected domain: got %q, expected %q", domain, testcase.domain) t.Errorf("unexpected domain: got %q, expected %q", domain, tc.domain)
} }
if name != testcase.name { if name != tc.name {
failf("unexpected name: got %q, expected %q", name, testcase.name) t.Errorf("unexpected name: got %q, expected %q", name, tc.name)
} }
})
} }
} }
@ -553,7 +556,7 @@ func TestMatchError(t *testing.T) {
func TestMatch(t *testing.T) { func TestMatch(t *testing.T) {
t.Parallel() t.Parallel()
matchCases := []struct { tests := []struct {
reference string reference string
pattern string pattern string
expected bool expected bool
@ -604,24 +607,28 @@ func TestMatch(t *testing.T) {
expected: true, expected: true,
}, },
} }
for _, c := range matchCases { for _, tc := range tests {
named, err := ParseAnyReference(c.reference) tc := tc
t.Run(tc.reference, func(t *testing.T) {
t.Parallel()
named, err := ParseAnyReference(tc.reference)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
actual, err := FamiliarMatch(c.pattern, named) actual, err := FamiliarMatch(tc.pattern, named)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if actual != c.expected { if actual != tc.expected {
t.Fatalf("expected %s match %s to be %v, was %v", c.reference, c.pattern, c.expected, actual) t.Fatalf("expected %s match %s to be %v, was %v", tc.reference, tc.pattern, tc.expected, actual)
} }
})
} }
} }
func TestParseDockerRef(t *testing.T) { func TestParseDockerRef(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
name string name string
input string input string
expected string expected string
@ -682,17 +689,17 @@ func TestParseDockerRef(t *testing.T) {
expected: "gcr.io/library/busybox@sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59582", expected: "gcr.io/library/busybox@sha256:e6693c20186f837fc393390135d8a598a96a833917917789d63766cab6c59582",
}, },
} }
for _, test := range testcases { for _, tc := range tests {
test := test tc := tc
t.Run(test.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel() t.Parallel()
normalized, err := ParseDockerRef(test.input) normalized, err := ParseDockerRef(tc.input)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
output := normalized.String() output := normalized.String()
if output != test.expected { if output != tc.expected {
t.Fatalf("expected %q to be parsed as %v, got %v", test.input, test.expected, output) t.Fatalf("expected %q to be parsed as %v, got %v", tc.input, tc.expected, output)
} }
_, err = Parse(output) _, err = Parse(output)
if err != nil { if err != nil {

View file

@ -12,9 +12,9 @@ import (
func TestReferenceParse(t *testing.T) { func TestReferenceParse(t *testing.T) {
t.Parallel() t.Parallel()
// referenceTestcases is a unified set of testcases for // tests is a unified set of testcases for
// testing the parsing of references // testing the parsing of references
referenceTestcases := []struct { tests := []struct {
// input is the repository name or name component testcase // input is the repository name or name component testcase
input string input string
// err is the error expected from Parse, or nil // err is the error expected from Parse, or nil
@ -267,43 +267,43 @@ func TestReferenceParse(t *testing.T) {
err: ErrReferenceInvalidFormat, err: ErrReferenceInvalidFormat,
}, },
} }
for _, testcase := range referenceTestcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
repo, err := Parse(testcase.input) repo, err := Parse(tc.input)
if testcase.err != nil { if tc.err != nil {
if err == nil { if err == nil {
t.Errorf("missing expected error: %v", testcase.err) t.Errorf("missing expected error: %v", tc.err)
} else if testcase.err != err { } else if tc.err != err {
t.Errorf("mismatched error: got %v, expected %v", err, testcase.err) t.Errorf("mismatched error: got %v, expected %v", err, tc.err)
} }
return return
} else if err != nil { } else if err != nil {
t.Errorf("unexpected parse error: %v", err) t.Errorf("unexpected parse error: %v", err)
return return
} }
if repo.String() != testcase.input { if repo.String() != tc.input {
t.Errorf("mismatched repo: got %q, expected %q", repo.String(), testcase.input) t.Errorf("mismatched repo: got %q, expected %q", repo.String(), tc.input)
} }
if named, ok := repo.(Named); ok { if named, ok := repo.(Named); ok {
if named.Name() != testcase.repository { if named.Name() != tc.repository {
t.Errorf("unexpected repository: got %q, expected %q", named.Name(), testcase.repository) t.Errorf("unexpected repository: got %q, expected %q", named.Name(), tc.repository)
} }
domain, _ := SplitHostname(named) domain, _ := SplitHostname(named)
if domain != testcase.domain { if domain != tc.domain {
t.Errorf("unexpected domain: got %q, expected %q", domain, testcase.domain) t.Errorf("unexpected domain: got %q, expected %q", domain, tc.domain)
} }
} else if testcase.repository != "" || testcase.domain != "" { } else if tc.repository != "" || tc.domain != "" {
t.Errorf("expected named type, got %T", repo) t.Errorf("expected named type, got %T", repo)
} }
tagged, ok := repo.(Tagged) tagged, ok := repo.(Tagged)
if testcase.tag != "" { if tc.tag != "" {
if ok { if ok {
if tagged.Tag() != testcase.tag { if tagged.Tag() != tc.tag {
t.Errorf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag) t.Errorf("unexpected tag: got %q, expected %q", tagged.Tag(), tc.tag)
} }
} else { } else {
t.Errorf("expected tagged type, got %T", repo) t.Errorf("expected tagged type, got %T", repo)
@ -313,10 +313,10 @@ func TestReferenceParse(t *testing.T) {
} }
digested, ok := repo.(Digested) digested, ok := repo.(Digested)
if testcase.digest != "" { if tc.digest != "" {
if ok { if ok {
if digested.Digest().String() != testcase.digest { if digested.Digest().String() != tc.digest {
t.Errorf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest) t.Errorf("unexpected digest: got %q, expected %q", digested.Digest().String(), tc.digest)
} }
} else { } else {
t.Errorf("expected digested type, got %T", repo) t.Errorf("expected digested type, got %T", repo)
@ -332,7 +332,7 @@ func TestReferenceParse(t *testing.T) {
// should succeed are covered by TestSplitHostname, below. // should succeed are covered by TestSplitHostname, below.
func TestWithNameFailure(t *testing.T) { func TestWithNameFailure(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
input string input string
err error err error
}{ }{
@ -361,13 +361,13 @@ func TestWithNameFailure(t *testing.T) {
err: ErrReferenceInvalidFormat, err: ErrReferenceInvalidFormat,
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
_, err := WithName(testcase.input) _, err := WithName(tc.input)
if err == nil { if err == nil {
t.Errorf("no error parsing name. expected: %s", testcase.err) t.Errorf("no error parsing name. expected: %s", tc.err)
} }
}) })
} }
@ -375,7 +375,7 @@ func TestWithNameFailure(t *testing.T) {
func TestSplitHostname(t *testing.T) { func TestSplitHostname(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
input string input string
domain string domain string
name string name string
@ -411,20 +411,20 @@ func TestSplitHostname(t *testing.T) {
name: "foo", name: "foo",
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
named, err := WithName(testcase.input) named, err := WithName(tc.input)
if err != nil { if err != nil {
t.Errorf("error parsing name: %s", err) t.Errorf("error parsing name: %s", err)
} }
domain, name := SplitHostname(named) domain, name := SplitHostname(named)
if domain != testcase.domain { if domain != tc.domain {
t.Errorf("unexpected domain: got %q, expected %q", domain, testcase.domain) t.Errorf("unexpected domain: got %q, expected %q", domain, tc.domain)
} }
if name != testcase.name { if name != tc.name {
t.Errorf("unexpected name: got %q, expected %q", name, testcase.name) t.Errorf("unexpected name: got %q, expected %q", name, tc.name)
} }
}) })
} }
@ -437,7 +437,7 @@ type serializationType struct {
func TestSerialization(t *testing.T) { func TestSerialization(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
description string description string
input string input string
name string name string
@ -467,13 +467,13 @@ func TestSerialization(t *testing.T) {
digest: "sha256:1234567890098765432112345667890098765432112345667890098765432112", digest: "sha256:1234567890098765432112345667890098765432112345667890098765432112",
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.description, func(t *testing.T) { t.Run(tc.description, func(t *testing.T) {
t.Parallel() t.Parallel()
m := map[string]string{ m := map[string]string{
"Description": testcase.description, "Description": tc.description,
"Field": testcase.input, "Field": tc.input,
} }
b, err := json.Marshal(m) b, err := json.Marshal(m)
if err != nil { if err != nil {
@ -482,37 +482,37 @@ func TestSerialization(t *testing.T) {
st := serializationType{} st := serializationType{}
if err := json.Unmarshal(b, &st); err != nil { if err := json.Unmarshal(b, &st); err != nil {
if testcase.err == nil { if tc.err == nil {
t.Errorf("error unmarshalling: %v", err) t.Errorf("error unmarshalling: %v", err)
} }
if err != testcase.err { if err != tc.err {
t.Errorf("wrong error, expected %v, got %v", testcase.err, err) t.Errorf("wrong error, expected %v, got %v", tc.err, err)
} }
return return
} else if testcase.err != nil { } else if tc.err != nil {
t.Errorf("expected error unmarshalling: %v", testcase.err) t.Errorf("expected error unmarshalling: %v", tc.err)
} }
if st.Description != testcase.description { if st.Description != tc.description {
t.Errorf("wrong description, expected %q, got %q", testcase.description, st.Description) t.Errorf("wrong description, expected %q, got %q", tc.description, st.Description)
} }
ref := st.Field.Reference() ref := st.Field.Reference()
if named, ok := ref.(Named); ok { if named, ok := ref.(Named); ok {
if named.Name() != testcase.name { if named.Name() != tc.name {
t.Errorf("unexpected repository: got %q, expected %q", named.Name(), testcase.name) t.Errorf("unexpected repository: got %q, expected %q", named.Name(), tc.name)
} }
} else if testcase.name != "" { } else if tc.name != "" {
t.Errorf("expected named type, got %T", ref) t.Errorf("expected named type, got %T", ref)
} }
tagged, ok := ref.(Tagged) tagged, ok := ref.(Tagged)
if testcase.tag != "" { if tc.tag != "" {
if ok { if ok {
if tagged.Tag() != testcase.tag { if tagged.Tag() != tc.tag {
t.Errorf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag) t.Errorf("unexpected tag: got %q, expected %q", tagged.Tag(), tc.tag)
} }
} else { } else {
t.Errorf("expected tagged type, got %T", ref) t.Errorf("expected tagged type, got %T", ref)
@ -522,10 +522,10 @@ func TestSerialization(t *testing.T) {
} }
digested, ok := ref.(Digested) digested, ok := ref.(Digested)
if testcase.digest != "" { if tc.digest != "" {
if ok { if ok {
if digested.Digest().String() != testcase.digest { if digested.Digest().String() != tc.digest {
t.Errorf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest) t.Errorf("unexpected digest: got %q, expected %q", digested.Digest().String(), tc.digest)
} }
} else { } else {
t.Errorf("expected digested type, got %T", ref) t.Errorf("expected digested type, got %T", ref)
@ -535,7 +535,7 @@ func TestSerialization(t *testing.T) {
} }
st = serializationType{ st = serializationType{
Description: testcase.description, Description: tc.description,
Field: AsField(ref), Field: AsField(ref),
} }
@ -560,7 +560,7 @@ func TestSerialization(t *testing.T) {
func TestWithTag(t *testing.T) { func TestWithTag(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
name string name string
digest digest.Digest digest digest.Digest
tag string tag string
@ -593,28 +593,28 @@ func TestWithTag(t *testing.T) {
combined: "test.com:8000/foo:TAG5@sha256:1234567890098765432112345667890098765", combined: "test.com:8000/foo:TAG5@sha256:1234567890098765432112345667890098765",
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.combined, func(t *testing.T) { t.Run(tc.combined, func(t *testing.T) {
t.Parallel() t.Parallel()
named, err := WithName(testcase.name) named, err := WithName(tc.name)
if err != nil { if err != nil {
t.Errorf("error parsing name: %s", err) t.Errorf("error parsing name: %s", err)
} }
if testcase.digest != "" { if tc.digest != "" {
canonical, err := WithDigest(named, testcase.digest) canonical, err := WithDigest(named, tc.digest)
if err != nil { if err != nil {
t.Errorf("error adding digest") t.Errorf("error adding digest")
} }
named = canonical named = canonical
} }
tagged, err := WithTag(named, testcase.tag) tagged, err := WithTag(named, tc.tag)
if err != nil { if err != nil {
t.Errorf("WithTag failed: %s", err) t.Errorf("WithTag failed: %s", err)
} }
if tagged.String() != testcase.combined { if tagged.String() != tc.combined {
t.Errorf("unexpected: got %q, expected %q", tagged.String(), testcase.combined) t.Errorf("unexpected: got %q, expected %q", tagged.String(), tc.combined)
} }
}) })
} }
@ -622,7 +622,7 @@ func TestWithTag(t *testing.T) {
func TestWithDigest(t *testing.T) { func TestWithDigest(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
name string name string
digest digest.Digest digest digest.Digest
tag string tag string
@ -650,27 +650,27 @@ func TestWithDigest(t *testing.T) {
combined: "test.com:8000/foo:latest@sha256:1234567890098765432112345667890098765", combined: "test.com:8000/foo:latest@sha256:1234567890098765432112345667890098765",
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.combined, func(t *testing.T) { t.Run(tc.combined, func(t *testing.T) {
t.Parallel() t.Parallel()
named, err := WithName(testcase.name) named, err := WithName(tc.name)
if err != nil { if err != nil {
t.Errorf("error parsing name: %s", err) t.Errorf("error parsing name: %s", err)
} }
if testcase.tag != "" { if tc.tag != "" {
tagged, err := WithTag(named, testcase.tag) tagged, err := WithTag(named, tc.tag)
if err != nil { if err != nil {
t.Errorf("error adding tag") t.Errorf("error adding tag")
} }
named = tagged named = tagged
} }
digested, err := WithDigest(named, testcase.digest) digested, err := WithDigest(named, tc.digest)
if err != nil { if err != nil {
t.Errorf("WithDigest failed: %s", err) t.Errorf("WithDigest failed: %s", err)
} }
if digested.String() != testcase.combined { if digested.String() != tc.combined {
t.Errorf("unexpected: got %q, expected %q", digested.String(), testcase.combined) t.Errorf("unexpected: got %q, expected %q", digested.String(), tc.combined)
} }
}) })
} }
@ -678,7 +678,7 @@ func TestWithDigest(t *testing.T) {
func TestParseNamed(t *testing.T) { func TestParseNamed(t *testing.T) {
t.Parallel() t.Parallel()
testcases := []struct { tests := []struct {
input string input string
domain string domain string
name string name string
@ -721,30 +721,30 @@ func TestParseNamed(t *testing.T) {
err: ErrNameNotCanonical, err: ErrNameNotCanonical,
}, },
} }
for _, testcase := range testcases { for _, tc := range tests {
testcase := testcase tc := tc
t.Run(testcase.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
named, err := ParseNamed(testcase.input) named, err := ParseNamed(tc.input)
if err != nil && testcase.err == nil { if err != nil && tc.err == nil {
t.Errorf("error parsing name: %s", err) t.Errorf("error parsing name: %s", err)
return return
} else if err == nil && testcase.err != nil { } else if err == nil && tc.err != nil {
t.Errorf("parsing succeeded: expected error %v", testcase.err) t.Errorf("parsing succeeded: expected error %v", tc.err)
return return
} else if err != testcase.err { } else if err != tc.err {
t.Errorf("unexpected error %v, expected %v", err, testcase.err) t.Errorf("unexpected error %v, expected %v", err, tc.err)
return return
} else if err != nil { } else if err != nil {
return return
} }
domain, name := SplitHostname(named) domain, name := SplitHostname(named)
if domain != testcase.domain { if domain != tc.domain {
t.Errorf("unexpected domain: got %q, expected %q", domain, testcase.domain) t.Errorf("unexpected domain: got %q, expected %q", domain, tc.domain)
} }
if name != testcase.name { if name != tc.name {
t.Errorf("unexpected name: got %q, expected %q", name, testcase.name) t.Errorf("unexpected name: got %q, expected %q", name, tc.name)
} }
}) })
} }

View file

@ -36,7 +36,7 @@ func checkRegexp(t *testing.T, r *regexp.Regexp, m regexpMatch) {
func TestDomainRegexp(t *testing.T) { func TestDomainRegexp(t *testing.T) {
t.Parallel() t.Parallel()
hostcases := []struct { tests := []struct {
input string input string
match bool match bool
}{ }{
@ -162,7 +162,7 @@ func TestDomainRegexp(t *testing.T) {
}, },
} }
r := regexp.MustCompile(`^` + DomainRegexp.String() + `$`) r := regexp.MustCompile(`^` + DomainRegexp.String() + `$`)
for _, tc := range hostcases { for _, tc := range tests {
tc := tc tc := tc
t.Run(tc.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -181,7 +181,7 @@ func TestFullNameRegexp(t *testing.T) {
anchoredNameRegexp, anchoredNameRegexp.NumSubexp()) anchoredNameRegexp, anchoredNameRegexp.NumSubexp())
} }
testcases := []regexpMatch{ tests := []regexpMatch{
{ {
input: "", input: "",
match: false, match: false,
@ -465,7 +465,7 @@ func TestFullNameRegexp(t *testing.T) {
match: false, match: false,
}, },
} }
for _, tc := range testcases { for _, tc := range tests {
tc := tc tc := tc
t.Run(tc.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -481,7 +481,7 @@ func TestReferenceRegexp(t *testing.T) {
ReferenceRegexp, ReferenceRegexp.NumSubexp()) ReferenceRegexp, ReferenceRegexp.NumSubexp())
} }
testcases := []regexpMatch{ tests := []regexpMatch{
{ {
input: "registry.com:8080/myapp:tag", input: "registry.com:8080/myapp:tag",
match: true, match: true,
@ -540,7 +540,7 @@ func TestReferenceRegexp(t *testing.T) {
}, },
} }
for _, tc := range testcases { for _, tc := range tests {
tc := tc tc := tc
t.Run(tc.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()
@ -551,7 +551,7 @@ func TestReferenceRegexp(t *testing.T) {
func TestIdentifierRegexp(t *testing.T) { func TestIdentifierRegexp(t *testing.T) {
t.Parallel() t.Parallel()
fullCases := []struct { tests := []struct {
input string input string
match bool match bool
}{ }{
@ -576,7 +576,7 @@ func TestIdentifierRegexp(t *testing.T) {
match: false, match: false,
}, },
} }
for _, tc := range fullCases { for _, tc := range tests {
tc := tc tc := tc
t.Run(tc.input, func(t *testing.T) { t.Run(tc.input, func(t *testing.T) {
t.Parallel() t.Parallel()

View file

@ -34,11 +34,14 @@ var ErrorCodeTest3 = Register("test.errors", ErrorDescriptor{
// TestErrorCodes ensures that error code format, mappings and // TestErrorCodes ensures that error code format, mappings and
// marshaling/unmarshaling. round trips are stable. // marshaling/unmarshaling. round trips are stable.
func TestErrorCodes(t *testing.T) { func TestErrorCodes(t *testing.T) {
t.Parallel()
if len(errorCodeToDescriptors) == 0 { if len(errorCodeToDescriptors) == 0 {
t.Fatal("errors aren't loaded!") t.Fatal("errors aren't loaded!")
} }
for ec, desc := range errorCodeToDescriptors { for ec, desc := range errorCodeToDescriptors {
t.Run(ec.String(), func(t *testing.T) {
t.Parallel()
if ec != desc.Code { if ec != desc.Code {
t.Fatalf("error code in descriptor isn't correct, %q != %q", ec, desc.Code) t.Fatalf("error code in descriptor isn't correct, %q != %q", ec, desc.Code)
} }
@ -48,7 +51,7 @@ func TestErrorCodes(t *testing.T) {
} }
if ec.Message() != desc.Message { if ec.Message() != desc.Message {
t.Fatalf("ec.Message doesn't mtach desc.Message: %q != %q", ec.Message(), desc.Message) t.Fatalf("ec.Message doesn't match desc.Message: %q != %q", ec.Message(), desc.Message)
} }
// Test (de)serializing the ErrorCode // Test (de)serializing the ErrorCode
@ -85,6 +88,7 @@ func TestErrorCodes(t *testing.T) {
if ec.Error() != expectedErrorString { if ec.Error() != expectedErrorString {
t.Fatalf("unexpected return from %v.Error(): %q != %q", ec, ec.Error(), expectedErrorString) t.Fatalf("unexpected return from %v.Error(): %q != %q", ec, ec.Error(), expectedErrorString)
} }
})
} }
} }

View file

@ -29,7 +29,8 @@ type routeTestCase struct {
// //
// This may go away as the application structure comes together. // This may go away as the application structure comes together.
func TestRouter(t *testing.T) { func TestRouter(t *testing.T) {
testCases := []routeTestCase{ t.Parallel()
tests := []routeTestCase{
{ {
RouteName: RouteNameBase, RouteName: RouteNameBase,
RequestURI: "/v2/", RequestURI: "/v2/",
@ -172,12 +173,13 @@ func TestRouter(t *testing.T) {
}, },
} }
checkTestRouter(t, testCases, "", true) checkTestRouter(t, tests, "", true)
checkTestRouter(t, testCases, "/prefix/", true) checkTestRouter(t, tests, "/prefix/", true)
} }
func TestRouterWithPathTraversals(t *testing.T) { func TestRouterWithPathTraversals(t *testing.T) {
testCases := []routeTestCase{ t.Parallel()
tests := []routeTestCase{
{ {
RouteName: RouteNameBlobUploadChunk, RouteName: RouteNameBlobUploadChunk,
RequestURI: "/v2/foo/../../blobs/uploads/D95306FA-FAD3-4E36-8D41-CF1C93EF8286", RequestURI: "/v2/foo/../../blobs/uploads/D95306FA-FAD3-4E36-8D41-CF1C93EF8286",
@ -194,12 +196,13 @@ func TestRouterWithPathTraversals(t *testing.T) {
}, },
}, },
} }
checkTestRouter(t, testCases, "", false) checkTestRouter(t, tests, "", false)
} }
func TestRouterWithBadCharacters(t *testing.T) { func TestRouterWithBadCharacters(t *testing.T) {
t.Parallel()
if testing.Short() { if testing.Short() {
testCases := []routeTestCase{ tests := []routeTestCase{
{ {
RouteName: RouteNameBlobUploadChunk, RouteName: RouteNameBlobUploadChunk,
RequestURI: "/v2/foo/blobs/uploads/不95306FA-FAD3-4E36-8D41-CF1C93EF8286", RequestURI: "/v2/foo/blobs/uploads/不95306FA-FAD3-4E36-8D41-CF1C93EF8286",
@ -212,26 +215,26 @@ func TestRouterWithBadCharacters(t *testing.T) {
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
}, },
} }
checkTestRouter(t, testCases, "", true) checkTestRouter(t, tests, "", true)
} else { } else {
// in the long version we're going to fuzz the router // in the long version we're going to fuzz the router
// with random UTF8 characters not in the 128 bit ASCII range. // with random UTF8 characters not in the 128 bit ASCII range.
// These are not valid characters for the router and we expect // These are not valid characters for the router and we expect
// 404s on every test. // 404s on every test.
rand.Seed(time.Now().UTC().UnixNano()) rand.Seed(time.Now().UTC().UnixNano())
testCases := make([]routeTestCase, 1000) tests := make([]routeTestCase, 1000)
for idx := range testCases { for idx := range tests {
testCases[idx] = routeTestCase{ tests[idx] = routeTestCase{
RouteName: RouteNameTags, RouteName: RouteNameTags,
RequestURI: fmt.Sprintf("/v2/%v/%v/tags/list", randomString(10), randomString(10)), RequestURI: fmt.Sprintf("/v2/%v/%v/tags/list", randomString(10), randomString(10)),
StatusCode: http.StatusNotFound, StatusCode: http.StatusNotFound,
} }
} }
checkTestRouter(t, testCases, "", true) checkTestRouter(t, tests, "", true)
} }
} }
func checkTestRouter(t *testing.T, testCases []routeTestCase, prefix string, deeplyEqual bool) { func checkTestRouter(t *testing.T, tests []routeTestCase, prefix string, deeplyEqual bool) {
router := RouterWithPrefix(prefix) router := RouterWithPrefix(prefix)
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@ -252,40 +255,44 @@ func checkTestRouter(t *testing.T, testCases []routeTestCase, prefix string, dee
// Startup test server // Startup test server
server := httptest.NewServer(router) server := httptest.NewServer(router)
for _, testcase := range testCases { for _, tc := range tests {
testcase.RequestURI = strings.TrimSuffix(prefix, "/") + testcase.RequestURI tc := tc
requestURI := strings.TrimSuffix(prefix, "/") + tc.RequestURI
t.Run("("+tc.RouteName+")"+requestURI, func(t *testing.T) {
t.Parallel()
tc.RequestURI = requestURI
// Register the endpoint // Register the endpoint
route := router.GetRoute(testcase.RouteName) route := router.GetRoute(tc.RouteName)
if route == nil { if route == nil {
t.Fatalf("route for name %q not found", testcase.RouteName) t.Fatalf("route for name %q not found", tc.RouteName)
} }
route.Handler(testHandler) route.Handler(testHandler)
u := server.URL + testcase.RequestURI u := server.URL + tc.RequestURI
resp, err := http.Get(u) resp, err := http.Get(u)
if err != nil { if err != nil {
t.Fatalf("error issuing get request: %v", err) t.Fatalf("error issuing get request: %v", err)
} }
if testcase.StatusCode == 0 { if tc.StatusCode == 0 {
// Override default, zero-value // Override default, zero-value
testcase.StatusCode = http.StatusOK tc.StatusCode = http.StatusOK
} }
if testcase.ExpectedURI == "" { if tc.ExpectedURI == "" {
// Override default, zero-value // Override default, zero-value
testcase.ExpectedURI = testcase.RequestURI tc.ExpectedURI = tc.RequestURI
} }
if resp.StatusCode != testcase.StatusCode { if resp.StatusCode != tc.StatusCode {
t.Fatalf("unexpected status for %s: %v %v", u, resp.Status, resp.StatusCode) t.Fatalf("unexpected status for %s: %v %v", u, resp.Status, resp.StatusCode)
} }
if testcase.StatusCode != http.StatusOK { if tc.StatusCode != http.StatusOK {
resp.Body.Close() resp.Body.Close()
// We don't care about json response. // We don't care about json response.
continue return
} }
dec := json.NewDecoder(resp.Body) dec := json.NewDecoder(resp.Body)
@ -297,23 +304,24 @@ func checkTestRouter(t *testing.T, testCases []routeTestCase, prefix string, dee
// Needs to be set out of band // Needs to be set out of band
actualRouteInfo.StatusCode = resp.StatusCode actualRouteInfo.StatusCode = resp.StatusCode
if actualRouteInfo.RequestURI != testcase.ExpectedURI { if actualRouteInfo.RequestURI != tc.ExpectedURI {
t.Fatalf("URI %v incorrectly parsed, expected %v", actualRouteInfo.RequestURI, testcase.ExpectedURI) t.Fatalf("URI %v incorrectly parsed, expected %v", actualRouteInfo.RequestURI, tc.ExpectedURI)
} }
if actualRouteInfo.RouteName != testcase.RouteName { if actualRouteInfo.RouteName != tc.RouteName {
t.Fatalf("incorrect route %q matched, expected %q", actualRouteInfo.RouteName, testcase.RouteName) t.Fatalf("incorrect route %q matched, expected %q", actualRouteInfo.RouteName, tc.RouteName)
} }
// when testing deep equality, the actualRouteInfo has an empty ExpectedURI, we don't want // when testing deep equality, the actualRouteInfo has an empty ExpectedURI, we don't want
// that to make the comparison fail. We're otherwise done with the testcase so empty the // that to make the comparison fail. We're otherwise done with the testcase so empty the
// testcase.ExpectedURI // testcase.ExpectedURI
testcase.ExpectedURI = "" tc.ExpectedURI = ""
if deeplyEqual && !reflect.DeepEqual(actualRouteInfo, testcase) { if deeplyEqual && !reflect.DeepEqual(actualRouteInfo, tc) {
t.Fatalf("actual does not equal expected: %#v != %#v", actualRouteInfo, testcase) t.Fatalf("actual does not equal expected: %#v != %#v", actualRouteInfo, tc)
} }
resp.Body.Close() resp.Body.Close()
})
} }
} }

View file

@ -138,23 +138,23 @@ func TestURLBuilder(t *testing.T) {
t.Fatalf("unexpected error creating urlbuilder: %v", err) t.Fatalf("unexpected error creating urlbuilder: %v", err)
} }
for _, testCase := range makeURLBuilderTestCases(urlBuilder) { for _, tc := range makeURLBuilderTestCases(urlBuilder) {
url, err := testCase.build() buildURL, err := tc.build()
expectedErr := testCase.expectedErr expectedErr := tc.expectedErr
if !reflect.DeepEqual(expectedErr, err) { if !reflect.DeepEqual(expectedErr, err) {
t.Fatalf("%s: Expecting %v but got error %v", testCase.description, expectedErr, err) t.Fatalf("%s: Expecting %v but got error %v", tc.description, expectedErr, err)
} }
if expectedErr != nil { if expectedErr != nil {
continue continue
} }
expectedURL := testCase.expectedPath expectedURL := tc.expectedPath
if !relative { if !relative {
expectedURL = root + expectedURL expectedURL = root + expectedURL
} }
if url != expectedURL { if buildURL != expectedURL {
t.Fatalf("%s: %q != %q", testCase.description, url, expectedURL) t.Fatalf("%s: %q != %q", tc.description, buildURL, expectedURL)
} }
} }
} }
@ -178,22 +178,22 @@ func TestURLBuilderWithPrefix(t *testing.T) {
t.Fatalf("unexpected error creating urlbuilder: %v", err) t.Fatalf("unexpected error creating urlbuilder: %v", err)
} }
for _, testCase := range makeURLBuilderTestCases(urlBuilder) { for _, tc := range makeURLBuilderTestCases(urlBuilder) {
url, err := testCase.build() buildURL, err := tc.build()
expectedErr := testCase.expectedErr expectedErr := tc.expectedErr
if !reflect.DeepEqual(expectedErr, err) { if !reflect.DeepEqual(expectedErr, err) {
t.Fatalf("%s: Expecting %v but got error %v", testCase.description, expectedErr, err) t.Fatalf("%s: Expecting %v but got error %v", tc.description, expectedErr, err)
} }
if expectedErr != nil { if expectedErr != nil {
continue continue
} }
expectedURL := testCase.expectedPath expectedURL := tc.expectedPath
if !relative { if !relative {
expectedURL = root[0:len(root)-1] + expectedURL expectedURL = root[0:len(root)-1] + expectedURL
} }
if url != expectedURL { if buildURL != expectedURL {
t.Fatalf("%s: %q != %q", testCase.description, url, expectedURL) t.Fatalf("%s: %q != %q", tc.description, buildURL, expectedURL)
} }
} }
} }
@ -424,23 +424,23 @@ func TestBuilderFromRequest(t *testing.T) {
builder = NewURLBuilderFromRequest(tr.request, relative) builder = NewURLBuilderFromRequest(tr.request, relative)
} }
for _, testCase := range makeURLBuilderTestCases(builder) { for _, tc := range makeURLBuilderTestCases(builder) {
buildURL, err := testCase.build() buildURL, err := tc.build()
expectedErr := testCase.expectedErr expectedErr := tc.expectedErr
if !reflect.DeepEqual(expectedErr, err) { if !reflect.DeepEqual(expectedErr, err) {
t.Fatalf("%s: Expecting %v but got error %v", testCase.description, expectedErr, err) t.Fatalf("%s: Expecting %v but got error %v", tc.description, expectedErr, err)
} }
if expectedErr != nil { if expectedErr != nil {
continue continue
} }
expectedURL := testCase.expectedPath expectedURL := tc.expectedPath
if !relative { if !relative {
expectedURL = tr.base + expectedURL expectedURL = tr.base + expectedURL
} }
if buildURL != expectedURL { if buildURL != expectedURL {
t.Errorf("[relative=%t, request=%q, case=%q]: %q != %q", relative, tr.name, testCase.description, buildURL, expectedURL) t.Errorf("[relative=%t, request=%q, case=%q]: %q != %q", relative, tr.name, tc.description, buildURL, expectedURL)
} }
} }
} }
@ -497,11 +497,11 @@ func TestBuilderFromRequestWithPrefix(t *testing.T) {
builder = NewURLBuilderFromRequest(tr.request, false) builder = NewURLBuilderFromRequest(tr.request, false)
} }
for _, testCase := range makeURLBuilderTestCases(builder) { for _, tc := range makeURLBuilderTestCases(builder) {
buildURL, err := testCase.build() buildURL, err := tc.build()
expectedErr := testCase.expectedErr expectedErr := tc.expectedErr
if !reflect.DeepEqual(expectedErr, err) { if !reflect.DeepEqual(expectedErr, err) {
t.Fatalf("%s: Expecting %v but got error %v", testCase.description, expectedErr, err) t.Fatalf("%s: Expecting %v but got error %v", tc.description, expectedErr, err)
} }
if expectedErr != nil { if expectedErr != nil {
continue continue
@ -510,7 +510,7 @@ func TestBuilderFromRequestWithPrefix(t *testing.T) {
var expectedURL string var expectedURL string
proto, ok := tr.request.Header["X-Forwarded-Proto"] proto, ok := tr.request.Header["X-Forwarded-Proto"]
if !ok { if !ok {
expectedURL = testCase.expectedPath expectedURL = tc.expectedPath
if !relative { if !relative {
expectedURL = tr.base[0:len(tr.base)-1] + expectedURL expectedURL = tr.base[0:len(tr.base)-1] + expectedURL
} }
@ -520,7 +520,7 @@ func TestBuilderFromRequestWithPrefix(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
urlBase.Scheme = proto[0] urlBase.Scheme = proto[0]
expectedURL = testCase.expectedPath expectedURL = tc.expectedPath
if !relative { if !relative {
expectedURL = urlBase.String()[0:len(urlBase.String())-1] + expectedURL expectedURL = urlBase.String()[0:len(urlBase.String())-1] + expectedURL
} }
@ -528,7 +528,7 @@ func TestBuilderFromRequestWithPrefix(t *testing.T) {
} }
if buildURL != expectedURL { if buildURL != expectedURL {
t.Fatalf("%s: %q != %q", testCase.description, buildURL, expectedURL) t.Fatalf("%s: %q != %q", tc.description, buildURL, expectedURL)
} }
} }
} }

View file

@ -6,8 +6,9 @@ import (
) )
func TestAudienceList_Unmarshal(t *testing.T) { func TestAudienceList_Unmarshal(t *testing.T) {
t.Parallel()
t.Run("OK", func(t *testing.T) { t.Run("OK", func(t *testing.T) {
testCases := []struct { tests := []struct {
value string value string
expected AudienceList expected AudienceList
}{ }{
@ -25,23 +26,24 @@ func TestAudienceList_Unmarshal(t *testing.T) {
}, },
} }
for _, testCase := range testCases { for _, tc := range tests {
testCase := testCase tc := tc
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
t.Parallel()
var actual AudienceList var actual AudienceList
err := json.Unmarshal([]byte(testCase.value), &actual) err := json.Unmarshal([]byte(tc.value), &actual)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
assertStringListEqual(t, testCase.expected, actual) assertStringListEqual(t, tc.expected, actual)
}) })
} }
}) })
t.Run("Error", func(t *testing.T) { t.Run("Error", func(t *testing.T) {
t.Parallel()
var actual AudienceList var actual AudienceList
err := json.Unmarshal([]byte("1234"), &actual) err := json.Unmarshal([]byte("1234"), &actual)

View file

@ -45,8 +45,8 @@ var secrets = []string{
func TestLayerUploadTokens(t *testing.T) { func TestLayerUploadTokens(t *testing.T) {
secret := hmacKey("supersecret") secret := hmacKey("supersecret")
for _, testcase := range blobUploadStates { for _, tc := range blobUploadStates {
token, err := secret.packUploadState(testcase) token, err := secret.packUploadState(tc)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -56,7 +56,7 @@ func TestLayerUploadTokens(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
assertBlobUploadStateEquals(t, testcase, lus) assertBlobUploadStateEquals(t, tc, lus)
} }
} }
@ -68,8 +68,8 @@ func TestHMACValidation(t *testing.T) {
secret2 := hmacKey(secret) secret2 := hmacKey(secret)
badSecret := hmacKey("DifferentSecret") badSecret := hmacKey("DifferentSecret")
for _, testcase := range blobUploadStates { for _, tc := range blobUploadStates {
token, err := secret1.packUploadState(testcase) token, err := secret1.packUploadState(tc)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -79,7 +79,7 @@ func TestHMACValidation(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
assertBlobUploadStateEquals(t, testcase, lus) assertBlobUploadStateEquals(t, tc, lus)
_, err = badSecret.unpackUploadState(token) _, err = badSecret.unpackUploadState(token)
if err == nil { if err == nil {
@ -105,6 +105,7 @@ func TestHMACValidation(t *testing.T) {
} }
func assertBlobUploadStateEquals(t *testing.T, expected blobUploadState, received blobUploadState) { func assertBlobUploadStateEquals(t *testing.T, expected blobUploadState, received blobUploadState) {
t.Helper()
if expected.Name != received.Name { if expected.Name != received.Name {
t.Fatalf("Expected Name=%q, Received Name=%q", expected.Name, received.Name) t.Fatalf("Expected Name=%q, Received Name=%q", expected.Name, received.Name)
} }

View file

@ -8,12 +8,11 @@ import (
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"reflect" // used as a replacement for testify
"testing" "testing"
"time" "time"
dcontext "github.com/distribution/distribution/v3/context" dcontext "github.com/distribution/distribution/v3/context"
"reflect" // used as a replacement for testify
) )
// Rather than pull in all of testify // Rather than pull in all of testify
@ -262,7 +261,8 @@ func TestUpdateCalledRegularly(t *testing.T) {
} }
func TestEligibleForS3(t *testing.T) { func TestEligibleForS3(t *testing.T) {
awsIPs := &awsIPs{ t.Parallel()
ips := &awsIPs{
ipv4: []net.IPNet{{ ipv4: []net.IPNet{{
IP: net.ParseIP("192.168.1.1"), IP: net.ParseIP("192.168.1.1"),
Mask: net.IPv4Mask(255, 255, 255, 0), Mask: net.IPv4Mask(255, 255, 255, 0),
@ -278,7 +278,7 @@ func TestEligibleForS3(t *testing.T) {
return dcontext.WithRequest(empty, req) return dcontext.WithRequest(empty, req)
} }
cases := []struct { tests := []struct {
Context context.Context Context context.Context
Expected bool Expected bool
}{ }{
@ -287,17 +287,18 @@ func TestEligibleForS3(t *testing.T) {
{Context: makeContext("192.168.0.2"), Expected: false}, {Context: makeContext("192.168.0.2"), Expected: false},
} }
for _, testCase := range cases { for _, tc := range tests {
name := fmt.Sprintf("Client IP = %v", tc := tc
testCase.Context.Value("http.request.ip")) t.Run(fmt.Sprintf("Client IP = %v", tc.Context.Value("http.request.ip")), func(t *testing.T) {
t.Run(name, func(t *testing.T) { t.Parallel()
assertEqual(t, testCase.Expected, eligibleForS3(testCase.Context, awsIPs)) assertEqual(t, tc.Expected, eligibleForS3(tc.Context, ips))
}) })
} }
} }
func TestEligibleForS3WithAWSIPNotInitialized(t *testing.T) { func TestEligibleForS3WithAWSIPNotInitialized(t *testing.T) {
awsIPs := &awsIPs{ t.Parallel()
ips := &awsIPs{
ipv4: []net.IPNet{{ ipv4: []net.IPNet{{
IP: net.ParseIP("192.168.1.1"), IP: net.ParseIP("192.168.1.1"),
Mask: net.IPv4Mask(255, 255, 255, 0), Mask: net.IPv4Mask(255, 255, 255, 0),
@ -313,7 +314,7 @@ func TestEligibleForS3WithAWSIPNotInitialized(t *testing.T) {
return dcontext.WithRequest(empty, req) return dcontext.WithRequest(empty, req)
} }
cases := []struct { tests := []struct {
Context context.Context Context context.Context
Expected bool Expected bool
}{ }{
@ -322,11 +323,11 @@ func TestEligibleForS3WithAWSIPNotInitialized(t *testing.T) {
{Context: makeContext("192.168.0.2"), Expected: false}, {Context: makeContext("192.168.0.2"), Expected: false},
} }
for _, testCase := range cases { for _, tc := range tests {
name := fmt.Sprintf("Client IP = %v", tc := tc
testCase.Context.Value("http.request.ip")) t.Run(fmt.Sprintf("Client IP = %v", tc.Context.Value("http.request.ip")), func(t *testing.T) {
t.Run(name, func(t *testing.T) { t.Parallel()
assertEqual(t, testCase.Expected, eligibleForS3(testCase.Context, awsIPs)) assertEqual(t, tc.Expected, eligibleForS3(tc.Context, ips))
}) })
} }
} }
@ -364,8 +365,8 @@ func BenchmarkContainsRandom(b *testing.B) {
numNetworksPerType := 1000 // keep in sync with the above numNetworksPerType := 1000 // keep in sync with the above
// intentionally skip constructor when creating awsIPs, to avoid updater routine. // intentionally skip constructor when creating awsIPs, to avoid updater routine.
// This benchmark is only concerned with contains() performance. // This benchmark is only concerned with contains() performance.
awsIPs := awsIPs{} ips := awsIPs{}
populateRandomNetworks(b, &awsIPs, numNetworksPerType, numNetworksPerType) populateRandomNetworks(b, &ips, numNetworksPerType, numNetworksPerType)
ipv4 := make([][]byte, b.N) ipv4 := make([][]byte, b.N)
ipv6 := make([][]byte, b.N) ipv6 := make([][]byte, b.N)
@ -377,13 +378,13 @@ func BenchmarkContainsRandom(b *testing.B) {
} }
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
awsIPs.contains(ipv4[i]) ips.contains(ipv4[i])
awsIPs.contains(ipv6[i]) ips.contains(ipv6[i])
} }
} }
func BenchmarkContainsProd(b *testing.B) { func BenchmarkContainsProd(b *testing.B) {
awsIPs := newAWSIPs(defaultIPRangesURL, defaultUpdateFrequency, nil) ips := newAWSIPs(defaultIPRangesURL, defaultUpdateFrequency, nil)
ipv4 := make([][]byte, b.N) ipv4 := make([][]byte, b.N)
ipv6 := make([][]byte, b.N) ipv6 := make([][]byte, b.N)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -394,7 +395,7 @@ func BenchmarkContainsProd(b *testing.B) {
} }
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
awsIPs.contains(ipv4[i]) ips.contains(ipv4[i])
awsIPs.contains(ipv6[i]) ips.contains(ipv6[i])
} }
} }