コード例 #1
0
ファイル: build_test.py プロジェクト: bschmaltz/bravado-core
def test_validate_swagger_spec_failure(petstore_dict):
    # induce failure
    del petstore_dict['swagger']
    spec = Spec(petstore_dict)
    with pytest.raises(SwaggerValidationError) as excinfo:
        spec.build()
    assert "'swagger' is a required property" in str(excinfo.value)
コード例 #2
0
ファイル: conftest.py プロジェクト: isysd/bravado
def minimal_swagger_spec(getPetById_spec):
    spec_dict = {
        'paths': {
            '/pet/{petId}': {
                'get': getPetById_spec
            }
        }
    }
    spec = Spec(spec_dict)
    spec.api_url = 'http://localhost/swagger.json'
    return spec
コード例 #3
0
def test_security_parameter_cannot_override_path_or_operation_parameter(
        security_dict,
):
    security_dict['paths']['/example1']['get']['parameters'] = [{
        'description': 'sec1 as query parameter',
        'required': True,
        'in': 'query',
        'type': 'integer',
        'name': 'apiKey1',
    }]

    with pytest.raises(SwaggerSchemaError):
        Spec.from_dict(security_dict)
コード例 #4
0
def test_produces_on_op_overrides_produces_from_swagger_spec(
        minimal_swagger_dict):
    op_spec = {'produces': ['application/xml']}
    minimal_swagger_dict['produces'] = ['application/json']
    minimal_swagger_spec = Spec.from_dict(minimal_swagger_dict)
    op = Operation(minimal_swagger_spec, '/foo', 'get', op_spec)
    assert ['application/xml'] == op.produces
コード例 #5
0
def generate_cli(spec):
    origin_url = None
    if isinstance(spec, str):
        if spec.startswith('https://') or spec.startswith('http://'):
            origin_url = spec
            r = requests.get(spec)
            r.raise_for_status()
            spec = yaml.safe_load(r.text)
        else:
            with open(spec, 'rb') as fd:
                spec = yaml.safe_load(fd.read())

    spec = sanitize_spec(spec)

    cli = clickclick.AliasedGroup(context_settings=CONTEXT_SETTINGS)

    spec = Spec.from_dict(spec, origin_url=origin_url)
    for res_name, res in spec.resources.items():
        grp = clickclick.AliasedGroup(normalize_command_name(res_name), short_help='Manage {}'.format(res_name))
        cli.add_command(grp)
        for op_name, op in res.operations.items():
            name = get_command_name(op)

            cmd = click.Command(name, callback=partial(invoke, op=op), short_help=op.op_spec.get('summary'))
            for param_name, param in op.params.items():
                if param.required:
                    arg = click.Argument([param.name])
                    cmd.params.append(arg)
                else:
                    arg = click.Option(['--' + param.name])
                    cmd.params.append(arg)

            grp.add_command(cmd)

    return cli
コード例 #6
0
ファイル: conftest.py プロジェクト: jakul/bravado-core
def recursive_swagger_spec(minimal_swagger_dict, node_spec):
    """
    Return a swager_spec with a #/definitions/Node that is
    recursive.
    """
    minimal_swagger_dict['definitions']['Node'] = node_spec
    return Spec(minimal_swagger_dict)
コード例 #7
0
def test_Nones_are_reintroduced_for_declared_properties_that_are_not_present(
        petstore_dict, pet_dict):
    petstore_spec = Spec.from_dict(petstore_dict)
    Pet = petstore_spec.definitions['Pet']
    Tag = petstore_spec.definitions['Tag']
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']

    # Deleting "status" and "category" from pet_dict means that should still be
    # attrs on Pet with a None value after unmarshaling
    del pet_dict['status']
    del pet_dict['category']

    pet = unmarshal_model(petstore_spec, pet_spec, pet_dict)

    assert isinstance(pet, Pet)
    assert 1 == pet.id
    assert 'Fido' == pet.name
    assert pet.status is None
    assert ['wagtail.png', 'bark.png'] == pet.photoUrls
    assert pet.category is None
    assert isinstance(pet.tags, list)
    assert 2 == len(pet.tags)
    assert isinstance(pet.tags[0], Tag)
    assert 99 == pet.tags[0].id
    assert 'mini' == pet.tags[0].name
    assert isinstance(pet.tags[1], Tag)
    assert 100 == pet.tags[1].id
    assert 'brown' == pet.tags[1].name
コード例 #8
0
def test_validate_config_fail(
    mock_warnings, minimal_swagger_dict, minimal_swagger_abspath,
    config, expected_different_config, expected_warnings_call,
):
    spec = Spec.from_dict(minimal_swagger_dict, origin_url=get_url(minimal_swagger_abspath), config=config)
    assert (spec.config != dict(CONFIG_DEFAULTS, **config)) is expected_different_config
    mock_warnings.warn.assert_called_once_with(message=expected_warnings_call, category=Warning)
コード例 #9
0
def test_path_param_and_op_param(minimal_swagger_dict):
    op_spec = {
        'operationId':
        'get_pet_by_id',
        'parameters': [{
            'name': 'pet_id',
            'in': 'query',
            'required': True,
            'type': 'integer',
        }],
        'responses': {
            '200': {}
        }
    }
    path_spec = {
        'get':
        op_spec,
        'parameters': [{
            'name': 'sort_key',
            'in': 'query',
            'required': False,
            'type': 'string',
        }],
    }
    minimal_swagger_dict['paths']['/pets'] = path_spec
    swagger_spec = Spec(minimal_swagger_dict)
    op = Operation(swagger_spec, '/pets', 'get', op_spec)
    params = build_params(op)
    assert len(params) == 2
    assert 'pet_id' in params
    assert 'sort_key' in params
コード例 #10
0
def test_pet(petstore_dict, pet_dict):
    # Covers:
    #   - model with primitives properties
    #   - model with an array
    #   - model with a nested model
    petstore_spec = Spec.from_dict(petstore_dict)
    Pet = petstore_spec.definitions['Pet']
    Category = petstore_spec.definitions['Category']
    Tag = petstore_spec.definitions['Tag']
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']

    pet = unmarshal_model(petstore_spec, pet_spec, pet_dict)

    assert isinstance(pet, Pet)
    assert 1 == pet.id
    assert 'Fido' == pet.name
    assert 'sold' == pet.status
    assert ['wagtail.png', 'bark.png'] == pet.photoUrls
    assert isinstance(pet.category, Category)
    assert 200 == pet.category.id
    assert 'friendly' == pet.category.name
    assert isinstance(pet.tags, list)
    assert 2 == len(pet.tags)
    assert isinstance(pet.tags[0], Tag)
    assert 99 == pet.tags[0].id
    assert 'mini' == pet.tags[0].name
    assert isinstance(pet.tags[1], Tag)
    assert 100 == pet.tags[1].id
    assert 'brown' == pet.tags[1].name
コード例 #11
0
def test_op_param_overrides_path_param(minimal_swagger_dict):
    # Override 'required' to be True for the sort_key param
    op_spec = {
        'operationId':
        'get_pet_by_id',
        'parameters': [{
            'name': 'sort_key',
            'in': 'query',
            'required': True,
            'type': 'string',
        }],
        'responses': {
            '200': {}
        }
    }
    path_spec = {
        'get':
        op_spec,
        'parameters': [{
            'name': 'sort_key',
            'in': 'query',
            'required': False,
            'type': 'string',
        }],
    }
    minimal_swagger_dict['paths']['/pets'] = path_spec
    swagger_spec = Spec(minimal_swagger_dict)
    op = Operation(swagger_spec, '/pets', 'get', op_spec)
    params = build_params(op)
    assert len(params) == 1
    assert 'sort_key' in params
    assert params['sort_key'].required
コード例 #12
0
def test_ref_to_external_path_with_ref_to_local_model():
    # Test that an an external ref to a path (in swagger.json) which contains
    # a local ref to a model (in pet.json) works as expected:
    # - model type for Pet is created
    # - de-reffed spec_dict contains 'x-model' annotations
    #
    # This is really a test for `tag_models`. Migrate over there
    #
    # swagger.json
    #   paths:
    #     /pet:
    #       $ref: pet.json#/paths/pet   (1)
    #
    # pet.json
    #   definitions:
    #     Pet: ...                      (4)
    #   paths:                          (2)
    #      ...
    #      $ref: #/definitions/Pet      (3)
    #
    my_dir = os.path.abspath(os.path.dirname(__file__))

    swagger_json_path = os.path.join(
        my_dir, '../../test-data/2.0/x-model/swagger.json')

    with open(swagger_json_path) as f:
        swagger_json_content = json.loads(f.read())

    swagger_json_url = urlparse.urljoin('file:', swagger_json_path)
    spec = Spec.from_dict(swagger_json_content, swagger_json_url)
    assert 'Pet' in spec.definitions
コード例 #13
0
def multi_file_multi_directory_spec(request, multi_file_multi_directory_dict,
                                    multi_file_multi_directory_abspath):
    return Spec.from_dict(
        multi_file_multi_directory_dict,
        origin_url=get_url(multi_file_multi_directory_abspath),
        config={'internally_dereference_refs': request.param},
    )
コード例 #14
0
def test_missing_object_spec_defaulting_on(petstore_dict):
    """When default_type_to_object config option is set to True,
    then missing types default to object
    """
    petstore_spec = Spec.from_dict(petstore_dict, config={'use_models': False, 'default_type_to_object': True})
    category_spec = copy.deepcopy(
        petstore_spec.spec_dict['definitions']['Category']
    )

    # now a missing type will default to object type
    category_spec['properties']['id'].pop('type')

    result = unmarshal_schema_object(
        petstore_spec,
        category_spec,
        {'id': {'foo': 'bar'}, 'name': 'short-hair'})

    assert result == {'id': {'foo': 'bar'}, 'name': 'short-hair'}

    # so a different type will fail
    with pytest.raises(SwaggerMappingError):
        result = unmarshal_schema_object(
            petstore_spec,
            category_spec,
            {'id': 'blahblah', 'name': 'short-hair'})
