From 9a98f7771fcb25d750d737f0adb1acd3ea63dbab 2014-04-17 21:27:34 From: Jessica B. Hamrick Date: 2014-04-17 21:27:34 Subject: [PATCH] Misc style changes, add more docstrings --- diff --git a/IPython/nbformat/validator.py b/IPython/nbformat/validator.py index 41ea72d..d330ca1 100644 --- a/IPython/nbformat/validator.py +++ b/IPython/nbformat/validator.py @@ -4,7 +4,7 @@ from __future__ import print_function import json import os -from IPython.external.jsonschema import Draft3Validator +from IPython.external.jsonschema import Draft3Validator, SchemaError import IPython.external.jsonpointer as jsonpointer from IPython.utils.py3compat import iteritems @@ -14,20 +14,36 @@ schema_path = os.path.join( os.path.split(__file__)[0], "v%d" % nbformat, nbformat_schema) -def isvalid(nbjson, key='/notebook', verbose=False): - errors = validate(nbjson, key=key, verbose=verbose) +def isvalid(nbjson, verbose=False): + """Checks whether the given notebook JSON conforms to the current + notebook format schema. Returns True if the JSON is valid, and + False otherwise. + + If `verbose` is set, then print out each error that is detected. + + """ + + errors = validate(nbjson, verbose=verbose) return errors == 0 -def validate(nbjson, key='/notebook', verbose=False): +def validate(nbjson, verbose=False): + """Checks whether the given notebook JSON conforms to the current + notebook format schema, and returns the number of errors. + + If `verbose` is set, then print out each error that is detected. + + """ + # load the schema file with open(schema_path, 'r') as fh: schema_json = json.load(fh) # resolve internal references v3schema = resolve_ref(schema_json) - v3schema = jsonpointer.resolve_pointer(v3schema, key) + v3schema = jsonpointer.resolve_pointer(v3schema, '/notebook') + # count how many errors there are errors = 0 v = Draft3Validator(v3schema) for error in v.iter_errors(nbjson): @@ -39,9 +55,14 @@ def validate(nbjson, key='/notebook', verbose=False): def resolve_ref(json, schema=None): - """return a json with resolved internal references + """Resolve internal references within the given JSON. This essentially + means that dictionaries of this form: + + {"$ref": "/somepointer"} + + will be replaced with the resolved reference to `/somepointer`. + This only supports local reference to the same JSON file. - only support local reference to the same json """ if not schema: @@ -58,10 +79,13 @@ def resolve_ref(json, schema=None): elif type(json) is dict: resolved = {} for key, ref in iteritems(json): + # if the key is equal to $ref, then replace the entire # dictionary with the resolved value if key == '$ref': - assert len(json) == 1 + if len(json) != 1: + raise SchemaError( + "objects containing a $ref should only have one item") pointer = jsonpointer.resolve_pointer(schema, ref) resolved = resolve_ref(pointer, schema=schema)