Files
connexion/tests/test_api.py
João Santos 44ea9336fe Connexion 2.0 (#619)
- App and Api options must be provided through the "options" argument (``old_style_options`` have been removed).
- You must specify a form content-type in 'consumes' in order to consume form data.
- The `Operation` interface has been formalized in the `AbstractOperation` class.
- The `Operation` class has been renamed to `Swagger2Operation`.
- Array parameter deserialization now follows the Swagger 2.0 spec more closely.
  In situations when a query parameter is passed multiple times, and the collectionFormat is either csv or pipes, the right-most value will be used.
  For example, `?q=1,2,3&q=4,5,6` will result in `q = [4, 5, 6]`.
  The old behavior is available by setting the collectionFormat to `multi`, or by importing `decorators.uri_parsing.AlwaysMultiURIParser` and passing `parser_class=AlwaysMultiURIParser` to your Api.
- The spec validator library has changed from `swagger-spec-validator` to `openapi-spec-validator`.
- Errors that previously raised `SwaggerValidationError` now raise the `InvalidSpecification` exception.
  All spec validation errors should be wrapped with `InvalidSpecification`.
- Support for nullable/x-nullable, readOnly and writeOnly/x-writeOnly has been added to the standard json schema validator.
- Custom validators can now be specified on api level (instead of app level).
- Added support for basic authentication and apikey authentication
- If unsupported security requirements are defined or ``x-tokenInfoFunc``/``x-tokenInfoUrl`` is missing, connexion now denies requests instead of allowing access without security-check.
- Accessing ``connexion.request.user`` / ``flask.request.user`` is no longer supported, use ``connexion.context['user']`` instead
2018-11-05 14:50:42 +01:00

138 lines
5.1 KiB
Python

# coding: utf-8
import pathlib
import tempfile
from yaml import YAMLError
import pytest
from connexion import FlaskApi
from connexion.apis.abstract import canonical_base_path
from connexion.exceptions import InvalidSpecification, ResolverError
from mock import MagicMock
TEST_FOLDER = pathlib.Path(__file__).parent
def test_canonical_base_path():
assert canonical_base_path('') == ''
assert canonical_base_path('/') == ''
assert canonical_base_path('/api') == '/api'
assert canonical_base_path('/api/') == '/api'
def test_api():
api = FlaskApi(TEST_FOLDER / "fixtures/simple/swagger.yaml", base_path="/api/v1.0")
assert api.blueprint.name == '/api/v1_0'
assert api.blueprint.url_prefix == '/api/v1.0'
api2 = FlaskApi(TEST_FOLDER / "fixtures/simple/swagger.yaml")
assert api2.blueprint.name == '/v1_0'
assert api2.blueprint.url_prefix == '/v1.0'
api3 = FlaskApi(TEST_FOLDER / "fixtures/simple/openapi.yaml", base_path="/api/v1.0")
assert api3.blueprint.name == '/api/v1_0'
assert api3.blueprint.url_prefix == '/api/v1.0'
api4 = FlaskApi(TEST_FOLDER / "fixtures/simple/openapi.yaml")
assert api4.blueprint.name == '/v1_0'
assert api4.blueprint.url_prefix == '/v1.0'
def test_api_base_path_slash():
api = FlaskApi(TEST_FOLDER / "fixtures/simple/basepath-slash.yaml")
assert api.blueprint.name == ''
assert api.blueprint.url_prefix == ''
def test_template():
api1 = FlaskApi(TEST_FOLDER / "fixtures/simple/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'test'})
assert api1.specification['info']['title'] == 'test'
api2 = FlaskApi(TEST_FOLDER / "fixtures/simple/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'other test'})
assert api2.specification['info']['title'] == 'other test'
def test_invalid_operation_does_stop_application_to_setup():
with pytest.raises(ImportError):
FlaskApi(TEST_FOLDER / "fixtures/op_error_api/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'})
with pytest.raises(ValueError):
FlaskApi(TEST_FOLDER / "fixtures/missing_op_id/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'})
with pytest.raises(ImportError):
FlaskApi(TEST_FOLDER / "fixtures/module_not_implemented/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'})
with pytest.raises(ValueError):
FlaskApi(TEST_FOLDER / "fixtures/user_module_loading_error/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'})
def test_invalid_operation_does_not_stop_application_in_debug_mode():
api = FlaskApi(TEST_FOLDER / "fixtures/op_error_api/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'}, debug=True)
assert api.specification['info']['title'] == 'OK'
api = FlaskApi(TEST_FOLDER / "fixtures/missing_op_id/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'}, debug=True)
assert api.specification['info']['title'] == 'OK'
api = FlaskApi(TEST_FOLDER / "fixtures/module_not_implemented/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'}, debug=True)
assert api.specification['info']['title'] == 'OK'
api = FlaskApi(TEST_FOLDER / "fixtures/user_module_loading_error/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'}, debug=True)
assert api.specification['info']['title'] == 'OK'
def test_other_errors_stop_application_to_setup():
# Errors should still result exceptions!
with pytest.raises(InvalidSpecification):
FlaskApi(TEST_FOLDER / "fixtures/bad_specs/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'})
def test_invalid_schema_file_structure():
with pytest.raises(InvalidSpecification):
FlaskApi(TEST_FOLDER / "fixtures/invalid_schema/swagger.yaml",
base_path="/api/v1.0", arguments={'title': 'OK'}, debug=True)
def test_invalid_encoding():
with tempfile.NamedTemporaryFile(mode='wb') as f:
f.write(u"swagger: '2.0'\ninfo:\n title: Foo 整\n version: v1\npaths: {}".encode('gbk'))
f.flush()
FlaskApi(pathlib.Path(f.name), base_path="/api/v1.0")
def test_use_of_safe_load_for_yaml_swagger_specs():
with pytest.raises(YAMLError):
with tempfile.NamedTemporaryFile() as f:
f.write('!!python/object:object {}\n'.encode())
f.flush()
try:
FlaskApi(pathlib.Path(f.name), base_path="/api/v1.0")
except InvalidSpecification:
pytest.fail("Could load invalid YAML file, use yaml.safe_load!")
def test_validation_error_on_completely_invalid_swagger_spec():
with pytest.raises(InvalidSpecification):
with tempfile.NamedTemporaryFile() as f:
f.write('[1]\n'.encode())
f.flush()
FlaskApi(pathlib.Path(f.name), base_path="/api/v1.0")
@pytest.fixture
def mock_api_logger(monkeypatch):
mocked_logger = MagicMock(name='mocked_logger')
monkeypatch.setattr('connexion.apis.abstract.logger', mocked_logger)
return mocked_logger