diff --git a/CHANGELOG.md b/CHANGELOG.md index b86bd3fc6..7d1396b77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- `datacontract test`: test Excel workbooks (`format: xlsx`) (new `xlsx` extra) (#1717) - `datacontract edit --language` shows the editor in English, German, Swedish or French ### Changed diff --git a/README.md b/README.md index 0047fe162..b5b74965e 100644 --- a/README.md +++ b/README.md @@ -284,6 +284,7 @@ A list of available extras: | DuckDB (local file, CSV import and API response testing) | `pip install datacontract-cli[duckdb]` | | Exasol | `pip install datacontract-cli[exasol]` | | Excel | `pip install datacontract-cli[excel]` | +| Excel workbooks (testing) | `pip install datacontract-cli[xlsx]` | | GCS | `pip install datacontract-cli[gcs]` | | SAP HANA / Datasphere | `pip install datacontract-cli[hana]` (not part of `all`: `hdbcli` is proprietary) | | Apache Iceberg (schema import and export, REST catalog testing) | `pip install datacontract-cli[iceberg]` | diff --git a/datacontract/engines/checks/create_checks.py b/datacontract/engines/checks/create_checks.py index 7f2da764e..927cbf601 100644 --- a/datacontract/engines/checks/create_checks.py +++ b/datacontract/engines/checks/create_checks.py @@ -32,11 +32,13 @@ Instance, instantiate, placeholder_pattern, + sql_literal, ) from datacontract.engines.checks.dimensions import default_dimension from datacontract.engines.checks.sql_guard import dialect_for_server_type, refusal_reason, sqlglot_dialect_by_name from datacontract.engines.checks.type_normalize import normalize_type_name from datacontract.engines.ibis.native_type import supports_native_type_introspection +from datacontract.export.duckdb_type_converter import convert_to_duckdb_csv_type from datacontract.model.enum_values import get_enum_values from datacontract.model.map_type import get_map_key, get_map_value from datacontract.model.server import get_server_type @@ -68,7 +70,7 @@ def is_check_types(server: Optional[Server]) -> bool: """Type checks only make sense where the data source carries real types.""" if server is None: return True - return server.format not in ("json", "csv", "avro", "xml") + return server.format not in ("json", "csv", "avro", "xml", "xlsx") def to_schema_name(schema_object: SchemaObject, server_type: Optional[str]) -> str: @@ -271,7 +273,9 @@ def _to_schema_checks( properties = schema_object.properties or [] check_types = is_check_types(server) uses_raw_view = ( - server is not None and server_type in _FILE_SERVER_TYPES and server.format in ("csv", "parquet", "json", "xml") + server is not None + and server_type in _FILE_SERVER_TYPES + and server.format in ("csv", "parquet", "json", "xml", "xlsx") ) # A primary key is both not-null and unique. A composite key is unique as a @@ -288,6 +292,7 @@ def _to_schema_checks( # of nested elements with children. The required top-level properties are still checked for presence. xml = server is not None and server.format == "xml" documents = server is not None and server.format in ("json", "xml") + xlsx = server is not None and server.format == "xlsx" if xml: # A record element that matches nothing would pass every other check checks.append( @@ -322,6 +327,23 @@ def _to_schema_checks( ) ) + # A cell of the wrong type reads as NULL, so the checks of its column would miss it + if xlsx and not nested and convert_to_duckdb_csv_type(prop) != "VARCHAR": + type_errors = exp.to_identifier(f"{model}__type_errors__", quoted=True).sql(dialect="duckdb") + checks.append( + CheckSpec( + key=f"{model}__{field}__field_type", + category="schema", + type="field_type", + name=f"Check that field {field} has type {prop.logicalType or prop.physicalType}", + model=model, + field=field, + metric=MetricType.CUSTOM_SQL, + query=f"SELECT count(*) FROM {type_errors} WHERE field = {sql_literal(field, 'duckdb')}", + threshold=Threshold(Op.EQ, 0), + ) + ) + prop_type = _property_type(prop) implied_type = _implied_type(prop) own_type = prop diff --git a/datacontract/engines/ibis/connections/connect.py b/datacontract/engines/ibis/connections/connect.py index 1019fd803..a4350e161 100644 --- a/datacontract/engines/ibis/connections/connect.py +++ b/datacontract/engines/ibis/connections/connect.py @@ -32,7 +32,7 @@ logger = logging.getLogger(__name__) _FILE_SERVER_TYPES = {"s3", "gcs", "azure", "local"} -_SUPPORTED_FILE_FORMATS = {"json", "parquet", "csv", "delta", "xml"} +_SUPPORTED_FILE_FORMATS = {"json", "parquet", "csv", "delta", "xml", "xlsx"} def _import_ibis(): diff --git a/datacontract/engines/ibis/connections/duckdb_connection.py b/datacontract/engines/ibis/connections/duckdb_connection.py index c1dbde5b1..6d9308eb7 100644 --- a/datacontract/engines/ibis/connections/duckdb_connection.py +++ b/datacontract/engines/ibis/connections/duckdb_connection.py @@ -10,6 +10,7 @@ from datacontract.engines.ibis.connections.aws_credentials import resolve_aws_credentials from datacontract.export.duckdb_type_converter import convert_to_duckdb_csv_type, convert_to_duckdb_json_type from datacontract.export.sql_type_converter import convert_to_duckdb +from datacontract.model.exceptions import DataContractException from datacontract.model.run import Run if TYPE_CHECKING: @@ -68,6 +69,9 @@ def get_duckdb_connection( con.load_extension("webbed") except Exception as e: raise RuntimeError("Failed to install the 'webbed' DuckDB community extension to read XML files.") from e + if server.format == "xlsx": + check_xlsx_locations(data_contract, path) + _load_extension(con, "excel", "xlsx") model_paths = _model_paths(data_contract, path, schema_name) if untrusted_contract and own_connection: @@ -122,6 +126,8 @@ def get_duckdb_connection( con.sql(f"""CREATE VIEW "{model_name}" AS SELECT * FROM delta_scan('{model_path}');""") elif server.format == "xml": create_xml_views(con, schema_obj, model_path) + elif server.format == "xlsx": + create_xlsx_views(con, schema_obj, model_path) table_info = con.sql(f"PRAGMA table_info({_quote(model_name)});").fetchall() if table_info: run.log_info(f"DuckDB Table Info: {table_info}") @@ -399,6 +405,118 @@ def _xml_name(prop: SchemaProperty) -> str: return prop.physicalName or prop.name +# Day 0 of Excel's 1900 date system; not 1899-12-31, because Excel counts a 29 February 1900 that never was +_EXCEL_EPOCH = "1899-12-30" +_TEMPORAL_TYPES = ("DATE", "TIMESTAMP", "TIME") +_MILLISECONDS_PER_DAY = 86_400_000 + + +def check_xlsx_locations(data_contract: OpenDataContractStandard, path: str) -> None: + """Refuse locations read_xlsx would read silently wrong. + + read_xlsx reads the first file a glob matches and nothing else, and a model without a physicalName + reads the first sheet, so in a workbook shared by several models that sheet would be tested for each. + """ + if _is_glob(path): + raise DataContractException( + type="xlsx-connection", + name="glob_path", + reason=f"The xlsx path '{path}' is a glob, but Excel workbooks are read one file at a time.", + ) + by_workbook: dict[str, list[SchemaObject]] = {} + for schema_obj in data_contract.schema_ or []: + by_workbook.setdefault(_model_path(path, schema_obj.name), []).append(schema_obj) + for workbook, schema_objs in by_workbook.items(): + unnamed = [s.name for s in schema_objs if not s.physicalName] + if len(schema_objs) > 1 and unnamed: + raise DataContractException( + type="xlsx-connection", + name="sheet_not_named", + reason=( + f"The model(s) {', '.join(unnamed)} share the workbook '{workbook}' with other models, " + "so each needs the name of its sheet as physicalName." + ), + ) + + +def create_xlsx_views(con, schema_obj: SchemaObject, model_path: str): + """Views over one sheet: the model with the contract's types, its raw text, and its cells of the wrong type. + + The sheet is read twice, lined up row by row: typed, for the dates that only the cell format tells + apart from numbers, and as text, for the values that the type read_xlsx infers from the first row + turns into NULL. The checks address a schema by its physical name, quality SQL often by its name, + so both name the model view. + """ + sheet = schema_obj.physicalName + view = sheet or schema_obj.name + # Without stop_at_empty=false, read_xlsx stops at the first empty row and the rows below go unchecked + options = f"'{_sql_literal(model_path)}', header=true, stop_at_empty=false" + if sheet: + options += f", sheet='{_sql_literal(sheet)}'" + typed = f"read_xlsx({options}, ignore_errors=true)" + text = f"read_xlsx({options}, all_varchar=true)" + cells = f"(SELECT * FROM {typed}) AS t POSITIONAL JOIN (SELECT * FROM {text}) AS r" + + # Raw view without the contract's columns to check for absent columns (check_property_is_present) + con.sql(f"CREATE VIEW {_quote(view + '__raw__')} AS SELECT * FROM {text};") + + # Like DuckDB's own identifiers, a header answers to its name in any case + headers = {row[0].lower(): row for row in con.sql(f"DESCRIBE SELECT * FROM {typed}").fetchall()} + # A row that is empty in every column is a spacer, not a record + not_empty = f"coalesce({', '.join(f'r.{_quote(row[0])}' for row in headers.values())}) IS NOT NULL" + columns, errors = [], [] + for name, sql_type in (to_csv_types(schema_obj) or {}).items(): + sql_type = sql_type or "VARCHAR" + if name.lower() not in headers: + columns.append(f"NULL::{sql_type} AS {_quote(name)}") + continue + header, inferred_type = headers[name.lower()][:2] + value = _cell_value(_quote(header), sql_type, inferred_type) + columns.append(f"{value} AS {_quote(name)}") + if sql_type != "VARCHAR": + errors.append( + f"SELECT '{_sql_literal(name)}' AS field, r.{_quote(header)} AS value FROM {cells} " + f"WHERE r.{_quote(header)} IS NOT NULL AND {value} IS NULL" + ) + if columns: + con.sql(f"CREATE VIEW {_quote(view)} AS SELECT {', '.join(columns)} FROM {cells} WHERE {not_empty};") + else: + con.sql(f"CREATE VIEW {_quote(view)} AS SELECT t.* FROM {cells} WHERE {not_empty};") + if not errors: + errors.append("SELECT NULL::VARCHAR AS field, NULL::VARCHAR AS value WHERE false") + con.sql(f"CREATE VIEW {_quote(view + '__type_errors__')} AS {' UNION ALL '.join(errors)};") + # DuckDB identifiers are case-insensitive, so sheet Orders already answers to orders + if schema_obj.name.lower() != view.lower(): + con.sql(f"CREATE VIEW {_quote(schema_obj.name)} AS SELECT * FROM {_quote(view)};") + + +def _cell_value(column: str, sql_type: str, inferred_type: str) -> str: + """The value of a cell as `sql_type`, NULL if it has none of that type. + + A date read as a number is the Excel serial number of its days, with the time of day as fraction. + """ + typed, text = f"t.{column}", f"r.{column}" + read_as_temporal = inferred_type in _TEMPORAL_TYPES + if sql_type == "VARCHAR": + return f"COALESCE(CAST({typed} AS VARCHAR), {text})" if read_as_temporal else text + if sql_type == "BIGINT": + # TRY_CAST rounds '1.5' to 2, which would hide a fraction in an integer column + number = f"TRY_CAST({text} AS DOUBLE)" + return f"CASE WHEN {number} = floor({number}) THEN TRY_CAST({number} AS BIGINT) END" + if sql_type not in _TEMPORAL_TYPES: + return f"TRY_CAST({text} AS {sql_type})" + serial = f"TRY_CAST({text} AS DOUBLE)" + since_epoch = f"to_milliseconds(CAST(round({serial} * {_MILLISECONDS_PER_DAY}) AS BIGINT))" + from_serial = { + "DATE": f"CAST(DATE '{_EXCEL_EPOCH}' + CAST(floor({serial}) AS INTEGER) AS DATE)", + "TIMESTAMP": f"TIMESTAMP '{_EXCEL_EPOCH}' + {since_epoch}", + "TIME": f"CAST(TIMESTAMP '{_EXCEL_EPOCH}' + {since_epoch} AS TIME)", + }[sql_type] + candidates = [f"TRY_CAST({typed} AS {sql_type})"] if read_as_temporal else [] + candidates += [f"TRY_CAST({text} AS {sql_type})", from_serial] + return f"COALESCE({', '.join(candidates)})" + + def _quote(name: str) -> str: return '"' + name.replace('"', '""') + '"' diff --git a/datacontract/export/sodacl_check_builder.py b/datacontract/export/sodacl_check_builder.py index 43df14cd0..5396e03ba 100644 --- a/datacontract/export/sodacl_check_builder.py +++ b/datacontract/export/sodacl_check_builder.py @@ -318,7 +318,7 @@ def check_property_is_present( uses_raw_view = ( server is not None and server.type in ["local", "s3", "gcs", "azure"] - and server.format in ["csv", "parquet", "json", "xml"] + and server.format in ["csv", "parquet", "json", "xml", "xlsx"] ) target = f"{model_name}__raw__" if uses_raw_view else model_name sodacl_check_dict = { diff --git a/docs/docs/installation.md b/docs/docs/installation.md index a97a38ffa..ff634418d 100644 --- a/docs/docs/installation.md +++ b/docs/docs/installation.md @@ -134,7 +134,8 @@ Available extras: | DBML | `pip install datacontract-cli[dbml]` | | DuckDB (local file, CSV import and API response testing) | `pip install datacontract-cli[duckdb]` | | Exasol | `pip install datacontract-cli[exasol]` | -| Excel | `pip install datacontract-cli[excel]` | +| Excel (import / export) | `pip install datacontract-cli[excel]` | +| Excel workbooks (testing) | `pip install datacontract-cli[xlsx]` | | GCS | `pip install datacontract-cli[gcs]` | | Apache Hive | `pip install datacontract-cli[hive]` | | SAP HANA / Datasphere | `pip install datacontract-cli[hana]` (not part of `all`: `hdbcli` is proprietary) | diff --git a/docs/docs/reference/local.md b/docs/docs/reference/local.md index 77a63b8bd..e828b9309 100644 --- a/docs/docs/reference/local.md +++ b/docs/docs/reference/local.md @@ -16,7 +16,7 @@ servers: - server: local type: local path: ./*.parquet # glob patterns and a {model} placeholder are supported - format: parquet # parquet, json, csv, xml, or delta + format: parquet # parquet, json, csv, xml, xlsx, or delta ``` ## Data types @@ -47,6 +47,7 @@ Type handling depends on the `format` in the `servers` block: | `csv` | The file is read **as the contract's types** — no type checks are generated; a value that can't be coerced surfaces as a read error. | | `json` | Same as CSV, plus every record is validated against a JSON Schema derived from the contract's `logicalType`s (with `format` options like `date-time`, `uuid`). | | `xml` | Like CSV: the documents are read **as the contract's types**, with nested elements as structs and repeated elements as lists. | +| `xlsx` | Each cell is read as the contract's type of its column, including Excel dates stored as numbers. A cell that has a value of another type fails the type check of its column. | | `parquet` | The file is read **as the contract's types**, like CSV, so checking its types is not supported yet, and a value that can't be cast surfaces as a read error. | | `delta` | Column types come from the Delta table; the contract's `logicalType` is checked by category. | diff --git a/docs/docs/testing/local.md b/docs/docs/testing/local.md index f7acbe51f..17c0c7b09 100644 --- a/docs/docs/testing/local.md +++ b/docs/docs/testing/local.md @@ -1,12 +1,12 @@ --- sidebar_position: 17 title: "Local files" -description: "Test local files in Parquet, JSON, CSV, XML, or Delta format — the fastest way to try the CLI, no credentials needed." +description: "Test local files in Parquet, JSON, CSV, XML, Excel, or Delta format — the fastest way to try the CLI, no credentials needed." --- # Local files -Test local files in Parquet, JSON, CSV, XML, or Delta format. This is the fastest way to see the CLI in action — no warehouse, no credentials. +Test local files in Parquet, JSON, CSV, XML, Excel, or Delta format. This is the fastest way to see the CLI in action — no warehouse, no credentials. ## 1. Install @@ -74,6 +74,25 @@ duplicate_count(status) was 1, expected = 0 The command exits with code `1`, so the same call works as a gate in [CI/CD pipelines](../scheduling/index.md). +## Excel workbooks + +Excel workbooks (`format: xlsx`) need `pip install 'datacontract-cli[xlsx]'`. Each schema is one sheet: its `physicalName` is the sheet's name, matched case-sensitively, and a contract with a single schema may leave it out to read the first sheet. The first row of a sheet holds the column names. Columns before the first and after the last header cell are not read, and a column with an empty header cell between them gets a generated name. Rows that are empty in every column are skipped. + +```yaml +servers: + - server: local + type: local + path: ./delivery.xlsx + format: xlsx +schema: + - name: orders + physicalName: Orders + - name: country_codes + physicalName: Country Codes +``` + +The `path` names a single workbook, without a glob. When several schemas share it, each needs its `physicalName`. Formulas are read as the values Excel last stored for them, and the older `.xls` format is not supported. + ## XML files XML documents (`format: xml`) have a guide of their own, from importing their XML Schema to testing nested elements and attributes: **[XML files](./xml.md)**. @@ -89,7 +108,7 @@ JSON files (`.json`, `.jsonl`, `.ndjson`) are also validated against a JSON Sche ## Troubleshooting - **`No files found that match the pattern`** — the `path` is a glob over file paths, not a directory, and it is resolved relative to the working directory rather than to the contract. -- **No checks run at all** — the `format` in the `servers` block must be one of `csv`, `json`, `parquet`, `xml`, or `delta`. It is never guessed at test time (only `datacontract import` infers it from the file suffix), so a missing or misspelled `format` leaves the table unreadable. +- **No checks run at all** — the `format` in the `servers` block must be one of `csv`, `json`, `parquet`, `xml`, `xlsx`, or `delta`. It is never guessed at test time (only `datacontract import` infers it from the file suffix), so a missing or misspelled `format` leaves the table unreadable. - **Every schema reads the same files** — with more than one schema in the contract, put the `{model}` placeholder in the `path` (e.g. `./data/{model}/*.parquet`); it is substituted with each schema's name. - **A CSV or XML value fails as a read error instead of a type check** — CSV and XML files are read *as* the contract's types, so a value that cannot be coerced surfaces while reading. See [Data types](../reference/local.md#data-types). diff --git a/pyproject.toml b/pyproject.toml index 85c29df6b..9f05cdfcc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -97,6 +97,12 @@ excel = [ "openpyxl>=3.1.5,<4.0.0", ] +# Tests Excel workbooks (`format: xlsx`) +xlsx = [ + "datacontract-cli[duckdb]", + "duckdb-extension-excel>=1.5.0,<1.6.0", +] + # The dataframe server type runs against a Spark session the caller passes to # `DataContract(spark=...)`, so pyspark is necessarily importable in that process @@ -266,7 +272,7 @@ dbml = [ ] # duckdb must stay in lockstep with the bundled duckdb-extension-* wheels -# (httpfs/aws/azure) used for air-gapped installs, since those extensions are +# (httpfs/aws/azure/excel) used for air-gapped installs, since those extensions are # built per duckdb version. Both are pinned to the 1.5.x line. duckdb = [ "duckdb>=1.5.0,<1.6.0", @@ -302,7 +308,7 @@ xml = [ # the `all` meta-extra would pull a proprietary package into a default-ish # install, so HANA support must be opted into explicitly via `datacontract-cli[hana]`. all = [ - "datacontract-cli[avro,kafka,bigquery,csv,excel,snowflake,postgres,redshift,mysql,dataframe,databricks,sqlserver,s3,gcs,azure,athena,trino,exasol,impala,clickhouse,hive,dbml,duckdb,iceberg,parquet,rdf,api,protobuf,oracle,xml]" + "datacontract-cli[avro,kafka,bigquery,csv,excel,snowflake,postgres,redshift,mysql,dataframe,databricks,sqlserver,s3,gcs,azure,athena,trino,exasol,impala,clickhouse,hive,dbml,duckdb,iceberg,parquet,rdf,api,protobuf,oracle,xml,xlsx]" ] # for development, we pin all libraries to an exact version diff --git a/tests/fixtures/xlsx/datacontract.yaml b/tests/fixtures/xlsx/datacontract.yaml new file mode 100644 index 000000000..19138ac17 --- /dev/null +++ b/tests/fixtures/xlsx/datacontract.yaml @@ -0,0 +1,50 @@ +version: 1.0.0 +kind: DataContract +apiVersion: v3.2.0 +id: delivery-xlsx +name: delivery +status: draft +servers: +- server: local + type: local + path: fixtures/xlsx/delivery.xlsx + format: xlsx +schema: +- name: orders + physicalName: Orders + logicalType: object + properties: + - name: order_id + logicalType: string + required: true + unique: true + - name: customer_id + logicalType: string + logicalTypeOptions: + pattern: ^[0-9]{5}$ + - name: order_date + logicalType: date + required: true + - name: order_timestamp + logicalType: timestamp + - name: amount + logicalType: number + logicalTypeOptions: + minimum: 0 + - name: quantity + logicalType: integer + - name: paid + logicalType: boolean + - name: note + logicalType: string +- name: country_codes + physicalName: Country Codes + logicalType: object + properties: + - name: code + logicalType: string + required: true + logicalTypeOptions: + maxLength: 2 + - name: name + logicalType: string diff --git a/tests/fixtures/xlsx/delivery.xlsx b/tests/fixtures/xlsx/delivery.xlsx new file mode 100644 index 000000000..f92256f90 Binary files /dev/null and b/tests/fixtures/xlsx/delivery.xlsx differ diff --git a/tests/fixtures/xlsx/helper/create_xlsx_files.py b/tests/fixtures/xlsx/helper/create_xlsx_files.py new file mode 100644 index 000000000..ab6f3b4e7 --- /dev/null +++ b/tests/fixtures/xlsx/helper/create_xlsx_files.py @@ -0,0 +1,29 @@ +"""Writes ../delivery.xlsx, kept as a script so the workbook can be reviewed and rebuilt.""" + +import datetime as dt +from pathlib import Path + +from openpyxl import Workbook + +ORDERS = [ + ["order_id", "customer_id", "order_date", "order_timestamp", "amount", "quantity", "paid", "note"], + ["A1", "00123", dt.date(2026, 1, 2), dt.datetime(2026, 1, 2, 13, 45), 10.5, 2, True, "first"], + ["A2", "00456", dt.date(2026, 1, 3), dt.datetime(2026, 1, 3, 8, 0), 7, 1, False, None], + ["A3", "00789", dt.date(2026, 1, 5), dt.datetime(2026, 1, 5, 0, 0), 3.25, 5, True, "third"], +] +COUNTRY_CODES = [["code", "name"], ["DE", "Germany"], ["FR", "France"]] + +workbook = Workbook() +workbook.remove(workbook.active) +for title, rows in {"Orders": ORDERS, "Country Codes": COUNTRY_CODES}.items(): + sheet = workbook.create_sheet(title) + for row in rows: + sheet.append(row) + # Excel stores dates as numbers; only the format makes them dates + for cells in sheet.iter_rows(min_row=2): + for cell in cells: + if isinstance(cell.value, dt.datetime): + cell.number_format = "yyyy-mm-dd hh:mm" + elif isinstance(cell.value, dt.date): + cell.number_format = "yyyy-mm-dd" +workbook.save(Path(__file__).parent.parent / "delivery.xlsx") diff --git a/tests/test_test_local_xlsx.py b/tests/test_test_local_xlsx.py new file mode 100644 index 000000000..fb667f62e --- /dev/null +++ b/tests/test_test_local_xlsx.py @@ -0,0 +1,190 @@ +"""`datacontract test` against Excel workbooks, read through DuckDB's excel extension.""" + +import datetime as dt +import shutil +from pathlib import Path + +import pytest +import yaml +from openpyxl import load_workbook + +from datacontract.data_contract import DataContract +from datacontract.engines.ibis.connections.duckdb_connection import get_duckdb_connection +from datacontract.lint import resolve +from datacontract.model.run import Run + +CONTRACT = "fixtures/xlsx/datacontract.yaml" +WORKBOOK = "fixtures/xlsx/delivery.xlsx" + + +def contract(path: str, models: list[str] | None = None, **order_changes) -> str: + data = yaml.safe_load(Path(CONTRACT).read_text()) + data["servers"][0]["path"] = path + if models is not None: + data["schema"] = [s for s in data["schema"] if s["name"] in models] + data["schema"][0].update(order_changes) + return yaml.safe_dump(data) + + +def edited(tmp_path: Path, sheet_title: str = "Orders", **cells) -> str: + """The fixture workbook with cells of its Orders sheet changed, e.g. E3="n/a".""" + workbook = load_workbook(WORKBOOK) + orders = workbook["Orders"] + for cell, value in cells.items(): + orders[cell] = value + if isinstance(value, dt.date): + orders[cell].number_format = "yyyy-mm-dd" + orders.title = sheet_title + workbook.save(tmp_path / "delivery.xlsx") + return str(tmp_path / "delivery.xlsx") + + +def failed(run) -> dict: + return {check.name: check.reason for check in run.checks if check.result is None or check.result.value != "passed"} + + +def rows(contract_str: str, view: str) -> list[tuple]: + data_contract = resolve.resolve_data_contract(data_contract_str=contract_str) + con = get_duckdb_connection(data_contract, data_contract.servers[0], Run.create_run()) + return con.sql(f'SELECT * FROM "{view}"').fetchall() + + +def test_both_sheets_of_a_workbook_are_checked(): + run = DataContract(data_contract_file=CONTRACT).test() + + assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"] + assert {"Orders", "Country Codes"} <= {check.model for check in run.checks} + + +def test_cells_are_read_with_the_types_of_the_contract(): + first, second, _ = rows(contract(WORKBOOK), "orders") + + assert first == ("A1", "00123", dt.date(2026, 1, 2), dt.datetime(2026, 1, 2, 13, 45), 10.5, 2, True, "first") + assert second[-1] is None + + +def test_a_model_without_physical_name_reads_the_first_sheet(): + data = yaml.safe_load(contract(WORKBOOK, models=["orders"])) + del data["schema"][0]["physicalName"] + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + assert run.result == "passed", failed(run) + + +def test_models_that_share_a_workbook_must_name_their_sheet(): + data = yaml.safe_load(contract(WORKBOOK)) + del data["schema"][1]["physicalName"] + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + assert run.result != "passed" + assert any("physicalName" in (c.reason or "") and "country_codes" in (c.reason or "") for c in run.checks) + + +def test_a_glob_path_is_refused(tmp_path: Path): + for name in ("a.xlsx", "b.xlsx"): + shutil.copy(WORKBOOK, tmp_path / name) + + run = DataContract(data_contract_str=contract(str(tmp_path / "*.xlsx"), models=["orders"])).test() + + assert run.result != "passed" + assert any("glob" in (c.reason or "").lower() for c in run.checks) + + +def test_a_sheet_that_is_not_in_the_workbook_fails(): + run = DataContract(data_contract_str=contract(WORKBOOK, physicalName="Shipments")).test() + + assert run.result != "passed" + assert any("Shipments" in (c.reason or "") for c in run.checks) + + +def test_a_value_of_the_wrong_type_fails_only_its_column(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, E3="n/a"), models=["orders"])).test() + + assert failed(run) == {"Check that field amount has type number": "Actual custom_sql(amount) was 1, expected = 0"} + + +def test_rows_below_an_empty_row_are_checked(tmp_path: Path): + workbook = load_workbook(WORKBOOK) + workbook["Orders"].insert_rows(3) + workbook["Orders"]["E5"] = "n/a" + workbook.save(tmp_path / "delivery.xlsx") + + run = DataContract(data_contract_str=contract(str(tmp_path / "delivery.xlsx"), models=["orders"])).test() + + # the empty row itself is skipped, or its order_id and order_date would be missing + assert failed(run) == {"Check that field amount has type number": "Actual custom_sql(amount) was 1, expected = 0"} + + +def test_a_fraction_in_an_integer_column_is_not_rounded(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, F3=1.5), models=["orders"])).test() + + assert failed(run) == { + "Check that field quantity has type integer": "Actual custom_sql(quantity) was 1, expected = 0" + } + + +def test_a_header_is_matched_regardless_of_case(tmp_path: Path): + contract_str = contract(edited(tmp_path, A1="ORDER_ID"), models=["orders"]) + + assert [row[0] for row in rows(contract_str, "orders")] == ["A1", "A2", "A3"] + + +def test_a_date_that_is_not_a_date_fails_its_column(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, C3="soon"), models=["orders"])).test() + + # as for JSON, the value reads as NULL, so the column being required reports it too + assert failed(run) == { + "Check that field order_date has type date": "Actual custom_sql(order_date) was 1, expected = 0", + "Check that field order_date has no missing values": "Actual missing_count(order_date) was 1, expected = 0", + } + + +def test_dates_below_a_first_cell_that_is_not_a_date_are_still_dates(tmp_path: Path): + # DuckDB infers the type of a column from its first row, so these dates arrive as Excel serial numbers + contract_str = contract(edited(tmp_path, D2="unknown"), models=["orders"]) + + assert [row[3] for row in rows(contract_str, "orders")] == [ + None, + dt.datetime(2026, 1, 3, 8, 0), + dt.datetime(2026, 1, 5, 0, 0), + ] + + +def test_a_date_in_a_text_column_reads_as_the_date_not_its_serial_number(tmp_path: Path): + contract_str = contract(edited(tmp_path, H2=dt.date(2026, 2, 1)), models=["orders"]) + + assert [row[7] for row in rows(contract_str, "orders")] == ["2026-02-01", None, "third"] + + +def test_a_column_that_is_not_in_the_sheet_fails_its_presence_check(tmp_path: Path): + run = DataContract(data_contract_str=contract(edited(tmp_path, F1="qty"), models=["orders"])).test() + + assert "Check that field 'quantity' is present" in failed(run) + + +def test_a_nested_property_gets_no_type_check(): + data = yaml.safe_load(contract(WORKBOOK, models=["orders"])) + data["schema"][0]["properties"].append( + {"name": "meta", "logicalType": "object", "properties": [{"name": "source", "logicalType": "integer"}]} + ) + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + # a sheet has no nested columns, so such a check could only ever pass + assert not any("meta.source" in check.name and "has type" in check.name for check in run.checks) + + +@pytest.mark.parametrize("sheet", ["Bob's Orders", 'Orders"; DROP TABLE x; --']) +def test_a_sheet_name_is_not_run_as_sql(tmp_path: Path, sheet): + run = DataContract(data_contract_str=contract(edited(tmp_path, sheet_title=sheet), physicalName=sheet)).test() + + assert run.result == "passed", failed(run) + + +def test_an_untrusted_contract_reads_its_workbook(): + # The sandbox of an untrusted contract stops DuckDB from loading extensions on demand + run = DataContract(data_contract_file=CONTRACT, untrusted_contract=True, inline_references=False).test() + + assert run.result == "passed", failed(run) diff --git a/tests/test_test_s3_xlsx.py b/tests/test_test_s3_xlsx.py new file mode 100644 index 000000000..bd946f928 --- /dev/null +++ b/tests/test_test_s3_xlsx.py @@ -0,0 +1,43 @@ +from pathlib import Path + +import pytest +import yaml +from testcontainers.minio import MinioContainer + +from datacontract.data_contract import DataContract + +CONTRACT = "fixtures/xlsx/datacontract.yaml" +WORKBOOK = "fixtures/xlsx/delivery.xlsx" +bucket_name = "test-bucket" +s3_access_key = "test-access" +s3_secret_access_key = "test-secret" + + +@pytest.fixture(scope="session") +def minio_container(): + with MinioContainer( + image="cgr.dev/chainguard/minio", access_key=s3_access_key, secret_key=s3_secret_access_key + ) as minio_container: + yield minio_container + + +def test_test_s3_xlsx(minio_container, monkeypatch): + monkeypatch.setenv("DATACONTRACT_S3_ACCESS_KEY_ID", s3_access_key) + monkeypatch.setenv("DATACONTRACT_S3_SECRET_ACCESS_KEY", s3_secret_access_key) + minio_container.get_client().make_bucket(bucket_name) + minio_container.get_client().fput_object(bucket_name, "delivery.xlsx", WORKBOOK) + data = yaml.safe_load(Path(CONTRACT).read_text()) + data["servers"] = [ + { + "server": "s3", + "type": "s3", + "location": f"s3://{bucket_name}/delivery.xlsx", + "endpointUrl": f"http://{minio_container.get_container_host_ip()}:{minio_container.get_exposed_port(9000)}", + "format": "xlsx", + } + ] + + run = DataContract(data_contract_str=yaml.safe_dump(data)).test() + + assert run.result == "passed", [(c.name, c.reason) for c in run.checks if c.result != "passed"] + assert {"Orders", "Country Codes"} <= {check.model for check in run.checks}