Files
MarketGrid/tests/test_nr_buildings.py
T

225 lines
11 KiB
Python

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
from shapely import wkt
from shapely.geometry import Point
import GetNRBuildingsData as script
def square(x, y, half=0.001):
return (f"MULTIPOLYGON ((({x - half} {y - half},{x + half} {y - half},"
f"{x + half} {y + half},{x - half} {y + half},{x - half} {y - half})))")
class InteriorPointTest(unittest.TestCase):
def test_point_lies_inside_concave_shapes_where_centroid_and_bbox_center_do_not(self):
# U 形:外包框中心与质心都落在缺口里。
u_shape = ("POLYGON ((0 0, 10 0, 10 10, 7 10, 7 3, 3 3, 3 10, 0 10, 0 0))")
# L 形:外包框中心落在外面。
l_shape = ("POLYGON ((0 0, 10 0, 10 2, 2 2, 2 10, 0 10, 0 0))")
for text in (u_shape, l_shape):
geometry = wkt.loads(text)
x1, y1, x2, y2 = geometry.bounds
self.assertFalse(Point((x1 + x2) / 2, (y1 + y2) / 2).within(geometry), text)
lon, lat = script.interior_point(text)
self.assertTrue(Point(float(lon), float(lat)).within(geometry), text)
def test_multipolygon_uses_largest_part_and_invalid_input_is_rejected(self):
text = ("MULTIPOLYGON (((0 0, 1 0, 1 1, 0 1, 0 0)), ((5 5, 9 5, 9 9, 5 9, 5 5)))")
lon, lat = script.interior_point(text)
self.assertTrue(Point(float(lon), float(lat)).within(wkt.loads("POLYGON ((5 5, 9 5, 9 9, 5 9, 5 5))")))
for bad in ("", "not wkt", "POINT (1 1)", "POLYGON EMPTY", None):
with self.assertRaises(ValueError):
script.interior_point(bad)
def test_detect_encoding_falls_back_between_gbk_and_utf8(self):
with tempfile.TemporaryDirectory() as directory:
row = "WKT,building_id\n\"POLYGON ((0 0,1 0,1 1,0 0))\",甲楼\n"
utf8_bom = Path(directory) / "utf8_bom.csv"
utf8_bom.write_text(row, encoding="utf-8-sig")
utf8 = Path(directory) / "utf8.csv"
utf8.write_text(row, encoding="utf-8")
gbk = Path(directory) / "gbk.csv"
gbk.write_text(row, encoding="gbk")
ascii_only = Path(directory) / "ascii.csv"
ascii_only.write_text("WKT,building_id\n\"POLYGON ((0 0,1 0,1 1,0 0))\",JM1\n", encoding="ascii")
other = Path(directory) / "other.csv"
other.write_text("序号,经度\n1,2\n", encoding="gbk")
# 首选 gbk 但内容是 UTF-8(含/不含 BOM)时自动切换,反之亦然。
self.assertEqual(script.detect_encoding(utf8_bom, "gbk"), "utf-8-sig")
self.assertEqual(script.detect_encoding(utf8, "gbk"), "utf-8-sig")
self.assertEqual(script.detect_encoding(gbk, "utf-8-sig"), "gbk")
self.assertEqual(script.detect_encoding(gbk, "gbk"), "gbk")
self.assertEqual(script.detect_encoding(ascii_only, "gbk"), "gbk")
self.assertEqual(script.detect_encoding(ascii_only, "utf-8-sig"), "utf-8-sig")
with self.assertRaisesRegex(ValueError, "building_id"):
script.detect_encoding(other, "gbk")
with utf8.open(encoding=script.detect_encoding(utf8, "gbk"), newline="") as source:
self.assertEqual(list(csv.DictReader(source))[0]["building_id"], "甲楼")
def test_real_sample_rows_from_source_file(self):
path = Path(script.INPUT_CSV)
if not path.is_file():
self.skipTest("源文件不存在")
with path.open(encoding=script.detect_encoding(path, script.INPUT_ENCODING), newline="") as source:
reader = csv.DictReader(source)
for _, row in zip(range(200), reader):
geometry = wkt.loads(row["WKT"])
lon, lat = script.interior_point(row["WKT"])
self.assertTrue(Point(float(lon), float(lat)).within(geometry), row["building_id"])
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(["WKT", "building_id"])
# 以 (i, 22) 为中心的正方形,内部点应为 POINT(i 22)。
writer.writerows([[square(i, 22), str(i)] 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="gbk", newline="", errors="replace") 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 = round(float(re.search(r"POINT\(([-\d.]+) ([-\d.]+)\)", 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()