From 9afdf020b71392b046fd2abd4d012985b3271f36 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Wed, 20 Jul 2016 00:20:12 +0200 Subject: [PATCH] Minor refactor and beter coverage for pkg/stringid This slightly simplifies TruncateID() by only trimming the string if needed. Also improved unit-tests for this package; - Add a test for GenerateNonCryptoID() - Add a test for shortening a sha-256 ID - Make TestShortenId() more "unit", by using a fixed string, instead of calling GenerateRandomID() Signed-off-by: Sebastiaan van Stijn Upstream-commit: 78eab14d0b2128ffaff2b3c0cd32c5339ef35ad7 Component: engine --- components/engine/pkg/stringid/stringid.go | 8 +++----- .../engine/pkg/stringid/stringid_test.go | 20 +++++++++++++++++-- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/components/engine/pkg/stringid/stringid.go b/components/engine/pkg/stringid/stringid.go index 161184ff8a..fa35d8bad5 100644 --- a/components/engine/pkg/stringid/stringid.go +++ b/components/engine/pkg/stringid/stringid.go @@ -29,11 +29,10 @@ func TruncateID(id string) string { if i := strings.IndexRune(id, ':'); i >= 0 { id = id[i+1:] } - trimTo := shortLen - if len(id) < shortLen { - trimTo = len(id) + if len(id) > shortLen { + id = id[:shortLen] } - return id[:trimTo] + return id } func generateID(crypto bool) string { @@ -60,7 +59,6 @@ func generateID(crypto bool) string { // GenerateRandomID returns a unique id. func GenerateRandomID() string { return generateID(true) - } // GenerateNonCryptoID generates unique id without using cryptographically diff --git a/components/engine/pkg/stringid/stringid_test.go b/components/engine/pkg/stringid/stringid_test.go index bcb1365495..8ff6b4383d 100644 --- a/components/engine/pkg/stringid/stringid_test.go +++ b/components/engine/pkg/stringid/stringid_test.go @@ -13,10 +13,26 @@ func TestGenerateRandomID(t *testing.T) { } } +func TestGenerateNonCryptoID(t *testing.T) { + id := GenerateNonCryptoID() + + if len(id) != 64 { + t.Fatalf("Id returned is incorrect: %s", id) + } +} + func TestShortenId(t *testing.T) { - id := GenerateRandomID() + id := "90435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a2" truncID := TruncateID(id) - if len(truncID) != 12 { + if truncID != "90435eec5c4e" { + t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID) + } +} + +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) } }