|
| 1 | +package plugin |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "gotest.tools/v3/assert" |
| 9 | + is "gotest.tools/v3/assert/cmp" |
| 10 | + "pgregory.net/rapid" |
| 11 | +) |
| 12 | + |
| 13 | +// unmarshalJSON is a copy of the original PluginInterfaceType.UnmarshalJSON |
| 14 | +// parser, used to test that the new parser produces the same results for |
| 15 | +// well-formed inputs. |
| 16 | +func (t *CapabilityID) unmarshalJSON(p []byte) error { |
| 17 | + versionIndex := len(p) |
| 18 | + prefixIndex := 0 |
| 19 | + if len(p) < 2 || p[0] != '"' || p[len(p)-1] != '"' { |
| 20 | + return fmt.Errorf("%q is not a plugin interface type", p) |
| 21 | + } |
| 22 | + p = p[1 : len(p)-1] |
| 23 | +loop: |
| 24 | + for i, b := range p { |
| 25 | + switch b { |
| 26 | + case '.': |
| 27 | + prefixIndex = i |
| 28 | + case '/': |
| 29 | + versionIndex = i |
| 30 | + break loop |
| 31 | + } |
| 32 | + } |
| 33 | + t.Prefix = string(p[:prefixIndex]) |
| 34 | + t.Capability = string(p[prefixIndex+1 : versionIndex]) |
| 35 | + if versionIndex < len(p) { |
| 36 | + t.Version = string(p[versionIndex+1:]) |
| 37 | + } |
| 38 | + return nil |
| 39 | +} |
| 40 | + |
| 41 | +func TestCapabilityID_MarshalUnmarshal(t *testing.T) { |
| 42 | + stringgen := rapid.StringMatching(`[a-z0-9-./]*`) |
| 43 | + rapid.Check(t, func(t *rapid.T) { |
| 44 | + typ := CapabilityID{ |
| 45 | + Capability: stringgen.Draw(t, "Capability"), |
| 46 | + Prefix: stringgen.Draw(t, "Prefix"), |
| 47 | + Version: stringgen.Draw(t, "Version"), |
| 48 | + } |
| 49 | + b, err := typ.MarshalText() |
| 50 | + if err != nil { |
| 51 | + t.Skipf("unmarshalable value: %v", err) |
| 52 | + } |
| 53 | + t.Logf("InterfaceType(%q)", b) |
| 54 | + |
| 55 | + var roundtrip CapabilityID |
| 56 | + err = roundtrip.UnmarshalText(b) |
| 57 | + assert.Assert(t, err) |
| 58 | + assert.Assert(t, is.DeepEqual(typ, roundtrip)) |
| 59 | + |
| 60 | + jb, err := json.Marshal(string(b)) |
| 61 | + assert.Assert(t, err) |
| 62 | + var oldparser CapabilityID |
| 63 | + err = oldparser.unmarshalJSON(jb) |
| 64 | + assert.Assert(t, err) |
| 65 | + assert.Assert(t, is.DeepEqual(typ, oldparser), "new parser does not match the old parser") |
| 66 | + }) |
| 67 | +} |
| 68 | + |
| 69 | +func TestCapabilityID_JSONMarshalUnmarshal(t *testing.T) { |
| 70 | + type rt struct { |
| 71 | + Type CapabilityID |
| 72 | + } |
| 73 | + a := rt{ |
| 74 | + Type: CapabilityID{ |
| 75 | + Capability: "foo", |
| 76 | + Prefix: "bar", |
| 77 | + Version: "baz", |
| 78 | + }, |
| 79 | + } |
| 80 | + b, err := json.Marshal(a) |
| 81 | + assert.Assert(t, err) |
| 82 | + t.Logf("JSON: %s", b) |
| 83 | + |
| 84 | + var roundtrip rt |
| 85 | + err = json.Unmarshal(b, &roundtrip) |
| 86 | + assert.Assert(t, err) |
| 87 | + assert.Assert(t, is.DeepEqual(a, roundtrip)) |
| 88 | +} |
0 commit comments