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 (#209)

closes #208
  • Loading branch information
ostridm committed Sep 14, 2023
1 parent 5d15e91 commit 749b6d8
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
8 changes: 5 additions & 3 deletions packages/openapi-sampler/src/samplers/StringSampler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ export class StringSampler implements Sampler {
'regex': () => '/regex/',
'pattern': (
_min: number,
_max: 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 ?? randExp.max;
randExp.randInt = (a, b) => Math.floor((a + b) / 2);

return randExp.gen();
Expand Down
55 changes: 55 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,51 @@ 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]{1,15}$',
maxLength: 10
},
expected: 'RRRRRRRR'
},
{
input: {
type: 'string',
format: 'pattern',
pattern: '^\\w{5,5}\\d{5,5}$',
maxLength: 10
},
expected: 'EEEEE44444'
},
{
input: {
type: 'string',
format: 'pattern',
pattern: '^[A-Z0-9]*$',
maxLength: 0
},
expected: ''
},
{
input: {
type: 'string',
Expand Down Expand Up @@ -221,6 +266,16 @@ describe('StringSampler', () => {
expected:
'Sample string cannot be generated by boundaries: maxLength=5, format=pattern'
},
{
input: {
type: 'string',
format: 'pattern',
pattern: '^\\w{5,5}\\d{5,5}$',
maxLength: 9
},
expected:
'Sample string cannot be generated by boundaries: maxLength=9, format=pattern'
},
{
input: {
type: 'string',
Expand Down

0 comments on commit 749b6d8

Please sign in to comment.