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 <github@gone.nl>
| ... | ... |
@@ -29,11 +29,10 @@ func TruncateID(id string) string {
|
| 29 | 29 |
if i := strings.IndexRune(id, ':'); i >= 0 {
|
| 30 | 30 |
id = id[i+1:] |
| 31 | 31 |
} |
| 32 |
- trimTo := shortLen |
|
| 33 |
- if len(id) < shortLen {
|
|
| 34 |
- trimTo = len(id) |
|
| 32 |
+ if len(id) > shortLen {
|
|
| 33 |
+ id = id[:shortLen] |
|
| 35 | 34 |
} |
| 36 |
- return id[:trimTo] |
|
| 35 |
+ return id |
|
| 37 | 36 |
} |
| 38 | 37 |
|
| 39 | 38 |
func generateID(crypto bool) string {
|
| ... | ... |
@@ -60,7 +59,6 @@ func generateID(crypto bool) string {
|
| 60 | 60 |
// GenerateRandomID returns a unique id. |
| 61 | 61 |
func GenerateRandomID() string {
|
| 62 | 62 |
return generateID(true) |
| 63 |
- |
|
| 64 | 63 |
} |
| 65 | 64 |
|
| 66 | 65 |
// GenerateNonCryptoID generates unique id without using cryptographically |
| ... | ... |
@@ -13,10 +13,26 @@ func TestGenerateRandomID(t *testing.T) {
|
| 13 | 13 |
} |
| 14 | 14 |
} |
| 15 | 15 |
|
| 16 |
+func TestGenerateNonCryptoID(t *testing.T) {
|
|
| 17 |
+ id := GenerateNonCryptoID() |
|
| 18 |
+ |
|
| 19 |
+ if len(id) != 64 {
|
|
| 20 |
+ t.Fatalf("Id returned is incorrect: %s", id)
|
|
| 21 |
+ } |
|
| 22 |
+} |
|
| 23 |
+ |
|
| 16 | 24 |
func TestShortenId(t *testing.T) {
|
| 17 |
- id := GenerateRandomID() |
|
| 25 |
+ id := "90435eec5c4e124e741ef731e118be2fc799a68aba0466ec17717f24ce2ae6a2" |
|
| 26 |
+ truncID := TruncateID(id) |
|
| 27 |
+ if truncID != "90435eec5c4e" {
|
|
| 28 |
+ t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
|
|
| 29 |
+ } |
|
| 30 |
+} |
|
| 31 |
+ |
|
| 32 |
+func TestShortenSha256Id(t *testing.T) {
|
|
| 33 |
+ id := "sha256:4e38e38c8ce0b8d9041a9c4fefe786631d1416225e13b0bfe8cfa2321aec4bba" |
|
| 18 | 34 |
truncID := TruncateID(id) |
| 19 |
- if len(truncID) != 12 {
|
|
| 35 |
+ if truncID != "4e38e38c8ce0" {
|
|
| 20 | 36 |
t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID)
|
| 21 | 37 |
} |
| 22 | 38 |
} |