swagger-ui icon indicating copy to clipboard operation
swagger-ui copied to clipboard

Swagger fails to generate a valid example for complex regex patterns.

Open doubleyooz opened this issue 3 years ago • 1 comments

Q&A (please complete the following information)

  • OS: Windows 11
  • Browser: Brave, Firefox
  • Version: latest?
  • Method of installation: yarn]
  • Swagger-UI version: 4.6.2
  • Swagger/OpenAPI version: Swagger 2.0

Content & configuration

Example Swagger/OpenAPI definition:

{
    type: 'string',
    pattern: '^[A-Za-z0-9]+\.(png|jpg|jpeg){1}$',
    minLength: 39,
    maxLength: 54,
    description: 'A randomly generated unique id with the file extension',
}

Describe the bug you're encountering

Swagger does not generate a valid example for complex regex patterns. It generates a random string that does not match the provided pattern.

Initially this was my regex ^(?=.{39,54}$)([A-Za-z0-9]+\.(png|jpg|jpeg){1})$, it was completely ignoring the length check (besides not matching the extension) then I read somewhere that the first check it's not supported, so I began to use minLength and maxLength removing the need for the first check. Now they are matching the length specified in the properties, but still not matching the regex pattern ^[A-Za-z0-9]+\.(png|jpg|jpeg){1}$.

Actually not even this website https://onlinestringtools.com/generate-string-from-regex can generate a proper one. My guess is the specification used by Swagger (ECMA-262 or some customized version) might have properties/limitations I'm not aware of. The regex patterns I'm producing work just fine and pass my own tests locally and on websites such as https://regexr.com/ and https://www.regexpal.com/.

I'd like to hear your take on the issue and if there's any workaround for it, besides strictly defining the example.

To reproduce...

Steps to reproduce the behavior:

  1. Create a field for a string that requires a complex regex pattern:
    type: 'string',
    pattern: '^[A-Za-z0-9]+\.(png|jpg|jpeg){1}$',
    minLength: 39,
    maxLength: 54,
    description: 'A randomly generated unique id with the file extension',

  1. Make sure everything else is fine.
  2. Run the server and go see the generated documentation
  3. See the error

Expected behavior

I expected swagger to be able to generate a proper string that matches the given regex.

Screenshots

Sometimes the extension doesn't appear at all, and you can try to test using the generated string, it fails. img1

doubleyooz avatar May 17 '22 18:05 doubleyooz

+1

thomasklinger1234 avatar Aug 08 '22 11:08 thomasklinger1234

Same for me with the regex: ^[a-zA-Z0-9](-*[a-zA-Z0-9]|\.?[a-zA-Z0-9])*$ It almost always generates examples that end with a -, although that is not valid.

Blackstar513 avatar May 25 '23 12:05 Blackstar513

The same for ^[^.]+$. Use example to provide static value.

djstrong avatar Jun 18 '23 22:06 djstrong