| 1 | package uuid |
| 2 | |
| 3 | import "testing" |
| 4 | |
| 5 | // TestParseAndUnmarshalTextParity ensures that the public Parse(string) |
| 6 | // helper and the encoding.TextUnmarshaler implementation share the same |
| 7 | // behaviour after refactor (see parseBytes). We verify both success and |
| 8 | // failure scenarios across multiple input variations. |
| 9 | func TestParseAndUnmarshalTextParity(t *testing.T) { |
| 10 | cases := []struct { |
| 11 | name string |
| 12 | input string |
| 13 | valid bool |
| 14 | }{ |
| 15 | {"canonical", "6ba7b810-9dad-11d1-80b4-00c04fd430c8", true}, |
| 16 | {"hash", "6ba7b8109dad11d180b400c04fd430c8", true}, |
| 17 | {"bracedCanonical", "{6ba7b810-9dad-11d1-80b4-00c04fd430c8}", true}, |
| 18 | {"bracedHash", "{6ba7b8109dad11d180b400c04fd430c8}", true}, |
| 19 | {"urnCanonical", "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8", true}, |
| 20 | {"urnHash", "urn:uuid:6ba7b8109dad11d180b400c04fd430c8", true}, |
| 21 | |
| 22 | {"invalidLength", "6ba7b810-9dad-11d1-80b4", false}, |
| 23 | {"invalidDashPositions", "6ba7b8109dad-11d1-80b4-00c04fd430c8", false}, |
| 24 | {"invalidHexChar", "6ba7b810-9dad-11d1-80b4-00c04fd43zzz", false}, |
| 25 | {"invalidURNPrefix", "urn:uuid6ba7b810-9dad-11d1-80b4-00c04fd430c8", false}, |
| 26 | } |
| 27 | |
| 28 | for _, tc := range cases { |
| 29 | t.Run(tc.name, func(t *testing.T) { |
| 30 | var p1, p2 UUID |
| 31 | |
| 32 | err1 := p1.Parse(tc.input) |
| 33 | err2 := p2.UnmarshalText([]byte(tc.input)) |
| 34 | |
| 35 | if tc.valid { |
| 36 | if err1 != nil { |
| 37 | t.Fatalf("Parse returned unexpected error: %v", err1) |
| 38 | } |
| 39 | if err2 != nil { |
| 40 | t.Fatalf("UnmarshalText returned unexpected error: %v", err2) |
| 41 | } |
| 42 | if p1 != p2 { |
| 43 | t.Fatalf("Parse and UnmarshalText results differ: %v vs %v", p1, p2) |
| 44 | } |
| 45 | } else { |
| 46 | if err1 == nil { |
| 47 | t.Errorf("Parse should fail for invalid input") |
| 48 | } |
| 49 | if err2 == nil { |
| 50 | t.Errorf("UnmarshalText should fail for invalid input") |
| 51 | } |
| 52 | } |
| 53 | }) |
| 54 | } |
| 55 | } |