import tempfile import unittest import xml.etree.ElementTree as ET import zipfile from pathlib import Path import numpy as np import tifffile from shapely import STRtree from shapely.geometry import Polygon, box import main class SignalRulesTest(unittest.TestCase): def test_signal_level_boundaries(self): self.assertEqual(main.signal_level(None), "无采集信息") self.assertEqual(main.signal_level(-105), "较差") self.assertEqual(main.signal_level(-95), "一般") self.assertEqual(main.signal_level(-94.9), "正常") class RankedHeatmapTest(unittest.TestCase): def test_equal_values_are_not_split_between_colors(self): values = np.array([[10.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) result, thresholds, counts = main.ranked_pixel_rgb_for_values( values, mask, main.EXCELLENT_COLORS, main.EXCELLENT_PERCENT_STEPS, ) self.assertEqual(thresholds, [0.0, 0.0, 0.0]) self.assertEqual(counts, [1, 0, 0, 5]) self.assertTrue(np.all(result[values == 0] == main.EXCELLENT_COLORS[-1])) self.assertTrue(np.all(result[values == 10] == main.EXCELLENT_COLORS[0])) def test_invalid_color_threshold_configuration_fails(self): values = np.array([[1.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) with self.assertRaises(ValueError): main.ranked_pixel_rgb_for_values(values, mask, ((255, 0, 0),), (0.5,)) def test_ranked_colors_can_reuse_existing_thresholds(self): values = np.array([[20.0, 10.0, 5.0, 1.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) result, counts = main.ranked_pixel_rgb_for_values_with_thresholds( values, mask, main.EXCELLENT_COLORS, [15.0, 7.5, 2.5], ) self.assertEqual(counts, [1, 1, 1, 1]) self.assertEqual(result[0, 0].tolist(), list(main.EXCELLENT_COLORS[0])) self.assertEqual(result[0, 1].tolist(), list(main.EXCELLENT_COLORS[1])) self.assertEqual(result[0, 2].tolist(), list(main.EXCELLENT_COLORS[2])) self.assertEqual(result[0, 3].tolist(), list(main.EXCELLENT_COLORS[3])) class UserCountMergeTest(unittest.TestCase): def test_4g_and_5g_counts_are_summed_by_grid20_id_without_duplicates(self): records = {} self.assertTrue(main.merge_user_count_record(records, "shared", (0, 1, 0, 1), 10.0, "5G", True)) self.assertTrue(main.merge_user_count_record(records, "shared", (0, 1, 1, 2), 5.0, "4G")) self.assertTrue(main.merge_user_count_record(records, "4g-only", (0, 1, 1, 2), 7.0, "4G")) self.assertTrue(main.merge_user_count_record(records, "5g-only", (0, 1, 2, 3), 3.0, "5G", True)) self.assertFalse(main.merge_user_count_record(records, " ", (0, 1, 0, 1), 99.0, "4G")) state = main.build_merged_user_count_state(records, 1, 3) metadata = main.merged_user_count_metadata(records, {"5G": {}, "4G": {}}) self.assertEqual(state["value_sum"].tolist(), [[15.0, 7.0, 3.0]]) self.assertEqual(state["value_weight"].tolist(), [[1, 1, 1]]) self.assertEqual(state["painted_cells"], 3) self.assertEqual(metadata["merged_grid_count"], 3) self.assertEqual(metadata["shared_grid_count"], 1) self.assertEqual(metadata["four_g_only_grid_count"], 1) self.assertEqual(metadata["five_g_only_grid_count"], 1) def test_local_summary_render_matches_full_canvas_colors(self): records = {} main.merge_user_count_record(records, "a", (24, 27, 24, 27), 20.0, "5G", True) main.merge_user_count_record(records, "b", (28, 31, 28, 31), 10.0, "5G", True) main.merge_user_count_record(records, "c", (32, 35, 32, 35), 5.0, "4G") thresholds = [15.0, 7.5, 2.5] full_state = main.build_merged_user_count_state(records, 64, 64) full_mask = full_state["value_weight"] > 0 full_values = np.zeros((64, 64), dtype=np.float32) np.divide( full_state["value_sum"], full_state["value_weight"], out=full_values, where=full_mask, ) full_ranked, _ = main.ranked_pixel_rgb_for_values_with_thresholds( full_values, full_mask, main.EXCELLENT_COLORS, thresholds, ) expected = main.smooth_rgb_inside_mask(full_ranked, full_mask, main.HEATMAP_SMOOTH_RADIUS) local = main.render_merged_user_count_records(records, 64, 64, thresholds) actual = np.zeros_like(expected) row_start, row_stop, col_start, col_stop = local["window"] actual[row_start:row_stop, col_start:col_stop] = local["rgb"] np.testing.assert_array_equal(actual, expected) self.assertLess(local["data_mask"].size, full_mask.size) class CompetitorSignalTest(unittest.TestCase): def test_filter_accepts_weak_coverage_or_zero_competitor_samples(self): self.assertTrue(main.competitor_signal_is_eligible(199.0, 1000.0, 1.0, 1.0)) self.assertTrue(main.competitor_signal_is_eligible(199.0, 1000.0, None, 0.0)) self.assertFalse(main.competitor_signal_is_eligible(200.0, 1000.0, 1.0, 1.0)) self.assertFalse(main.competitor_signal_is_eligible(199.0, 1000.0, 20.0, 100.0)) def test_filter_rejects_invalid_ratio_fields(self): invalid_cases = ( (None, 1000.0, 201.0, 1001.0), (1.0, 0.0, 201.0, 1001.0), (-1.0, 1000.0, 201.0, 1001.0), (199.0, 1000.0, None, 1001.0), (199.0, 1000.0, -1.0, 1001.0), (199.0, 1000.0, 1.0, -1.0), ) for values in invalid_cases: with self.subTest(values=values): self.assertEqual(main.competitor_signal_filter_reason(*values), "invalid_fields") def test_competitor_signal_uses_eight_discrete_color_classes(self): values = np.array( [[-200.0, -110.1, -110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0, 0.0, 0.1, np.nan]], dtype=np.float32, ) colors, valid_mask = main.competitor_signal_rsrp_rgb_for_values(values) expected_colors = [ main.COMPETITOR_SIGNAL_RSRP_COLORS[0], main.COMPETITOR_SIGNAL_RSRP_COLORS[0], main.COMPETITOR_SIGNAL_RSRP_COLORS[1], main.COMPETITOR_SIGNAL_RSRP_COLORS[2], main.COMPETITOR_SIGNAL_RSRP_COLORS[3], main.COMPETITOR_SIGNAL_RSRP_COLORS[4], main.COMPETITOR_SIGNAL_RSRP_COLORS[5], main.COMPETITOR_SIGNAL_RSRP_COLORS[6], main.COMPETITOR_SIGNAL_RSRP_COLORS[7], main.COMPETITOR_SIGNAL_RSRP_COLORS[7], ] self.assertEqual(colors[0, :10].tolist(), [list(color) for color in expected_colors]) self.assertEqual(valid_mask.tolist(), [[True] * 10 + [False, False]]) self.assertEqual(colors[0, 10:].tolist(), [[0, 0, 0], [0, 0, 0]]) def test_adjacent_grid_geometries_do_not_share_pixels(self): canvas = { "minx": -0.1, "maxy": 1.0, "pixel_width": 0.25, "pixel_height": 0.25, "width": 9, "height": 4, } left_geometry = box(0, 0, 1, 1) right_geometry = box(1, 0, 2, 1) left_window = main.pixel_window_for_bounds(left_geometry.bounds, **canvas) right_window = main.pixel_window_for_bounds(right_geometry.bounds, **canvas) left_mask = main.pixel_center_mask_for_geometry( left_geometry, left_window, canvas["minx"], canvas["maxy"], canvas["pixel_width"], canvas["pixel_height"], ) right_mask = main.pixel_center_mask_for_geometry( right_geometry, right_window, canvas["minx"], canvas["maxy"], canvas["pixel_width"], canvas["pixel_height"], ) left_pixels = np.zeros((canvas["height"], canvas["width"]), dtype=bool) right_pixels = np.zeros_like(left_pixels) lr0, lr1, lc0, lc1 = left_window rr0, rr1, rc0, rc1 = right_window left_pixels[lr0:lr1, lc0:lc1] = left_mask right_pixels[rr0:rr1, rc0:rc1] = right_mask self.assertFalse(np.any(left_pixels & right_pixels)) self.assertFalse(left_pixels[:, 4].any()) self.assertTrue(right_pixels[:, 4].all()) def test_zero_competitor_samples_render_red_without_rsrp(self): state = { "value_sum": np.array([[-90.0, 0.0]], dtype=np.float32), "value_weight": np.array([[1, 0]], dtype=np.uint16), "zero_total_mask": np.array([[False, True]], dtype=bool), "painted_cells": 2, "skipped_no_value": 0, } market = main.MarketFeature(1, "1-test", "test", box(0, 0, 2, 1)) with tempfile.TemporaryDirectory() as temp_dir: output_path = Path(temp_dir) / main.COMPETITOR_SIGNAL_OUTPUT_FILENAME result = main.render_competitor_signal_raster( state, market, output_path, 0, 1, 1, 1, 2, 1, 2, ) image = tifffile.imread(output_path) self.assertEqual(image[0, 1, :3].tolist(), list(main.COMPETITOR_SIGNAL_RSRP_COLORS[0])) self.assertEqual(image[0, 1, 3], main.HEATMAP_ALPHA) self.assertEqual(result["zero_total_pixels"], 1) def test_smoothing_radius_must_be_a_nonnegative_integer(self): main.validate_smoothing_radius("radius", 0) main.validate_smoothing_radius("radius", 10) for value in (-1, 1.5, True): with self.subTest(value=value): with self.assertRaises(ValueError): main.validate_smoothing_radius("radius", value) class SpatialNameIndexTest(unittest.TestCase): def test_largest_intersection_wins(self): geometries = [box(0, 0, 1, 1), box(0, 0, 2, 2)] index = (STRtree(geometries), geometries, ["小建筑", "大建筑"]) self.assertEqual(main.match_building_info_name(index, box(0, 0, 1.5, 1.5)), "大建筑") def test_batch_matching_matches_scalar_results(self): info_geometries = [box(0, 0, 1, 1), box(0, 0, 2, 2), box(5, 5, 6, 6)] index = (STRtree(info_geometries), info_geometries, ["小建筑", "大建筑", "远端建筑"]) buildings = [box(0, 0, 1.5, 1.5), box(5.2, 5.2, 5.8, 5.8), box(10, 10, 11, 11)] expected = [main.match_building_info_name(index, geometry) for geometry in buildings] self.assertEqual(main.match_building_info_names(index, buildings), expected) class GaussianBlurTest(unittest.TestCase): def test_batch_convolution_matches_scalar_reference(self): array = np.arange(30, dtype=np.float32).reshape(5, 6) kernel = main.gaussian_kernel(2) radius = kernel.size // 2 padded = np.pad(array, ((radius, radius), (0, 0)), mode="edge") moved = np.moveaxis(padded, 0, 0) expected = np.empty_like(array) for index in range(expected.shape[0]): expected[index] = np.tensordot(kernel, moved[index:index + kernel.size], axes=(0, 0)) actual = main.convolve_axis(array, kernel, axis=0) np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-6) padded = np.pad(array, ((0, 0), (radius, radius)), mode="edge") moved = np.moveaxis(padded, 1, 0) expected = np.empty_like(np.moveaxis(array, 1, 0)) for index in range(expected.shape[0]): expected[index] = np.tensordot(kernel, moved[index:index + kernel.size], axes=(0, 0)) actual = main.convolve_axis(array, kernel, axis=1) np.testing.assert_allclose(actual, np.moveaxis(expected, 0, 1), rtol=1e-6, atol=1e-6) class OutputSafetyTest(unittest.TestCase): def test_summary_market_unions_all_market_geometries(self): markets = [ main.MarketFeature(1, "1-a", "a", box(0, 0, 1, 1)), main.MarketFeature(2, "2-b", "b", box(2, 0, 3, 1)), ] summary_market = main.build_summary_market(markets) self.assertEqual(summary_market.code, main.SUMMARY_MARKET_CODE) self.assertEqual(summary_market.geometry.bounds, (0.0, 0.0, 3.0, 1.0)) self.assertEqual(summary_market.geometry.area, 2.0) def test_summary_market_requires_input(self): with self.assertRaises(ValueError): main.build_summary_market([]) def test_summary_market_repairs_invalid_geometry(self): invalid_geometry = Polygon([(0, 0), (1, 1), (1, 0), (0, 1), (0, 0)]) self.assertFalse(invalid_geometry.is_valid) summary_market = main.build_summary_market( [main.MarketFeature(1, "1-a", "a", invalid_geometry)] ) self.assertTrue(summary_market.geometry.is_valid) self.assertFalse(summary_market.geometry.is_empty) def test_raster_layout_respects_pixel_limit(self): original_limit = main.MAX_RASTER_PIXELS main.MAX_RASTER_PIXELS = 100 try: layout = main.market_raster_layout((0, 0, 10, 10), 0.1, 0.1) finally: main.MAX_RASTER_PIXELS = original_limit self.assertLessEqual(layout[6] * layout[7], 100) self.assertGreater(layout[8], 1.0) def test_summary_raster_layout_uses_independent_pixel_limit(self): layout = main.market_raster_layout((0, 0, 10, 10), 0.1, 0.1, 400) self.assertLessEqual(layout[6] * layout[7], 400) self.assertEqual((layout[6], layout[7]), (20, 20)) def test_zip_output_is_complete(self): with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) workspace = root / "workspace" workspace.mkdir() (workspace / "a.txt").write_text("a", encoding="utf-8") (workspace / "b.txt").write_text("b", encoding="utf-8") zip_path = root / "market.zip" market = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) result = main.write_market_zip(workspace, zip_path, market) with zipfile.ZipFile(zip_path) as archive: self.assertEqual(sorted(archive.namelist()), ["a.txt", "b.txt"]) self.assertEqual(result["entries"], ["a.txt", "b.txt"]) self.assertFalse((root / ".market.zip.tmp").exists()) def test_full_source_file_is_copied_without_filtering(self): with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) source = root / "CellData.gpkg" output = root / "result" / "CellData.gpkg" output.parent.mkdir() source.write_bytes(b"cell-data") market = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) result = main.copy_full_source_file(source, output, market) self.assertEqual(output.read_bytes(), b"cell-data") self.assertTrue(result["copied_full_source"]) self.assertEqual(result["bytes"], len(b"cell-data")) class QgisProjectTest(unittest.TestCase): def test_project_extent_tracks_building_info(self): project_xml = b'''\xef\xbb\xbf 0011 100100200200 cell-idCellData./CellData.gpkg|layername=_20260701 BuildingInfo./BuildingInfo.gpkg|layername=BuildingInfo0011 用户量./用户量.tif100100200200100100200200 竟对信号./竟对信号.tif100100200200100100200200 ''' with tempfile.TemporaryDirectory() as temp_dir: root_dir = Path(temp_dir) source_path = root_dir / "source.qgz" output_path = root_dir / "GIS.qgz" with zipfile.ZipFile(source_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: archive.writestr("GIS.qgs", project_xml) archive.writestr("styles.db", b"style-data") market = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) result = main.copy_gis_project_to_market( source_path, output_path, market, (10, 20, 30, 40), (0, -1, 2, 1), include_cell_data=False, ) with zipfile.ZipFile(output_path) as archive: updated_xml = archive.read("GIS.qgs") self.assertTrue(updated_xml.startswith(b"\xef\xbb\xbf