コード例 #15
0
    def from_spec(cls,
                  spec_dict,
                  origin_url=None,
                  http_client=None,
                  config=None):
        """
        Build a :class:`SwaggerClient` from a Swagger spec in dict form.

        :param spec_dict: a dict with a Swagger spec in json-like form
        :param origin_url: the url used to retrieve the spec_dict
        :type  origin_url: str
        :param config: Configuration dict - see spec.CONFIG_DEFAULTS

        :rtype: :class:`bravado_core.spec.Spec`
        """
        http_client = http_client or RequestsClient()

        # Apply bravado config defaults
        config = dict(CONFIG_DEFAULTS, **(config or {}))

        also_return_response = config.pop('also_return_response', False)
        swagger_spec = Spec.from_dict(
            spec_dict,
            origin_url,
            http_client,
            config,
        )
        return cls(swagger_spec, also_return_response=also_return_response)
コード例 #16
0
ファイル: model_test.py プロジェクト: bschmaltz/bravado-core
def test_ensure_polymorphic_objects_are_correctly_build_in_case_of_fully_dereferenced_specs(
    polymorphic_dict, validate_responses, use_models, internally_dereference_refs,
):
    raw_response = [{'name': 'name', 'type': 'Dog', 'birth_date': '2017-11-02'}]

    spec = Spec.from_dict(
        spec_dict=polymorphic_dict,
        config={
            'validate_responses': validate_responses,
            'use_models': use_models,
            'internally_dereference_refs': internally_dereference_refs,
        },
        origin_url='',
    )

    response = Mock(
        spec=IncomingResponse,
        status_code=200,
        headers={'content-type': APP_JSON},
        json=Mock(return_value=raw_response),
    )

    unmarshaled_response = unmarshal_response(response, spec.resources['pets'].get_pets)
    if use_models:
        assert repr(unmarshaled_response) == "[Dog(birth_date=datetime.date(2017, 11, 2), name='name', type='Dog')]"
    else:
        assert unmarshaled_response == raw_response
コード例 #17
0
def test_array_of_models(petstore_dict):
    petstore_spec = Spec.from_dict(petstore_dict)
    Pet = petstore_spec.definitions['Pet']
    Category = petstore_spec.definitions['Category']
    Tag = petstore_spec.definitions['Tag']

    array_of_pets_spec = {
        'type': 'array',
        'items': petstore_spec.spec_dict['definitions']['Pet']
    }

    fido = Pet(
        id=1,
        name='Fido',
        status='sold',
        photoUrls=['wagtail.png', 'bark.png'],
        category=Category(id=200, name='friendly'),
        tags=[
            Tag(id=99, name='mini'),
            Tag(id=100, name='brown')
        ]
    )

    darwin = Pet(
        id=2,
        name='Darwin',
        status='pending',
        photoUrls=['snausages.png', 'bacon.png'],
        category=Category(id=300, name='mascot'),
        tags=[],
    )

    sumi = Pet(
        id=3,
        name='Sumi',
        status='available',
        photoUrls=['puggies.png', 'bumblebee.png'],
        category=Category(id=400, name='pugly'),
        tags=[
            Tag(id=101, name='sumiwoo'),
        ],
    )

    pets = [fido, darwin, sumi]
    result = marshal_array(petstore_spec, array_of_pets_spec, pets)

    for i, expected in enumerate(pets):
        actual = result[i]
        assert expected.name == actual['name']
        assert expected.id == actual['id']
        assert expected.photoUrls == actual['photoUrls']
        assert expected.status == actual['status']

        for j, expected_tag in enumerate(expected.tags):
            actual_tag = actual['tags'][j]
            assert expected_tag.id == actual_tag['id']
            assert expected_tag.name == actual_tag['name']

        assert expected.category.id == actual['category']['id']
        assert expected.category.name == actual['category']['name']
コード例 #18
0
def test_complicated_refs():
    # Split the swagger spec into a bunch of different json files and use
    # $refs all over to place to wire stuff together - see the test-data
    # files or this will make no sense whatsoever.
    file_path = "../../test-data/2.0/simple_crossref/swagger.json"
    swagger_dict, origin_url = get_spec_json_and_url(file_path)
    swagger_spec = Spec.from_dict(swagger_dict, origin_url=origin_url)

    # Verify things are 'reachable' (hence, have been ingested correctly)

    # Resource
    assert swagger_spec.resources["pingpong"]

    # Operation
    op = swagger_spec.resources["pingpong"].ping
    assert op

    # Parameter
    assert swagger_spec.resources["pingpong"].ping.params["pung"]

    # Parameter name
    assert swagger_spec.resources["pingpong"].ping.params["pung"].name == "pung"

    # Response
    response = get_response_spec(200, op)
    assert response["description"] == "pong"
コード例 #19
0
def test_Nones_are_reintroduced_for_declared_properties_that_are_not_present(
        petstore_dict, pet_dict):
    petstore_spec = Spec.from_dict(petstore_dict)
    Pet = petstore_spec.definitions['Pet']
    Tag = petstore_spec.definitions['Tag']
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']

    # Deleting "status" and "category" from pet_dict means that should still be
    # attrs on Pet with a None value after unmarshaling
    del pet_dict['status']
    del pet_dict['category']

    pet = unmarshal_model(petstore_spec, pet_spec, pet_dict)

    assert isinstance(pet, Pet)
    assert 1 == pet.id
    assert 'Fido' == pet.name
    assert pet.status is None
    assert ['wagtail.png', 'bark.png'] == pet.photoUrls
    assert pet.category is None
    assert isinstance(pet.tags, list)
    assert 2 == len(pet.tags)
    assert isinstance(pet.tags[0], Tag)
    assert 99 == pet.tags[0].id
    assert 'mini' == pet.tags[0].name
    assert isinstance(pet.tags[1], Tag)
    assert 100 == pet.tags[1].id
    assert 'brown' == pet.tags[1].name
コード例 #20
0
def test_visits_refs_only_once():
    # bar should only be de-reffed once even though there are two refs to it
    spec_dict = {
        'ref_one': {
            '$ref': '#/bar'
        },
        'ref_two': {
            '$ref': '#/bar'
        },
        'bar': 'baz'
    }
    swagger_spec = Spec(spec_dict)

    # Yech! mock doesn't make this easy
    mutable = {'cnt': 0}

    def callback(container, json_reference, mutable):
        # Bump the mutable counter every time bar is de-reffed
        if json_reference.endswith('/bar'):
            mutable['cnt'] += 1

    _post_process_spec(
        spec_dict=swagger_spec.spec_dict,
        spec_resolver=swagger_spec.resolver,
        on_container_callbacks=[
            functools.partial(
                callback,
                mutable=mutable,
            ),
        ],
    )

    assert mutable['cnt'] == 1
コード例 #21
0
def test_spec_with_dereffed_and_tagged_models_works(minimal_swagger_dict):
    # In cases where the Swagger spec being ingested has already been de-reffed
    # and had models tagged with 'x-model', we still need to be able to
    # detect them and make them available as model types. For example, a spec
    # ingested via http from pyramid_swagger contains de-reffed models.
    pet_path_spec = {
        'get': {
            'responses': {
                '200': {
                    'description': 'Returns a Pet',
                    'schema': {
                        MODEL_MARKER: 'Pet',
                        'type': 'object',
                        'properties': {
                            'name': {
                                'type': 'string'
                            }
                        }
                    }
                }
            }
        }
    }
    minimal_swagger_dict['paths']['/pet'] = pet_path_spec
    spec = Spec.from_dict(minimal_swagger_dict)
    assert spec.definitions['Pet']
コード例 #22
0
ファイル: deref_test.py プロジェクト: JoelO/bravado-core
def test_ref(minimal_swagger_dict):
    foo_spec = {
        'type': 'object'
    }
    minimal_swagger_dict['definitions']['Foo'] = foo_spec
    swagger_spec = Spec.from_dict(minimal_swagger_dict)
    assert swagger_spec.deref({'$ref': '#/definitions/Foo'}) == foo_spec
コード例 #23
0
def test_spec_with_dereffed_and_tagged_models_works(minimal_swagger_dict):
    # In cases where the Swagger spec being ingested has already been de-reffed
    # and had models tagged with 'x-model', we still need to be able to
    # detect them and make them available as model types. For example, a spec
    # ingested via http from pyramid_swagger contains de-reffed models.
    pet_path_spec = {
        'get': {
            'responses': {
                '200': {
                    'description': 'Returns a Pet',
                    'schema': {
                        'x-model': 'Pet',
                        'type': 'object',
                        'properties': {
                            'name': {
                                'type': 'string'
                            }
                        }
                    }
                }
            }
        }
    }
    minimal_swagger_dict['paths']['/pet'] = pet_path_spec
    spec = Spec.from_dict(minimal_swagger_dict)
    assert spec.definitions['Pet']
コード例 #24
0
ファイル: ingest.py プロジェクト: striglia/pyramid_swagger
def get_swagger_spec(settings):
    """Return a :class:`bravado_core.spec.Spec` constructed from
    the swagger specs in `pyramid_swagger.schema_directory`. If
    `pyramid_swagger.enable_swagger_spec_validation` is enabled the schema
    will be validated before returning it.

    :param settings: a pyramid registry settings with configuration for
        building a swagger schema
    :type settings: dict
    :rtype: :class:`bravado_core.spec.Spec`
    """
    schema_dir = settings.get('pyramid_swagger.schema_directory', 'api_docs/')
    schema_filename = settings.get('pyramid_swagger.schema_file',
                                   'swagger.json')
    schema_path = os.path.join(schema_dir, schema_filename)
    schema_url = urlparse.urljoin('file:', pathname2url(os.path.abspath(schema_path)))

    handlers = build_http_handlers(None)  # don't need http_client for file:
    file_handler = handlers['file']
    spec_dict = file_handler(schema_url)

    return Spec.from_dict(
        spec_dict,
        config=create_bravado_core_config(settings),
        origin_url=schema_url)
コード例 #25
0
def test_ref_to_external_path_with_ref_to_local_model():
    # Test that an an external ref to a path (in swagger.json) which contains
    # a local ref to a model (in pet.json) works as expected:
    # - model type for Pet is created
    # - de-reffed spec_dict contains 'x-model' annotations
    #
    # This is really a test for `tag_models`. Migrate over there
    #
    # swagger.json
    #   paths:
    #     /pet:
    #       $ref: pet.json#/paths/pet   (1)
    #
    # pet.json
    #   definitions:
    #     Pet: ...                      (4)
    #   paths:                          (2)
    #      ...
    #      $ref: #/definitions/Pet      (3)
    #
    my_dir = os.path.abspath(os.path.dirname(__file__))

    swagger_json_path = os.path.join(my_dir, "../../test-data/2.0/x-model/swagger.json")

    with open(swagger_json_path) as f:
        swagger_json_content = json.loads(f.read())

    swagger_json_url = urlparse.urljoin("file:", swagger_json_path)
    spec = Spec.from_dict(swagger_json_content, swagger_json_url)
    assert "Pet" in spec.definitions
コード例 #26
0
def test_pet(petstore_dict, pet_dict):
    # Covers:
    #   - model with primitives properties
    #   - model with an array
    #   - model with a nested model
    petstore_spec = Spec.from_dict(petstore_dict)
    Pet = petstore_spec.definitions['Pet']
    Category = petstore_spec.definitions['Category']
    Tag = petstore_spec.definitions['Tag']
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']

    pet = unmarshal_model(petstore_spec, pet_spec, pet_dict)

    assert isinstance(pet, Pet)
    assert 1 == pet.id
    assert 'Fido' == pet.name
    assert 'sold' == pet.status
    assert ['wagtail.png', 'bark.png'] == pet.photoUrls
    assert isinstance(pet.category, Category)
    assert 200 == pet.category.id
    assert 'friendly' == pet.category.name
    assert isinstance(pet.tags, list)
    assert 2 == len(pet.tags)
    assert isinstance(pet.tags[0], Tag)
    assert 99 == pet.tags[0].id
    assert 'mini' == pet.tags[0].name
    assert isinstance(pet.tags[1], Tag)
    assert 100 == pet.tags[1].id
    assert 'brown' == pet.tags[1].name
コード例 #27
0
ファイル: consumes_test.py プロジェクト: JoelO/bravado-core
def test_returns_consumes_from_op(minimal_swagger_dict):
    op_spec = {
        'consumes': ['multipart/form-data']
    }
    minimal_swagger_spec = Spec.from_dict(minimal_swagger_dict)
    op = Operation(minimal_swagger_spec, '/foo', 'get', op_spec)
    assert ['multipart/form-data'] == op.consumes
コード例 #28
0
def test_object_is_ref(minimal_swagger_dict, address_spec, address):
    minimal_swagger_dict['definitions']['Address'] = address_spec
    address_ref_spec = {'$ref': '#/definitions/Address'}
    swagger_spec = Spec.from_dict(minimal_swagger_dict)
    result = get_spec_for_prop(
        swagger_spec, address_ref_spec, address, 'street_type')
    assert address_spec['properties']['street_type'] == result
コード例 #29
0
def test_use_models_false(petstore_dict):
    petstore_spec = Spec.from_dict(petstore_dict, config={"use_models": False})
    category_spec = petstore_spec.spec_dict["definitions"]["Category"]

    result = unmarshal_schema_object(petstore_spec, category_spec, {"id": 200, "name": "short-hair"})

    assert isinstance(result, dict)
コード例 #30
0
def main(argv=None):
    parser = ArgumentParser(
        description=
        'Tool to introduce HTTP/200 mock responses into response examples', )

    parser.add_argument('-c', '--custom-views', nargs='*',
                        dest='custom_view')  # FIXME
    parser.add_argument('swagger_spec', help='Path of the swagger-specs')
    parser.add_argument('mock_responses',
                        help='Path of the pyramid-mock-server mock responses')

    parser.add_argument('-o',
                        '--output',
                        help='Output file. If not set stdout will be used')
    parser.add_argument(
        '--ignore-validation',
        dest='ignore_validation',
        action='store_true',
        default=False,
        help='By default the generated specs are validated to ensure that they '
        'could be used in clientlibs',
    )
    args = parser.parse_args(argv)

    mock_server_app = _mock_server_app(
        args.swagger_spec,
        args.mock_responses,
        args.custom_view,
    )
    bravado_core_spec = _bravado_core_spec(mock_server_app)
    flattened_enhanced_specs = _insert_examples_in_flattened_specs(
        mock_server_app=mock_server_app,
        bravado_core_spec=bravado_core_spec,
    )

    if not args.ignore_validation:
        # If specs are invalid this is going to throw an exception
        # NOTE: Spec.from_dict alters the input specs, so we need to copy them
        Spec.from_dict(deepcopy(flattened_enhanced_specs))

    if not args.output:
        print(json.dumps(flattened_enhanced_specs, sort_keys=True, indent=2))
    else:
        with open(args.output, 'w') as f:
            json.dump(flattened_enhanced_specs, f, sort_keys=True, indent=2)

    return 0
