Ejemplo n.º 1
0
 def test_parse_object(self):
     parser = jsonschema2md.Parser()
     expected_output = [
         '- **`fruits`** *(array)*\n', '  - **Items** *(string)*\n'
     ]
     assert expected_output == parser._parse_object(
         self.test_schema["properties"]["fruits"], "fruits")
Ejemplo n.º 2
0
    def test_parse_top_level_pattern_properties(self):
        parser = jsonschema2md.Parser()

        test_schema = {
            "$id": "https://example.com/arrays.schema.json",
            "$schema": "http://json-schema.org/draft-07/schema#",
            "description": "Diet preferences",
            "type": "object",
            "additionalProperties": False,
            "patternProperties": {
                "^iLike(Meat|Drinks)$": {
                    "type": "boolean",
                    "description": "Do I like it?"
                }
            },
        }

        expected_output = [
            '# JSON Schema\n'
            '\n',
            '*Diet preferences*\n'
            '\n',
            '## Pattern Properties\n'
            '\n',
            '- **`^iLike(Meat|Drinks)$`** *(boolean)*: Do I like it?\n',
        ]

        assert expected_output == parser.parse_schema(test_schema)
Ejemplo n.º 3
0
def write_md(model):
    sj_rm = model.schema_json()
    parser = jsonschema2md.Parser()
    parser.tab_size = 4
    md_lines = parser.parse_schema(json.loads(sj_rm))

    filename = model.__name__ + ".md"
    with open(os.path.join("docs", filename), "w") as f:
        f.writelines(md_lines)
Ejemplo n.º 4
0
 def test_parse_schema(self):
     parser = jsonschema2md.Parser()
     expected_output = [
         '# JSON Schema\n\n', '*Vegetable preferences*\n\n',
         '## Properties\n\n', '- **`fruits`** *(array)*\n',
         '  - **Items** *(string)*\n', '- **`vegetables`** *(array)*\n',
         '  - **Items**: Refer to *#/definitions/veggie*.\n',
         '## Definitions\n\n', '- **`veggie`** *(object)*\n',
         '  - **`veggieName`** *(string)*: The name of the vegetable.\n',
         '  - **`veggieLike`** *(boolean)*: Do I like this vegetable?\n'
     ]
     assert expected_output == parser.parse_schema(self.test_schema)
Ejemplo n.º 5
0
def parse_schema(schema: Dict) -> Sequence[str]:
    """Parse schema using jsonschema2md parser and returns MD as a string

    :param schema: Valid schema from the get_schema function
    :type schema: Dict
    :return: Sequence of strings with parsed schema as a Markdown
    :rtype: Sequence[str]
    """
    parser = jsonschema2md.Parser(
        examples_as_yaml=False,
        show_examples="all",
    )

    return parser.parse_schema(schema)
Ejemplo n.º 6
0
 def test_parse_schema_examples_yaml(self):
     parser = jsonschema2md.Parser(examples_as_yaml=True)
     expected_output = [
         '# JSON Schema\n\n', '*Vegetable preferences*\n\n',
         '## Additional Properties\n'
         '\n',
         '- **Additional Properties** *(object)*: Additional info about foods you may '
         'like.\n',
         '  - **`^iLike(Meat|Drinks)$`** *(boolean)*: Do I like it?\n',
         '## Properties\n\n', '- **`fruits`** *(array)*\n',
         '  - **Items** *(string)*\n', '- **`vegetables`** *(array)*\n',
         '  - **Items**: Refer to *#/definitions/veggie*.\n',
         '## Definitions\n\n', '- **`veggie`** *(object)*\n',
         '  - **`veggieName`** *(string)*: The name of the vegetable.\n',
         '  - **`veggieLike`** *(boolean)*: Do I like this vegetable?\n',
         '## Examples\n\n',
         '  ```yaml\n  fruits:\n  - apple\n  - orange\n  vegetables:\n  -   veggieLike: true\n      veggieName: cabbage\n  ```\n\n'
     ]
     assert expected_output == parser.parse_schema(self.test_schema)
