<commit_before>"""Pedantic service providing REST API for fixture validation."""

from __future__ import absolute_import, unicode_literals
import json

from flask import Flask, request, jsonify
from jsonschema.exceptions import ValidationError

from .check_against_schema import (
    validate_request_against_schema,
    validate_response_against_schema,
    is_whitelisted,
    get_spec,
    parse_data,
    JSONSchemaValidationError,
    UndefinedSchemaError,
)

app = Flask(__name__)

schema = None
whiltelist = None


def set_proxy_settings(schema_arg, whitelist_arg):
    global schema
    global whitelist

    schema = json.loads(schema_arg)
    if whitelist_arg:
        whitelist = json.loads(whitelist_arg)


@app.route('/', methods=['POST'])
def validator():
    """
    .. http:POST:: /

        Receives relevant fixture information as POST JSON data payload. The
        data is validated and the validation result is returned.
        
        **Example request**:

        .. code-block:: bash

            curl -X POST -i http://localhost:5000/ --data '{"method":
            "POST", "path_info": "/api/v5/test/", "request":
            {"x": "data"}}' -H "Content-Type: application/json"

        **Success response**:

        .. sourcecode:: http

            HTTP/1.0 200 OK
            Content-Type: application/json
            Content-Length: 66

            {
              "message": "All is well with the world (and your fixture)."
            }

        **Failure response**:

        .. sourcecode:: http

            HTTP/1.0 400 BAD REQUEST
            Content-Type: application/json
            Content-Length: 78

            {
              "error": "The requested resource '/dummy/path/' was not found in spec."
            }

            

        :return: On success 200 is returned, otherwise 400 with error detail.
    
        **JSON Schema Definition:**
        
        .. code-block:: json
        
            {
                "title": "Pedantic POST API",
                "type": "object",
                "properties": {
                    "path_info": {
                        "description": "Path to the mock resource.",
                        "type": "string",
                        "example": "/some/endpoint/"
                    },
                    "method": {
                        "description": "Method of mock request.",
                        "type": "string",
                        "example": "GET",
                    },
                    "request": {
                        "description": "Payload of mock request.",
                        "type": "object",
                        "example": { "some_prop": "some_value" }
                    },
                    "response": {
                        "description": "Payload of mock response.",
                        "type": "object",
                        "example": { "data": { "some_prop": "some_value" } }
                    },
                    "query_string": {
                        "description": "Mock request query string.",
                        "example": "param1=a_string,param2=123",
                        "type": "string"
                    },
                    "status_code": {
                        "description": "Status of mock response.",
                        "example": 200,
                        "type": "number"
                    }
                },
                "required": [ "path_info", "method" ],
                "oneOf" : [
                    { "required" : [ "request" ] },
                    { "required" : [ "response", "status_code" ] }
                ]
            }
    """

    if 'application/json' not in request.headers.get('Content-Type'):
        msg = 'Transport header `Content-Type` must be `application/json`.'
        error = {'error': msg}
        return jsonify(error), 400

    json = request.get_json()
    try:
        data = parse_data(json)
    except ValidationError as e:
        err_msg = "Pedantic error{}".format(str(e))
        msg = {'error': err_msg, 'data': json}
        return jsonify(msg), 400

    # Get the specific schema under test
    try:
        spec = get_spec(data, schema)
    except UndefinedSchemaError as e:
        if whitelist:
            if is_whitelisted(data, whitelist):
                msg = 'Requested endpoint `{}` is whitelisted against ' \
                      'validation.'.format(data.path)
                value = {'warning': msg}
                return jsonify(value), 200
        msg = {'error': str(e)}
        return jsonify(msg), 400

    # Validate the request and/or response
    errors = ''
    if data.request:
        try:
            validate_request_against_schema(data, spec)
        except JSONSchemaValidationError as e:
            errors = '{}\n\n'.format(str(e))

    if data.response:
        try:
            validate_response_against_schema(data, spec)
        except JSONSchemaValidationError as e:
            errors += str(e)

    # Return the results
    if not errors:
        msg = {'message': 'All is well with the world (and your fixture).'}
        return jsonify(msg), 200
    else:
        msg = {'error': errors}
        return jsonify(msg), 400
<commit_msg>update JSON Schema in docs<commit_after>"""Pedantic service providing REST API for fixture validation."""

from __future__ import absolute_import, unicode_literals
import json

from flask import Flask, request, jsonify
from jsonschema.exceptions import ValidationError

from .check_against_schema import (
    validate_request_against_schema,
    validate_response_against_schema,
    is_whitelisted,
    get_spec,
    parse_data,
    JSONSchemaValidationError,
    UndefinedSchemaError,
)

app = Flask(__name__)

schema = None
whiltelist = None


def set_proxy_settings(schema_arg, whitelist_arg):
    global schema
    global whitelist

    schema = json.loads(schema_arg)
    if whitelist_arg:
        whitelist = json.loads(whitelist_arg)


@app.route('/', methods=['POST'])
def validator():
    """
    .. http:POST:: /

        Receives relevant fixture information as POST JSON data payload. The
        data is validated and the validation result is returned.
        
        **Example request**:

        .. code-block:: bash

            curl -X POST -i http://localhost:5000/ --data '{"method":
            "POST", "path_info": "/api/v5/test/", "request":
            {"x": "data"}}' -H "Content-Type: application/json"

        **Success response**:

        .. sourcecode:: http

            HTTP/1.0 200 OK
            Content-Type: application/json
            Content-Length: 66

            {
              "message": "All is well with the world (and your fixture)."
            }

        **Failure response**:

        .. sourcecode:: http

            HTTP/1.0 400 BAD REQUEST
            Content-Type: application/json
            Content-Length: 78

            {
              "error": "The requested resource '/dummy/path/' was not found in spec."
            }

            

        :return: On success 200 is returned, otherwise 400 with error detail.
    
        **JSON Schema Definition:**
        
        .. code-block:: json
        
            {
                "title": "Pedantic POST API",
                "type": "object",
                "additionalProperties": False,
                "properties": {
                    "path_info": {
                        "description": "Path to the mock resource.",
                        "type": "string",
                        "pattern": "^/*",
                        "example": "/some/endpoint/"
                    },
                    "method": {
                        "description": "Method of mock request.",
                        "type": "string",
                        "example": "GET",
                    },
                    "request": {
                        "description": "Payload of mock request.",
                        "type": "object",
                        "example": {"some_prop": "some_value"}
                    },
                    "response": {
                        "description": "Payload of mock response.",
                        "type": "object",
                        "example": {"data": {"some_prop": "some_value"}}
                    },
                    "query_string": {
                        "description": "Mock request query string.",
                        "example": "param1=a_string,param2=123",
                        "type": "string"
                    },
                    "status_code": {
                        "description": "Status of mock response.",
                        "example": 200,
                        "type": "number"
                    }
                },
                "required": ["path_info", "method"],
                "anyOf": [
                    {"required": ["request"]},
                    {"required": ["response", "status_code"]}
                ]
            }
    """

    if 'application/json' not in request.headers.get('Content-Type'):
        msg = 'Transport header `Content-Type` must be `application/json`.'
        error = {'error': msg}
        return jsonify(error), 400

    json = request.get_json()
    try:
        data = parse_data(json)
    except ValidationError as e:
        err_msg = "Pedantic error{}".format(str(e))
        msg = {'error': err_msg, 'data': json}
        return jsonify(msg), 400

    # Get the specific schema under test
    try:
        spec = get_spec(data, schema)
    except UndefinedSchemaError as e:
        if whitelist:
            if is_whitelisted(data, whitelist):
                msg = 'Requested endpoint `{}` is whitelisted against ' \
                      'validation.'.format(data.path)
                value = {'warning': msg}
                return jsonify(value), 200
        msg = {'error': str(e)}
        return jsonify(msg), 400

    # Validate the request and/or response
    errors = ''
    if data.request:
        try:
            validate_request_against_schema(data, spec)
        except JSONSchemaValidationError as e:
            errors = '{}\n\n'.format(str(e))

    if data.response:
        try:
            validate_response_against_schema(data, spec)
        except JSONSchemaValidationError as e:
            errors += str(e)

    # Return the results
    if not errors:
        msg = {'message': 'All is well with the world (and your fixture).'}
        return jsonify(msg), 200
    else:
        msg = {'error': errors}
        return jsonify(msg), 400

{'fraction_non_alphanumeric': 0.11216101294528961, 'fraction_numerical': 0.00963809883775867, 'mean_word_length': 1.474631751227496, 'pattern_counts': {'":': 79, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3491022', 'n_tokens_mistral': 2862, 'n_tokens_neox': 2596, 'n_words': 743}