# Path: schema_salad/exceptions.py
# class ValidationException(SchemaSaladException):
#     """Indicates error with document against the provided schema."""
# 
# Path: schema_salad/ref_resolver.py
# def file_uri(path: str, split_frag: bool = False) -> str:
#     if path.startswith("file://"):
#         return path
#     if split_frag:
#         pathsp = path.split("#", 2)
#         if len(pathsp) == 2:
#             frag = "#" + urllib.parse.quote(str(pathsp[1]))
#         else:
#             frag = ""
#         urlpath = urllib.request.pathname2url(str(pathsp[0]))
#     else:
#         urlpath = urllib.request.pathname2url(path)
#         frag = ""
#     if urlpath.startswith("//"):
#         return f"file:{urlpath}{frag}"
#     return f"file://{urlpath}{frag}"
# 
# Path: schema_salad/utils.py
# def yaml_no_ts() -> YAML:
#     """
#     Get a YAML loader that won't parse timestamps into datetime objects.
# 
#     Such datetime objects can't be easily dumped into JSON.
#     """
#     yaml = YAML(typ="rt")
#     yaml.preserve_quotes = True  # type: ignore
#     yaml.Constructor = _RoundTripNoTimeStampConstructor
#     return yaml
# 
# Path: schema_salad/tests/matcher.py
# class JsonDiffMatcher:
#     """Raise AssertionError with a readable JSON diff when not __eq__().
# 
#     Used with assert_called_with() so it's possible for a human to see
#     the differences between expected and actual call arguments that
#     include non-trivial data structures.
#     """
# 
#     def __init__(self, expected: Any):
#         self.expected = expected
# 
#     def __eq__(self, actual: Any) -> bool:
#         expected_json = json_dumps(self.expected, sort_keys=True, indent=2)
#         actual_json = json_dumps(actual, sort_keys=True, indent=2)
#         if expected_json != actual_json:
#             raise AssertionError(
#                 "".join(
#                     difflib.context_diff(
#                         expected_json.splitlines(True),
#                         actual_json.splitlines(True),
#                         fromfile="Expected",
#                         tofile="Actual",
#                     )
#                 )
#             )
#         return True
# 
# Path: schema_salad/tests/util.py
# def get_data(filename):  # type: (Text) -> Optional[Text]
#     filename = os.path.normpath(filename)  # normalizing path depending on OS
#     # or else it will cause problem when joining path
#     filepath = None
#     try:
#         filepath = resource_filename(Requirement.parse("schema-salad"), filename)
#     except ResolutionError:
#         pass
#     if not filepath or not os.path.isfile(filepath):
#         filepath = os.path.join(os.path.dirname(__file__), os.pardir, filename)
#     return filepath


import json
import os
import pytest
import schema_salad.metaschema as cg_metaschema
from typing import Any
from schema_salad.exceptions import ValidationException
from schema_salad.ref_resolver import file_uri
from schema_salad.utils import yaml_no_ts
from .matcher import JsonDiffMatcher
from .util import get_data


def test_load_by_yaml_metaschema(metaschema_pre: Any) -> None:
    path = get_data("metaschema/metaschema.yml")
    assert path
    with open(path) as path_handle:
        yaml = yaml_no_ts()
        yaml_doc = yaml.load(path_handle)
    doc = cg_metaschema.load_document_by_yaml(
        yaml_doc,
        file_uri(path),
        None,
    )
    saved = [d.save(relative_uris=False) for d in doc]
    assert saved == JsonDiffMatcher(metaschema_pre)


def test_load_cwlschema() -> None:
    path = get_data("tests/test_schema/CommonWorkflowLanguage.yml")
    assert path
    doc = cg_metaschema.load_document(
        file_uri(path),
        "",
        cg_metaschema.LoadingOptions(),
    )
    path2 = get_data("tests/cwl-pre.yml")
    assert path2
    with open(path2) as f:
        pre = json.load(f)
    saved = [d.save(relative_uris=False) for d in doc]

