|
| 1 | +# Copyright (c) 2025 Airbyte, Inc., all rights reserved. |
| 2 | +"""Job runner for Airbyte Standard Tests.""" |
| 3 | + |
| 4 | +import logging |
| 5 | +import tempfile |
| 6 | +import uuid |
| 7 | +from dataclasses import asdict |
| 8 | +from pathlib import Path |
| 9 | +from typing import Any, Callable, Literal |
| 10 | + |
| 11 | +import orjson |
| 12 | +from typing_extensions import Protocol, runtime_checkable |
| 13 | + |
| 14 | +from airbyte_cdk.models import ( |
| 15 | + ConfiguredAirbyteCatalog, |
| 16 | + Status, |
| 17 | +) |
| 18 | +from airbyte_cdk.test import entrypoint_wrapper |
| 19 | +from airbyte_cdk.test.standard_tests.models import ( |
| 20 | + ConnectorTestScenario, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +def _errors_to_str( |
| 25 | + entrypoint_output: entrypoint_wrapper.EntrypointOutput, |
| 26 | +) -> str: |
| 27 | + """Convert errors from entrypoint output to a string.""" |
| 28 | + if not entrypoint_output.errors: |
| 29 | + # If there are no errors, return an empty string. |
| 30 | + return "" |
| 31 | + |
| 32 | + return "\n" + "\n".join( |
| 33 | + [ |
| 34 | + str(error.trace.error).replace( |
| 35 | + "\\n", |
| 36 | + "\n", |
| 37 | + ) |
| 38 | + for error in entrypoint_output.errors |
| 39 | + if error.trace |
| 40 | + ], |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +@runtime_checkable |
| 45 | +class IConnector(Protocol): |
| 46 | + """A connector that can be run in a test scenario. |
| 47 | +
|
| 48 | + Note: We currently use 'spec' to determine if we have a connector object. |
| 49 | + In the future, it would be preferred to leverage a 'launch' method instead, |
| 50 | + directly on the connector (which doesn't yet exist). |
| 51 | + """ |
| 52 | + |
| 53 | + def spec(self, logger: logging.Logger) -> Any: |
| 54 | + """Connectors should have a `spec` method.""" |
| 55 | + |
| 56 | + |
| 57 | +def run_test_job( |
| 58 | + connector: IConnector | type[IConnector] | Callable[[], IConnector], |
| 59 | + verb: Literal["read", "check", "discover"], |
| 60 | + test_scenario: ConnectorTestScenario, |
| 61 | + *, |
| 62 | + catalog: ConfiguredAirbyteCatalog | dict[str, Any] | None = None, |
| 63 | +) -> entrypoint_wrapper.EntrypointOutput: |
| 64 | + """Run a test scenario from provided CLI args and return the result.""" |
| 65 | + if not connector: |
| 66 | + raise ValueError("Connector is required") |
| 67 | + |
| 68 | + if catalog and isinstance(catalog, ConfiguredAirbyteCatalog): |
| 69 | + # Convert the catalog to a dict if it's already a ConfiguredAirbyteCatalog. |
| 70 | + catalog = asdict(catalog) |
| 71 | + |
| 72 | + connector_obj: IConnector |
| 73 | + if isinstance(connector, type) or callable(connector): |
| 74 | + # If the connector is a class or a factory lambda, instantiate it. |
| 75 | + connector_obj = connector() |
| 76 | + elif isinstance(connector, IConnector): |
| 77 | + connector_obj = connector |
| 78 | + else: |
| 79 | + raise ValueError( |
| 80 | + f"Invalid connector input: {type(connector)}", |
| 81 | + ) |
| 82 | + |
| 83 | + args: list[str] = [verb] |
| 84 | + if test_scenario.config_path: |
| 85 | + args += ["--config", str(test_scenario.config_path)] |
| 86 | + elif test_scenario.config_dict: |
| 87 | + config_path = ( |
| 88 | + Path(tempfile.gettempdir()) / "airbyte-test" / f"temp_config_{uuid.uuid4().hex}.json" |
| 89 | + ) |
| 90 | + config_path.parent.mkdir(parents=True, exist_ok=True) |
| 91 | + config_path.write_text(orjson.dumps(test_scenario.config_dict).decode()) |
| 92 | + args += ["--config", str(config_path)] |
| 93 | + |
| 94 | + catalog_path: Path | None = None |
| 95 | + if verb not in ["discover", "check"]: |
| 96 | + # We need a catalog for read. |
| 97 | + if catalog: |
| 98 | + # Write the catalog to a temp json file and pass the path to the file as an argument. |
| 99 | + catalog_path = ( |
| 100 | + Path(tempfile.gettempdir()) |
| 101 | + / "airbyte-test" |
| 102 | + / f"temp_catalog_{uuid.uuid4().hex}.json" |
| 103 | + ) |
| 104 | + catalog_path.parent.mkdir(parents=True, exist_ok=True) |
| 105 | + catalog_path.write_text(orjson.dumps(catalog).decode()) |
| 106 | + elif test_scenario.configured_catalog_path: |
| 107 | + catalog_path = Path(test_scenario.configured_catalog_path) |
| 108 | + |
| 109 | + if catalog_path: |
| 110 | + args += ["--catalog", str(catalog_path)] |
| 111 | + |
| 112 | + # This is a bit of a hack because the source needs the catalog early. |
| 113 | + # Because it *also* can fail, we have to redundantly wrap it in a try/except block. |
| 114 | + |
| 115 | + result: entrypoint_wrapper.EntrypointOutput = entrypoint_wrapper._run_command( # noqa: SLF001 # Non-public API |
| 116 | + source=connector_obj, # type: ignore [arg-type] |
| 117 | + args=args, |
| 118 | + expecting_exception=test_scenario.expect_exception, |
| 119 | + ) |
| 120 | + if result.errors and not test_scenario.expect_exception: |
| 121 | + raise AssertionError( |
| 122 | + f"Expected no errors but got {len(result.errors)}: \n" + _errors_to_str(result) |
| 123 | + ) |
| 124 | + |
| 125 | + if verb == "check": |
| 126 | + # Check is expected to fail gracefully without an exception. |
| 127 | + # Instead, we assert that we have a CONNECTION_STATUS message with |
| 128 | + # a failure status. |
| 129 | + assert len(result.connection_status_messages) == 1, ( |
| 130 | + "Expected exactly one CONNECTION_STATUS message. Got " |
| 131 | + f"{len(result.connection_status_messages)}:\n" |
| 132 | + + "\n".join([str(msg) for msg in result.connection_status_messages]) |
| 133 | + + _errors_to_str(result) |
| 134 | + ) |
| 135 | + if test_scenario.expect_exception: |
| 136 | + conn_status = result.connection_status_messages[0].connectionStatus |
| 137 | + assert conn_status, ( |
| 138 | + "Expected CONNECTION_STATUS message to be present. Got: \n" |
| 139 | + + "\n".join([str(msg) for msg in result.connection_status_messages]) |
| 140 | + ) |
| 141 | + assert conn_status.status == Status.FAILED, ( |
| 142 | + "Expected CONNECTION_STATUS message to be FAILED. Got: \n" |
| 143 | + + "\n".join([str(msg) for msg in result.connection_status_messages]) |
| 144 | + ) |
| 145 | + |
| 146 | + return result |
| 147 | + |
| 148 | + # For all other verbs, we assert check that an exception is raised (or not). |
| 149 | + if test_scenario.expect_exception: |
| 150 | + if not result.errors: |
| 151 | + raise AssertionError("Expected exception but got none.") |
| 152 | + |
| 153 | + return result |
| 154 | + |
| 155 | + assert not result.errors, ( |
| 156 | + f"Expected no errors but got {len(result.errors)}: \n" + _errors_to_str(result) |
| 157 | + ) |
| 158 | + |
| 159 | + return result |
0 commit comments