Example #1
0
def _collect_models(container, json_reference, models, swagger_spec):
    """
    Callback used during the swagger spec ingestion to collect all the
    tagged models and create appropriate python types for them.

    NOTE: this callback creates the model python type only if the container
    represents a valid "model", the container has been marked with a model name
    (has MODEL_MARKER key) and the referenced model does not have the python
    model type generated.

    :param container: container being visited
    :param json_reference: URI of the current container
    :type json_reference: str
    :param models: created model types are placed here
    :type swagger_spec: :class:`bravado_core.spec.Spec`
    """
    key = json_reference.split('/')[-1]
    if key == MODEL_MARKER and is_object(swagger_spec, container):
        model_spec = swagger_spec.deref(container)
        model_name = _get_model_name(container)
        model_type = models.get(model_name)
        if not model_type:
            models[model_name] = create_model_type(
                swagger_spec=swagger_spec,
                model_name=model_name,
                model_spec=model_spec,
                json_reference=re.sub(
                    '/{MODEL_MARKER}$'.format(MODEL_MARKER=MODEL_MARKER), '',
                    json_reference),
            )
        elif (
                # the condition with strip_xscope is the most selective check
                # but it implies memory allocation, so additional lightweight checks
                # are added to avoid strip_xscope check
                id(model_type._model_spec) != id(model_spec)
                and model_type._model_spec != model_spec and strip_xscope(
                    model_type._model_spec) != strip_xscope(model_spec)):
            return _raise_or_warn_duplicated_model(
                swagger_spec=swagger_spec,
                message=
                'Identified duplicated model: model_name "{model_name}", uri: {json_reference}.\n'
                '    Known model spec: "{model_type._model_spec}"\n'
                '    New model spec: "{model_spec}"\n'
                'TIP: enforce different model naming by using {MODEL_MARKER}'.
                format(
                    json_reference=json_reference,
                    model_name=model_name,
                    model_type=model_type,
                    model_spec=model_spec,
                    MODEL_MARKER=MODEL_MARKER,
                ),
            )
Example #2
0
    def client_spec_dict(self):
        """Return a copy of spec_dict with x-scope metadata removed so that it
        is suitable for consumption by Swagger clients.

        You may be asking, "Why is there a difference between the Swagger spec
        a client sees and the one used internally?". Well, as part of the
        ingestion process, x-scope metadata is added to spec_dict so that
        $refs can be de-reffed successfully during request/response validation
        and marshalling. This metadata is specific to the context of the
        server and contains files and paths that are not relevant to the
        client. This is required so the client does not re-use (and in turn,
        re-creates) the invalid x-scope metadata created by the server.

        For example, a section of spec_dict that contains a ref would change
        as follows.

        Before:

          'MON': {
            '$ref': '#/definitions/DayHours',
            'x-scope': [
                'file:///happyhour/api_docs/swagger.json',
                'file:///happyhour/api_docs/swagger.json#/definitions/WeekHours'
            ]
          }

        After:

          'MON': {
            '$ref': '#/definitions/DayHours'
          }

        """
        return strip_xscope(self.spec_dict)
Example #3
0
    def flattened_spec(self):
        """
        Representation of the current swagger specs that could be written to a single file.
        :rtype: dict
        """

        if not self.config['validate_swagger_spec']:
            log.warning(
                'Flattening unvalidated specs could produce invalid specs. '
                'Use it at your risk or enable `validate_swagger_specs`', )

        return strip_xscope(spec_dict=flattened_spec(swagger_spec=self), )
Example #4
0
def test_no_op():
    fragment = {
        'MON': {
            '$ref': '#/definitions/DayHours',
        }
    }
    expected = {
        'MON': {
            '$ref': '#/definitions/DayHours',
        }
    }
    assert expected == strip_xscope(fragment)
Example #5
0
def test_contained_in_list():
    fragment = [{
        '$ref':
        '#/definitions/DayHours',
        'x-scope': [
            'file:///happyhour/api_docs/swagger.json',
            'file:///happyhour/api_docs/swagger.json#/definitions/WeekHours'
        ]
    }]
    expected = [{
        '$ref': '#/definitions/DayHours',
    }]
    assert expected == strip_xscope(fragment)
    assert 'x-scope' in fragment[0]
Example #6
0
def test_contained_in_dict():
    fragment = {
        'MON': {
            '$ref': '#/definitions/DayHours',
            'x-scope': [
                'file:///happyhour/api_docs/swagger.json',
                'file:///happyhour/api_docs/swagger.json#/definitions/WeekHours'
            ]
        }
    }
    expected = {
        'MON': {
            '$ref': '#/definitions/DayHours',
        }
    }
    assert expected == strip_xscope(fragment)
    assert 'x-scope' in fragment['MON']
Example #7
0
    def flattened_spec(self):
        """
        Representation of the current swagger specs that could be written to a single file.
        NOTE: The representation strips out all the definitions that are not referenced
        :return:
        """

        if not self.config['validate_swagger_spec']:
            raise RuntimeError('Swagger Specs have to be validated before flattening.')

        # If resources are defined it means that Spec has been built and so swagger specs have been validated
        if self.resources is None:
            self._validate_spec()

        return strip_xscope(
            spec_dict=flattened_spec(
                spec_dict=self.spec_dict,
                spec_resolver=self.resolver,
                spec_url=self.origin_url,
                http_handlers=build_http_handlers(self.http_client),
                spec_definitions=self.definitions,
            ),
        )
Example #8
0
def test_petstore_spec(petstore_spec):
    assert petstore_spec.client_spec_dict == strip_xscope(petstore_spec.spec_dict)
Example #9
0
def test_empty():
    assert {} == strip_xscope({})