def test_yaml() -> None:
    """Test loading the schema from a YAML file. The schema is the same as the case "with_definitions"."""
    with tempfile.NamedTemporaryFile(mode="w+") as temp_file:
        with open(
                os.path.abspath(
                    os.path.join(examples_dir, "cases",
                                 f"yaml.yaml"))) as schema_fp:
            generate_from_file_object(schema_fp, temp_file, True, False, False,
                                      True)

        temp_file.seek(0)
        soup = BeautifulSoup(temp_file.read(), "html.parser")

    # Order of properties is only preserved in Python 3.7+
    tests.html_schema_doc_asserts.assert_property_names(
        soup,
        [
            "billing_address", "street_address", "city", "state",
            "shipping_address"
        ],
    )
    tests.html_schema_doc_asserts.assert_types(
        soup, ["object", "object", "string", "string", "string", "object"])
    tests.html_schema_doc_asserts.assert_required(
        soup, [False, True, True, True, False])
예제 #2
0
def schema(output_file, output_format, data_type, url, database):
    print_messages = _log.isEnabledFor(logging.ERROR)
    if output_file:
        stream = output_file
    else:
        stream = sys.stdout
    schema_data = edb_schemas[data_type]
    if output_format == "json":
        json.dump(schema_data, stream, indent=2)
    else:
        if output_format == "markdown":
            tmpl = "md"
        elif output_format == "html":
            tmpl = "flat"
        elif output_format == "html-js":
            tmpl = "js"
        config = GenerationConfiguration(template_name=tmpl)
        with tempfile.TemporaryDirectory() as tmpdir_name:
            schema_path = pathlib.Path(tmpdir_name) / "schema.json"
            with schema_path.open("w+", encoding="utf-8") as schema_file:
                json.dump(schema_data, schema_file)
                schema_file.seek(0)
                schema_gen.generate_from_file_object(schema_file,
                                                     stream,
                                                     config=config)
예제 #3
0
def test_generate_from_file_object_deprecation_warning(
        tmp_path: Path, caplog: LogCaptureFixture, minify: bool,
        expect_warning: bool) -> None:
    result_file_path = tmp_path / "result_file.html"

    caplog.set_level(logging.INFO)
    with open(get_test_case_path("basic")) as test_case_fp:
        with result_file_path.open("w", encoding="utf-8") as result_write_fp:
            generate_from_file_object(test_case_fp,
                                      result_write_fp,
                                      minify=minify)

    _assert_deprecation_message(caplog, expect_warning)
예제 #4
0
def main():
    prs = argparse.ArgumentParser(description="Generate schema docs")
    prs.add_argument("directory", help="Directory to put generated schema docs")
    args = prs.parse_args()
    output_dir = Path(args.directory)
    for schema in "component", "reaction":
        schema_file = output_dir / f"{schema}.json"
        with schema_file.open("w") as f:
            json.dump(schemas[schema], f)
        output_file = (output_dir / f"{schema}.html").open("w")
        generate_from_file_object(schema_file.open("r"), output_file)
        print(f"Docs for {schema} at: {output_file.name}")
    return 0
def test_json_with_tabs() -> None:
    """Test loading the schema when tabs are present rather than spaces. Regression test for #45"""
    temp_schema_file = tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json")
    created_filename = temp_schema_file.name
    with open(os.path.abspath(os.path.join(os.path.dirname(__file__), "cases", f"basic.json"))) as schema_fp:
        for line in schema_fp:
            temp_schema_file.write(line.replace("  ", "\t"))
    with tempfile.NamedTemporaryFile(mode="w+") as temp_html_file:
        temp_schema_file.seek(0)
        generate_from_file_object(temp_schema_file, temp_html_file, True, False, False, True)
        temp_schema_file.close()
        os.remove(created_filename)
        temp_html_file.seek(0)
        soup = BeautifulSoup(temp_html_file.read(), "html.parser")
        tests.html_schema_doc_asserts.assert_basic_case(soup)
