コード例 #1
0
def test_invalid_api_call_with_polymorphism():
    request_payload = """{
        "events": [
            {
                "eventType": "Impression",
                "timestamp": 12312312
            }
        ]
    }"""
    responses.add(responses.POST,
                  "http://test.com/poly/report",
                  body="{}",
                  status=200,
                  content_type="application/json")

    response = requests.post("http://test.com/poly/report",
                             json=json.loads(request_payload))

    schema = load(os.path.join(BASE_DIR, 'schemas', 'polymorphism.yaml'))

    with pytest.raises(ValidationError) as err:
        validate_api_call(schema,
                          raw_request=response.request,
                          raw_response=response)

    assert_message_in_errors(
        MESSAGES['required']['required'],
        err.value.detail,
    )
コード例 #2
0
def test_validate_api_call(httpbin):
    schema = load(os.path.join(BASE_DIR, 'schemas', 'httpbin.yaml'))
    response = requests.get(urlparse.urljoin(httpbin.url, '/get'))
    print response.text
    validate_api_call(schema,
                      raw_request=response.request,
                      raw_response=response)
コード例 #3
0
ファイル: cli.py プロジェクト: djta/5GCORE-1
def main(source):
    """
    For a given command line supplied argument, negotiate the content, parse
    the schema and then return any issues to stdout or if no schema issues,
    return success exit code.
    """
    if source is None:
        click.echo(
            "You need to supply a file or url to a schema to a swagger schema, for"
            "the validator to work."
        )
        return 1
    try:
        load(source)
        click.echo("Validation passed")
        return 0
    except ValidationError as e:
        raise click.ClickException(str(e))
コード例 #4
0
ファイル: cli.py プロジェクト: jmdcal/flex
def main(source):
    """
    For a given command line supplied argument, negotiate the content, parse
    the schema and then return any issues to stdout or if no schema issues,
    return success exit code.
    """
    if source is None:
        click.echo(
            "You need to supply a file or url to a schema to a swagger schema, for"
            "the validator to work."
        )
        return 1
    try:
        load(source)
        click.echo("Validation passed")
        return 0
    except ValueError as e:
        raise click.ClickException(str(e))
コード例 #5
0
def test_get_openapi_sorted(get, schema):
    openapi = get('/openapi')
    assert openapi.content_type == 'application/json'

    source = openapi.data.decode("utf-8")
    check = load(get('/openapi').json)
    sorted_true = json.dumps(check, sort_keys=True)
    sorted_false = json.dumps(check, sort_keys=False)
    assert source == sorted_true
    assert source != sorted_false
コード例 #6
0
def test_get_openapi_sorted(get, schema):
    openapi = get('/openapi')
    assert openapi.content_type == 'application/json'

    source = openapi.data.decode("utf-8")
    check = load(get('/openapi').json)
    sorted_true = json.dumps(check, sort_keys=True)
    sorted_false = json.dumps(check, sort_keys=False)
    assert source == sorted_true
    assert source != sorted_false
コード例 #7
0
 def validate_swagger_schema(self, endpoint, timeout=5):
     start = time.time()
     schema_uri = endpoint
     response = requests.request('GET',
                                 schema_uri,
                                 timeout=timeout,
                                 verify=False)
     schema = load(response.text)
     logger.info('Load swagger schema from %s: %ss' %
                 (endpoint, time.time() - start))
     return schema
コード例 #8
0
def test_post_request(request_path):
    schema = load('swagger.awsexport.json')

    URL = 'https://' + schema['host'] + schema['basePath'] + request_path
    lambdaArn = 'arn:aws:lambda:us-east-1:769482945897:function:' \
                'anon-service-Lambda-1CNEQSHUD7Z25'

    time = str(datetime.now() + relativedelta(months=1))
    postdata = json.dumps({"lambdaArn": lambdaArn, "time": time})
    headers = {'Content-Type': 'application/json'}

    # r => response
    r = requests.post(URL, data=postdata, headers=headers)
    validate_api_call(schema, raw_request=r.request, raw_response=r)
コード例 #9
0
def test_valid_api_call_with_polymorphism():
    request_payload = """{
        "events": [
            {
                "eventType": "Impression",
                "advertisementId" : "ad7",
                "timestamp": 12312312
            }
        ]
    }"""
    responses.add(responses.POST, "http://test.com/poly/report",
                  body="{}", status=200, content_type="application/json")
    response = requests.post("http://test.com/poly/report",
                             json=json.loads(request_payload))
    schema = load(os.path.join(BASE_DIR, 'schemas', 'polymorphism.yaml'))
    validate_api_call(schema, raw_request=response.request, raw_response=response)
コード例 #10
0
def test_valid_api_call_with_polymorphism():
    request_payload = """{
        "events": [
            {
                "eventType": "Impression",
                "advertisementId" : "ad7",
                "timestamp": 12312312
            }
        ]
    }"""
    responses.add(responses.POST, "http://test.com/poly/report",
                  body="{}", status=200, content_type="application/json")
    response = requests.post("http://test.com/poly/report",
                             json=json.loads(request_payload))
    schema = load(os.path.join(BASE_DIR, 'schemas', 'polymorphism.yaml'))
    validate_api_call(schema, raw_request=response.request, raw_response=response)