コード例 #31
0
def test_build_raises_in_case_of_duplicated_models_in_paths(
        minimal_swagger_dict):
    """This test ensures that inline schemas gets tagged as models they have title attribute"""
    model_name = 'model'
    model_200 = {
        'type': 'object',
        'x-location': '200',
        'x-model': model_name,
    }
    model_201 = {
        'type': 'object',
        'x-location': '201',
        'x-model': model_name,
    }
    minimal_swagger_dict['paths'] = {
        '/endpoint': {
            'get': {
                'responses': {
                    '200': {
                        'description': '200 description',
                        'schema': model_200,
                    },
                    '201': {
                        'description': '201 description',
                        'schema': model_201,
                    },
                },
            },
        },
    }
    with pytest.raises(ValueError) as exinfo:
        Spec.from_dict(minimal_swagger_dict)

    # NOTE: the exception depends on the descending order
    expected_exception_string = (
        'Identified duplicated model: model_name "{mod_name}", uri: {json_reference}.\n'
        '    Known model spec: "{known_model}"\n'
        '    New model spec: "{new_model}"\n'
        'TIP: enforce different model naming by using {MODEL_MARKER}'.format(
            known_model=model_200,
            mod_name=model_name,
            MODEL_MARKER='x-model',
            new_model=model_201,
            json_reference='#/paths//endpoint/get/responses/201/schema/x-model',
        ))

    assert expected_exception_string == str(exinfo.value)
コード例 #32
0
def test_ref(minimal_swagger_dict, param_spec):
    minimal_swagger_dict['parameters'] = {
        'FooParam': param_spec
    }
    ref_spec = {'$ref': '#/parameters/FooParam'}
    swagger_spec = Spec(minimal_swagger_dict)
    result = marshal_collection_format(swagger_spec, ref_spec, [1, 2, 3])
    assert result == '1,2,3'
コード例 #33
0
    def __init__(self):

        self.animaldict = {'id': 1}
        with open('../specs/zoo.yaml', 'r') as f:
            self.raw_spec = yaml.load(f)
        self.data = self.create_json()
        self.animal = self.raw_spec['definitions']['Animals']
        self.spec = Spec.from_dict(self.raw_spec)
コード例 #34
0
 def new_spec():
     return Spec.from_dict(
         spec_dict=minimal_swagger_dict,
         origin_url=get_url(minimal_swagger_abspath),
         config={
             'internally_dereference_refs': internally_dereference_refs
         },
     )
コード例 #35
0
def test_security_parameter_cannot_override_path_or_operation_parameter(
        security_dict):
    security_dict['paths']['/example1']['get']['parameters'] = [{
        'description':
        'sec1 as query parameter',
        'required':
        True,
        'in':
        'query',
        'type':
        'integer',
        'name':
        'apiKey1',
    }]

    with pytest.raises(SwaggerSchemaError):
        Spec.from_dict(security_dict)
コード例 #36
0
def test_ref(minimal_swagger_dict, body_param_spec):
    minimal_swagger_dict['parameters'] = {
        'PetIdParam': body_param_spec,
    }
    param_ref_spec = {'$ref': '#/parameters/PetIdParam'}
    swagger_spec = Spec(minimal_swagger_dict)
    param = Param(swagger_spec, Mock(spec=Operation), param_ref_spec)
    assert {'type': 'string'} == get_param_type_spec(param)
コード例 #37
0
def test_value_is_not_dict_like_raises_error(petstore_dict):
    petstore_spec = Spec.from_dict(petstore_dict)
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']

    with pytest.raises(SwaggerMappingError) as excinfo:
        unmarshal_model(petstore_spec, pet_spec, 'i am not a dict')

    assert 'Expected type to be dict' in str(excinfo.value)
コード例 #38
0
def test_flattened_spec_raises_if_specs_are_not_built_and_validated(
    mock_flattened_dict,
    mock_build_api_serving_url,
    petstore_spec,
    build_spec_object,
):
    petstore_spec = Spec(mock_flattened_dict,
                         config=dict(
                             CONFIG_DEFAULTS,
                             validate_swagger_spec=not build_spec_object))
    if build_spec_object:
        petstore_spec.build()

    with pytest.raises(RuntimeError) as excinfo:
        petstore_spec.flattened_spec
    assert 'Swagger Specs have to be built and validated before flattening.' == str(
        excinfo.value)
コード例 #39
0
def test_many_resources_with_the_same_operation_cuz_multiple_tags(paths_spec):
    tags = ['foo', 'bar', 'baz', 'bing', 'boo']
    paths_spec['/pet/findByStatus']['get']['tags'] = tags
    spec_dict = {'paths': paths_spec}
    resources = build_resources(Spec(spec_dict))
    assert len(tags) == len(resources)
    for tag in tags:
        assert resources[tag].findPetsByStatus
コード例 #40
0
def assert_validate_call_count(expected_call_count, config, petstore_dict):
    with patch('bravado_core.param.validate_schema_object') as m_validate:
        petstore_spec = Spec.from_dict(petstore_dict, config=config)
        request = Mock(spec=IncomingRequest, path={'petId': 34})
        op = petstore_spec.resources['pet'].operations['getPetById']
        param = op.params['petId']
        unmarshal_param(param, request)
        assert expected_call_count == m_validate.call_count
コード例 #41
0
def assert_validate_call_count(expected_call_count, config, petstore_dict):
    with patch('bravado_core.param.validate_schema_object') as m_validate:
        petstore_spec = Spec.from_dict(petstore_dict, config=config)
        request = {'url': '/pet/{petId}'}
        op = petstore_spec.resources['pet'].operations['getPetById']
        param = op.params['petId']
        marshal_param(param, 34, request)
        assert expected_call_count == m_validate.call_count
コード例 #42
0
    def __init__(self, specpath, jsonpath):
        with open(specpath, 'r') as f:
            self.raw_spec = yaml.load(f)

        self.data = self.create_json(jsonpath)
        self.key = list(self.data.keys())
        self.spec = Spec.from_dict(self.raw_spec)
        self.obj = self.raw_spec['definitions'][self.key[0]]
コード例 #43
0
def test_value_is_not_dict_like_raises_error(petstore_dict):
    petstore_spec = Spec.from_dict(petstore_dict)
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']

    with pytest.raises(SwaggerMappingError) as excinfo:
        unmarshal_model(petstore_spec, pet_spec, 'i am not a dict')

    assert 'Expected type to be dict' in str(excinfo.value)
コード例 #44
0
def assert_validate_call_count(expected_call_count, config, petstore_dict):
    with patch('bravado_core.param.validate_schema_object') as m_validate:
        petstore_spec = Spec.from_dict(petstore_dict, config=config)
        request = {'url': '/pet/{petId}'}
        op = petstore_spec.resources['pet'].operations['getPetById']
        param = op.params['petId']
        marshal_param(param, 34, request)
        assert expected_call_count == m_validate.call_count
コード例 #45
0
def test_resource_with_sanitized_tag(paths_spec):
    paths_spec['/pet/findByStatus']['get']['tags'][0] = 'Pets & Animals'
    spec_dict = {'paths': paths_spec}
    resources = build_resources(Spec(spec_dict))
    assert 1 == len(resources)
    assert 'Pets & Animals' in resources
    assert 'Pets_Animals' in resources
    assert resources['Pets_Animals'] is resources['Pets & Animals']
コード例 #46
0
ファイル: tag_models_test.py プロジェクト: wting/bravado-core
def test_path_too_short(minimal_swagger_dict, pet_model_spec):
    minimal_swagger_dict['definitions']['Pet'] = pet_model_spec
    swagger_spec = Spec(minimal_swagger_dict)
    tag_models(minimal_swagger_dict,
               'definitions', ['definitions'],
               visited_models={},
               swagger_spec=swagger_spec)
    assert MODEL_MARKER not in pet_model_spec
コード例 #47
0
def assert_validate_call_count(expected_call_count, config, petstore_dict):
    with patch("bravado_core.param.validate_schema_object") as m_validate:
        petstore_spec = Spec.from_dict(petstore_dict, config=config)
        request = {"url": "/pet/{petId}"}
        op = petstore_spec.resources["pet"].operations["getPetById"]
        param = op.params["petId"]
        marshal_param(param, 34, request)
        assert expected_call_count == m_validate.call_count
コード例 #48
0
ファイル: tag_models_test.py プロジェクト: wting/bravado-core
def test_tags_model(minimal_swagger_dict, pet_model_spec):
    minimal_swagger_dict['definitions']['Pet'] = pet_model_spec
    swagger_spec = Spec(minimal_swagger_dict)
    tag_models(minimal_swagger_dict['definitions'],
               'Pet', ['definitions', 'Pet'],
               visited_models={},
               swagger_spec=swagger_spec)
    assert pet_model_spec[MODEL_MARKER] == 'Pet'
コード例 #49
0
def assert_validate_call_count(expected_call_count, config, petstore_dict):
    with patch('bravado_core.param.validate_schema_object') as m_validate:
        petstore_spec = Spec.from_dict(petstore_dict, config=config)
        request = Mock(spec=IncomingRequest, path={'petId': 34})
        op = petstore_spec.resources['pet'].operations['getPetById']
        param = op.params['petId']
        unmarshal_param(param, request)
        assert expected_call_count == m_validate.call_count
コード例 #50
0
def test_self_property_with_model(minimal_swagger_dict):
    link_spec = {
        'type': 'object',
        'required': ['_links'],
        'properties': {
            '_links': {
                '$ref': '#/definitions/Self',
            },
        },
    }

    self_spec = {
        'type': 'object',
        'required': ['self'],
        'properties': {
            'self': {
                'type': 'object',
                'required': ['href'],
                'properties': {
                    'href': {
                        'type': 'string',
                    },
                },
            },
        },
    }

    minimal_swagger_dict['definitions']['Links'] = link_spec
    minimal_swagger_dict['definitions']['Self'] = self_spec

    self_link_response = {
        'get': {
            'responses': {
                '200': {
                    'description': 'A self link.',
                    'schema': {
                        '$ref': '#/definitions/Links',
                    }
                }
            }
        }
    }
    minimal_swagger_dict['paths']['/foo'] = self_link_response

    self_link_swagger_spec = Spec.from_dict(minimal_swagger_dict)

    href = "http://example.com"
    self_link_dict = {
        "_links": {
            "self": {
                "href": href,
            },
        },
    }

    self_link = unmarshal_object(self_link_swagger_spec, link_spec,
                                 self_link_dict)
    assert self_link["_links"].self["href"] == href