예제 #6
0
def test_generate_from_file_object(tmp_path: Path) -> None:
    """Test generating from open file objects for input and output"""
    result_file_path = tmp_path / "result_with_another_name.html"

    with open(get_test_case_path("basic")) as test_case_fp:
        with result_file_path.open("w", encoding="utf-8") as result_write_fp:
            generate_from_file_object(test_case_fp, result_write_fp, False,
                                      False, False, False)

    with result_file_path.open(encoding="utf-8") as result_fp:
        soup = BeautifulSoup(result_fp.read(), "html.parser")

    assert_basic_case(soup)

    assert (tmp_path / "result_with_another_name.html").exists()

    assert (tmp_path / "schema_doc.min.js").exists()
예제 #7
0
def schema_docs(schemas):
    """Generates jsonschema docs for data models."""
    for schema_path in schemas:
        click.secho(f'Generating docs for schema {schema_path}')
        schema = current_jsonschemas.get_schema(schema_path, with_refs=False, resolved=False)
        schema = JsonRef.replace_refs(
            schema,
            jsonschema=True,
            base_uri=current_app.config.get('JSONSCHEMAS_HOST'),
            loader=_records_state.loader_cls(),
        )

        # TODO: this is necessary to resolve JSONRefs in allOf
        schema = json.loads(json.dumps(schema, default=lambda x: x.__subject__))

        # Generate and save html docs for the schema
        with tempfile.NamedTemporaryFile(mode="w+") as schema_source:
            schema_source.write(json.dumps(schema))
            schema_source.flush()

            with open(f'docs/schemas/{basename(schema_path.rstrip(".json"))}.html', mode='w+') as result_file:
                click.secho(f'Writing schema docs to {result_file.name}', color='green')
                generate_from_file_object(
                    schema_file=schema_source,
                    result_file=result_file,
                    minify=True,
                    expand_buttons=True
                )

    # Generate and save schema index page
    index_md = r"""---
layout: default
---

# Data Models Schema Docs

"""
    for f in os.listdir('docs/schemas/'):
        if f.endswith('.html'):
            index_md += f'- [{f.rstrip(".html")}](./{f})\n'

    with open(f'docs/schemas/index.md', mode='w+') as index_file:
        index_file.write(index_md)
예제 #8
0
def build_docs(schemas):
    """Generates API docs for included / specified data models."""
    from json_schema_for_humans.generate import generate_from_file_object

    for schema_path in schemas or current_jsonschemas.list_schemas():
        click.secho(f'Generating docs for schema {schema_path}')
        schema = current_jsonschemas.get_schema(schema_path,
                                                with_refs=False,
                                                resolved=False)

        try:
            schema = JsonRef.replace_refs(
                schema,
                jsonschema=True,
                base_uri=current_app.config.get('JSONSCHEMAS_HOST'),
                loader=_records_state.loader_cls(),
            )

            # TODO: this is necessary to resolve JSONRefs in allOf
            schema = json.loads(
                json.dumps(schema, default=lambda x: x.__subject__))

            # Resolve definition schemas
            if 'definitions' in schema:
                definitions = list(schema['definitions'].keys())
                # Consider only a first definition as a schema for now
                schema = schema['definitions'][definitions[0]]

            click.secho(f'Schema resolved to: {json.dumps(schema)}',
                        color='blue')

        except JsonRefError as e:
            click.secho(f'Error resolving schema: {e}. Skipping...',
                        color='red')
            continue

        # Generate and save html docs for the schema
        with tempfile.NamedTemporaryFile(mode="w+") as schema_source:
            schema_source.write(json.dumps(schema))
            schema_source.flush()

            with open(
                    f'docs/schemas/{basename(schema_path.rstrip(".json"))}.html',
                    mode='w+') as result_file:
                click.secho(f'Writing schema docs to {result_file.name}',
                            color='green')
                generate_from_file_object(schema_file=schema_source,
                                          result_file=result_file,
                                          minify=True,
                                          expand_buttons=True)

    # Generate and save schema index page
    index_md = r"""---
layout: default
---

# Data Models Schema Docs

"""
    for f in os.listdir('docs/schemas/'):
        if f.endswith('.html'):
            index_md += f'- [{f.rstrip(".html")}](./{f})\n'

    with open(f'docs/schemas/index.md', mode='w+') as index_file:
        index_file.write(index_md)