feat: 异步查询楼宇并实时单线程写入CSV

This commit is contained in:
RBP15P
2026-09-10 17:18:15 +08:00
parent 05c751db88
commit 1c95f88e93
4 changed files with 331 additions and 91 deletions
+157
View File
@@ -0,0 +1,157 @@
import asyncio
import csv
from pathlib import Path
import re
import signal
import tempfile
import threading
import unittest
from unittest.mock import patch
from aiohttp import web
from aiohttp.test_utils import TestServer
import GetNRBuildingsData as script
class AsyncBuildingsTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.input = Path(self.directory.name) / "points.csv"
self.output = Path(self.directory.name) / "results.csv"
with self.input.open("w", encoding="utf-8-sig", newline="") as destination:
writer = csv.writer(destination)
writer.writerow(["序号", "经度", "维度"])
writer.writerows([[str(i), str(i), "22"] for i in range(6)])
settings = patch.multiple(script, INPUT_CSV=self.input, OUTPUT_CSV=self.output,
INPUT_ENCODING="utf-8-sig", URL="http://127.0.0.1/wfs", COOKIES="test-session",
START_ROW=1, LIMIT=6, CONCURRENCY=3, REQUEST_INTERVAL=0, MAX_RETRIES=0)
settings.start()
self.addCleanup(settings.stop)
def read_rows(self):
with self.output.open(encoding="utf-8-sig", newline="") as source:
reader = csv.DictReader(source)
return reader.fieldnames, list(reader)
async def test_bounded_concurrency_and_live_single_thread_writes(self):
gate = asyncio.Event()
wrote_early = asyncio.Event()
active, maximum = 0, 0
loop = asyncio.get_running_loop()
writer_threads = set()
real_write = script.StreamingCsvWriter.write_result
def record_write(writer, result):
writer_threads.add(threading.get_ident())
real_write(writer, result)
loop.call_soon_threadsafe(wrote_early.set)
async def handler(request):
nonlocal active, maximum
identifier = int(re.search(r"POINT\((\d+) 22\)", request.query["CQL_FILTER"]).group(1))
active += 1
maximum = max(maximum, active)
try:
if identifier == 0:
await gate.wait()
else:
await asyncio.sleep(0.01 * identifier)
properties = {"building_id": f"building-{identifier}", "metric": identifier}
if identifier == 0:
properties["late_field"] = "last response"
features = [{"id": str(identifier), "properties": properties}]
if identifier == 1:
features = []
if identifier == 2:
features.append({"id": "second", "properties": {"building_id": "second", "extra": [1, 2]}})
return web.json_response({"type": "FeatureCollection", "features": features, "numberMatched": len(features)})
finally:
active -= 1
app = web.Application()
app.router.add_get("/wfs", handler)
async with TestServer(app) as server:
with patch.object(script, "URL", str(server.make_url("/wfs"))), \
patch.object(script.StreamingCsvWriter, "write_result", record_write):
task = asyncio.create_task(script.async_main(handle_signals=False))
try:
await asyncio.wait_for(wrote_early.wait(), 5)
_, early = self.read_rows()
self.assertTrue(early)
self.assertNotIn("0", [row["查询序号"] for row in early])
self.assertFalse(task.done())
finally:
gate.set()
self.assertEqual(await asyncio.wait_for(task, 5), 0)
headers, rows = self.read_rows()
self.assertGreaterEqual(maximum, 2)
self.assertLessEqual(maximum, 3)
self.assertEqual(len(writer_threads), 1)
self.assertNotIn(threading.get_ident(), writer_threads)
self.assertEqual(len(rows), 7)
self.assertEqual({row["查询序号"] for row in rows}, {str(i) for i in range(6)})
self.assertIn("late_field", headers)
self.assertIn("extra", headers)
self.assertTrue(all(None not in row for row in rows))
self.assertEqual(next(row for row in rows if row["查询序号"] == "0")["late_field"], "last response")
self.assertEqual(next(row for row in rows if row["查询序号"] == "1")["查询状态"], "未命中")
self.assertEqual(len([row for row in rows if row["查询序号"] == "2"]), 2)
self.assertEqual(list(Path(self.directory.name).glob("*.tmp")), [])
async def test_writer_failure_cancels_workers_without_queue_deadlock(self):
async def immediate(*args):
return [{"id": "id", "properties": {"building_id": "test"}}]
with patch.object(script, "fetch_features", immediate), \
patch.object(script.StreamingCsvWriter, "write_result", side_effect=OSError("write failed")):
with self.assertRaisesRegex(OSError, "write failed"):
await asyncio.wait_for(script.async_main(handle_signals=False), 5)
async def test_authentication_failure_stops_taking_new_points(self):
calls = 0
async def unauthorized(*args):
nonlocal calls
calls += 1
await asyncio.sleep(0.01)
raise script.AuthenticationError("expired")
with patch.object(script, "fetch_features", unauthorized):
self.assertEqual(await asyncio.wait_for(script.async_main(handle_signals=False), 5), 1)
_, rows = self.read_rows()
self.assertLessEqual(calls, script.CONCURRENCY)
self.assertEqual(len(rows), calls)
self.assertTrue(all(row["查询状态"] == "请求失败" for row in rows))
async def test_interrupt_finishes_inflight_results_before_closing_writer(self):
started = asyncio.Event()
release = asyncio.Event()
calls = 0
async def slow(*args):
nonlocal calls
calls += 1
if calls == script.CONCURRENCY:
started.set()
await release.wait()
return [{"id": "id", "properties": {"building_id": "test"}}]
with patch.object(script, "fetch_features", slow):
task = asyncio.create_task(script.async_main())
try:
await asyncio.wait_for(started.wait(), 5)
signal.raise_signal(signal.SIGINT)
await asyncio.sleep(0)
finally:
release.set()
self.assertEqual(await asyncio.wait_for(task, 5), 1)
_, rows = self.read_rows()
self.assertEqual(calls, script.CONCURRENCY)
self.assertEqual(len(rows), calls)
self.assertTrue(all(row["查询状态"] == "成功" for row in rows))
if __name__ == "__main__":
unittest.main()