Skip to content

Commit

Permalink
pkg/stringid: replace TestShortenIdXXX with TestTruncateID table test
Browse files Browse the repository at this point in the history
These tests were named confusingly as they're testing `TruncateID`.
While renaming, let's also combine them into a single test using
a test-table, so that the test-cases can carry some description
what they're testing.

Signed-off-by: Sebastiaan van Stijn <[email protected]>
  • Loading branch information
thaJeztah committed Oct 20, 2024
1 parent b0632b2 commit c837027
Showing 1 changed file with 38 additions and 27 deletions.
65 changes: 38 additions & 27 deletions pkg/stringid/stringid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,46 @@ func TestGenerateRandomID(t *testing.T) {
}
}

func TestShortenId(t *testing.T) {
id := "90435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a2"
truncID := TruncateID(id)
if truncID != "90435eec5c4e" {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
func TestTruncateID(t *testing.T) {
tests := []struct {
doc, id, expected string
}{
{
doc: "empty ID",
id: "",
expected: "",
},
{
// IDs are expected to be 12 (short) or 64 characters, and not be numeric only,
// but TruncateID should handle these gracefully.
doc: "invalid ID",
id: "1234",
expected: "1234",
},
{
doc: "full ID",
id: "90435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a2",
expected: "90435eec5c4e",
},
{
doc: "digest",
id: "sha256:90435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a2",
expected: "90435eec5c4e",
},
{
doc: "very long ID",
id: "90435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a290435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a2",
expected: "90435eec5c4e",
},
}
}

func TestShortenSha256Id(t *testing.T) {
id := "sha256:4e38e38c8ce0b8d9041a9c4fefe786631d1416225e13b0bfe8cfa2321aec4bba"
truncID := TruncateID(id)
if truncID != "4e38e38c8ce0" {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
}
}

func TestShortenIdEmpty(t *testing.T) {
id := ""
truncID := TruncateID(id)
if len(truncID) > len(id) {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
}
}

func TestShortenIdInvalid(t *testing.T) {
id := "1234"
truncID := TruncateID(id)
if len(truncID) != len(id) {
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
for _, tc := range tests {
t.Run(tc.doc, func(t *testing.T) {
actual := TruncateID(tc.id)
if actual != tc.expected {
t.Errorf("expected: %q, got: %q", tc.expected, actual)
}
})
}
}

Expand Down

0 comments on commit c837027

Please sign in to comment.