Skip to content

Commit

Permalink
fix(sampler): introduce max-length support for string pattern format …
Browse files Browse the repository at this point in the history
…sample

closes #208
  • Loading branch information
ostridm committed Sep 14, 2023
1 parent 5d15e91 commit 34bd1ef
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/openapi-sampler/src/samplers/StringSampler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class StringSampler implements Sampler {
_min: number,
_max: number,
{ pattern }: { pattern: string | RegExp }
) => this.patternSample(pattern),
) => this.patternSample(pattern, _max),
'default': (min: number, max: number) =>
this.adjustLength('lorem', min, max)
};
Expand All @@ -47,8 +47,10 @@ export class StringSampler implements Sampler {
return this.checkLength(sampler(min || 0, max, schema), format, min, max);
}

private patternSample(pattern: string | RegExp): string {
private patternSample(pattern: string | RegExp, max: number): string {
const randExp = new RandExp(pattern);

randExp.max = max != null ? max : randExp.max;
randExp.randInt = (a, b) => Math.floor((a + b) / 2);

return randExp.gen();
Expand Down
27 changes: 27 additions & 0 deletions packages/openapi-sampler/tests/string.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,33 @@ describe('StringSampler', () => {
},
expected: '44'
},
{
input: {
type: 'string',
format: 'pattern',
pattern: '^[a-z\\u05D0-\\u05EAA-Z0-9-/\\\\.\\u05F4,\'":&#;+()\\s]*$',
maxLength: 50
},
expected: 'MMMMMMMMMMMMMMMMMMMMMMMMM'
},
{
input: {
type: 'string',
format: 'pattern',
pattern: '^[A-Z0-9]*$',
maxLength: 10
},
expected: 'RRRRR'
},
{
input: {
type: 'string',
format: 'pattern',
pattern: '^[A-Z0-9]*$',
maxLength: 0
},
expected: ''
},
{
input: {
type: 'string',
Expand Down

0 comments on commit 34bd1ef

Please sign in to comment.