supaflow-connector-testkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- supaflow_connector_testkit-0.1.0.dist-info/METADATA +12 -0
- supaflow_connector_testkit-0.1.0.dist-info/RECORD +12 -0
- supaflow_connector_testkit-0.1.0.dist-info/WHEEL +5 -0
- supaflow_connector_testkit-0.1.0.dist-info/top_level.txt +1 -0
- supaflow_python_testkit/__init__.py +23 -0
- supaflow_python_testkit/connector_harness.py +155 -0
- supaflow_python_testkit/csv_parser.py +90 -0
- supaflow_python_testkit/discovery.py +260 -0
- supaflow_python_testkit/jsonl_parity.py +299 -0
- supaflow_python_testkit/manifest_validation.py +195 -0
- supaflow_python_testkit/namespace_contract.py +334 -0
- supaflow_python_testkit/read_harness.py +1669 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: supaflow-connector-testkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Portable testing utilities for Supaflow Python connectors.
|
|
5
|
+
Author-email: Supaflow <support@supa-flow.io>
|
|
6
|
+
License-Expression: LicenseRef-Proprietary
|
|
7
|
+
Project-URL: Homepage, https://www.supa-flow.io
|
|
8
|
+
Project-URL: Documentation, https://www.supa-flow.io/docs
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: supaflow-python-sdk>=1.0.73.dev0
|
|
11
|
+
Provides-Extra: declarative
|
|
12
|
+
Requires-Dist: supaflow-connector-runtime>=0.1.0; extra == "declarative"
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
supaflow_python_testkit/__init__.py,sha256=VE1aXuu1JTT0q55Y-oiB7G9b5Sn68kF5miBtKsDB4pM,922
|
|
2
|
+
supaflow_python_testkit/connector_harness.py,sha256=CXAv6V7kzSXwaXTmostYh_PmciCo8Lh0YghmclqSk2o,4843
|
|
3
|
+
supaflow_python_testkit/csv_parser.py,sha256=6PUuENgfDsdgMT3f2L8_xaMeyVnD7H_TbY4DP5H_1I0,3603
|
|
4
|
+
supaflow_python_testkit/discovery.py,sha256=x7mzP1tLqRizN0T_rydBv5lY_cLXG2FClziQD8Hhnb0,10766
|
|
5
|
+
supaflow_python_testkit/jsonl_parity.py,sha256=XopOXVu7KbNw2CUpbSI0UGPbz7BURXJjUBhdVIg3R84,12054
|
|
6
|
+
supaflow_python_testkit/manifest_validation.py,sha256=GJzGsRZBgBMFwLLGubHtXfXuqNDVhXh5kQNDWn-ZU8s,8724
|
|
7
|
+
supaflow_python_testkit/namespace_contract.py,sha256=y7f7xbeKMToJBYLt9C__CigfLNtibpiFnhLn94GS6nE,13747
|
|
8
|
+
supaflow_python_testkit/read_harness.py,sha256=Jo7O15WEonbl17ieQBst6im5WL86JsGQ3hRyyMTWRqM,73584
|
|
9
|
+
supaflow_connector_testkit-0.1.0.dist-info/METADATA,sha256=ToxnUWvByJGpni0LjapcNkAfGRLDb76NmS6VUG8DVIw,506
|
|
10
|
+
supaflow_connector_testkit-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
11
|
+
supaflow_connector_testkit-0.1.0.dist-info/top_level.txt,sha256=dVSBy7jFfZ9cs_72xC79xZXpFmNnbIKVGEIpD7tVkzU,24
|
|
12
|
+
supaflow_connector_testkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
supaflow_python_testkit
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Supaflow Python Testkit -- portable connector testing utilities.
|
|
2
|
+
|
|
3
|
+
Provides:
|
|
4
|
+
- ConnectorHarness: lifecycle test harness for init/schema/read
|
|
5
|
+
- ReadHarness: CSV read, identity and parent/child validation
|
|
6
|
+
- collect_manifest_violations: manifest compliance validator
|
|
7
|
+
- discover_declarative_connectors: shared connector discovery
|
|
8
|
+
- detect_connector_dirs: path-only connector directory detection
|
|
9
|
+
"""
|
|
10
|
+
from supaflow_python_sdk import ConnectorFixture as ConnectorFixture
|
|
11
|
+
from supaflow_python_testkit.connector_harness import ( # noqa: F401
|
|
12
|
+
CollectingEmitter,
|
|
13
|
+
ConnectorHarness,
|
|
14
|
+
)
|
|
15
|
+
from supaflow_python_testkit.manifest_validation import ( # noqa: F401
|
|
16
|
+
collect_manifest_violations,
|
|
17
|
+
)
|
|
18
|
+
from supaflow_python_testkit.discovery import ( # noqa: F401
|
|
19
|
+
detect_connector_dirs,
|
|
20
|
+
discover_declarative_connectors,
|
|
21
|
+
load_connector_fixture,
|
|
22
|
+
)
|
|
23
|
+
from supaflow_python_testkit.read_harness import ReadHarness as ReadHarness
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Reusable harness for testing Python source connectors.
|
|
2
|
+
|
|
3
|
+
Runs the init -> schema -> read lifecycle without an agent or pipeline.
|
|
4
|
+
Always validates schema compliance automatically.
|
|
5
|
+
|
|
6
|
+
Usage:
|
|
7
|
+
harness = ConnectorHarness(StripeConnector, config)
|
|
8
|
+
schema_result = harness.run_schema()
|
|
9
|
+
# schema compliance already asserted
|
|
10
|
+
|
|
11
|
+
for obj in schema_result.objects:
|
|
12
|
+
read_result, records = harness.run_read(
|
|
13
|
+
object_name=obj.name,
|
|
14
|
+
fields=obj.fields,
|
|
15
|
+
)
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import tempfile
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from supaflow_python_sdk.base_connector import BaseConnector
|
|
24
|
+
from supaflow_python_sdk.models import (
|
|
25
|
+
InitRequest, InitResult,
|
|
26
|
+
SchemaRequest, SchemaResult,
|
|
27
|
+
ReadRequest, ReadResult,
|
|
28
|
+
ReadObjectMetadata, MetadataField,
|
|
29
|
+
SyncStateRequest,
|
|
30
|
+
SchemaFieldInfo,
|
|
31
|
+
)
|
|
32
|
+
from supaflow_python_sdk.source import RecordEmitResult
|
|
33
|
+
from supaflow_python_sdk.schema_compliance import assert_schema_result_contract
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class CollectingEmitter:
|
|
38
|
+
"""RecordEmitter that collects records in memory."""
|
|
39
|
+
records: list[dict] = field(default_factory=list)
|
|
40
|
+
_closed: bool = False
|
|
41
|
+
|
|
42
|
+
def emit(self, record: dict[str, Any]) -> None:
|
|
43
|
+
if self._closed:
|
|
44
|
+
raise RuntimeError("emit() after close()")
|
|
45
|
+
self.records.append(dict(record))
|
|
46
|
+
|
|
47
|
+
def complete(self) -> RecordEmitResult:
|
|
48
|
+
return RecordEmitResult(records_emitted=len(self.records))
|
|
49
|
+
|
|
50
|
+
def close(self) -> None:
|
|
51
|
+
self._closed = True
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ConnectorHarness:
|
|
55
|
+
"""Lightweight test harness for Python source connectors.
|
|
56
|
+
|
|
57
|
+
Handles init, schema, and read without an agent or pipeline.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
connector_cls: type[BaseConnector],
|
|
63
|
+
config: dict[str, Any],
|
|
64
|
+
work_dir: str | None = None,
|
|
65
|
+
):
|
|
66
|
+
self.config = config
|
|
67
|
+
self.work_dir = work_dir or tempfile.mkdtemp()
|
|
68
|
+
self.connector = connector_cls()
|
|
69
|
+
self._init_result: InitResult | None = None
|
|
70
|
+
self._schema_result: SchemaResult | None = None
|
|
71
|
+
|
|
72
|
+
def run_init(self) -> InitResult:
|
|
73
|
+
"""Run init() and return the result."""
|
|
74
|
+
self._init_result = self.connector.init(InitRequest(
|
|
75
|
+
request_id="harness-init",
|
|
76
|
+
config=self.config,
|
|
77
|
+
work_dir=self.work_dir,
|
|
78
|
+
))
|
|
79
|
+
return self._init_result
|
|
80
|
+
|
|
81
|
+
def run_schema(self, level: str = "FULL") -> SchemaResult:
|
|
82
|
+
"""Run schema() and assert compliance.
|
|
83
|
+
|
|
84
|
+
Calls init() automatically if not already called.
|
|
85
|
+
"""
|
|
86
|
+
if self._init_result is None:
|
|
87
|
+
self.run_init()
|
|
88
|
+
|
|
89
|
+
self._schema_result = self.connector.schema(SchemaRequest(
|
|
90
|
+
request_id="harness-schema",
|
|
91
|
+
config=self.config,
|
|
92
|
+
level=level,
|
|
93
|
+
work_dir=self.work_dir,
|
|
94
|
+
))
|
|
95
|
+
|
|
96
|
+
# Always validate compliance
|
|
97
|
+
assert_schema_result_contract(self._schema_result)
|
|
98
|
+
|
|
99
|
+
return self._schema_result
|
|
100
|
+
|
|
101
|
+
def run_read(
|
|
102
|
+
self,
|
|
103
|
+
object_name: str,
|
|
104
|
+
fields: list[SchemaFieldInfo] | None = None,
|
|
105
|
+
sync_state: SyncStateRequest | None = None,
|
|
106
|
+
) -> tuple[ReadResult, list[dict]]:
|
|
107
|
+
"""Run read() for a single object and return (result, records).
|
|
108
|
+
|
|
109
|
+
If fields is None and schema() was already called, uses the
|
|
110
|
+
fields from the schema result for that object.
|
|
111
|
+
"""
|
|
112
|
+
if self._init_result is None:
|
|
113
|
+
self.run_init()
|
|
114
|
+
|
|
115
|
+
# Resolve fields from schema if not provided
|
|
116
|
+
if fields is None and self._schema_result:
|
|
117
|
+
for obj in (self._schema_result.objects or []):
|
|
118
|
+
if obj.name == object_name:
|
|
119
|
+
fields = obj.fields
|
|
120
|
+
break
|
|
121
|
+
|
|
122
|
+
metadata_fields = []
|
|
123
|
+
if fields:
|
|
124
|
+
metadata_fields = [
|
|
125
|
+
MetadataField(
|
|
126
|
+
name=f.name,
|
|
127
|
+
canonical_type=f.canonical_type,
|
|
128
|
+
original_data_type=f.original_data_type,
|
|
129
|
+
primary_key=f.source_primary_key or False,
|
|
130
|
+
cursor_field=f.source_cursor_field or False,
|
|
131
|
+
precision=f.precision,
|
|
132
|
+
scale=f.scale,
|
|
133
|
+
)
|
|
134
|
+
for f in fields
|
|
135
|
+
]
|
|
136
|
+
|
|
137
|
+
emitter = CollectingEmitter()
|
|
138
|
+
|
|
139
|
+
result = self.connector.read(ReadRequest(
|
|
140
|
+
request_id=f"harness-read-{object_name}",
|
|
141
|
+
config=self.config,
|
|
142
|
+
work_dir=self.work_dir,
|
|
143
|
+
record_emitter=emitter,
|
|
144
|
+
object_metadata=ReadObjectMetadata(
|
|
145
|
+
name=object_name,
|
|
146
|
+
fields=metadata_fields,
|
|
147
|
+
),
|
|
148
|
+
sync_state=sync_state,
|
|
149
|
+
))
|
|
150
|
+
|
|
151
|
+
return result, emitter.records
|
|
152
|
+
|
|
153
|
+
def close(self) -> None:
|
|
154
|
+
"""Clean up connector resources."""
|
|
155
|
+
self.connector.close()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Parse CSV files produced by ``CsvRecordEmitter`` back into dicts.
|
|
2
|
+
|
|
3
|
+
``CsvRecordEmitter`` writes one or more ``success_part_{idx}.csv.gz`` files
|
|
4
|
+
to its output directory. Each file carries a 2-row header (field names,
|
|
5
|
+
field types) followed by data rows encoded with the Java ``CsvWriter``
|
|
6
|
+
rules (see ``supaflow_python_sdk.csv_record_emitter``).
|
|
7
|
+
|
|
8
|
+
The parser concatenates every chunk in a directory, retains the first
|
|
9
|
+
file's header, and yields the data rows as dicts keyed by the header
|
|
10
|
+
names. Null markers are converted back to ``None``; every other value
|
|
11
|
+
is returned as a string. Downstream consumers (the harness's assertion
|
|
12
|
+
helpers) perform semantic coercions as needed.
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import csv
|
|
17
|
+
import glob
|
|
18
|
+
import gzip
|
|
19
|
+
import os
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_DEFAULT_NULL_MARKER = "\\N"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def parse_csv_dir(
|
|
28
|
+
directory: str | os.PathLike,
|
|
29
|
+
*,
|
|
30
|
+
null_marker: str = _DEFAULT_NULL_MARKER,
|
|
31
|
+
) -> tuple[list[str], list[str], list[dict[str, Any]]]:
|
|
32
|
+
"""Parse every ``success_part_*.csv.gz`` file in ``directory``.
|
|
33
|
+
|
|
34
|
+
Returns ``(header_names, header_types, rows)``.
|
|
35
|
+
|
|
36
|
+
* ``header_names`` / ``header_types`` come from the first chunk file.
|
|
37
|
+
* Subsequent chunks' 2-row headers must match exactly (otherwise an
|
|
38
|
+
``AssertionError`` is raised — that would indicate a runtime bug).
|
|
39
|
+
* Data rows are dicts keyed by the header names. Values matching
|
|
40
|
+
``null_marker`` are converted to ``None``; all others are kept as
|
|
41
|
+
strings. Any row whose column count differs from the header width
|
|
42
|
+
raises a ``ValueError``.
|
|
43
|
+
|
|
44
|
+
If no chunk files exist, returns ``([], [], [])`` — the harness
|
|
45
|
+
treats that as "zero rows" and may ``pytest.skip`` the resource.
|
|
46
|
+
"""
|
|
47
|
+
paths = sorted(glob.glob(str(Path(directory) / "success_part_*.csv.gz")))
|
|
48
|
+
if not paths:
|
|
49
|
+
paths = sorted(glob.glob(str(Path(directory) / "success_part_*.csv")))
|
|
50
|
+
if not paths:
|
|
51
|
+
return ([], [], [])
|
|
52
|
+
|
|
53
|
+
header_names: list[str] = []
|
|
54
|
+
header_types: list[str] = []
|
|
55
|
+
rows: list[dict[str, Any]] = []
|
|
56
|
+
|
|
57
|
+
for file_idx, path in enumerate(paths):
|
|
58
|
+
opener = gzip.open if path.endswith(".gz") else open
|
|
59
|
+
with opener(path, "rt", encoding="utf-8", newline="") as f:
|
|
60
|
+
reader = csv.reader(f)
|
|
61
|
+
try:
|
|
62
|
+
names_row = next(reader)
|
|
63
|
+
types_row = next(reader)
|
|
64
|
+
except StopIteration:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
f"CSV chunk {path!r} is missing the 2-row header"
|
|
67
|
+
)
|
|
68
|
+
if file_idx == 0:
|
|
69
|
+
header_names = list(names_row)
|
|
70
|
+
header_types = list(types_row)
|
|
71
|
+
else:
|
|
72
|
+
assert list(names_row) == header_names, (
|
|
73
|
+
f"chunk {path!r} header names diverge from first chunk: "
|
|
74
|
+
f"got {list(names_row)!r}, expected {header_names!r}"
|
|
75
|
+
)
|
|
76
|
+
assert list(types_row) == header_types, (
|
|
77
|
+
f"chunk {path!r} header types diverge from first chunk: "
|
|
78
|
+
f"got {list(types_row)!r}, expected {header_types!r}"
|
|
79
|
+
)
|
|
80
|
+
for raw in reader:
|
|
81
|
+
if len(raw) != len(header_names):
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"row in {path!r} has {len(raw)} columns, "
|
|
84
|
+
f"expected {len(header_names)}"
|
|
85
|
+
)
|
|
86
|
+
rows.append({
|
|
87
|
+
name: (None if val == null_marker else val)
|
|
88
|
+
for name, val in zip(header_names, raw)
|
|
89
|
+
})
|
|
90
|
+
return header_names, header_types, rows
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""Shared connector discovery for declarative dlt connectors.
|
|
2
|
+
|
|
3
|
+
Provides utilities to find connector package directories and
|
|
4
|
+
DeclarativeDltConnector subclasses, replacing the duplicated
|
|
5
|
+
discovery logic in test files, scripts, and the CLI.
|
|
6
|
+
|
|
7
|
+
Supports both monorepo layout (connectors under a parent package)
|
|
8
|
+
and standalone single-connector repos (package at the root).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import importlib
|
|
13
|
+
import importlib.util
|
|
14
|
+
from importlib.metadata import EntryPoint
|
|
15
|
+
import inspect
|
|
16
|
+
import runpy
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from supaflow_python_sdk import BaseConnector, ConnectorFixture
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_connector_fixture(project_root: Path) -> ConnectorFixture | None:
|
|
24
|
+
"""Load the project's tests/connector_fixture.py when contract tests request it."""
|
|
25
|
+
path = project_root / "tests" / "connector_fixture.py"
|
|
26
|
+
if not path.exists():
|
|
27
|
+
return None
|
|
28
|
+
fixture = runpy.run_path(str(path)).get("CONNECTOR_FIXTURE")
|
|
29
|
+
if not isinstance(fixture, ConnectorFixture):
|
|
30
|
+
raise ValueError(f"{path} must define CONNECTOR_FIXTURE as a ConnectorFixture")
|
|
31
|
+
return fixture
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Monorepo defaults
|
|
35
|
+
_DEFAULT_CONNECTORS_ROOT = Path(__file__).resolve().parents[1] / "connectors"
|
|
36
|
+
_DEFAULT_MODULE_PREFIX = "connectors"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def detect_connector_dirs(root: Path) -> list[Path]:
|
|
40
|
+
"""Detect connector package directories under a root, supporting both layouts.
|
|
41
|
+
|
|
42
|
+
Shared monorepo layout: root/supaflow_connector_*/connector.py
|
|
43
|
+
(where root is the connectors/ directory)
|
|
44
|
+
Single-connector layout: root/supaflow_connector_*/connector.py
|
|
45
|
+
(where root is the repo root)
|
|
46
|
+
|
|
47
|
+
This is a pure path-scanning utility with no Python imports.
|
|
48
|
+
Used by both ``discover_declarative_connectors`` (testkit) and
|
|
49
|
+
the CLI manifest/stamp commands.
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
Sorted list of connector package directory paths.
|
|
53
|
+
"""
|
|
54
|
+
return sorted(
|
|
55
|
+
p.parent for p in root.glob("supaflow_connector_*/connector.py")
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _evict_package(package_name: str) -> None:
|
|
60
|
+
"""Remove a package and ALL its submodules from sys.modules.
|
|
61
|
+
|
|
62
|
+
This is necessary before file-based loading when the same package
|
|
63
|
+
name might exist under different filesystem roots. Without eviction,
|
|
64
|
+
Python reuses the cached parent package and its submodules from the
|
|
65
|
+
first root, so a second root containing the same package name would
|
|
66
|
+
get stale imports for any sibling or relative imports.
|
|
67
|
+
"""
|
|
68
|
+
to_remove = [
|
|
69
|
+
key for key in sys.modules
|
|
70
|
+
if key == package_name or key.startswith(package_name + ".")
|
|
71
|
+
]
|
|
72
|
+
for key in to_remove:
|
|
73
|
+
del sys.modules[key]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def resolve_connector_entrypoint(entrypoint: str, project_root: Path) -> tuple[EntryPoint, Path]:
|
|
77
|
+
"""Resolve the declared entry point and its top-level source package/module."""
|
|
78
|
+
entry = EntryPoint(name="connector", value=entrypoint, group="supaflow.connectors")
|
|
79
|
+
try:
|
|
80
|
+
module_parts = entry.module.split(".")
|
|
81
|
+
if not all(part.isidentifier() for part in module_parts) or not (
|
|
82
|
+
entry.attr and entry.attr.isidentifier()
|
|
83
|
+
) or entry.extras:
|
|
84
|
+
raise ValueError("entry point must use module:ClassName")
|
|
85
|
+
except (AttributeError, ValueError) as exc:
|
|
86
|
+
raise ImportError(f"Invalid connector entry point: {entrypoint}") from exc
|
|
87
|
+
|
|
88
|
+
sources = []
|
|
89
|
+
for source_root in (project_root / "src", project_root):
|
|
90
|
+
module_path = source_root.joinpath(*module_parts)
|
|
91
|
+
if module_path.with_suffix(".py").is_file() or (module_path / "__init__.py").is_file():
|
|
92
|
+
sources.append(source_root)
|
|
93
|
+
if len(sources) != 1:
|
|
94
|
+
raise ImportError(
|
|
95
|
+
f"{entrypoint}: expected exactly one module under {project_root}/src or {project_root}"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
source_root, = sources
|
|
99
|
+
package = source_root / module_parts[0]
|
|
100
|
+
return entry, package if package.is_dir() else package.with_suffix(".py")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def load_connector_entrypoint(entrypoint: str, project_root: Path) -> type[BaseConnector]:
|
|
104
|
+
"""Load the declared class from a project's src/ or root source layout."""
|
|
105
|
+
entry, package = resolve_connector_entrypoint(entrypoint, project_root)
|
|
106
|
+
source_root = package.parent
|
|
107
|
+
module_parts = entry.module.split(".")
|
|
108
|
+
_evict_package(module_parts[0])
|
|
109
|
+
old_path = sys.path[:]
|
|
110
|
+
sys.path.insert(0, str(source_root))
|
|
111
|
+
try:
|
|
112
|
+
try:
|
|
113
|
+
connector = entry.load()
|
|
114
|
+
except AttributeError as exc:
|
|
115
|
+
raise ImportError(f"{entrypoint}: declared connector class was not found") from exc
|
|
116
|
+
if not inspect.isclass(connector) or not issubclass(connector, BaseConnector):
|
|
117
|
+
raise ImportError(f"{entrypoint}: must identify a BaseConnector subclass")
|
|
118
|
+
origin = Path(inspect.getfile(connector)).resolve()
|
|
119
|
+
belongs = origin.is_relative_to(package.resolve()) if package.is_dir() else origin == package.resolve()
|
|
120
|
+
if not belongs:
|
|
121
|
+
raise ImportError(f"{entrypoint}: connector class must belong to the declared source package")
|
|
122
|
+
return connector
|
|
123
|
+
finally:
|
|
124
|
+
sys.path[:] = old_path
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _load_module_from_file(module_name: str, file_path: Path):
|
|
128
|
+
"""Load a Python module from an explicit file path.
|
|
129
|
+
|
|
130
|
+
Derives the fully-qualified package name from module_name (e.g.,
|
|
131
|
+
"connectors.supaflow_connector_test.connector" -> package is
|
|
132
|
+
"connectors.supaflow_connector_test"). Evicts the entire package
|
|
133
|
+
hierarchy from sys.modules first, then loads the package __init__.py
|
|
134
|
+
and the target module from the specified file path.
|
|
135
|
+
|
|
136
|
+
This ensures full isolation when the same function is called with
|
|
137
|
+
different roots that contain packages with the same name.
|
|
138
|
+
"""
|
|
139
|
+
# Derive the fully-qualified package name from the module name.
|
|
140
|
+
# "connectors.supaflow_connector_test.connector" -> "connectors.supaflow_connector_test"
|
|
141
|
+
# "supaflow_connector_test.connector" -> "supaflow_connector_test"
|
|
142
|
+
package_fqn = module_name.rsplit(".", 1)[0]
|
|
143
|
+
|
|
144
|
+
# Also derive the bare package name for eviction of unprefixed entries
|
|
145
|
+
bare_pkg = file_path.parent.name # e.g., "supaflow_connector_test"
|
|
146
|
+
|
|
147
|
+
# Evict both the fully-qualified and bare package trees.
|
|
148
|
+
# This handles the case where a prior call used a different prefix
|
|
149
|
+
# or no prefix for the same bare package name.
|
|
150
|
+
_evict_package(package_fqn)
|
|
151
|
+
if bare_pkg != package_fqn:
|
|
152
|
+
_evict_package(bare_pkg)
|
|
153
|
+
|
|
154
|
+
# Load the package __init__.py under its fully-qualified name
|
|
155
|
+
# so that relative imports within the module resolve correctly.
|
|
156
|
+
pkg_init = file_path.parent / "__init__.py"
|
|
157
|
+
if pkg_init.exists():
|
|
158
|
+
pkg_spec = importlib.util.spec_from_file_location(
|
|
159
|
+
package_fqn, pkg_init,
|
|
160
|
+
submodule_search_locations=[str(file_path.parent)],
|
|
161
|
+
)
|
|
162
|
+
if pkg_spec and pkg_spec.loader:
|
|
163
|
+
pkg_module = importlib.util.module_from_spec(pkg_spec)
|
|
164
|
+
sys.modules[package_fqn] = pkg_module
|
|
165
|
+
pkg_spec.loader.exec_module(pkg_module)
|
|
166
|
+
|
|
167
|
+
# Load the target module (e.g., connectors.supaflow_connector_test.connector)
|
|
168
|
+
spec = importlib.util.spec_from_file_location(module_name, file_path)
|
|
169
|
+
if spec is None or spec.loader is None:
|
|
170
|
+
raise ImportError(f"Cannot create module spec for {file_path}")
|
|
171
|
+
module = importlib.util.module_from_spec(spec)
|
|
172
|
+
sys.modules[module_name] = module
|
|
173
|
+
try:
|
|
174
|
+
spec.loader.exec_module(module)
|
|
175
|
+
except Exception:
|
|
176
|
+
sys.modules.pop(module_name, None)
|
|
177
|
+
raise
|
|
178
|
+
return module
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def discover_declarative_connectors(
|
|
182
|
+
connectors_root: Path | None = None,
|
|
183
|
+
module_prefix: str | None = None,
|
|
184
|
+
strict: bool = False,
|
|
185
|
+
) -> list[tuple[str, type]]:
|
|
186
|
+
"""Discover all DeclarativeDltConnector subclasses under a root.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
connectors_root: Directory containing connector packages.
|
|
190
|
+
Defaults to the monorepo ``python/connectors/`` directory.
|
|
191
|
+
module_prefix: Python module prefix for imports.
|
|
192
|
+
Defaults to ``"connectors"`` (monorepo layout).
|
|
193
|
+
Pass ``""`` (empty string) for single-connector repos where
|
|
194
|
+
the package is directly importable from sys.path without a
|
|
195
|
+
parent package prefix.
|
|
196
|
+
strict: If True, raise ImportError instead of skipping connectors
|
|
197
|
+
that fail to import. CLI commands and test suites should use
|
|
198
|
+
strict=True so broken connectors fail loudly instead of
|
|
199
|
+
silently disappearing from validation.
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
List of (class_name, class) tuples, sorted by name.
|
|
203
|
+
"""
|
|
204
|
+
from supaflow_dlt_runtime.declarative import DeclarativeDltConnector
|
|
205
|
+
|
|
206
|
+
root = connectors_root or _DEFAULT_CONNECTORS_ROOT
|
|
207
|
+
# None -> monorepo default; "" -> no prefix (single-connector)
|
|
208
|
+
prefix = module_prefix if module_prefix is not None else _DEFAULT_MODULE_PREFIX
|
|
209
|
+
|
|
210
|
+
if not root.is_dir():
|
|
211
|
+
return []
|
|
212
|
+
|
|
213
|
+
# Ensure the right directory is on sys.path for the connector's own
|
|
214
|
+
# imports (e.g., from supaflow_dlt_runtime import ...).
|
|
215
|
+
if prefix:
|
|
216
|
+
path_entry = str(root.parent)
|
|
217
|
+
else:
|
|
218
|
+
path_entry = str(root)
|
|
219
|
+
if path_entry not in sys.path:
|
|
220
|
+
sys.path.insert(0, path_entry)
|
|
221
|
+
|
|
222
|
+
# When using monorepo defaults, use normal import_module so modules
|
|
223
|
+
# integrate with the standard sys.modules cache. This is necessary for
|
|
224
|
+
# test mocking to work (mocks patch the cached module, and tests that
|
|
225
|
+
# import the same connector via normal import must get the same object).
|
|
226
|
+
#
|
|
227
|
+
# When a non-default root is provided (CLI tooling, standalone repos,
|
|
228
|
+
# temp directories in tests), use file-based loading to avoid cache
|
|
229
|
+
# collisions between different roots that contain same-named packages.
|
|
230
|
+
use_file_loading = connectors_root is not None
|
|
231
|
+
|
|
232
|
+
discovered: list[tuple[str, type]] = []
|
|
233
|
+
for pkg_dir in detect_connector_dirs(root):
|
|
234
|
+
if prefix:
|
|
235
|
+
module_name = f"{prefix}.{pkg_dir.name}.connector"
|
|
236
|
+
else:
|
|
237
|
+
module_name = f"{pkg_dir.name}.connector"
|
|
238
|
+
|
|
239
|
+
try:
|
|
240
|
+
if use_file_loading:
|
|
241
|
+
connector_file = pkg_dir / "connector.py"
|
|
242
|
+
module = _load_module_from_file(module_name, connector_file)
|
|
243
|
+
else:
|
|
244
|
+
module = importlib.import_module(module_name)
|
|
245
|
+
except ImportError:
|
|
246
|
+
if strict:
|
|
247
|
+
raise
|
|
248
|
+
continue
|
|
249
|
+
|
|
250
|
+
for _, obj in inspect.getmembers(module, inspect.isclass):
|
|
251
|
+
if obj is DeclarativeDltConnector:
|
|
252
|
+
continue
|
|
253
|
+
# Skip imported base/helper classes; we only want connector
|
|
254
|
+
# classes defined in this module.
|
|
255
|
+
if obj.__module__ != module.__name__:
|
|
256
|
+
continue
|
|
257
|
+
if issubclass(obj, DeclarativeDltConnector):
|
|
258
|
+
discovered.append((obj.__name__, obj))
|
|
259
|
+
|
|
260
|
+
return sorted(discovered, key=lambda t: t[0])
|