Skip to content

Models - #392

Open
ialarmedalien wants to merge 3 commits into
developfrom
models
Open

Models#392
ialarmedalien wants to merge 3 commits into
developfrom
models

Conversation

@ialarmedalien

Copy link
Copy Markdown
Collaborator

Add validation to JSON Schemas and XSV JSON Schemas.
Closes #386

@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

❌ 9 Tests Failed:

Tests completed Failed Passed Skipped
8546 9 8537 122
View the top 3 failed test(s) by shortest run time
tests/cdm_data_loaders/pipelines/xsv/test_xsv_settings.py::test_convert_xsv_schema_to_pyarrow_pass[dereferences_root_ref_and_preserves_dollar_schema]
Stack Traces | 0.012s run time
raw_schema = {'$schema': 'https://json-schema..../draft/2020-12/schema', '$ref': '#/$defs/RowDef', 'required': ['id', 'label'], '$defs': {'RowDef': {'type': 'object', 'properties': {'id': {'type': 'integer'}, 'label': {'type': ['string', 'null']}}}}}
expected_pa_schema = id: int64 not null
label: string

    @pytest.mark.parametrize(
        ("raw_schema", "expected_pa_schema"),
        [
            pytest.param(
                {
                    "$schema": VALID_SCHEMA_URI,
                    "required": ["unlisted_col", "non_null_int", "nullable_str"],
                    "properties": {
                        "non_null_int": {"type": "integer"},
                        "nullable_str": {"type": ["string", "null"]},
                        "extra_col": {"type": "boolean"},
                    },
                },
                pa.schema(
                    [
                        pa.field("unlisted_col", pa.string(), nullable=True),
                        pa.field("non_null_int", pa.int64(), nullable=False),
                        pa.field("nullable_str", pa.string(), nullable=True),
                        pa.field("extra_col", pa.bool_(), nullable=True),
                    ]
                ),
                id="orders_required_defaults_unlisted_and_keeps_extra_nullable",
            ),
            pytest.param(
                {
                    "$schema": VALID_SCHEMA_URI,
                    "required": [
                        "str_not_null",
                        "list_not_null",
                        "list_with_null",
                        "anyof_not_null",
                        "anyof_with_null",
                        "oneof_not_null",
                        "oneof_with_null",
                        "enum_not_null",
                        "enum_with_null",
                    ],
                    "properties": {
                        "str_not_null": {"type": "string"},
                        "list_not_null": {"type": ["integer"]},
                        "list_with_null": {"type": ["integer", "null"]},
                        "anyof_not_null": {"anyOf": [{"type": "integer"}, {"type": "integer"}]},
                        "anyof_with_null": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
                        "oneof_not_null": {"oneOf": [{"type": "string"}]},
                        "oneof_with_null": {"oneOf": [{"type": "string"}, {"type": "null"}]},
                        "enum_not_null": {"enum": ["a", "b"]},
                        "enum_with_null": {"enum": ["a", "b", None]},
                    },
                },
                pa.schema(
                    [
                        pa.field("str_not_null", pa.string(), nullable=False),
                        pa.field("list_not_null", pa.int64(), nullable=False),
                        pa.field("list_with_null", pa.int64(), nullable=True),
                        pa.field("anyof_not_null", pa.int64(), nullable=False),
                        pa.field("anyof_with_null", pa.int64(), nullable=True),
                        pa.field("oneof_not_null", pa.string(), nullable=False),
                        pa.field("oneof_with_null", pa.string(), nullable=True),
                        pa.field("enum_not_null", pa.string(), nullable=False),
                        pa.field("enum_with_null", pa.string(), nullable=True),
                    ]
                ),
                id="nullability_inference_across_type_anyof_oneof_and_enum",
            ),
            pytest.param(
                {
                    "$schema": "https://json-schema..../draft/2020-12/schema",
                    "$ref": "#/$defs/RowDef",
                    "required": ["id", "label"],
                    "$defs": {
                        "RowDef": {
                            "type": "object",
                            "properties": {
                                "id": {"type": "integer"},
                                "label": {"type": ["string", "null"]},
                            },
                        }
                    },
                },
                pa.schema(
                    [
                        pa.field("id", pa.int64(), nullable=False),
                        pa.field("label", pa.string(), nullable=True),
                    ]
                ),
                id="dereferences_root_ref_and_preserves_dollar_schema",
            ),
        ],
    )
    def test_convert_xsv_schema_to_pyarrow_pass(
        raw_schema: dict[str, Any],
        expected_pa_schema: pa.Schema,
    ) -> None:
        """convert_xsv_schema_to_pyarrow orders columns by required_cols, infers nullability, and dereferences $ref."""