コード例 #51
0
ファイル: consumes_test.py プロジェクト: JoelO/bravado-core
def test_consumes_on_op_overrides_consumes_from_swagger_spec(
        minimal_swagger_dict):
    op_spec = {
        'consumes': ['application/x-www-form-urlencoded']
    }
    minimal_swagger_dict['consumes'] = ['multipart/form-data']
    minimal_swagger_spec = Spec.from_dict(minimal_swagger_dict)
    op = Operation(minimal_swagger_spec, '/foo', 'get', op_spec)
    assert ['application/x-www-form-urlencoded'] == op.consumes
コード例 #52
0
def test_get_undefined_operation(paths_spec):
    paths_spec['/pet/findByStatus']['get']['tags'] = ['tag']
    spec_dict = {'paths': paths_spec}
    resources = build_resources(Spec(spec_dict))
    resource = resources['tag']
    with pytest.raises(AttributeError) as excinfo:
        resource.undefined_operation
    assert "Resource 'tag' has no operation 'undefined_operation'" in str(
        excinfo.value)
コード例 #53
0
def test_ref_false(minimal_swagger_dict):
    minimal_swagger_dict['responses'] = {
        'InvalidInput': {
            'description': 'Invalid input'
        }
    }
    response_spec = {'$ref': '#/responses/InvalidInput'}
    swagger_spec = Spec.from_dict(minimal_swagger_dict)
    assert not is_param_spec(swagger_spec, response_spec)
コード例 #54
0
ファイル: consumes_test.py プロジェクト: JoelO/bravado-core
def test_returns_consumes_from_swagger_spec_when_not_present_on_op(
        minimal_swagger_dict):
    op_spec = {
        # 'consumes' left out intentionally
    }
    minimal_swagger_dict['consumes'] = ['multipart/form-data']
    minimal_swagger_spec = Spec.from_dict(minimal_swagger_dict)
    op = Operation(minimal_swagger_spec, '/foo', 'get', op_spec)
    assert ['multipart/form-data'] == op.consumes
コード例 #55
0
def test_non_nullable_array_properties(petstore_dict, pet_dict):
    pet_spec_dict = petstore_dict['definitions']['Pet']
    pet_spec_dict['required'].append('tags')
    petstore_spec = Spec.from_dict(petstore_dict)
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']
    pet_dict['tags'] = None

    with pytest.raises(SwaggerMappingError):
        unmarshal_model(petstore_spec, pet_spec, pet_dict)
コード例 #56
0
def test_non_nullable_array_properties(petstore_dict, pet_dict):
    pet_spec_dict = petstore_dict['definitions']['Pet']
    pet_spec_dict['required'].append('tags')
    petstore_spec = Spec.from_dict(petstore_dict)
    pet_spec = petstore_spec.spec_dict['definitions']['Pet']
    pet_dict['tags'] = None

    with pytest.raises(SwaggerMappingError):
        unmarshal_model(petstore_spec, pet_spec, pet_dict)
コード例 #57
0
ファイル: consumes_test.py プロジェクト: JoelO/bravado-core
def test_consumes_not_present_on_swagger_spec_returns_empty_array(
        minimal_swagger_dict):
    # The point being, None should never be returned
    op_spec = {
        # 'consumes' left out intentionally
    }
    minimal_swagger_spec = Spec.from_dict(minimal_swagger_dict)
    op = Operation(minimal_swagger_spec, '/foo', 'get', op_spec)
    assert [] == op.consumes
コード例 #58
0
def test_self_property_with_model(minimal_swagger_dict):
    link_spec = {
        'type': 'object',
        'required': ['_links'],
        'properties': {
            '_links': {
                '$ref': '#/definitions/Self',
            },
        },
    }

    self_spec = {
        'type': 'object',
        'required': ['self'],
        'properties': {
            'self': {
                'type': 'object',
                'required': ['href'],
                'properties': {
                    'href': {
                        'type': 'string',
                    },
                },
            },
        },
    }

    minimal_swagger_dict['definitions']['Links'] = link_spec
    minimal_swagger_dict['definitions']['Self'] = self_spec

    self_link_response = {
        'get': {
            'responses': {
                '200': {
                    'description': 'A self link.',
                    'schema': {
                        '$ref': '#/definitions/Links',
                    }
                }
            }
        }
    }
    minimal_swagger_dict['paths']['/foo'] = self_link_response

    self_link_swagger_spec = Spec.from_dict(minimal_swagger_dict)

    href = "http://example.com"
    self_link_dict = {
        "_links": {
            "self": {
                "href": href,
            },
        },
    }

    self_link = unmarshal_object(self_link_swagger_spec, link_spec, self_link_dict)
    assert self_link["_links"].self["href"] == href
コード例 #59
0
ファイル: to_wire_test.py プロジェクト: JoelO/bravado-core
def test_ref(minimal_swagger_dict):
    minimal_swagger_dict['definitions']['Int32'] = {
        'type': 'integer', 'format': 'int32'
    }
    int_ref_spec = {'$ref': '#/definitions/Int32'}
    swagger_spec = Spec.from_dict(minimal_swagger_dict)
    result = to_wire(swagger_spec, int_ref_spec, 999)
    assert 999 == result
    assert isinstance(result, int)