# Path: schema_salad/exceptions.py
# class ValidationException(SchemaSaladException):
#     """Indicates error with document against the provided schema."""
# 
# Path: schema_salad/ref_resolver.py
# def file_uri(path: str, split_frag: bool = False) -> str:
#     if path.startswith("file://"):
#         return path
#     if split_frag:
#         pathsp = path.split("#", 2)
#         if len(pathsp) == 2:
#             frag = "#" + urllib.parse.quote(str(pathsp[1]))
#         else:
#             frag = ""
#         urlpath = urllib.request.pathname2url(str(pathsp[0]))
#     else:
#         urlpath = urllib.request.pathname2url(path)
#         frag = ""
#     if urlpath.startswith("//"):
#         return f"file:{urlpath}{frag}"
#     return f"file://{urlpath}{frag}"
# 
# Path: schema_salad/utils.py
# def yaml_no_ts() -> YAML:
#     """
#     Get a YAML loader that won't parse timestamps into datetime objects.
# 
#     Such datetime objects can't be easily dumped into JSON.
#     """
#     yaml = YAML(typ="rt")
#     yaml.preserve_quotes = True  # type: ignore
#     yaml.Constructor = _RoundTripNoTimeStampConstructor
#     return yaml
# 
# Path: schema_salad/tests/matcher.py
# class JsonDiffMatcher:
#     """Raise AssertionError with a readable JSON diff when not __eq__().
# 
#     Used with assert_called_with() so it's possible for a human to see
#     the differences between expected and actual call arguments that
#     include non-trivial data structures.
#     """
# 
#     def __init__(self, expected: Any):
#         self.expected = expected
# 
#     def __eq__(self, actual: Any) -> bool:
#         expected_json = json_dumps(self.expected, sort_keys=True, indent=2)
#         actual_json = json_dumps(actual, sort_keys=True, indent=2)
#         if expected_json != actual_json:
#             raise AssertionError(
#                 "".join(
#                     difflib.context_diff(
#                         expected_json.splitlines(True),
#                         actual_json.splitlines(True),
#                         fromfile="Expected",
#                         tofile="Actual",
#                     )
#                 )
#             )
#         return True
# 
# Path: schema_salad/tests/util.py
# def get_data(filename):  # type: (Text) -> Optional[Text]
#     filename = os.path.normpath(filename)  # normalizing path depending on OS
#     # or else it will cause problem when joining path
#     filepath = None
#     try:
#         filepath = resource_filename(Requirement.parse("schema-salad"), filename)
#     except ResolutionError:
#         pass
#     if not filepath or not os.path.isfile(filepath):
#         filepath = os.path.join(os.path.dirname(__file__), os.pardir, filename)
#     return filepath


# Path: schema_salad/tests/test_cg.py
import json
import os
import pytest
import schema_salad.metaschema as cg_metaschema
from typing import Any
from schema_salad.exceptions import ValidationException
from schema_salad.ref_resolver import file_uri
from schema_salad.utils import yaml_no_ts
from .matcher import JsonDiffMatcher
from .util import get_data



def test_load_by_yaml_metaschema(metaschema_pre: Any) -> None:
    path = get_data("metaschema/metaschema.yml")
    assert path
    with open(path) as path_handle:
        yaml = yaml_no_ts()
        yaml_doc = yaml.load(path_handle)
    doc = cg_metaschema.load_document_by_yaml(
        yaml_doc,
        file_uri(path),
        None,
    )
    saved = [d.save(relative_uris=False) for d in doc]
    assert saved == JsonDiffMatcher(metaschema_pre)


def test_load_cwlschema() -> None:
    path = get_data("tests/test_schema/CommonWorkflowLanguage.yml")
    assert path
    doc = cg_metaschema.load_document(
        file_uri(path),
        "",
        cg_metaschema.LoadingOptions(),
    )
    path2 = get_data("tests/cwl-pre.yml")
    assert path2
    with open(path2) as f:
        pre = json.load(f)
    saved = [d.save(relative_uris=False) for d in doc]

    assert saved == JsonDiffMatcher(pre)