Ejemplo n.º 7
0
    def on_files(self, files, config, **kwargs):
        """Generate overview over configuration schema and add to mkdoc's files."""
        path_to_schema = Path.cwd() / self.config["path_to_schema"]
        path_to_md = Path.cwd() / self.config["path_to_src_dir"] / self.config[
            "path_to_md_relative_to_site"]
        path_to_md.parent.mkdir(parents=True, exist_ok=True)

        parser = jsonschema2md.Parser()
        parser.tab_size = 4
        with path_to_schema.open("r") as f_schema:
            schema = yaml.safe_load(f_schema)
        with path_to_md.open("w") as f_md:
            lines = parser.parse_schema(schema)
            lines = SchemaPlugin.customise_markdown(lines)
            f_md.writelines(lines)

        schema_md_file = File(path=self.config["path_to_md_relative_to_site"],
                              src_dir=self.config["path_to_src_dir"],
                              dest_dir=config["site_dir"],
                              use_directory_urls=config["use_directory_urls"])
        files.append(schema_md_file)
        return files
Ejemplo n.º 8
0
    def test_parse_top_level_items(self):
        parser = jsonschema2md.Parser()

        test_schema = {
            "$id": "https://example.com/arrays.schema.json",
            "$schema": "http://json-schema.org/draft-07/schema#",
            "title": "Fruits",
            "description": "Fruits I like",
            "type": "array",
            "items": {
                "description": "A list of fruits",
                "type": "object",
                "properties": {
                    "name": {
                        "description": "The name of the fruit",
                        "type": "string"
                    },
                    "sweet": {
                        "description": "Whether it is sweet or not",
                        "type": "boolean",
                    }
                }
            },
        }

        expected_output = [
            '# Fruits\n'
            '\n',
            '*Fruits I like*\n'
            '\n',
            '## Items\n'
            '\n',
            '- **Items** *(object)*: A list of fruits.\n',
            '  - **`name`** *(string)*: The name of the fruit.\n',
            '  - **`sweet`** *(boolean)*: Whether it is sweet or not.\n',
        ]

        assert expected_output == parser.parse_schema(test_schema)
Ejemplo n.º 9
0
 def test_parse_schema(self):
     parser = jsonschema2md.Parser()
     expected_output = [
         "# JSON Schema\n\n",
         "*Vegetable preferences*\n\n",
         "## Additional Properties\n"
         "\n",
         "- **Additional Properties** *(object)*: Additional info about foods you may "
         "like.\n",
         "  - **`^iLike(Meat|Drinks)$`** *(boolean)*: Do I like it?\n",
         "## Properties\n\n",
         "- **`fruits`** *(array)*\n",
         "  - **Items** *(string)*\n",
         "- **`vegetables`** *(array)*\n",
         "  - **Items**: Refer to *#/definitions/veggie*.\n",
         "## Definitions\n\n",
         "- **`veggie`** *(object)*\n",
         "  - **`veggieName`** *(string)*: The name of the vegetable.\n",
         "  - **`veggieLike`** *(boolean)*: Do I like this vegetable?\n",
         "## Examples\n\n",
         "  ```json\n"
         "  {\n"
         '      "fruits": [\n'
         '          "apple",\n'
         '          "orange"\n'
         "      ],\n"
         '      "vegetables": [\n'
         "          {\n"
         '              "veggieName": "cabbage",\n'
         '              "veggieLike": true\n'
         "          }\n"
         "      ]\n"
         "  }\n"
         "  ```\n\n",
     ]
     assert expected_output == parser.parse_schema(self.test_schema)
Ejemplo n.º 10
0
    def test_construct_description_line(self):
        test_cases = [{
            "input": {},
            "add_type": False,
            "expected_output": ""
        }, {
            "input": {
                "description": "The name of the vegetable.",
            },
            "add_type": False,
            "expected_output": ": The name of the vegetable."
        }, {
            "input": {
                "description": "The name of the vegetable.",
                "default": "eggplant",
                "type": "string",
                "$ref": "#/definitions/veggies",
                "enum": ["eggplant", "spinach", "cabbage"]
            },
            "add_type":
            True,
            "expected_output":
            (": The name of the vegetable. Must be of type *string*. "
             "Must be one of: `['eggplant', 'spinach', 'cabbage']`. "
             "Refer to *#/definitions/veggies*. "
             "Default: `eggplant`.")
        }, {
            "input": {
                "description": "Number of vegetables",
                "default": 0,
                "type": "number",
                "minimum": 0,
                "maximum": 999,
                "additionalProperties": True,
            },
            "add_type":
            False,
            "expected_output":
            (": Number of vegetables. Minimum: `0`. Maximum: `999`. "
             "Can contain additional properties. Default: `0`.")
        }, {
            "input": {
                "description": "List of vegetables",
                "default": [],
                "type": "array",
                "additionalProperties": False,
            },
            "add_type":
            False,
            "expected_output":
            (": List of vegetables. Cannot contain additional properties. "
             "Default: `[]`.")
        }]

        parser = jsonschema2md.Parser()

        for case in test_cases:
            observed_output = " ".join(
                parser._construct_description_line(case["input"],
                                                   add_type=case["add_type"]))
            assert case["expected_output"] == observed_output
    '$schema': master_schema,
    'title': 'Node',
    'description': 'Biolink knowledge graph node',
    'properties': node_properties,
    'required': node_required
}

edge_properties = dict()
schema_edges = {
    '$schema': master_schema,
    'title': 'Edge',
    'description': 'Biolink knowledge graph edge',
    'properties': edge_properties
}

js2md_parser = jsonschema2md.Parser()


def get_properties(slot_names: str, class_info: dict) -> dict:
    properties = dict()
    slot_info_all = biolink_model['slots']
    for slot_name in slot_names:
        slot_info = slot_info_all[slot_name]
        description = slot_info.get('description',
                                    '').replace('\n', '').replace(' * ', '')
        slot_uri = slot_info.get('slot_uri', None)
        multivalued = slot_info.get('multivalued', False)
        required = slot_info.get('required', False)
        slot_usage_info = class_info.get('slot_usage', {})
        if slot_name in slot_usage_info:
            slot_usage_info_individual = slot_usage_info[slot_name]
    def on_files(self, files, config):
        # Add json files within included files/directories to list
        locations = []

        for entry in self.config["include"]:
            if entry.endswith(".json"):
                locations.append(entry)

            elif os.path.isdir(entry):
                for root, dirs, filenames in os.walk(entry):
                    for file in filenames:
                        if file.endswith(".json"):
                            locations.append(os.path.join(root, file))

            else:
                logging.warning(f"Could not locate {entry}")

        parser = jsonschema2md.Parser()
        schema_list = []
        schema_dict = {"Schema": schema_list}

        for filepath in locations:
            file = os.path.basename(filepath)

            with open(filepath) as f:
                # Check file is a schema file
                data = f.read()
                schema_syntax = ["$schema", "$ref"]

                if any(x in data for x in schema_syntax):
                    # write converted markdown file to this location
                    path = f"site/schema/{file[:-5]}.md"
                    if not os.path.isdir("./site/schema"):
                        os.makedirs("./site/schema", exist_ok=True)

                    try:
                        with open(path, "w") as md:
                            lines = parser.parse_schema(json.loads(data))
                            for line in lines:
                                md.write(line)

                    except Exception:
                        logging.exception(
                            f"Exception handling {filepath}\n The file may not be valid Schema, consider excluding it."
                        )
                        continue

                    # Add to Files object
                    mkdfile = File(
                        f"schema/{file[:-5]}.md",
                        f"{os.getcwd()}/site",
                        config["site_dir"],
                        config["use_directory_urls"],
                    )
                    files.append(mkdfile)

                    # Add to schema list
                    schema_list.append(
                        {f"{mkdfile.name}": f"{mkdfile.src_path}"})

                else:
                    logging.warning(
                        f"{filepath} does not seem to be a valid Schema JSON file"
                    )

        # Add schemas to nav
        config["nav"].append(schema_dict)

        return files