Exemplo n.º 1
0
def validate_spec(spec):
    """Validate the output of an :class:`APISpec` object against the
    OpenAPI specification.

    Note: Requires installing apispec with the ``[validation]`` extras.
    ::

        pip install 'apispec[validation]'

    :raise: apispec.exceptions.OpenAPIError if validation fails.
    """
    try:
        import prance
    except ImportError as error:  # re-raise with a more verbose message
        exc_class = type(error)
        raise exc_class(
            'validate_spec requires prance to be installed. '
            'You can install all validation requirements using:\n'
            "    pip install 'apispec[validation]'", )
    parser_kwargs = {}
    if spec.openapi_version.version[0] == 3:
        parser_kwargs['backend'] = 'openapi-spec-validator'
    try:
        prance.BaseParser(spec_string=json.dumps(spec.to_dict()),
                          **parser_kwargs)
    except prance.ValidationError as err:
        raise exceptions.OpenAPIError(*err.args)
    else:
        return True
Exemplo n.º 2
0
def __parser_for_url(url, resolve, backend, strict):  # noqa: N802
    """Return a parser instance for the URL and the given parameters."""
    # Try the URL
    formatted = click.format_filename(url)
    click.echo('Processing "%s"...' % (formatted, ))

    from prance.util import fs
    fsurl = fs.abspath(url)
    import os.path
    if os.path.exists(fs.from_posix(fsurl)):
        url = fsurl

    # Create parser to use
    if resolve:
        click.echo(' -> Resolving external references.')
        return CustomResolvingParser(url,
                                     lazy=True,
                                     backend=backend,
                                     strict=strict,
                                     recursion_limit=2), formatted
    else:
        click.echo(' -> Not resolving external references.')
        return prance.BaseParser(url,
                                 lazy=True,
                                 backend=backend,
                                 strict=strict), formatted
Exemplo n.º 3
0
def __parser_for_url(url, resolve, backend, strict, encoding):  # noqa: N802
  """Return a parser instance for the URL and the given parameters."""
  # Try the URL
  formatted = click.format_filename(url)
  click.echo('Processing "%s"...' % (formatted, ))

  from prance.util import fs
  fsurl = fs.abspath(url)
  import os.path
  if os.path.exists(fs.from_posix(fsurl)):
    url = fsurl

  # Create parser to use
  parser = None
  if resolve:
    click.echo(' -> Resolving external references.')
    parser = prance.ResolvingParser(url, lazy = True, backend = backend,
            strict = strict, encoding = encoding)
  else:
    click.echo(' -> Not resolving external references.')
    parser = prance.BaseParser(url, lazy = True, backend = backend,
            strict = strict, encoding = encoding)

  # XXX maybe enable tihs in debug mode or something.
  # click.echo(' -> Using backend: {0.backend}'.format(parser))
  return parser, formatted
Exemplo n.º 4
0
def validate(resolve, strict, output_file, urls):
    """
  Validate the given spec or specs.

  If the --resolve option is set, references will be resolved before
  validation.

  Note that this can yield unexpected results. The swagger-spec-validator used
  as a basis for prance cannot deal with relative file path references, and
  will report them. However, resolving these references before validation will
  skip these errors.

  If the --output-file option is given, the validated spec is written to that
  file. Please note that with that option given, only one input file may be
  specified.
  """
    # Ensure that when an output file is given, only one input file exists.
    if output_file and len(urls) > 1:
        raise click.UsageError('If --output-file is given, only one input URL '
                               'is allowed!')

    import os.path
    from prance.util import fs
    # Process files
    for url in urls:
        formatted = click.format_filename(url)
        click.echo('Processing "%s"...' % (formatted, ))
        fsurl = fs.abspath(url)
        if os.path.exists(fs.from_posix(fsurl)):
            url = fsurl

        # Create parser to use
        if resolve:
            click.echo(' -> Resolving external references.')
            parser = prance.ResolvingParser(url, lazy=True, strict=strict)
        else:
            click.echo(' -> Not resolving external references.')
            parser = prance.BaseParser(url, lazy=True, strict=strict)

        # Try parsing
        from prance.util.url import ResolutionError
        from swagger_spec_validator.common import SwaggerValidationError
        try:
            parser.parse()
        except (ResolutionError, SwaggerValidationError) as err:
            msg = 'ERROR in "%s" [%s]: %s' % (formatted, type(err).__name__,
                                              str(err))
            click.secho(msg, err=True, fg='red')
            import sys
            sys.exit(1)

        # All good, next file.
        click.echo('Validates OK as Swagger/OpenAPI 2.0!')

        # If an output file is given, write the specs to it.
        if output_file:
            __write_to_file(output_file, parser.specification)