Skip to content

Commit

Permalink
Handle ID prefixes with underscores (#377)
Browse files Browse the repository at this point in the history
* Handle ID prefixes with underscores

* safer index handling
  • Loading branch information
pakrym-stripe committed Dec 9, 2022
1 parent 134e926 commit f2c0541
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
12 changes: 7 additions & 5 deletions server/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -891,11 +891,13 @@ func maybeGeneratePrimaryID(pathParams *PathParamsMap, data interface{}) *PathPa
return pathParams
}

// Splits something like `ch_123` into `["ch", "123"]`.
idParts := strings.Split(id, "_")
prefix := id

// Like `ch`.
prefix := idParts[0]
usInd := strings.LastIndex(id, "_")
// Like `sub_sched`.
if usInd != -1 {
prefix = id[:usInd]
}

newID := randomID(prefix)

Expand Down Expand Up @@ -928,7 +930,7 @@ func propertyNames(schema *spec.Schema) string {
//
// As with the real Stripe API, the general format looks like:
//
// <prefix>_<time_part><random_part>
// <prefix>_<time_part><random_part>
//
// The prefix helps identify the type of object. For example, charges have a
// `ch` prefix.
Expand Down
25 changes: 25 additions & 0 deletions server/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,31 @@ func TestGenerateResponseData(t *testing.T) {
data.(map[string]interface{})["id"])
}

// generated primary ID (double prefix)
{
generator := DataGenerator{testSpec.Components.Schemas, &spec.Fixtures{
Resources: map[spec.ResourceID]interface{}{
spec.ResourceID("charge"): map[string]interface{}{
"id": "ch_sub_123",
},
},
}, verbose}
data, err := generator.Generate(&GenerateParams{
PathParams: &PathParamsMap{},
Schema: &spec.Schema{Ref: "#/components/schemas/charge"},
})
assert.Nil(t, err)

// Should not be equal to our fixture's ID because it's generated.
assert.NotEqual(t, "ch_sub_123",
data.(map[string]interface{})["id"])

// However, the fixture's ID's prefix will have been used to generate
// the new ID, so it should share a prefix.
assert.Regexp(t, regexp.MustCompile("^ch_sub_"),
data.(map[string]interface{})["id"])
}

// generated primary ID (nil PathParamsMap)
{
generator := DataGenerator{testSpec.Components.Schemas, &spec.Fixtures{
Expand Down

0 comments on commit f2c0541

Please sign in to comment.