import pytest from leads.feed_guard import (StageError, assert_produced, check_payload, count_rows, fetch_to_cache) def test_a_failed_pull_keeps_the_previous_cache(tmp_path): cache = tmp_path / "ASH.jsonl" cache.write_text('{"parcel":"A-1"}\n') def broken_source(): yield {"parcel": "A-1"} raise ConnectionError("source went away mid-export") with pytest.raises(ConnectionError): fetch_to_cache("ASH", broken_source(), cache) assert cache.read_text() == '{"parcel":"A-1"}\n' assert not cache.with_suffix(".tmp").exists() def test_an_empty_export_does_not_replace_good_data(tmp_path): cache = tmp_path / "ASH.jsonl" cache.write_text('{"parcel":"A-1"}\n') with pytest.raises(StageError, match="0 rows"): fetch_to_cache("ASH", iter([]), cache) assert cache.read_text() == '{"parcel":"A-1"}\n' def test_a_complete_pull_replaces_the_cache(tmp_path): cache = tmp_path / "ASH.jsonl" cache.write_text('{"parcel":"old"}\n') assert fetch_to_cache("ASH", iter([{"parcel": "A-1"}, {"parcel": "A-2"}]), cache) == 2 assert count_rows(cache) == 2 def test_an_error_inside_a_200_response_is_a_failure(): with pytest.raises(RuntimeError, match="server error"): check_payload({"error": {"code": 400, "message": "Invalid query"}}) assert check_payload({"features": []}) == {"features": []} def test_a_header_only_csv_stops_the_stage(tmp_path): out = tmp_path / "owners.csv" out.write_text("name,tier\n") with pytest.raises(StageError) as err: assert_produced("portfolios", [out], resume="run --from portfolios") assert "produced 0 rows" in str(err.value) assert "resume with: run --from portfolios" in str(err.value) def test_a_missing_output_stops_the_stage(tmp_path): with pytest.raises(StageError, match="not created"): assert_produced("portfolios", [tmp_path / "owners.csv"]) def test_quoted_newlines_are_one_row(tmp_path): out = tmp_path / "owners.csv" out.write_text('name,note\n"KESTREL BAY HOLDINGS LLC","line one\nline two"\n') assert count_rows(out) == 1 assert_produced("portfolios", [out])