本文整理汇总了Python中bravado_core.spec.Spec类的典型用法代码示例。如果您正苦于以下问题:Python Spec类的具体用法?Python Spec怎么用?Python Spec使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Spec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_validate_swagger_spec_failure
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: minimal_swagger_spec
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: test_security_parameter_cannot_override_path_or_operation_parameter
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: test_validate_config_fail
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)
示例5: test_ensure_polymorphic_objects_are_correctly_build_in_case_of_fully_dereferenced_specs
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
示例6: test_missing_object_spec_defaulting_on
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'})
示例7: test_spec_with_dereffed_and_tagged_models_works
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']
示例8: test_array_of_models
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']
示例9: test_complicated_refs
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"
示例10: generate_cli
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
示例11: test_Nones_are_reintroduced_for_declared_properties_that_are_not_present
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
示例12: test_returns_consumes_from_op
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
示例13: test_ref_to_external_path_with_ref_to_local_model
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
示例14: test_use_models_false
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)
示例15: get_swagger_spec
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)