question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

JsonSchemaException is not right.

See original GitHub issue

When I ran unittest case test_nonExistProject with fastjsonschema in master branch of this repo

The output is AssertionError: False is not true : data.Code must match pattern MissingParameter

response: {‘RequestId’: ‘', ‘HostId’: '’, ‘Code’: ‘InvalidProject.NotFound’, ‘Message’: ‘Specified project is not found.’}

schema: {‘id’: ‘http://localhost:8000/’, ‘$ref’: ‘http://localhost:8000/definitions.json#/NotFoundDefinition’}

AssertionError suggests that I used the MissingParameter related jsonschema, but the debug info I add in is_data_validate function suggests that current error was from Invalid.NotFound related jsonschema. Why they are not the same?

def is_data_validate(response, name):
    schema = SCHEMAS[name]
    validator = fastjsonschema.compile(schema)
    try:
        validator(response)
    except fastjsonschema.JsonSchemaException as e:
        msg = e.message + "\n\nresponse: %s\n\nschema: %s" % (response, schema)
        return False, msg
    else:
        return True, "validate %s pass" % name

class RestTestCase(unittest.TestCase):
    def do_request_and_check_response(self, schema_name):
        self.response = myclient.do_action_with_exception(self.request)
        result, msg = is_data_validate(self.response, schema_name)
        self.assertTrue(result, msg)


class TestCreateTagSet(client.RestTestCase):
#here is the test case that ran with unexpected result.
    def test_nonExistProject(self):
        schema_project_list = [('MissingParameter', ""), ('Invalid.NotFound', "non-exists")]
        for schema_name, project in schema_project_list:
            self.request.set_Project(project)
            self.do_request_and_check_response(schema_name)

here is the json file for reference,

[
    {
        "name": "MissingParameter",
        "schema": {
            "id": "http://localhost:8000/",
            "type": "object",
            "allOf": [
                {"$ref": "definitions.json#/HostRequestDefinition"},
                {
                    "properties": {
                        "Code": {"type": "string", "pattern": "MissingParameter"},
                        "Message": {"type": "string", "pattern": "The parameter is missing."}
                    },
                    "required": ["Code", "Message"]
                }
            ]
        }
    },
    {
        "name": "Invalid.NotFound",
        "schema": {
            "id": "http://localhost:8000/",
            "$ref": "definitions.json#/NotFoundDefinition"
        }
    }
]

file: definitions.json

{
    "NotFoundDefinition": {
        "type": "object",
        "allOf": [
            {"$ref": "#/HostRequestDefinition"},
            {
                "properties": {
                    "Code": {"type": "string", "pattern": "Invalid(Set|Project).NotFound"},
                    "Message": {"type": "string", "pattern": "Specified (set|project) is not found."}
                },
                "required:": ["Code", "Message"]
            }
        ]
    }
}

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
ThreeOcommented, Sep 19, 2018

you should have for the exception class

  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

with no need for the message member variable. Then doing

raise JsonSchemaException(message)

will ensure that the str() of the exception is the message, which is the behavior of the base Exception class. Your way requires special treatment and will not get printed correctly by the default handler, for instance.

test case:

raise fastjsonschema.JsonSchemaException("test")

will print

JsonSchemaException:

instead of

JsonSchemaException: test
0reactions
ThreeOcommented, Sep 23, 2018

If you want to keep the message compatibility I would suggest to go with something like the following

class JsonSchemaException(ValueError):
    """
    Exception raised by validation function. Contains ``message`` with
    information what is wrong.
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @property
    def message(self):
      return str(self)

It’s somewhat more efficient and achieves the same result 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validating a json with the json schema validator throws an ...
Spring Boot json schema validation with version draft 07 throws JsonSchemaException: Unknown MetaSchema: https://json-schema.org/draft-07/schema.
Read more >
After recent update json schema validation fails - Airbyte
It prompts to reset and I get a message below in red: Something went wrong. Internal Server Error. Looking at the logs of...
Read more >
WS.validateJsonAgainstSchema is not working as expected
If I just add schema tag in my schema & provide any invalid schema in it…the above test step still returns true. Please...
Read more >
Handling Validation Errors - python-jsonschema
The error messages in this situation are not very helpful on their own. ... {} is not valid under any of the given...
Read more >
Fast JSON schema for Python — fastjsonschema documentation
JsonSchemaException (message, value=None, name=None, definition=None, ... message containing human-readable information what is wrong (e.g. ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found