コード例 #11
0
ファイル: middleware.py プロジェクト: rstormsf/smartz
    def __call__(self, request):
        if request.method == 'OPTIONS':
            request.is_swagger_schema_validated = True
            return self.get_response(request)

        schema = load(settings.SMARTZ_INTERNAL_API_SWAGGER_SCHEMA)

        request.is_swagger_schema_validated = False
        try:
            validate_api_request(schema, request)
            request.is_swagger_schema_validated = True
        except ValidationError as err:
            if 'path' in err.detail and isinstance(err.detail['path'], collections.Iterable) \
                    and len(err.detail['path'])>0 and 'No paths found for' in str(err.detail['path'][0]):
                self.logger.debug(str(err.detail['path'][0]))
                request.is_swagger_schema_validated = True
            else:
                self.logger.warning(str(err))
                return error_response("Invalid request", 500)

        return self.get_response(request)
コード例 #12
0
def test_invalid_api_call_with_polymorphism():
    request_payload = """{
        "events": [
            {
                "eventType": "Impression",
                "timestamp": 12312312
            }
        ]
    }"""
    responses.add(responses.POST, "http://test.com/poly/report",
                  body="{}", status=200, content_type="application/json")

    response = requests.post("http://test.com/poly/report",
                             json=json.loads(request_payload))

    schema = load(os.path.join(BASE_DIR, 'schemas', 'polymorphism.yaml'))

    with pytest.raises(ValidationError) as err:
        validate_api_call(schema, raw_request=response.request, raw_response=response)

    assert_message_in_errors(
        MESSAGES['required']['required'],
        err.value.detail,
    )
コード例 #13
0
def test_load_and_parse_schema(path):
    load(path)
コード例 #14
0
ファイル: test_example_schemas.py プロジェクト: dhilton/flex
def test_load_and_parse_schema(path):
    load(path)
コード例 #15
0
ファイル: test_schema.py プロジェクト: odorie/api-gestion-poc
def schema(get):
    resp = get('/openapi')
    return load(resp.json)
コード例 #16
0
class Client(object):
    schema = load(os.path.join(PROJECT_DIR, 'app/swagger.yml'))

    def __init__(self, username, password, test_app=None, app=None):
        self.test_app = test_app
        self.username = username
        self.password = password
        self.app = app
        self.validate_api_call = True

    def put_user(self, user_id, username=None, email=None, notify=None):
        data = {'username': username, 'email': email, 'notify': notify}
        data = strip_none(data)
        return self.request('/users/{}'.format(user_id),
                            method='PUT',
                            data=data)

    def listings(self):
        return self.request('/listings')

    def search_listings(self,
                        keywords=None,
                        min_rent=None,
                        max_rent=None,
                        min_room_count=None,
                        max_room_count=None,
                        min_surface_area=None,
                        max_surface_area=None,
                        amenities=None,
                        listing_type=None,
                        limit=None):
        data = locals()
        data.pop('self')
        data = strip_none(data)
        return self.request('/listings:search', params=data)

    def amenity_types(self):
        return self.request('/amenity-types')

    def auth(self):
        return self.request('/auth')

    def request(self, url, method='GET', params=None, data=None, headers=None):
        import base64
        from urllib import urlencode
        import flask

        content_type = None
        if data is not None:
            data = json.dumps(data)
            content_type = 'application/json'
        if params is not None:
            params = {k: v for k, v in params.items() if v is not None}
            url = url + '?' + urlencode(params, True)
        if headers is None:
            headers = {}
        headers['Authorization'] = 'Basic ' + base64.b64encode(self.username +
                                                               ':' +
                                                               self.password)
        r = self.test_app.open(url,
                               method=method,
                               headers=headers,
                               data=data,
                               content_type=content_type)
        if self.validate_api_call:
            try:
                old_r_data = r.data
                r.data = json.dumps(strip_none(json.loads(r.data)))
            except ValueError:
                print(r.data)
            else:
                with self.app.test_request_context(url,
                                                   method=method,
                                                   headers=headers,
                                                   data=data,
                                                   content_type=content_type):
                    try:
                        validate_api_call(self.schema,
                                          raw_request=flask.request,
                                          raw_response=r)
                    except ValidationError as e:
                        context = {
                            'url': url,
                            'method': method,
                            'params': params,
                            'data': data,
                            'headers': headers,
                            'r.data': json.loads(r.data),
                        }
                        print(json.dumps(context, indent=4))
                        raise e
                r.data = old_r_data
        return r
コード例 #17
0
import requests
from flex.core import load, validate, validate_api_call
from flex.exceptions import ValidationError

dir_path = os.path.dirname(os.path.realpath(__file__))
platform = sys.argv[1]
base_url = sys.argv[2]
paths = glob.glob(os.path.join(dir_path, "../", "definitions", platform) +
                  "/**/*.yml",
                  recursive=True)

exitcode = 0

for path in paths:
    schema = load(path)
    validate(schema)
    matches = re.match(".*/api(?P<path>.+)[.]yml$", path)
    if not matches:
        continue

    uri = "/api" + matches.group("path")
    print("testing endpoint %s... " % uri, end="", flush=True)
    response = requests.get(base_url + uri, verify=False)

    try:
        validate_api_call(schema,
                          raw_request=response.request,
                          raw_response=response)
    except ValidationError as ve:
        print("failed\n\n" + str(ve) + "\n")
コード例 #18
0
def test_validate_api_call(httpbin):
    schema = load(os.path.join(BASE_DIR, 'schemas', 'httpbin.yaml'))
    response = requests.get(urlparse.urljoin(httpbin.url, '/get'))
    validate_api_call(schema, raw_request=response.request, raw_response=response)
コード例 #19
0
def schema(get):
    return load(get('/openapi').json)
コード例 #20
0
def schema(get):
    return load(get('/openapi').json)