>       validated = ValidatedXsvSchema(jsonschema=raw_schema)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json... ['string', 'null']}}}}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../pipelines/xsv/test_xsv_settings.py:275: ValidationError
tests/cdm_data_loaders/pipelines/xsv/test_xsv_settings.py::test_convert_xsv_schema_to_pyarrow_pass[orders_required_defaults_unlisted_and_keeps_extra_nullable]
Stack Traces | 0.012s run time
raw_schema = {'$schema': 'https://json-schema..../draft/2020-12/schema', 'required': ['unlisted_col', 'non_null_int', 'nullable_str... {'non_null_int': {'type': 'integer'}, 'nullable_str': {'type': ['string', 'null']}, 'extra_col': {'type': 'boolean'}}}
expected_pa_schema = unlisted_col: string
non_null_int: int64 not null
nullable_str: string
extra_col: bool

    @pytest.mark.parametrize(
        ("raw_schema", "expected_pa_schema"),
        [
            pytest.param(
                {
                    "$schema": VALID_SCHEMA_URI,
                    "required": ["unlisted_col", "non_null_int", "nullable_str"],
                    "properties": {
                        "non_null_int": {"type": "integer"},
                        "nullable_str": {"type": ["string", "null"]},
                        "extra_col": {"type": "boolean"},
                    },
                },
                pa.schema(
                    [
                        pa.field("unlisted_col", pa.string(), nullable=True),
                        pa.field("non_null_int", pa.int64(), nullable=False),
                        pa.field("nullable_str", pa.string(), nullable=True),
                        pa.field("extra_col", pa.bool_(), nullable=True),
                    ]
                ),
                id="orders_required_defaults_unlisted_and_keeps_extra_nullable",
            ),
            pytest.param(
                {
                    "$schema": VALID_SCHEMA_URI,
                    "required": [
                        "str_not_null",
                        "list_not_null",
                        "list_with_null",
                        "anyof_not_null",
                        "anyof_with_null",
                        "oneof_not_null",
                        "oneof_with_null",
                        "enum_not_null",
                        "enum_with_null",
                    ],
                    "properties": {
                        "str_not_null": {"type": "string"},
                        "list_not_null": {"type": ["integer"]},
                        "list_with_null": {"type": ["integer", "null"]},
                        "anyof_not_null": {"anyOf": [{"type": "integer"}, {"type": "integer"}]},
                        "anyof_with_null": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
                        "oneof_not_null": {"oneOf": [{"type": "string"}]},
                        "oneof_with_null": {"oneOf": [{"type": "string"}, {"type": "null"}]},
                        "enum_not_null": {"enum": ["a", "b"]},
                        "enum_with_null": {"enum": ["a", "b", None]},
                    },
                },
                pa.schema(
                    [
                        pa.field("str_not_null", pa.string(), nullable=False),
                        pa.field("list_not_null", pa.int64(), nullable=False),
                        pa.field("list_with_null", pa.int64(), nullable=True),
                        pa.field("anyof_not_null", pa.int64(), nullable=False),
                        pa.field("anyof_with_null", pa.int64(), nullable=True),
                        pa.field("oneof_not_null", pa.string(), nullable=False),
                        pa.field("oneof_with_null", pa.string(), nullable=True),
                        pa.field("enum_not_null", pa.string(), nullable=False),
                        pa.field("enum_with_null", pa.string(), nullable=True),
                    ]
                ),
                id="nullability_inference_across_type_anyof_oneof_and_enum",
            ),
            pytest.param(
                {
                    "$schema": "https://json-schema..../draft/2020-12/schema",
                    "$ref": "#/$defs/RowDef",
                    "required": ["id", "label"],
                    "$defs": {
                        "RowDef": {
                            "type": "object",
                            "properties": {
                                "id": {"type": "integer"},
                                "label": {"type": ["string", "null"]},
                            },
                        }
                    },
                },
                pa.schema(
                    [
                        pa.field("id", pa.int64(), nullable=False),
                        pa.field("label", pa.string(), nullable=True),
                    ]
                ),
                id="dereferences_root_ref_and_preserves_dollar_schema",
            ),
        ],
    )
    def test_convert_xsv_schema_to_pyarrow_pass(
        raw_schema: dict[str, Any],
        expected_pa_schema: pa.Schema,
    ) -> None:
        """convert_xsv_schema_to_pyarrow orders columns by required_cols, infers nullability, and dereferences $ref."""
>       validated = ValidatedXsvSchema(jsonschema=raw_schema)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, XSV schemas must have the same set of properties listed under `required` and in `properties` [type=value_error, input_value={'$schema': 'https://json...': {'type': 'boolean'}}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../pipelines/xsv/test_xsv_settings.py:275: ValidationError
tests/cdm_data_loaders/readers/xsv/test_duckdb_reader.py::test_resolve_xsv_parsing_config_pass_has_header_true_inverts_to_missing_header_false
Stack Traces | 0.014s run time
def test_resolve_xsv_parsing_config_pass_has_header_true_inverts_to_missing_header_false() -> None:
        """x-has-header: true resolves to missing_header: false."""
>       schema = _schema(x_xsv_config={"x-has-header": True})
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.../readers/xsv/test_duckdb_reader.py:105: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

properties = None, x_xsv_config = {'x-has-header': True}

    def _schema(properties: dict[str, Any] | None = None, x_xsv_config: dict[str, Any] | None = None) -> ValidatedXsvSchema:
        """Build a minimal ValidatedXsvSchema, optionally with properties and/or an x-xsv-config block."""
        jsonschema: dict[str, Any] = {"$schema": VALID_SCHEMA_URI, "required": COLUMNS}
        if properties is not None:
            jsonschema["properties"] = properties
        if x_xsv_config is not None:
            jsonschema["x-xsv-config"] = x_xsv_config
>       return ValidatedXsvSchema(jsonschema=jsonschema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json... {'x-has-header': True}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../readers/xsv/test_duckdb_reader.py:29: ValidationError
tests/cdm_data_loaders/readers/xsv/test_duckdb_reader.py::test_resolve_xsv_parsing_config_pass_maps_all_keys
Stack Traces | 0.014s run time
def test_resolve_xsv_parsing_config_pass_maps_all_keys() -> None:
        """Every supported x-xsv-config key maps to its CleanerValidatorArgs kwarg name."""
>       schema = _schema(
            x_xsv_config={
                "x-delimiter": ",",
                "x-comment-char": ";",
                "x-quote": "'",
                "x-escape": "\\",
                "x-null-regex": "^NA$",
                "x-null-cols": ["float"],
                "x-has-header": False,
            }
        )

.../readers/xsv/test_duckdb_reader.py:80: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

properties = None
x_xsv_config = {'x-delimiter': ',', 'x-comment-char': ';', 'x-quote': "'", 'x-escape': '\\', ...}

    def _schema(properties: dict[str, Any] | None = None, x_xsv_config: dict[str, Any] | None = None) -> ValidatedXsvSchema:
        """Build a minimal ValidatedXsvSchema, optionally with properties and/or an x-xsv-config block."""
        jsonschema: dict[str, Any] = {"$schema": VALID_SCHEMA_URI, "required": COLUMNS}
        if properties is not None:
            jsonschema["properties"] = properties
        if x_xsv_config is not None:
            jsonschema["x-xsv-config"] = x_xsv_config
>       return ValidatedXsvSchema(jsonschema=jsonschema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json... 'x-has-header': False}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../readers/xsv/test_duckdb_reader.py:29: ValidationError
tests/cdm_data_loaders/readers/xsv/test_duckdb_reader.py::test_resolve_xsv_parsing_config_pass_no_config_block_returns_empty_dict
Stack Traces | 0.014s run time
def test_resolve_xsv_parsing_config_pass_no_config_block_returns_empty_dict() -> None:
        """A schema without an x-xsv-config block resolves to an empty dict."""
>       assert resolve_xsv_parsing_config(_schema()) == {}
                                          ^^^^^^^^^

.../readers/xsv/test_duckdb_reader.py:75: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

properties = None, x_xsv_config = None

    def _schema(properties: dict[str, Any] | None = None, x_xsv_config: dict[str, Any] | None = None) -> ValidatedXsvSchema:
        """Build a minimal ValidatedXsvSchema, optionally with properties and/or an x-xsv-config block."""
        jsonschema: dict[str, Any] = {"$schema": VALID_SCHEMA_URI, "required": COLUMNS}
        if properties is not None:
            jsonschema["properties"] = properties
        if x_xsv_config is not None:
            jsonschema["x-xsv-config"] = x_xsv_config
>       return ValidatedXsvSchema(jsonschema=jsonschema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json...', 'boolean', 'string']}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../readers/xsv/test_duckdb_reader.py:29: ValidationError
tests/cdm_data_loaders/readers/xsv/test_duckdb_reader.py::test_resolve_xsv_parsing_config_pass_partial_config_only_sets_present_keys
Stack Traces | 0.014s run time
def test_resolve_xsv_parsing_config_pass_partial_config_only_sets_present_keys() -> None:
        """Only keys present in x-xsv-config appear in the resolved config."""
>       schema = _schema(x_xsv_config={"x-delimiter": "\t"})
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.../readers/xsv/test_duckdb_reader.py:111: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

properties = None, x_xsv_config = {'x-delimiter': '\t'}

    def _schema(properties: dict[str, Any] | None = None, x_xsv_config: dict[str, Any] | None = None) -> ValidatedXsvSchema:
        """Build a minimal ValidatedXsvSchema, optionally with properties and/or an x-xsv-config block."""
        jsonschema: dict[str, Any] = {"$schema": VALID_SCHEMA_URI, "required": COLUMNS}
        if properties is not None:
            jsonschema["properties"] = properties
        if x_xsv_config is not None:
            jsonschema["x-xsv-config"] = x_xsv_config
>       return ValidatedXsvSchema(jsonschema=jsonschema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json...: {'x-delimiter': '\t'}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../readers/xsv/test_duckdb_reader.py:29: ValidationError
tests/cdm_data_loaders/readers/xsv/test_duckdb_reader.py::test_resolve_xsv_parsing_config_pass_quoting_policy_not_propagated
Stack Traces | 0.014s run time
def test_resolve_xsv_parsing_config_pass_quoting_policy_not_propagated() -> None:
        """x-quoting-policy configures XSV output, not qsv cleaning, and is never returned."""
>       schema = _schema(x_xsv_config={"x-delimiter": ",", "x-quoting-policy": "necessary"})
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.../readers/xsv/test_duckdb_reader.py:117: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

properties = None
x_xsv_config = {'x-delimiter': ',', 'x-quoting-policy': 'necessary'}

    def _schema(properties: dict[str, Any] | None = None, x_xsv_config: dict[str, Any] | None = None) -> ValidatedXsvSchema:
        """Build a minimal ValidatedXsvSchema, optionally with properties and/or an x-xsv-config block."""
        jsonschema: dict[str, Any] = {"$schema": VALID_SCHEMA_URI, "required": COLUMNS}
        if properties is not None:
            jsonschema["properties"] = properties
        if x_xsv_config is not None:
            jsonschema["x-xsv-config"] = x_xsv_config
>       return ValidatedXsvSchema(jsonschema=jsonschema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json...g-policy': 'necessary'}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../readers/xsv/test_duckdb_reader.py:29: ValidationError
tests/cdm_data_loaders/pipelines/xsv/test_xsv_spec.py::test_xsv_schema_errors_fail_error_manifest[E5-non_struct_root]
Stack Traces | 0.015s run time
self = XsvIngestSettings(preprocessors_module=None, transforms_module=None, output_schemas_module=None, log_config_file='/tmp... file_listing_path=PosixPath('.../test_xsv_schema_errors_fail_er5/output/file_listing.txt'))
default_pyarrow_schema = None

    def _resolve_settings_schema_map(self, default_pyarrow_schema: pa.Schema | None = None) -> None:
        """Load and validate the schema file, first-pass schema, parsing config, PyArrow schema, and `_schema_map`."""
        try:
>           self._validated_schema = validate_xsv_jsonschema(self.schema_file)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.../pipelines/xsv/settings.py:94: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

schema_path = PosixPath('.../spec/errors/non_struct_root.json')

    def validate_xsv_jsonschema(schema_path: Path) -> ValidatedXsvSchema:
        """Load and validate an XSV JSON Schema file from ``schema_path``.
    
        :param schema_path: path to the JSON Schema file
        :type schema_path: Path
        :return: validated XSV JSON Schema model
        :rtype: ValidatedXsvSchema
        :raises jsonschema.exceptions.SchemaError: if the schema fails metaschema validation
        """
        schema = json.loads(schema_path.read_bytes())
>       return ValidatedXsvSchema(jsonschema=schema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json...ms': {'type': 'string'}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../validation/jsonschema/models.py:118: ValidationError

The above exception was the direct cause of the following exception:

err = ErrorCase(file=PosixPath('.../spec/errors/non_stru...evel|object|struct', description='Root declares `"type": "array"` despite having `required`.', xml_tag=None, params={})
tmp_path = PosixPath('.../pytest-of-runner/pytest-0/test_xsv_schema_errors_fail_er5')
dlt_destination_config = 'local_fs'

    @pytest.mark.parametrize("err", ERROR_PARAMS)
    def test_xsv_schema_errors_fail_error_manifest(
        err: ErrorCase,
        tmp_path: Path,
        dlt_destination_config: str,
    ) -> None:
        """Each error fixture raises the ``XsvSchemaError`` subclass for its code when initializing settings."""
        input_dir = tmp_path / "input"
        input_dir.mkdir(parents=True, exist_ok=True)
        with pytest.raises(ERRORS_BY_CODE[err.code], match=err.match):
>           make_cts_settings(
                XsvIngestSettings,
                tmp_path,
                dataset_name="xsv_error_dataset",
                file_glob="*.csv",
                input_dir=str(input_dir),
                schema_file=str(err.file),
                table_name="my_table",
                use_destination=dlt_destination_config,
            )

.../pipelines/xsv/test_xsv_spec.py:225: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests/helpers/cli_assertions.py:153: in make_cts_settings
    return settings_cls(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../site-packages/pydantic_settings/main.py:292: in __init__
    super().__init__(**__pydantic_self__.__class__._settings_build_values(sources, init_kwargs))
.../core/transforms/settings_mixin.py:165: in _validate_transforms_module
    self._resolve_settings_schema_map()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = XsvIngestSettings(preprocessors_module=None, transforms_module=None, output_schemas_module=None, log_config_file='/tmp... file_listing_path=PosixPath('.../test_xsv_schema_errors_fail_er5/output/file_listing.txt'))
default_pyarrow_schema = None

    def _resolve_settings_schema_map(self, default_pyarrow_schema: pa.Schema | None = None) -> None:
        """Load and validate the schema file, first-pass schema, parsing config, PyArrow schema, and `_schema_map`."""
        try:
            self._validated_schema = validate_xsv_jsonschema(self.schema_file)
            self._first_pass_schema = generate_first_pass_schema(self._validated_schema)
            self._parsing_config = resolve_xsv_parsing_config(self._validated_schema)
            if (
                self.get_table_transform(self.table_name) is None
                and self._unreconciled_output_schemas is not None
                and self.table_name in self._unreconciled_output_schemas.registry
            ):
                dereference_schema(self._validated_schema.jsonschema)
                self._pyarrow_schema = self._unreconciled_output_schemas.registry[self.table_name]
            else:
                self._pyarrow_schema = default_pyarrow_schema or convert_xsv_schema_to_pyarrow(self.validated_schema)
        except Exception as e:
            err_msg = f"Could not load JSON Schema for XSV data: {e!s}"
            logger.exception(err_msg)
>           raise _classify_xsv_schema_error(e, err_msg) from e
E           cdm_data_loaders.pipelines.xsv.exceptions.InvalidXsvSchemaDefinitionError: Could not load JSON Schema for XSV data: 1 validation error for ValidatedXsvSchema
E           jsonschema
E             Value error, Could not find any properties in schema [type=value_error, input_value={'$schema': 'https://json...ms': {'type': 'string'}}, input_type=dict]
E               For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../pipelines/xsv/settings.py:109: InvalidXsvSchemaDefinitionError
tests/cdm_data_loaders/pipelines/presets/test_uniprot_idmapping.py::test_uniprot_idmapping_settings_defaults_and_schema_override[custom-schema-file]
Stack Traces | 0.025s run time
self = UniProtIdMappingSettings(preprocessors_module=None, log_config_file='.../pytest-of-runner/pytest-0/test_uniprot_idmap... file_listing_path=PosixPath('.../test_uniprot_idmapping_setting0/output/file_listing.txt'))
default_pyarrow_schema = None

    def _resolve_settings_schema_map(self, default_pyarrow_schema: pa.Schema | None = None) -> None:
        """Load and validate the schema file, first-pass schema, parsing config, PyArrow schema, and `_schema_map`."""
        try:
>           self._validated_schema = validate_xsv_jsonschema(self.schema_file)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.../pipelines/xsv/settings.py:94: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

schema_path = PosixPath('.../pytest-0/test_uniprot_idmapping_setting0/custom_idmapping.schema.json')

    def validate_xsv_jsonschema(schema_path: Path) -> ValidatedXsvSchema:
        """Load and validate an XSV JSON Schema file from ``schema_path``.
    
        :param schema_path: path to the JSON Schema file
        :type schema_path: Path
        :return: validated XSV JSON Schema model
        :rtype: ValidatedXsvSchema
        :raises jsonschema.exceptions.SchemaError: if the schema fails metaschema validation
        """
        schema = json.loads(schema_path.read_bytes())
>       return ValidatedXsvSchema(jsonschema=schema)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for ValidatedXsvSchema
E       jsonschema
E         Value error, XSV schemas must have the same set of properties listed under `required` and in `properties` [type=value_error, input_value={'$schema': 'https://kbas...e, 'x-delimiter': '\t'}}, input_type=dict]
E           For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../validation/jsonschema/models.py:118: ValidationError

The above exception was the direct cause of the following exception:

tmp_path = PosixPath('.../pytest-of-runner/pytest-0/test_uniprot_idmapping_setting0')
scenario = 'custom_schema_file'

    @pytest.mark.parametrize(
        "scenario",
        [
            pytest.param("preset_defaults", id="preset-defaults"),
            pytest.param("custom_schema_file", id="custom-schema-file"),
            pytest.param("jsonl_format", id="jsonl-format"),
        ],
    )
    def test_uniprot_idmapping_settings_defaults_and_schema_override(
        tmp_path: Path,
        scenario: str,
    ) -> None:
        """``UniProtIdMappingSettings`` sets preset defaults, binds Arrow transforms, and derives custom schemas."""
        input_dir = tmp_path / "in"
        input_dir.mkdir()
    
        overrides: dict[str, object] = {}
        custom_schema_file = tmp_path / "custom_idmapping.schema.json"
        if scenario == "custom_schema_file":
            custom_schema_doc = json.loads(IDMAPPING_SCHEMA_FILE.read_text(encoding="utf-8"))
            custom_schema_doc["properties"]["extra_col"] = {"type": ["integer", "null"], "description": "Optional rank"}
            custom_schema_file.write_text(json.dumps(custom_schema_doc), encoding="utf-8")
            overrides["schema_file"] = str(custom_schema_file)
        elif scenario == "jsonl_format":
            overrides["loader_file_format"] = "jsonl"
    
>       settings = make_cts_settings(
            UniProtIdMappingSettings,
            tmp_path,
            input_dir=str(input_dir),
            use_destination=LOCAL_FS,
            **overrides,
        )

.../pipelines/presets/test_uniprot_idmapping.py:85: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests/helpers/cli_assertions.py:153: in make_cts_settings
    return settings_cls(**kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^
.venv/lib/python3.13.../site-packages/pydantic_settings/main.py:292: in __init__
    super().__init__(**__pydantic_self__.__class__._settings_build_values(sources, init_kwargs))
.../core/transforms/settings_mixin.py:165: in _validate_transforms_module
    self._resolve_settings_schema_map()
.../pipelines/presets/uniprot_idmapping.py:83: in _resolve_settings_schema_map
    super()._resolve_settings_schema_map(default_pyarrow_schema=default_pyarrow_schema)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = UniProtIdMappingSettings(preprocessors_module=None, log_config_file='.../pytest-of-runner/pytest-0/test_uniprot_idmap... file_listing_path=PosixPath('.../test_uniprot_idmapping_setting0/output/file_listing.txt'))
default_pyarrow_schema = None

    def _resolve_settings_schema_map(self, default_pyarrow_schema: pa.Schema | None = None) -> None:
        """Load and validate the schema file, first-pass schema, parsing config, PyArrow schema, and `_schema_map`."""
        try:
            self._validated_schema = validate_xsv_jsonschema(self.schema_file)
            self._first_pass_schema = generate_first_pass_schema(self._validated_schema)
            self._parsing_config = resolve_xsv_parsing_config(self._validated_schema)
            if (
                self.get_table_transform(self.table_name) is None
                and self._unreconciled_output_schemas is not None
                and self.table_name in self._unreconciled_output_schemas.registry
            ):
                dereference_schema(self._validated_schema.jsonschema)
                self._pyarrow_schema = self._unreconciled_output_schemas.registry[self.table_name]
            else:
                self._pyarrow_schema = default_pyarrow_schema or convert_xsv_schema_to_pyarrow(self.validated_schema)
        except Exception as e:
            err_msg = f"Could not load JSON Schema for XSV data: {e!s}"
            logger.exception(err_msg)
>           raise _classify_xsv_schema_error(e, err_msg) from e
E           cdm_data_loaders.pipelines.xsv.exceptions.InvalidXsvSchemaDefinitionError: Could not load JSON Schema for XSV data: 1 validation error for ValidatedXsvSchema
E           jsonschema
E             Value error, XSV schemas must have the same set of properties listed under `required` and in `properties` [type=value_error, input_value={'$schema': 'https://kbas...e, 'x-delimiter': '\t'}}, input_type=dict]
E               For further information visit https://errors.pydantic.dev/2.14/v/value_error

.../pipelines/xsv/settings.py:109: InvalidXsvSchemaDefinitionError

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant