From c81047f9506758a4bb88c190e191c156b6dba39f Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 01:37:36 -0600 Subject: [PATCH 1/2] test(py): run shared reflection_api and flow_server conformance specs --- .github/workflows/python.yml | 2 + .../tests/flow_server_conformance_test.py | 195 +++++++++++++ .../endpoints/reflection_conformance_test.py | 264 ++++++++++++++++++ 3 files changed, 461 insertions(+) create mode 100644 packages/genkit-fastapi/tests/flow_server_conformance_test.py create mode 100644 packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 1a360229a..fb173a989 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -182,6 +182,8 @@ jobs: mkdir -p "$SPEC_DIR" curl -sSfL https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/specs/agent.yaml -o "$SPEC_DIR/agent.yaml" curl -sSfL https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/specs/generate.yaml -o "$SPEC_DIR/generate.yaml" + curl -sSfL https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/specs/reflection_api.yaml -o "$SPEC_DIR/reflection_api.yaml" + curl -sSfL https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/flow_server_tests.yaml -o "$SPEC_DIR/flow_server_tests.yaml" curl -sSfL https://raw.githubusercontent.com/genkit-ai/genkit/main/genkit-tools/genkit-schema.json -o "$SPEC_DIR/genkit-schema.json" echo "GENKIT_SPECS_DIR=$SPEC_DIR" >> "$GITHUB_ENV" diff --git a/packages/genkit-fastapi/tests/flow_server_conformance_test.py b/packages/genkit-fastapi/tests/flow_server_conformance_test.py new file mode 100644 index 000000000..d640c8b07 --- /dev/null +++ b/packages/genkit-fastapi/tests/flow_server_conformance_test.py @@ -0,0 +1,195 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Runs the shared tests/flow_server_tests.yaml spec against a flow served by serve_flow. + +The spec lives in genkit-ai/genkit and is not copied here. JS runs it through +tests/src/flow_server_test.ts against go/tests/test_app, reading the stream +with the ``streamFlow`` client. This harness serves the same ``streamy`` flow +and reads the response the way that client's ``__flowRunEnvelope`` does. +""" + +from __future__ import annotations + +import json +import os +import pathlib +import tempfile +import urllib.request +from typing import Any + +import pytest +import yaml +from fastapi import FastAPI +from genkit_fastapi import serve_flow +from httpx import ASGITransport, AsyncClient +from pydantic import BaseModel + +from genkit import FlowContext, Genkit + +SPEC_UPSTREAM = 'https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/' + +# Same delimiter as __flowStreamDelimiter in js/genkit/src/client/client.ts. +FLOW_STREAM_DELIMITER = '\n\n' + + +def spec_path(relative: str, *, start: pathlib.Path | None = None) -> pathlib.Path: + """Resolve ``tests/`` from genkit-ai/genkit. + + Lookup order: ``GENKIT_SPECS_DIR/`` (CI fetches the files flat), + then ``tests/`` in any parent or in a sibling ``genkit`` checkout, + then a download from the upstream main branch into a temp-dir cache. + """ + name = pathlib.PurePosixPath(relative).name + env_dir = os.environ.get('GENKIT_SPECS_DIR') + if env_dir: + candidate = pathlib.Path(env_dir) / name + if candidate.is_file(): + return candidate + + for parent in (start or pathlib.Path(__file__)).resolve().parents: + candidate = parent / 'tests' / relative + if candidate.is_file(): + return candidate + sibling = parent.parent / 'genkit' / 'tests' / relative + if sibling.is_file(): + return sibling + + cache_dir = pathlib.Path(tempfile.gettempdir()) / 'genkit-specs' + cache_dir.mkdir(parents=True, exist_ok=True) + cached = cache_dir / name + if not cached.is_file(): + tmp_file = cache_dir / f'{name}.{os.getpid()}.tmp' + urllib.request.urlretrieve(SPEC_UPSTREAM + relative, tmp_file) # noqa: S310 - fixed https URL + os.replace(tmp_file, cached) + return cached + + +class StreamyChunk(BaseModel): + """Chunk shape of streamy in go/tests/test_app (``chunk{Count int `json:"count"`}``).""" + + count: int + + +def build_flow_server() -> FastAPI: + """The Python twin of the flow server in go/tests/test_app.""" + ai = Genkit() + + @ai.flow() + async def streamy(count: int, ctx: FlowContext[StreamyChunk]) -> str: + i = 0 + while i < count: + ctx.send_chunk(StreamyChunk(count=i)) + i += 1 + return f'done {count}, streamed: {i} times' + + app = FastAPI() + # Default path is /, the same route Go mounts with "POST /"+a.Name(). + app.include_router(serve_flow(streamy)) + return app + + +def parse_flow_stream(body: str) -> tuple[list[Any], Any]: + """Split an SSE body into (chunks, result) exactly like __flowRunEnvelope. + + Each frame is ``data: `` followed by a blank line. ``message`` frames + are chunks, the ``result`` frame ends the stream, and an ``error`` frame + fails it. A body that ends without a result is an error too. + """ + chunks: list[Any] = [] + buffer = body + while FLOW_STREAM_DELIMITER in buffer: + frame, buffer = buffer.split(FLOW_STREAM_DELIMITER, 1) + payload = json.loads(frame[len('data: ') :]) + if 'message' in payload: + chunks.append(payload['message']) + elif 'result' in payload: + return chunks, payload['result'] + elif 'error' in payload: + error = payload['error'] + raise AssertionError(f'{error.get("status")}: {error.get("message")}\n{error.get("details")}') + else: + raise AssertionError(f'unknown chunk format: {json.dumps(payload)}') + raise AssertionError('stream did not terminate correctly') + + +def _load_spec() -> dict[str, Any]: + with spec_path('flow_server_tests.yaml').open(encoding='utf-8') as stream: + return yaml.safe_load(stream) + + +SPEC = _load_spec() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('test', SPEC['tests'], ids=[f'{t["path"]} data={t["post"]["data"]}' for t in SPEC['tests']]) +async def test_flow_server_spec(test: dict[str, Any]) -> None: + """Each flow in flow_server_tests.yaml streams the spec's chunks, then the spec's result.""" + data = test['post']['data'] + want_message: str = test['response']['message'] + want_result: str = test['response']['result'] + + async with AsyncClient(transport=ASGITransport(app=build_flow_server()), base_url='http://test') as client: + response = await client.post( + f'/{test["path"]}', + json={'data': data}, + headers={'Accept': 'text/event-stream', 'Content-Type': 'application/json'}, + ) + + assert response.status_code == 200, f'Server returned: {response.status_code}: {response.text}' + chunks, result = parse_flow_stream(response.text) + + for count, chunk in enumerate(chunks): + # The JS runner swaps only the first {count} in the message template. + expected = want_message.replace('{count}', str(count), 1) + assert chunk == json.loads(expected), f'chunk {count}: got {chunk!r}, want {expected}' + # The spec pins a string, so also match JSON.stringify output byte for byte. + assert json.dumps(chunk, separators=(',', ':'), ensure_ascii=False) == expected + assert len(chunks) == data, f'unexpected number of stream chunks received: got {len(chunks)}, want: {data}' + assert result == want_result.replace('{count}', str(len(chunks))) + + +def test_parse_flow_stream_follows_client_envelope() -> None: + """Message frames become chunks, the result frame ends the read, error and truncated streams fail.""" + body = 'data: {"message":{"count":0}}\n\ndata: {"result":"done 1, streamed: 1 times"}\n\n' + assert parse_flow_stream(body) == ([{'count': 0}], 'done 1, streamed: 1 times') + + with pytest.raises(AssertionError, match='INTERNAL: kitchen offline'): + parse_flow_stream('data: {"error":{"status":"INTERNAL","message":"kitchen offline"}}\n\n') + with pytest.raises(AssertionError, match='did not terminate'): + parse_flow_stream('data: {"message":{"count":0}}\n\n') + with pytest.raises(AssertionError, match='unknown chunk format'): + parse_flow_stream('data: {"order":"ramen"}\n\n') + + +def test_spec_path_downloads_flow_server_spec_from_tests_root( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """flow_server_tests.yaml sits at tests/, not tests/specs/, upstream; the fallback URL keeps that path.""" + fetched: list[str] = [] + + def fake_urlretrieve(src: str, dest: pathlib.Path) -> None: + fetched.append(src) + pathlib.Path(dest).write_text('tests: []\n', encoding='utf-8') + + monkeypatch.delenv('GENKIT_SPECS_DIR', raising=False) + monkeypatch.setattr(tempfile, 'gettempdir', lambda: str(tmp_path / 'tmp')) + monkeypatch.setattr(urllib.request, 'urlretrieve', fake_urlretrieve) + + path = spec_path('flow_server_tests.yaml', start=tmp_path / 'isolated' / 'repo' / 'conformance_test.py') + + assert fetched == ['https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/flow_server_tests.yaml'] + assert path == tmp_path / 'tmp' / 'genkit-specs' / 'flow_server_tests.yaml' diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py new file mode 100644 index 000000000..0187ee845 --- /dev/null +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py @@ -0,0 +1,264 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Runs the shared tests/specs/reflection_api.yaml spec against the Python reflection server. + +The spec lives in genkit-ai/genkit and is not copied here. JS runs it through +tests/src/reflection_api_test.ts and Go through go/tests/api_test.go. This +harness mirrors both: the app under test defines the same ``customReflector`` +echo model, and responses are compared the way Go's ``compare1`` does (every +key in the spec must match, extra keys in the response are ignored), skipping +the keys the JS runner excludes. +""" + +from __future__ import annotations + +import json +import os +import pathlib +import tempfile +import urllib.request +from typing import Any + +import pytest +import yaml +from httpx import ASGITransport, AsyncClient + +from genkit import FinishReason, Genkit, Message, ModelResponse, Part +from genkit._core._reflection import create_reflection_asgi_app +from genkit.model import GenerationUsage, ModelContext, ModelRequest + +SPEC_UPSTREAM = 'https://raw.githubusercontent.com/genkit-ai/genkit/main/tests/' + +# Same list as diffJSON's excludeKeys in tests/src/reflection_api_test.ts. +# Schemas and descriptions differ by SDK on purpose; telemetry, latency and +# usage are runtime values the JS runner never pins. +EXCLUDED_KEYS = frozenset({ + 'outputSchema', + 'inputSchema', + 'description', + 'telemetry', + 'latencyMs', + 'usage', +}) + + +def spec_path(relative: str, *, start: pathlib.Path | None = None) -> pathlib.Path: + """Resolve ``tests/`` from genkit-ai/genkit. + + Lookup order: ``GENKIT_SPECS_DIR/`` (CI fetches the files flat), + then ``tests/`` in any parent or in a sibling ``genkit`` checkout, + then a download from the upstream main branch into a temp-dir cache. + """ + name = pathlib.PurePosixPath(relative).name + env_dir = os.environ.get('GENKIT_SPECS_DIR') + if env_dir: + candidate = pathlib.Path(env_dir) / name + if candidate.is_file(): + return candidate + + for parent in (start or pathlib.Path(__file__)).resolve().parents: + candidate = parent / 'tests' / relative + if candidate.is_file(): + return candidate + sibling = parent.parent / 'genkit' / 'tests' / relative + if sibling.is_file(): + return sibling + + cache_dir = pathlib.Path(tempfile.gettempdir()) / 'genkit-specs' + cache_dir.mkdir(parents=True, exist_ok=True) + cached = cache_dir / name + if not cached.is_file(): + tmp_file = cache_dir / f'{name}.{os.getpid()}.tmp' + urllib.request.urlretrieve(SPEC_UPSTREAM + relative, tmp_file) # noqa: S310 - fixed https URL + os.replace(tmp_file, cached) + return cached + + +def go_compare(got: Any, want: Any, path: str = '', excluded: frozenset[str] = EXCLUDED_KEYS) -> list[str]: # noqa: ANN401 - decoded JSON + """Diff ``got`` against ``want`` with go/tests/api_test.go ``compare1`` semantics. + + Every key in ``want`` must be in ``got`` and match. Keys only in ``got`` are + ignored. Lists must have the same length. Keys in ``excluded`` are skipped + at any depth, as in the JS runner. + """ + where = path or 'top level' + if isinstance(want, dict): + if not isinstance(got, dict): + return [f'{where}: want object, got {type(got).__name__}'] + msgs: list[str] = [] + for key, want_value in want.items(): + if key in excluded: + continue + if key not in got: + msgs.append(f'{where}: missing key {key!r}') + continue + msgs.extend(go_compare(got[key], want_value, f'{path}.{key}' if path else key, excluded)) + return msgs + if isinstance(want, list): + if not isinstance(got, list): + return [f'{where}: want list, got {type(got).__name__}'] + if len(got) != len(want): + return [f'{where}: got list length {len(got)}, want {len(want)}'] + msgs = [] + for i, (got_item, want_item) in enumerate(zip(got, want, strict=True)): + msgs.extend(go_compare(got_item, want_item, f'{path}.{i}' if path else str(i), excluded)) + return msgs + # bool is an int subclass in Python; JSON true must not equal 1. + if isinstance(want, bool) or isinstance(got, bool): + same = type(got) is type(want) and got == want + else: + same = got == want + return [] if same else [f'{where}: got {got!r}, want {want!r}'] + + +def go_marshal(request: ModelRequest) -> str: + """Serialize a ModelRequest the way go/tests/test_app's echo does with json.Marshal. + + - Go struct fields marshal in declaration order, and the generated Go types + declare them alphabetically, so keys are sorted. + - Go uses compact separators and ``omitempty`` drops nil fields. + - ``exclude_unset`` drops ``output``: Python's ModelRequest fills it with + an empty ``OutputConfig`` default, while Go keeps a nil pointer that + ``omitempty`` omits and JS leaves it undefined. Without this the echo + would read ``{"messages":[...],"output":{}}``. + """ + body = request.model_dump(mode='json', by_alias=True, exclude_none=True, exclude_unset=True) + return json.dumps(body, sort_keys=True, separators=(',', ':'), ensure_ascii=False) + + +def build_test_app() -> Genkit: + """The Python twin of tests/test_js_app and go/tests/test_app.""" + ai = Genkit() + + async def custom_reflector(request: ModelRequest, ctx: ModelContext) -> ModelResponse: + message = Message(role='model', content=[Part.from_text(go_marshal(request))]) + # Same usage the JS app reports through getBasicUsageStats. + return ModelResponse( + finish_reason=FinishReason.STOP, + message=message, + usage=GenerationUsage.from_messages(request.messages, message), + ) + + ai.define_model('customReflector', custom_reflector) + return ai + + +def _load_spec() -> dict[str, Any]: + with spec_path('specs/reflection_api.yaml').open(encoding='utf-8') as stream: + return yaml.safe_load(stream) + + +def _test_id(test: dict[str, Any]) -> str: + post = test.get('post') + if post is None: + return f'GET {test["path"]}' + key = post.get('key') if isinstance(post, dict) else None + return f'POST {test["path"]} {key}' if key else f'POST {test["path"]}' + + +SPEC = _load_spec() + + +@pytest.mark.asyncio +@pytest.mark.parametrize('test', SPEC['tests'], ids=[_test_id(t) for t in SPEC['tests']]) +async def test_reflection_api_spec(test: dict[str, Any]) -> None: + """Each request in reflection_api.yaml gets 200 and a body matching the spec.""" + app = create_reflection_asgi_app(build_test_app()._registry) + async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: + if 'post' in test: + response = await client.post(test['path'], json=test['post']) + else: + response = await client.get(test['path']) + + assert response.status_code == 200, f'{test["path"]}: got status {response.status_code}: {response.text}' + got = response.json() + msgs = go_compare(got, test['body']) + assert not msgs, '\n'.join(msgs) + '\n\ngot:\n' + json.dumps(got, indent=2, sort_keys=True) + + +def test_go_compare_matches_go_semantics() -> None: + """Missing and mismatched spec keys fail; extra response keys and excluded keys don't.""" + want = {'result': {'finishReason': 'stop', 'usage': {'inputCharacters': 5}, 'flags': [True]}} + + assert go_compare({'result': {'finishReason': 'stop', 'flags': [True], 'custom': {}}}, want) == [] + assert go_compare({'result': {'finishReason': 'length', 'flags': [True]}}, want) == [ + "result.finishReason: got 'length', want 'stop'" + ] + assert go_compare({'result': {'flags': [True]}}, want) == ["result: missing key 'finishReason'"] + assert go_compare({'result': {'finishReason': 'stop', 'flags': [1]}}, want) == ['result.flags.0: got 1, want True'] + assert go_compare({'result': {'finishReason': 'stop', 'flags': []}}, want) == [ + 'result.flags: got list length 0, want 1' + ] + + +def test_go_marshal_matches_go_test_app_bytes() -> None: + """The echo text is byte-for-byte what Go's json.Marshal produces for the spec input.""" + request = ModelRequest.model_validate({'messages': [{'role': 'user', 'content': [{'text': 'hello'}]}]}) + + assert go_marshal(request) == '{"messages":[{"content":[{"text":"hello"}],"role":"user"}]}' + + +@pytest.mark.parametrize( + ('relative', 'url'), + [ + ('specs/reflection_api.yaml', SPEC_UPSTREAM + 'specs/reflection_api.yaml'), + ('flow_server_tests.yaml', SPEC_UPSTREAM + 'flow_server_tests.yaml'), + ], + ids=['tests/specs', 'tests root'], +) +def test_spec_path_downloads_when_no_checkout( + relative: str, url: str, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """With no env dir and no genkit checkout nearby, the spec is fetched once from upstream main.""" + fetched: list[str] = [] + + def fake_urlretrieve(src: str, dest: pathlib.Path) -> None: + fetched.append(src) + pathlib.Path(dest).write_text('tests: []\n', encoding='utf-8') + + monkeypatch.delenv('GENKIT_SPECS_DIR', raising=False) + monkeypatch.setattr(tempfile, 'gettempdir', lambda: str(tmp_path / 'tmp')) + monkeypatch.setattr(urllib.request, 'urlretrieve', fake_urlretrieve) + start = tmp_path / 'isolated' / 'repo' / 'conformance_test.py' + + first = spec_path(relative, start=start) + second = spec_path(relative, start=start) + + assert fetched == [url] + assert first == second == tmp_path / 'tmp' / 'genkit-specs' / pathlib.PurePosixPath(relative).name + assert first.read_text(encoding='utf-8') == 'tests: []\n' + assert list(first.parent.glob('*.tmp')) == [] + + +def test_spec_path_prefers_env_dir_then_sibling_checkout( + tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """GENKIT_SPECS_DIR wins; without it a sibling genkit checkout is used before any download.""" + monkeypatch.setattr(urllib.request, 'urlretrieve', lambda *_: pytest.fail('should not download')) + start = tmp_path / 'genkit-python' / 'packages' / 'conformance_test.py' + sibling = tmp_path / 'genkit' / 'tests' / 'flow_server_tests.yaml' + sibling.parent.mkdir(parents=True) + sibling.write_text('app: flow_server\n', encoding='utf-8') + env_dir = tmp_path / 'ci-specs' + env_dir.mkdir() + (env_dir / 'flow_server_tests.yaml').write_text('app: ci\n', encoding='utf-8') + + monkeypatch.setenv('GENKIT_SPECS_DIR', str(env_dir)) + assert spec_path('flow_server_tests.yaml', start=start) == env_dir / 'flow_server_tests.yaml' + + monkeypatch.delenv('GENKIT_SPECS_DIR') + assert spec_path('flow_server_tests.yaml', start=start) == sibling From 2e22152a3ec11aa2400d34167fdd6fecfd4124d8 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Tue, 10 Nov 2026 16:56:54 -0600 Subject: [PATCH 2/2] test(py): harden conformance spec download cleanup, SSE prefix, and health probes --- .../tests/flow_server_conformance_test.py | 17 ++++++++++++++--- .../endpoints/reflection_conformance_test.py | 10 ++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/packages/genkit-fastapi/tests/flow_server_conformance_test.py b/packages/genkit-fastapi/tests/flow_server_conformance_test.py index d640c8b07..3f0d04439 100644 --- a/packages/genkit-fastapi/tests/flow_server_conformance_test.py +++ b/packages/genkit-fastapi/tests/flow_server_conformance_test.py @@ -73,8 +73,12 @@ def spec_path(relative: str, *, start: pathlib.Path | None = None) -> pathlib.Pa cached = cache_dir / name if not cached.is_file(): tmp_file = cache_dir / f'{name}.{os.getpid()}.tmp' - urllib.request.urlretrieve(SPEC_UPSTREAM + relative, tmp_file) # noqa: S310 - fixed https URL - os.replace(tmp_file, cached) + try: + urllib.request.urlretrieve(SPEC_UPSTREAM + relative, tmp_file) # noqa: S310 - fixed https URL + os.replace(tmp_file, cached) + except BaseException: + tmp_file.unlink(missing_ok=True) + raise return cached @@ -113,7 +117,9 @@ def parse_flow_stream(body: str) -> tuple[list[Any], Any]: buffer = body while FLOW_STREAM_DELIMITER in buffer: frame, buffer = buffer.split(FLOW_STREAM_DELIMITER, 1) - payload = json.loads(frame[len('data: ') :]) + if not frame.startswith('data: '): + raise AssertionError(f'expected SSE data: prefix, got {frame!r}') + payload = json.loads(frame.removeprefix('data: ')) if 'message' in payload: chunks.append(payload['message']) elif 'result' in payload: @@ -143,6 +149,9 @@ async def test_flow_server_spec(test: dict[str, Any]) -> None: want_result: str = test['response']['result'] async with AsyncClient(transport=ASGITransport(app=build_flow_server()), base_url='http://test') as client: + # Non-SSE probe sent by tests/src/flow_server_test.ts before streaming tests run. + probe = await client.post(f'/{test["path"]}', json={'data': 1}) + assert probe.status_code == 200 response = await client.post( f'/{test["path"]}', json={'data': data}, @@ -173,6 +182,8 @@ def test_parse_flow_stream_follows_client_envelope() -> None: parse_flow_stream('data: {"message":{"count":0}}\n\n') with pytest.raises(AssertionError, match='unknown chunk format'): parse_flow_stream('data: {"order":"ramen"}\n\n') + with pytest.raises(AssertionError, match='expected SSE data: prefix'): + parse_flow_stream('event: {"result":"done"}\n\n') def test_spec_path_downloads_flow_server_spec_from_tests_root( diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py index 0187ee845..04b9e3292 100644 --- a/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_conformance_test.py @@ -83,8 +83,12 @@ def spec_path(relative: str, *, start: pathlib.Path | None = None) -> pathlib.Pa cached = cache_dir / name if not cached.is_file(): tmp_file = cache_dir / f'{name}.{os.getpid()}.tmp' - urllib.request.urlretrieve(SPEC_UPSTREAM + relative, tmp_file) # noqa: S310 - fixed https URL - os.replace(tmp_file, cached) + try: + urllib.request.urlretrieve(SPEC_UPSTREAM + relative, tmp_file) # noqa: S310 - fixed https URL + os.replace(tmp_file, cached) + except BaseException: + tmp_file.unlink(missing_ok=True) + raise return cached @@ -179,6 +183,8 @@ async def test_reflection_api_spec(test: dict[str, Any]) -> None: """Each request in reflection_api.yaml gets 200 and a body matching the spec.""" app = create_reflection_asgi_app(build_test_app()._registry) async with AsyncClient(transport=ASGITransport(app=app), base_url='http://test') as client: + health = await client.get('/api/__health') + assert health.status_code == 200 if 'post' in test: response = await client.post(test['path'], json=test['post']) else: