Repository navigation
Expand file tree
/
Copy pathtest_carpool.py
More file actions
2711 lines (2321 loc) · 157 KB
/
Copy pathtest_carpool.py
File metadata and controls
2711 lines (2321 loc) · 157 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: AGPL-3.0-or-later
"""离线测试:用假的高德客户端验证选站和拼车逻辑。
行车分钟 = 直线公里数(60km/h);公共交通分钟 = 公里数 / 3 + 30(火车约 180km/h 加市内接驳)。
python3 -m unittest -v test_carpool.py
"""
import ast
import contextlib
import datetime as dt
import importlib
import inspect
import io
import json
import math
import os
import random
import re
import subprocess
import sys
import tempfile
import threading
import time
import tomllib
import unittest
import urllib.error
import urllib.request
from http.server import ThreadingHTTPServer
from pathlib import Path
from unittest import mock
import base
import browser
import carpool
import share
import service
import taxi
import ui
from carpool import Place, km_between
from model import OUT
VENUE = "118.0,30.0"
NEAR = "118.0,30.8" # 目的地正北约 89km:离目的地最近的站
WEST = "117.0,30.0" # 目的地正西约 96km:恰好在老王的路上
WANG = "116.0,30.0" # 老王从西边开过来,直达约 193km
class FakeAmap:
"""只实现 carpool 用到的接口。"""
def __init__(self, places=None, pois=None, no_transit=(), around=None, routes_fail=()):
self.places = places or {}
self.pois = pois or []
self.around = around # 可选:(中心, 半径, 页码) -> POI 列表,测翻页和各圈不同的结果
self.routes_fail = set(routes_fail) # 这些车主的路线查不到
self.around_calls: list[tuple] = [] # 地点搜索调用(含翻页)
self.route_calls: list[tuple] = [] # 驾车路线调用
self.no_transit = set(no_transit) # 这些站查不到公共交通方案
self.calls = 0
def geocode(self, address, city=None):
self.calls += 1
lng, lat = carpool.parse_loc(self.places[address])
return Place(address, lng, lat, "fake")
find_station = geocode
def stations_near(self, center, radius_km):
self.calls += 1
return self.pois
def stations_around(self, center, radius_km, page=1):
self.calls += 1
self.around_calls.append((center, radius_km, page))
return self.around(center, radius_km, page) if self.around else self.pois
def drive_minutes(self, origins, dest):
self.calls += 1
return [km_between(o, dest) for o in origins]
def transit(self, a, b, date, clock):
self.calls += 1
if b.name in self.no_transit:
return None
return km_between(a, b) / 3 + 30, f"G1 某站→{b.name}"
def search(self, keywords, city=None, types=None):
self.calls += 1
return [{"name": keywords, "location": self.places.get(keywords, VENUE), "detail": "fake"}]
def drive_path(self, places):
# 沿直线插值,像真实路线一样有密集的点
self.calls += 1
pts = [[a.lat + (b.lat - a.lat) * k / 20, a.lng + (b.lng - a.lng) * k / 20]
for a, b in zip(places, places[1:]) for k in range(20)]
return pts + [[places[-1].lat, places[-1].lng]]
def _fake_routes(self, places, strategy=0, alt=False):
self.route_calls.append((places, strategy, alt))
if any(n in p.name for n in self.routes_fail for p in places):
raise carpool.AmapError("查不到路线")
path = self.drive_path(places)
km = sum(km_between(Place("", b[1], b[0]), Place("", a[1], a[0])) for a, b in zip(path, path[1:]))
routes = [{"path": path, "km": km, "minutes": km}] # 假高德:1 公里 1 分钟
if alt: # 备选路线:整体往北偏 0.3 度
routes.append({"path": [[lat + 0.3, lng] for lat, lng in path], "km": km * 1.05, "minutes": km * 1.05})
return routes
FakeAmap.drive_routes = _fake_routes
def person(name, loc, **kw):
return {"name": name, "from": name, "location": loc, **kw}
def config(people, stations=(("近站", NEAR), ("西站", WEST)), **options):
return {
"venue": {"name": "目的地", "location": VENUE},
"options": options,
"stations": [{"name": n, "location": loc} for n, loc in stations],
"people": people,
}
def best_plan(cfg, amap=None):
amap = amap or FakeAmap()
trip = carpool.load_trip(cfg, amap)
pts = carpool.points_of(trip)
T = carpool.build_matrix(amap, pts, set())
carpool.estimate_rail(amap, trip)
return carpool.solve(trip, T), pts, T, trip
class SolveTest(unittest.TestCase):
def test_picks_station_on_drivers_way_not_nearest(self):
plans, *_ = best_plan(config([
person("老王", WANG, car_seats=3),
person("小陈", "114.0,34.0"),
]))
best = plans[0]
self.assertEqual(best.rides, {"小陈": ("老王", "st:西站")})
self.assertLess(best.detour, 2)
def test_seat_limit_sends_rest_to_taxi_at_nearest_station(self):
plans, *_ = best_plan(config([
person("老王", WANG, car_seats=1),
person("小陈", "114.0,34.0"),
person("小李", "113.0,35.0"),
]))
best = plans[0]
self.assertEqual(len(best.rides), 1)
self.assertEqual(list(best.taxi.values()), ["st:近站"])
def test_home_pickup_on_the_way(self):
plans, *_ = best_plan(config([
person("老王", WANG, car_seats=3),
person("小李", "116.5,30.0"),
person("小陈", "114.0,34.0"),
]))
best = plans[0]
self.assertEqual(best.rides["小李"], ("老王", "home:小李"))
self.assertEqual(best.rides["小陈"], ("老王", "st:西站"))
self.assertEqual(best.routes[0].stops, ("home:小李", "st:西站"))
def test_rail_min_limits_stations(self):
plans, *_ = best_plan(config([
person("老王", WANG, car_seats=3),
person("小陈", "114.0,34.0", rail_min={"近站": 120}),
]))
best = plans[0]
self.assertEqual(best.rides, {})
self.assertEqual(best.taxi, {"小陈": "st:近站"})
self.assertEqual(best.routes[0].stops, ())
def test_detour_limit_respected(self):
plans, *_ = best_plan(config([
person("老王", WANG, car_seats=3, max_detour_min=10),
person("小陈", "114.0,34.0", stations=["近站"]),
]))
for plan in plans:
for r in plan.routes:
self.assertLessEqual(r.detour, 10)
def test_no_drivers_all_taxi(self):
plans, *_ = best_plan(config([person("小陈", "114.0,34.0"), person("我", "121.5,31.2")]))
self.assertEqual(plans[0].taxi, {"小陈": "st:近站", "我": "st:近站"})
def test_taxi_station_follows_riders_rail_direction(self):
east = "119.0,30.0" # 与西站到目的地距离相同,但在东边
plans, *_ = best_plan(config(
[person("我", "121.5,31.2"), person("小陈", "114.0,30.5")],
stations=(("东站", east), ("西站", WEST)),
))
self.assertEqual(plans[0].taxi, {"我": "st:东站", "小陈": "st:西站"})
def test_station_without_transit_is_excluded_with_warning(self):
plans, _, _, trip = best_plan(config([
person("老王", WANG, car_seats=3),
person("小陈", "114.0,34.0"),
]), FakeAmap(no_transit={"西站"}))
self.assertEqual(plans[0].rides, {})
self.assertEqual(plans[0].taxi, {"小陈": "st:近站"})
self.assertTrue(any("没查到 小陈 到 西站" in w for w in trip.warnings))
def test_no_transit_at_all_falls_back_to_flat_cost(self):
plans, _, _, trip = best_plan(config([
person("老王", WANG, car_seats=3),
person("小陈", "114.0,34.0"),
]), FakeAmap(no_transit={"西站", "近站"}))
self.assertEqual(plans[0].rides, {"小陈": ("老王", "st:西站")})
self.assertTrue(any("改按每站 60 分钟估算" in w for w in trip.warnings))
def test_travel_date_normalized(self):
*_, trip = best_plan(config([person("小陈", "114.0,34.0")], travel_date="2026-10-07"))
self.assertEqual(trip.travel_date, "2026-10-7")
def test_stranded_when_no_station_allowed(self):
plans, *_ = best_plan(config([
person("老王", WANG, car_seats=3),
person("小陈", "114.0,34.0", stations=["不存在站"], pickup_at_home=False),
]))
self.assertEqual(plans[0].stranded, ["小陈"])
def test_unknown_station_name_warns(self):
*_, trip = best_plan(config([person("小陈", "114.0,34.0", stations=["不存在站"])]))
self.assertTrue(any("不存在站" in w for w in trip.warnings))
def test_many_people_finishes_quickly(self):
stations = [(f"站{i}", f"{117.0 + 0.2 * i},{29.5 + 0.1 * i}") for i in range(10)]
drivers = [person(f"车主{i}", f"{115.0 + i * 0.3},{29.0 + i * 0.4}", car_seats=2) for i in range(4)]
riders = [person(f"乘客{i}", f"{112.0 + i},{33.0 + i * 0.2}") for i in range(6)]
start = time.perf_counter()
plans, *_ = best_plan(config(drivers + riders, stations=stations, max_detour_min=40))
elapsed = time.perf_counter() - start
self.assertTrue(plans)
self.assertLess(elapsed, 60)
print(f"\n4 车 6 乘客 10 站:{elapsed:.1f}s,最优方案 {len(plans[0].rides)} 人搭车")
class DiscoverTest(unittest.TestCase):
def test_filters_noise_dedupes_and_sorts(self):
venue = Place("v", 118.0, 30.0)
pois = [
{"name": "西站", "location": WEST, "typecode": "150200"},
{"name": "西站-进站口", "location": WEST, "typecode": "150200"},
{"name": "近站(东广场)", "location": NEAR, "typecode": "150200"},
{"name": "近站", "location": NEAR, "typecode": "150200"},
{"name": "近站", "location": NEAR, "typecode": "150200"},
{"name": "远站", "location": "110.0,30.0", "typecode": "150200"},
{"name": "某地铁站", "location": NEAR, "typecode": "150500"},
]
got = carpool.pick_stations(pois, venue, radius_km=120, limit=10)
self.assertEqual([p.name for p in got], ["近站", "西站"])
def test_auto_discovery_when_no_stations(self):
pois = [{"name": "近站", "location": NEAR}, {"name": "西站", "location": WEST}]
cfg = config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")])
del cfg["stations"]
report = carpool.run(cfg, FakeAmap(pois=pois))
self.assertIn("自动搜出来的", report)
self.assertIn("西站(接 小陈)", report)
class RenderTest(unittest.TestCase):
def test_report_has_plan_table_and_links(self):
cfg = config([
person("老王", WANG, car_seats=3),
person("老张", "118.5,31.5", car_seats=2),
person("小陈", "114.0,34.0"),
])
report = carpool.run(cfg, FakeAmap())
self.assertIn("## 推荐方案", report)
self.assertIn("## 候选站对比", report)
self.assertIn("https://uri.amap.com/navigation?from=116.000000,30.000000,", report)
self.assertIn("&via=117.000000,30.000000,", report)
self.assertIn("https://uri.amap.com/marker?position=118.000000,30.000000&name=", report)
self.assertIn("## 不开车的人到各站要多久", report)
self.assertIn("G1 某站→西站", report)
def test_resolves_addresses_through_client(self):
amap = FakeAmap(places={"杭州": WANG, "武汉": "114.0,34.0", "场地地址": VENUE, "西站": WEST})
cfg = {
"venue": {"name": "目的地", "address": "场地地址"},
"stations": [{"name": "西站"}],
"people": [{"name": "老王", "from": "杭州", "car_seats": 2}, {"name": "小陈", "from": "武汉"}],
}
self.assertIn("西站(接 小陈)", carpool.run(cfg, amap))
class StationLookupTest(unittest.TestCase):
def test_unknown_station_fails_instead_of_geocoding(self):
class NoStation(FakeAmap):
def find_station(self, name, city=None):
return None
cfg = config([person("小陈", "114.0,34.0")])
cfg["stations"] = [{"name": "清河西站"}]
with self.assertRaises(SystemExit) as ctx:
carpool.load_trip(cfg, NoStation(places={"清河西站": "124.0,42.0"}))
self.assertIn("city", str(ctx.exception))
class RetryTest(unittest.TestCase):
def ok(self, payload):
return io.BytesIO(json.dumps(payload).encode())
def test_retries_connection_reset_then_succeeds(self):
replies = [ConnectionResetError(104, "Connection reset by peer"),
carpool.urllib.error.URLError(ConnectionResetError(104, "reset")),
self.ok({"status": "1", "geocodes": []})]
with mock.patch("carpool.urllib.request.urlopen", side_effect=replies) as urlopen, \
mock.patch("carpool.time.sleep"):
self.assertIsNone(carpool.Amap("k").geocode("某地"))
self.assertEqual(urlopen.call_count, 3)
def test_retries_qps_limit(self):
replies = [self.ok({"status": "0", "info": "CUQPS_HAS_EXCEEDED_THE_LIMIT", "infocode": "10019"}),
self.ok({"status": "1", "geocodes": []})]
with mock.patch("carpool.urllib.request.urlopen", side_effect=replies), mock.patch("carpool.time.sleep"):
self.assertIsNone(carpool.Amap("k").geocode("某地"))
def test_gives_up_with_clear_error(self):
with mock.patch("carpool.urllib.request.urlopen", side_effect=ConnectionResetError(104, "reset")), \
mock.patch("carpool.time.sleep"), self.assertRaises(carpool.AmapError) as ctx:
carpool.Amap("k").geocode("某地")
self.assertIn("连不上高德", str(ctx.exception))
def test_quota_error_stops_without_retry(self):
reply = self.ok({"status": "0", "info": "DAILY_QUERY_OVER_LIMIT", "infocode": "10003"})
with mock.patch("carpool.urllib.request.urlopen", return_value=reply) as urlopen, \
mock.patch("carpool.time.sleep"), self.assertRaises(carpool.QuotaError) as ctx:
carpool.Amap("k").geocode("某地")
self.assertEqual(urlopen.call_count, 1)
self.assertIn("配额已用完", str(ctx.exception))
def test_quota_error_not_swallowed_downstream(self):
class QuotaAmap(FakeAmap):
def transit(self, a, b, date, clock):
raise carpool.QuotaError("配额已用完")
def drive_path(self, places):
raise carpool.QuotaError("配额已用完")
cfg = config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")])
with self.assertRaises(carpool.QuotaError): # 估算用时时不能当成「这个站查不到」
carpool.plan_trip(cfg, QuotaAmap())
cfg["people"][1]["rail_min"] = {"西站": 100}
with self.assertRaises(carpool.QuotaError): # 取路线时不能悄悄改画直线
service.compute(cfg, QuotaAmap())
def test_api_error_not_retried(self):
reply = self.ok({"status": "0", "info": "INVALID_USER_KEY", "infocode": "10001"})
with mock.patch("carpool.urllib.request.urlopen", return_value=reply) as urlopen, \
mock.patch("carpool.time.sleep"), self.assertRaises(carpool.AmapError):
carpool.Amap("k").geocode("某地")
self.assertEqual(urlopen.call_count, 1)
class TrainScheduleTest(unittest.TestCase):
def setUp(self):
self.cfg = config([
person("老王", WANG, car_seats=3),
person("小陈", "114.0,34.0", trains={"西站": "G1 小陈家07:00→西站10:00"}, note="带了喜糖"),
])
def test_trains_derive_minutes_and_limit_stations(self):
trip = carpool.load_trip(self.cfg, FakeAmap())
self.assertEqual(trip.people[1].rail_min, {"西站": 180 + 45})
self.cfg["options"] = {"station_access_min": 30}
self.assertEqual(carpool.load_trip(self.cfg, FakeAmap()).people[1].rail_min, {"西站": 210})
def test_driver_departure_backed_out_from_train(self):
plans, pts, T, trip = best_plan(self.cfg)
best = plans[0]
sched = carpool.route_schedule(best.routes[0], carpool.pickup_ready(best, trip), T)
ready = 10 * 60 + 15 # 10:00 到站 + 15 分钟出站
self.assertAlmostEqual(sched["depart"], ready - T[("car:老王", "st:西站")])
self.assertAlmostEqual(sched["times"]["venue"], ready + T[("st:西站", "venue")])
report = carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
self.assertIn(f"建议 **{carpool.clock(sched['depart'])} 出发**", report)
def test_share_page(self):
amap = FakeAmap()
state = service.compute(self.cfg, amap)
html = share.render_share(state, 0)
for text in ("G1 小陈家07:00→西站10:00", "上 <b>老王</b> 的车", "10:15", "带了喜糖", "uri.amap.com/navigation"):
self.assertIn(text, html)
self.assertNotIn('"lng": 114.0', html) # 不开车的人家的位置不进方案页
self.assertNotIn("[30.0, 116.0]", html) # 车主出发地不放精确位置:路线从约 2 公里外开始
self.assertNotRegex(html, r'"lng": 116\.0[,}]')
self.assertNotIn("116.000000,30.000000", html) # 导航链接也不写出发地:起点留空,手机上用当前位置
self.assertIn("老王 出发", html)
def test_share_page_expiry_and_print(self):
state = service.compute(self.cfg, FakeAmap())
html = share.render_share(state, 0, expires=dt.date(2027, 4, 5))
self.assertIn("这一页会在 2027-04-05 前后自动删除", html)
self.assertNotIn("自动删除", share.render_share(state, 0)) # 本地版没有保留期,不写这行
for text in ("window.print()", "@media print", "break-inside: avoid", "data:image/svg+xml"):
self.assertIn(text, html)
def test_share_page_hides_home_pickup(self):
cfg = config([person("老王", WANG, car_seats=3), person("小李", "116.5,30.0"), person("小陈", "114.0,34.0")])
state = service.compute(cfg, FakeAmap())
html = share.render_share(state, 0)
self.assertIn("到家附近接,具体地点在群里约", html)
self.assertNotIn("116.500000,30.000000", html) # 地图链接、导航链接都不指向小李家
self.assertNotIn("[30.0, 116.5]", html) # 小李家附近的路线不画
class BrowserBridgeTest(unittest.TestCase):
def setUp(self):
self._amap, browser.amap, browser._last = browser.amap, FakeAmap(), None
def tearDown(self):
browser.amap, browser._last = self._amap, None
def call(self, method, **args):
return json.loads(browser.handle(method, json.dumps(args)))
def test_plan_then_share(self):
self.assertIn("先点", self.call("share", plan=0)["error"])
cfg = config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")])
out = self.call("plan", config=cfg)
self.assertEqual(out["plans"][0]["rides"], {"小陈": ["老王", "st:西站"]})
self.assertIsNotNone(out["plans"][0]["routes"][0]["direct_path"]) # 直达路线用来对比绕路
self.assertTrue(self.call("share", plan=0)["html"].startswith("<!doctype html>"))
self.assertIn("没有方案", self.call("share", plan=7)["error"])
ms = int(dt.datetime(2027, 4, 5, 23, 30, tzinfo=dt.timezone(dt.timedelta(hours=8))).timestamp() * 1000) # 北京时间深夜,不能按 UTC 取日期
self.assertIn("这一页会在 2027-04-05 前后自动删除", self.call("share", plan=0, expires=ms)["html"])
self.assertNotIn("自动删除", self.call("share", plan=0)["html"])
def test_errors_become_messages(self):
self.assertIn("people", self.call("plan", config=config([]))["error"])
self.assertIn("未知操作", self.call("nope")["error"])
def test_prefetch_fills_cache_then_get_hits_it(self):
amap = browser.BrowserAmap(pause=0)
q1 = amap.geocode_query("杭州东站")
q2 = amap.distance_query([Place("a", 1, 2)], Place("b", 3, 4))
replies = {"results": [{"status": "1", "geocodes": []}, {"status": "0", "info": "ENGINE_RESPONSE_DATA_ERROR"}]}
with mock.patch.object(amap, "_post_json", return_value=replies) as post:
amap.prefetch([q1, q2, q1]) # 重复的只发一次
self.assertEqual(len(post.call_args[0][1]["requests"]), 2)
with mock.patch.object(amap, "_fetch", side_effect=AssertionError("不该再请求")):
self.assertIsNone(amap.geocode("杭州东站"))
self.assertNotIn(f"{q2[0]}?{carpool.urllib.parse.urlencode(q2[1])}", amap.cache) # 失败的留给逐个请求
def test_prefetch_stops_on_quota(self):
amap = browser.BrowserAmap(pause=0)
reply = {"results": [{"status": "0", "info": "USER_DAILY_QUERY_OVER_LIMIT", "infocode": "10044"}]}
with mock.patch.object(amap, "_post_json", return_value=reply), self.assertRaises(carpool.QuotaError):
amap.prefetch([amap.geocode_query("某地")])
def test_prefetch_network_failure_is_silent(self):
amap = browser.BrowserAmap(pause=0)
with mock.patch.object(amap, "_post_json", side_effect=ConnectionError("断网")):
amap.prefetch([amap.geocode_query("某地")])
self.assertEqual(amap.cache, {})
def test_share_tooltips_are_plain_text(self):
# 地图提示框里的成员名字不能当 HTML 解析(审计 S-13)
self.assertNotIn(".bindTooltip(r.label", share.TEMPLATE)
self.assertIn("function text(s)", share.TEMPLATE)
def test_browser_single_request_posts_query_in_body(self):
# 单个请求也走 POST 批量接口:地点文字不出现在网址上(审计 S-12/D-14)
amap = browser.BrowserAmap("/api/t/abc", pause=0)
sent = []
def fake_post(url, payload):
sent.append((url, payload))
return {"results": [{"status": "1", "info": "OK", "geocodes": []}]}
with mock.patch.object(amap, "_post_json", side_effect=fake_post):
data = amap._fetch(amap._url("/v3/geocode/geo", "address=%E5%AE%8F%E6%9D%91"))
self.assertEqual(data["info"], "OK")
self.assertEqual(sent, [("/api/t/abc/amap-batch", {"requests": [{"path": "/v3/geocode/geo", "query": "address=%E5%AE%8F%E6%9D%91"}]})])
with mock.patch.object(amap, "_post_json", return_value={"results": [{"status": "0", "info": "NETWORK_ERROR", "error": "连不上"}]}):
with self.assertRaises(ConnectionError):
amap._fetch(amap._url("/v3/distance", "a=1"))
with mock.patch.object(amap, "_post_json", return_value={"error": "需要用编辑链接打开", "info": "UNAUTHORIZED"}):
self.assertEqual(amap._fetch(amap._url("/v3/distance", "a=1"))["info"], "UNAUTHORIZED")
def test_browser_urls_go_through_proxy_without_key(self):
self.assertEqual(browser.BrowserAmap("/api/t/abc")._url("/v3/distance", "a=1"), "/api/t/abc/amap/v3/distance?a=1")
class ResolveAndSuggestTest(unittest.TestCase):
def test_text_places_are_written_back(self):
amap = FakeAmap(places={"场地地址": VENUE, "杭州": WANG, "武汉": "114.0,34.0", "西站": WEST})
cfg = {
"venue": {"name": "目的地", "address": "场地地址"},
"stations": [{"name": "西站"}, {"name": "近站", "location": NEAR}],
"people": [{"name": "老王", "from": "杭州", "car_seats": 2}, {"name": "小陈", "from": "武汉"}],
}
out = service.plan_payload(service.compute(cfg, amap))
self.assertEqual({r["path"]: r["location"] for r in out["resolved"]}, {
"venue": "118.000000,30.000000", "people.0": "116.000000,30.000000",
"people.1": "114.000000,34.000000", "stations.0": "117.000000,30.000000",
}) # 近站已经有坐标,不在里面
def test_suggest_finds_station_on_drivers_way_and_filters_freight(self):
pois = [{"name": n, "location": loc, "typecode": "150200"} for n, loc in
[("西站", WEST), ("近站", NEAR), ("货运站", "117.5,30.0"), ("远站", "110.0,30.0"), ("西站-进站口", WEST)]]
# 近站在目的地以北约 89 公里:目的地周边 50 公里搜不到,靠周围那一圈搜到
cfg = config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")], stations=())
out = service.suggest_stations(cfg, FakeAmap(pois=pois), valid_names={"西", "近", "远"})
names = [s["name"] for s in out["stations"]]
self.assertEqual(names[:2], ["西站", "近站"]) # 西站在老王路上,绕路最少
self.assertNotIn("货运站", names) # 12306 里没有
self.assertEqual(out["stations"][0]["best"], {"driver": "老王", "detour": 0})
def test_suggest_skips_existing_stations(self):
pois = [{"name": "西站", "location": WEST}, {"name": "近站", "location": NEAR}]
cfg = config([person("老王", WANG, car_seats=3)], stations=(("西站", WEST),))
self.assertEqual([s["name"] for s in service.suggest_stations(cfg, FakeAmap(pois=pois))["stations"]], ["近站"])
def test_progress_is_reported_by_stage(self):
seen = []
carpool.progress = lambda label, done, total: seen.append((label, done, total))
try:
service.compute(config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")]), FakeAmap())
finally:
carpool.progress = None
labels = list(dict.fromkeys(label for label, _, _ in seen))
self.assertEqual(labels[:2], ["定位目的地、成员和车站", "查询行车时间"])
self.assertIn("比较各种接人组合", labels)
self.assertEqual(labels[-1], "获取路线轨迹")
self.assertIn(("查询行车时间", 3, 4), seen) # 目的地、两个车站、小陈家
def test_trip_limit_errors_stop_like_quota(self):
with self.assertRaises(carpool.QuotaError) as ctx:
carpool.check_quota("TRIP_DAILY_LIMIT", "这个行程今天的高德调用已到上限")
self.assertIn("行程今天", str(ctx.exception))
def test_emergency_and_budget_infos_stop_like_quota(self):
for info in ("PUBLIC_PAUSED", "TRIP_BLOCKED", "MONTHLY_BUDGET"):
with self.assertRaises(carpool.QuotaError, msg=info) as ctx:
carpool.check_quota(info, "站点暂时停用了公共额度")
self.assertIn("额度", str(ctx.exception))
carpool.check_quota("OK") # 普通返回不受影响
class ReturnTripTest(unittest.TestCase):
"""返程插件:目的地 → 送人点 → 车主家,送到站要赶得上车次。"""
def cfg(self, train="G2 西站20:30→小陈家23:30", depart="18:00", drives=True):
c = config([person("老王", WANG, car_seats=3, return_drives=drives),
person("小陈", "114.0,34.0", return_trains={"西站": train})])
c["return"] = {"enabled": True, "depart_time": depart}
return c
def run_trip(self, cfg):
return carpool.plan_trip(cfg, FakeAmap())
def test_drop_off_on_the_way_home(self):
trip, pts, T, _ = self.run_trip(self.cfg())
best = trip.back_plans[0]
self.assertEqual(best.rides, {"小陈": ("老王", "st:西站")})
self.assertLess(best.detour, 2) # 西站就在老王回家的路上
times = carpool.stop_times(best.routes[0], T, trip.back)
self.assertAlmostEqual(times["st:西站"], 18 * 60 + T[("venue", "st:西站")])
self.assertAlmostEqual(times["car:老王"], 18 * 60 + T[("venue", "st:西站")] + T[("st:西站", "car:老王")])
def test_cannot_catch_train(self):
# 19:30 发车要 18:50 前到;18:00 出发开 96 分钟,19:36 才到:送不了,打车也赶不上
trip, pts, T, plans = self.run_trip(self.cfg(train="G2 西站19:30→小陈家22:30"))
back = trip.back_plans[0]
self.assertEqual((back.rides, back.taxi, back.stranded), ({}, {}, ["小陈"]))
self.assertIn("赶不上任何一个候选站的车次", carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans)))
def test_driver_not_driving_back(self):
trip, *_ = self.run_trip(self.cfg(drives=False))
back = trip.back_plans[0]
self.assertEqual(back.rides, {})
self.assertEqual(back.taxi, {"小陈": "st:西站"})
self.assertEqual(back.routes[0].stops, ())
def test_outbound_unchanged_by_return(self):
with_back = self.run_trip(self.cfg())[3]
cfg = self.cfg()
del cfg["return"]
without = self.run_trip(cfg)[3]
self.assertEqual([(p.rides, round(p.detour, 3)) for p in with_back], [(p.rides, round(p.detour, 3)) for p in without])
def test_report_has_return_section(self):
trip, pts, T, plans = self.run_trip(self.cfg())
report = carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
self.assertIn("## 返程(18:00 散场后出发,发车前 40 分钟到站)", report)
self.assertIn("送 小陈,赶 G2 西站20:30→小陈家23:30", report)
def test_share_page_and_payload_have_return(self):
state = service.compute(self.cfg(), FakeAmap())
payload = service.plan_payload(state)
self.assertEqual(payload["back"]["depart"], "18:00")
self.assertEqual(payload["back"]["plans"][0]["rides"], {"小陈": ["老王", "st:西站"]})
self.assertIsNotNone(payload["back"]["plans"][0]["routes"][0]["path"])
html = share.render_share(state, 0, 0)
self.assertIn("返程 · 18:00 散场后出发", html)
self.assertIn("坐 <b>G2 西站20:30→小陈家23:30</b>", html)
self.assertNotIn("116.000000,30.000000", html) # 返程导航也不指向车主家
def test_missing_depart_time_is_an_error(self):
cfg = self.cfg()
cfg["return"]["depart_time"] = ""
with self.assertRaises(SystemExit):
self.run_trip(cfg)
class ReturnOnlyTest(unittest.TestCase):
"""去程和返程各有开关:只规划返程时,不算去程,也不用去程的车次、日期。"""
def cfg(self, **options):
c = config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0", return_trains={"西站": "G2 西站20:30→小陈家23:30"})],
outbound=False, **options)
c["return"] = {"enabled": True, "depart_time": "18:00", "date": "2026-10-18"}
return c
def test_only_return_gets_plans(self):
trip, pts, T, plans = carpool.plan_trip(self.cfg(), FakeAmap())
self.assertEqual((plans, trip.outbound), ([], False))
self.assertEqual(trip.back_plans[0].rides, {"小陈": ("老王", "st:西站")})
self.assertEqual(trip.travel_date, "2026-10-18") # 没有去程日期可借用,取返程日期
def test_same_return_plans_as_with_outbound(self):
both = self.cfg()
del both["options"]["outbound"]
both["options"]["travel_date"] = "2026-10-17"
only = carpool.plan_trip(self.cfg(), FakeAmap())[0].back_plans
also = carpool.plan_trip(both, FakeAmap())[0].back_plans
self.assertEqual([(p.rides, p.taxi, round(p.cost, 3)) for p in only], [(p.rides, p.taxi, round(p.cost, 3)) for p in also])
def test_matrix_only_asks_for_return_directions(self):
_, _, T, _ = carpool.plan_trip(self.cfg(), FakeAmap())
self.assertFalse([k for k in T if k[0] != k[1] and (k[0].startswith("car:") or k[1] == "venue")]) # 没有「从车主家出发」和「到目的地」
self.assertIn(("venue", "car:老王"), T)
self.assertIn(("st:西站", "car:老王"), T)
cfg = self.cfg()
del cfg["options"]["outbound"]
trip = carpool.load_trip(cfg, FakeAmap()) # 默认只查去程
out = carpool.build_matrix(FakeAmap(), carpool.points_of(trip), set())
self.assertFalse([k for k in out if k[0] != k[1] and (k[0] == "venue" or k[1].startswith("car:"))])
def test_both_off_is_rejected_before_any_amap_call(self):
amap = FakeAmap()
cfg = self.cfg()
del cfg["return"]
with self.assertRaises(SystemExit) as ctx:
carpool.plan_trip(cfg, amap)
self.assertIn("至少要规划一段", str(ctx.exception))
cfg["return"] = {"enabled": False, "depart_time": "18:00", "date": "2026-10-18"}
with self.assertRaises(SystemExit):
carpool.plan_trip(cfg, amap)
self.assertEqual(amap.calls, 0)
def test_return_only_needs_a_date(self):
cfg = self.cfg()
del cfg["return"]["date"]
with self.assertRaises(SystemExit) as ctx:
carpool.plan_trip(cfg, FakeAmap())
self.assertIn("返程日期", str(ctx.exception))
def test_report_has_no_outbound_wording(self):
trip, pts, T, plans = carpool.plan_trip(self.cfg(), FakeAmap())
report = carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
self.assertTrue(report.startswith("# 返程方案:"))
for word in ("去程", "## 结论", "## 推荐方案", "备选方案", "站→目的地", "不开车的人到各站要多久", "接人"):
self.assertNotIn(word, report)
self.assertIn("## 返程(18:00 散场后出发", report)
self.assertIn("目的地→站车程", report)
self.assertIn("送 小陈,赶 G2 西站20:30→小陈家23:30", report)
def test_payload_and_share_page_only_have_return(self):
state = service.compute(self.cfg(), FakeAmap())
payload = service.plan_payload(state)
self.assertEqual((payload["outbound"], payload["plans"]), (False, []))
self.assertEqual(payload["back"]["plans"][0]["rides"], {"小陈": ["老王", "st:西站"]})
html = share.render_share(state, 0, 0)
self.assertIn("返程方案 1", html)
self.assertIn("返程 · 18:00 散场后出发", html)
self.assertIn("坐 <b>G2 西站20:30→小陈家23:30</b>", html)
for word in ("<h2>开车的</h2>", "<h2>坐车的</h2>", "去程", "出发地出发"):
self.assertNotIn(word, html)
self.assertNotIn("116.000000,30.000000", html) # 地图和链接都不指向车主家
self.assertNotIn("[30.0, 116.0]", html)
self.assertNotIn("@@", html)
def test_share_choice_is_checked(self):
state = service.compute(self.cfg(), FakeAmap())
with self.assertRaises(SystemExit) as ctx:
share.render_share(state, 0, 5)
self.assertIn("没有返程方案 6", str(ctx.exception))
both = service.compute(ReturnTripTest().cfg(), FakeAmap())
with self.assertRaises(SystemExit):
share.render_share(both, 3, 0)
def test_share_page_names_the_chosen_combination(self):
state = service.compute(ReturnTripTest().cfg(), FakeAmap())
self.assertIn("去程方案 2 + 返程方案 2", share.render_share(state, 1, 1))
no_back = service.compute(config([person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")]), FakeAmap())
self.assertIn("去程方案 1", share.render_share(no_back, 0))
self.assertNotIn("返程方案", share.render_share(no_back, 0))
def test_bridge_shares_return_only(self):
saved = browser.amap, browser._last
browser.amap, browser._last = FakeAmap(), None
try:
out = json.loads(browser.handle("plan", json.dumps({"config": self.cfg()})))
self.assertEqual(out["plans"], [])
html = json.loads(browser.handle("share", json.dumps({"plan": -1, "back_plan": 0})))["html"]
self.assertTrue(html.startswith("<!doctype html>"))
self.assertIn("没有返程方案", json.loads(browser.handle("share", json.dumps({"back_plan": 4})))["error"])
finally:
browser.amap, browser._last = saved
def test_suggest_stations_follows_the_way_home(self):
pois = [{"name": n, "location": loc, "typecode": "150200"} for n, loc in [("西站", WEST), ("近站", NEAR)]]
cfg = self.cfg()
cfg["stations"] = []
out = service.suggest_stations(cfg, FakeAmap(pois=pois))
self.assertEqual([s["name"] for s in out["stations"]][:2], ["西站", "近站"]) # 西站在老王回家的路上
self.assertEqual(out["stations"][0]["best"], {"driver": "老王", "detour": 0})
self.assertEqual(out["stations"][0]["to_venue"], round(km_between(Place("", 118, 30), Place("", 117, 30)))) # 目的地到站
def test_toml_keeps_the_return_table(self):
cfg = {"venue": {"name": "v"}, "options": {"outbound": False}, "return": {"enabled": True, "depart_time": "18:00", "date": "2026-10-18"},
"people": [{"name": "甲"}]}
self.assertEqual(tomllib.loads(carpool.dump_toml(cfg)), cfg)
class LeaveTimeTest(unittest.TestCase):
"""个人离场时间:车主几点走车就几点走;乘客准备好后最多等 max_wait_min;打车的人从自己的离场时间出发。"""
def cfg(self, driver=None, rider=None, train="G2 西站22:30→小陈家23:30", depart="18:00", **rider_kw):
driver_kw = {} if driver is None else {"leave_time": driver}
rider_kw = {**rider_kw, **({} if rider is None else {"leave_time": rider})}
c = config([person("老王", WANG, car_seats=3, **driver_kw), person("小陈", "114.0,34.0", return_trains={"西站": train}, **rider_kw)])
c["return"] = {"enabled": True, "depart_time": depart}
return c
def back(self, cfg):
trip, pts, T, plans = carpool.plan_trip(cfg, FakeAmap())
return trip, trip.back_plans[0], carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
def test_same_as_depart_time_changes_nothing(self):
def key(cfg):
return [(p.rides, p.taxi, p.stranded, round(p.cost, 3)) for p in carpool.plan_trip(cfg, FakeAmap())[0].back_plans]
self.assertEqual(key(self.cfg()), key(self.cfg(driver="18:00", rider="18:00")))
def test_driver_leaving_earlier_cannot_take_the_rider(self):
_, plan, report = self.back(self.cfg(driver="17:30"))
self.assertEqual((plan.rides, plan.taxi), ({}, {"小陈": "st:西站"}))
self.assertIn("17:30 从目的地直接回家", report)
def test_waiting_over_the_limit_cannot_board(self):
_, plan, _ = self.back(self.cfg(driver="18:45")) # 乘客 18:00 就绪,要等 45 分钟,超过默认的 30
self.assertEqual(plan.rides, {})
cfg = self.cfg(driver="18:45")
cfg["return"]["max_wait_min"] = 60
trip, plan, report = self.back(cfg)
self.assertEqual(trip.back.max_wait, 60)
self.assertEqual(plan.rides, {"小陈": ("老王", "st:西站")})
self.assertIn("18:45 从目的地出发", report)
self.assertIn("小陈等 45分钟", report)
def test_short_wait_is_fine_and_shown(self):
_, plan, report = self.back(self.cfg(driver="18:20"))
self.assertEqual(plan.rides, {"小陈": ("老王", "st:西站")})
self.assertIn("小陈等 20分钟", report)
def test_arrival_is_timed_from_the_drivers_leave_time(self):
# 车主 18:30 走,西站 96 分钟,20:06 到;乘客的车 20:30 发,要在 19:50 前到:赶不上
_, plan, _ = self.back(self.cfg(driver="18:30", train="G2 西站20:30→小陈家23:30"))
self.assertEqual(plan.rides, {})
_, plan, _ = self.back(self.cfg(driver="18:00", train="G2 西站20:30→小陈家23:30"))
self.assertEqual(plan.rides, {"小陈": ("老王", "st:西站")})
def test_taxi_leaves_at_own_time(self):
late = self.cfg(train="G2 西站19:30→小陈家22:30")
late["people"][0]["return_drives"] = False
self.assertEqual(self.back(late)[1].stranded, ["小陈"]) # 18:00 走赶不上 19:30 的车(和不填离场时间时一样)
early = self.cfg(train="G2 西站19:30→小陈家22:30", rider="17:00")
early["people"][0]["return_drives"] = False
trip, plan, report = self.back(early)
self.assertEqual((plan.stranded, plan.taxi), ([], {"小陈": "st:西站"}))
self.assertIn("17:00 从目的地一起打车去", report)
def test_taxi_group_with_different_times_goes_separately(self):
cfg = self.cfg(train="G2 西站22:30→a", rider="17:30", stations=["西站"])
cfg["people"][0]["return_drives"] = False
cfg["people"].append(person("小李", "113.0,35.0", return_trains={"西站": "G2 西站22:30→b"}, leave_time="19:00", stations=["西站"]))
_, plan, report = self.back(cfg)
self.assertEqual(plan.taxi, {"小陈": "st:西站", "小李": "st:西站"})
self.assertEqual(plan.taxi_cars, 2) # 差 90 分钟,各打各的车,各自从自己的离场时间出发
self.assertIn("小陈 17:30 从目的地一起打车去", report)
self.assertIn("小李 19:00 从目的地一起打车去", report)
def test_party_uses_its_registered_time(self):
for driver, carried in (("18:00", 0), ("18:30", 2)): # 同行的一组 18:30 就绪:车主 18:00 就走了,带不上
_, plan, _ = self.back(self.cfg(driver=driver, rider="18:30", party=2))
self.assertEqual(plan.carried, carried, driver)
def test_payload_and_share_page_show_each_cars_time(self):
state = service.compute(self.cfg(driver="18:20"), FakeAmap())
payload = service.plan_payload(state)
self.assertEqual(payload["back"]["plans"][0]["routes"][0]["depart"], "18:20")
html = share.render_share(state, 0, 0)
self.assertIn("返程 · 18:00 散场后出发", html) # 标题仍是默认的散场时间
self.assertIn("你 18:00 离场,等 20分钟", html)
self.assertRegex(html, r'<span class="t">18:20</span><span>从目的地出发')
def test_bad_leave_time_is_rejected(self):
for bad in ("25:00", "八点", "18:7"):
with self.assertRaises(SystemExit, msg=bad) as ctx:
carpool.load_trip(self.cfg(rider=bad), FakeAmap())
self.assertIn("小陈的离场时间", str(ctx.exception))
carpool.load_trip(self.cfg(rider="8:05"), FakeAmap())
self.assertIsNone(carpool.load_trip(self.cfg(), FakeAmap()).people[1].leave)
class TaxiPoolTest(unittest.TestCase):
"""拼车省钱:没搭上车的人,在多花不超过上限的前提下尽量拼一辆;到站或离场时间相差太多的拆成两辆;一辆最多 4 人。"""
def pair(self, **options):
# 老王绕路上限只有默认的 30 分钟,接不了小李;小李的最快站是西站,小陈的是近站,但近站对小李也只多花 20.9 分钟
cfg = config([person("老王", WANG, car_seats=3), person("小李", "116.5,30.4"), person("小陈", "114.0,34.0")], **options)
plans, *_ = best_plan(cfg)
return next(p for p in plans if not p.rides)
def test_save_mode_pools_two_people_with_different_fastest_stations(self):
save = self.pair()
self.assertEqual(save.taxi, {"小李": "st:近站", "小陈": "st:近站"})
self.assertEqual(save.taxi_cars, 1)
fast = self.pair(taxi_mode="fast")
self.assertEqual(fast.taxi, {"小李": "st:西站", "小陈": "st:近站"})
self.assertEqual(fast.taxi_cars, 2)
self.assertGreater(save.taxi_min, fast.taxi_min) # 拼车省钱,但总分钟多了一点
self.assertLess(save.taxi_ride, fast.taxi_ride) # 车数 × 车程少了
def test_extra_limit_is_respected(self):
# 小李去近站多花 20.9 分钟,小陈去西站多花 10.6 分钟
plan = self.pair(taxi_pool_extra_min=5) # 两人都超过上限:不拼
self.assertEqual((plan.taxi, plan.taxi_cars), ({"小李": "st:西站", "小陈": "st:近站"}, 2))
plan = self.pair(taxi_pool_extra_min=11) # 只有小陈能多走一点:一起去西站
self.assertEqual((plan.taxi, plan.taxi_cars), ({"小李": "st:西站", "小陈": "st:西站"}, 1))
plan = self.pair(taxi_pool_extra_min=21) # 两个站都行:去近站,车程短一点,车费省一点
self.assertEqual((plan.taxi, plan.taxi_cars), ({"小李": "st:近站", "小陈": "st:近站"}, 1))
def test_bad_taxi_mode_is_rejected(self):
with self.assertRaises(SystemExit) as ctx:
carpool.load_trip(config([person("小陈", "114.0,34.0")], taxi_mode="cheap"), FakeAmap())
self.assertIn("taxi_mode", str(ctx.exception))
def riders_to_one_station(self, arrivals, **options):
people = [person(f"乘客{i}", "114.0,34.0", trains={"近站": f"G{i} 07:00→{arr}"}) for i, arr in enumerate(arrivals)]
plans, pts, T, trip = best_plan(config(people, stations=(("近站", NEAR),), **options))
return plans[0], carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
def test_arrivals_far_apart_take_separate_cars(self):
plan, report = self.riders_to_one_station(["10:00", "10:20"]) # 差 20 分钟,在 30 分钟以内:一辆
self.assertEqual(plan.taxi_cars, 1)
self.assertIn("乘客0、乘客1 坐高铁到 **近站**", report)
plan, report = self.riders_to_one_station(["10:00", "11:05"]) # 差 65 分钟:两辆
self.assertEqual(plan.taxi_cars, 2)
self.assertEqual(report.count("**打车/包车组**"), 2)
self.assertIn("约 10:15 在站汇合", report)
self.assertIn("约 11:20 在站汇合", report)
plan, _ = self.riders_to_one_station(["10:00", "10:20"], taxi_wait_min=10) # 上限调小到 10 分钟:拆开
self.assertEqual(plan.taxi_cars, 2)
def test_more_than_four_people_split_into_cars(self):
plan, report = self.riders_to_one_station(["10:00"] * 5)
self.assertEqual(plan.taxi_cars, 2)
self.assertEqual(report.count("**打车/包车组**"), 2)
people = [person("大家", "114.0,34.0", party=3, trains={"近站": "G9 07:00→10:00"}),
person("甲", "114.0,34.0", trains={"近站": "G1 07:00→10:00"}), person("乙", "114.0,34.0", trains={"近站": "G2 07:00→10:00"})]
plans, *_ = best_plan(config(people, stations=(("近站", NEAR),)))
self.assertEqual(plans[0].taxi_cars, 2) # 3 + 1 坐满一辆,同行的一组不拆开,剩下一个另一辆
def test_people_without_trains_ride_with_anyone(self):
people = [person("甲", "114.0,34.0", trains={"近站": "G1 07:00→10:00"}), person("乙", "114.0,34.0", stations=["近站"])]
plans, pts, T, trip = best_plan(config(people, stations=(("近站", NEAR),)))
self.assertEqual(plans[0].taxi_cars, 1)
report = carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
self.assertIn("乙没填车次,按同一时间算", report)
html = share.render_share(service.compute(config(people, stations=(("近站", NEAR),)), FakeAmap()), 0)
self.assertIn("你没填车次,按同一时间算", html)
def test_return_taxi_waits_only_if_the_train_can_still_be_caught(self):
def cars(leave_b, train_a="G2 西站19:30→a"):
people = [person("甲", "114.0,34.0", return_trains={"西站": train_a}, leave_time="17:00", stations=["西站"]),
person("乙", "113.0,35.0", return_trains={"西站": "G3 西站22:30→b"}, leave_time=leave_b, stations=["西站"])]
c = config(people)
c["return"] = {"enabled": True, "depart_time": "18:00"}
trip, pts, T, _ = carpool.plan_trip(c, FakeAmap())
return trip.back_plans[0], carpool.render(trip, pts, T, [], carpool.timelines(trip, T, []))
plan, report = cars("17:10") # 乙晚 10 分钟,一起走:17:10 出发,甲要等 10 分钟
self.assertEqual(plan.taxi_cars, 1)
self.assertIn("甲、乙 17:10 从目的地一起打车去", report)
self.assertIn("甲等 10分钟", report)
plan, _ = cars("17:25") # 一起走要 17:25 才出发,甲的 19:30 那趟(17:13 前必须出发)就赶不上了:拆开
self.assertEqual(plan.taxi_cars, 2)
def test_too_many_combinations_use_the_greedy_fallback(self):
cfg = config([person("老王", WANG, car_seats=3), person("小李", "116.5,30.4"), person("小陈", "114.0,34.0")])
with mock.patch("carpool.TAXI_COMBO_LIMIT", 1), mock.patch.object(carpool.TaxiPool, "_greedy", autospec=True,
side_effect=carpool.TaxiPool._greedy) as greedy:
plans, *_ = best_plan(cfg)
self.assertTrue(greedy.called)
plan = next(p for p in plans if not p.rides)
self.assertEqual(plan.taxi, {"小李": "st:近站", "小陈": "st:近站"}) # 贪心也把人挪到已经有人去的站
self.assertEqual(plan.stranded, [])
def test_greedy_never_exceeds_the_extra_limit(self):
stations = [(f"站{i}", f"{117.0 + 0.2 * i},{29.5 + 0.1 * i}") for i in range(8)]
riders = [person(f"乘客{i}", f"{112.0 + i},{33.0 + i * 0.2}") for i in range(6)]
with mock.patch("carpool.TAXI_COMBO_LIMIT", 10):
plans, _, T, trip = best_plan(config(riders, stations=stations, taxi_pool_extra_min=20))
opts = {p.name: carpool.rider_options(p, [s.name for s in trip.stations], trip.station_cost) for p in trip.people}
cost = lambda name, stop: opts[name][stop] + T[(stop, "venue")] # noqa: E731
plan = plans[0]
self.assertEqual(sorted(plan.taxi), sorted(opts))
for name, stop in plan.taxi.items(): # 每个人比自己最快的走法多花的,不超过上限
fastest = min(cost(name, s) for s in opts[name] if s.startswith("st:"))
self.assertLessEqual(cost(name, stop), fastest + 20 + 1e-6, name)
fast = best_plan(config(riders, stations=stations, taxi_mode="fast"))[0][0]
self.assertLessEqual(plan.taxi_ride, fast.taxi_ride + 1e-6) # 贪心的结果不会比各走最快的站更贵
def test_rank_basis_shows_taxi_line_without_changing_the_ranking(self):
cfg = config([person("老王", WANG, car_seats=3), person("小李", "116.5,30.4"), person("小陈", "114.0,34.0")])
trip, pts, T, plans = carpool.plan_trip(cfg, FakeAmap())
report = carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
plan = plans[-1]
low, high = round(plan.taxi_ride * 2, -1), round(plan.taxi_ride * 3, -1)
self.assertIn(f"打车:1 辆,粗估 {low:.0f}–{high:.0f} 元", report)
no_taxi = carpool.rank_basis(carpool.Plan([], {}, {}, [], 0, 0, 0))
self.assertEqual(len(no_taxi), 1) # 没人打车就不显示这一行
# 打车费只用来选站:方案之间还是按(搭车人数、总分钟、停车次数)排
self.assertEqual([p.score for p in plans], sorted(p.score for p in plans))
self.assertEqual(plans[0].score[:1], (-plans[0].carried,))
def test_payload_and_share_page_describe_each_car(self):
cfg = config([person("老王", WANG, car_seats=3), person("小李", "116.5,30.4"), person("小陈", "114.0,34.0")])
state = service.compute(cfg, FakeAmap())
payload = service.plan_payload(state)
self.assertEqual([p["taxi_cars"] for p in payload["plans"]][-1], 1)
html = share.render_share(state, 2) # 第三个方案:两人都打车去近站
self.assertIn("和 小陈 汇合,打车", html)
self.assertIn("和 小李 汇合,打车", html)
class PartyTest(unittest.TestCase):
"""同行人数:一组人要么一起上同一辆车,要么一起打车。"""
def best(self, seats, *riders):
cfg = config([person("老王", WANG, car_seats=seats), *riders])
trip, pts, T, plans = carpool.plan_trip(cfg, FakeAmap())
return plans[0], carpool.render(trip, pts, T, plans, carpool.timelines(trip, T, plans))
def test_group_is_not_split(self):
plan, report = self.best(2, person("小陈一家", "114.0,34.0", party=3))
self.assertEqual((plan.rides, plan.carried), ({}, 0))
self.assertEqual(plan.taxi, {"小陈一家": "st:近站"})
self.assertIn("小陈一家(3 人)", report)
self.assertIn("打车粗估", report)
plan, _ = self.best(3, person("小陈一家", "114.0,34.0", party=3))
self.assertEqual((plan.rides, plan.carried), ({"小陈一家": ("老王", "st:西站")}, 3))
def test_seats_counted_by_people(self):
plan, report = self.best(3, person("甲家", "114.0,34.0", party=2), person("乙家", "113.0,35.0", party=2))
self.assertEqual((len(plan.rides), plan.carried), (1, 2))
self.assertIn("不开车的 4 人里,**2 人能搭上顺风车**", report)
class RideLimitTest(unittest.TestCase):
"""搭车最多多花(v3.13,计算规则第 3 版):搭顺风车的人,不算等人的全程不能比自己单独走多花过 ride_extra_min 分钟。"""
def out(self, people, **options):
plans, _, T, trip = best_plan(config(people, **options))
return plans, T, trip
def back(self, people, **options):
cfg = config(people, **options)
cfg["return"] = {"enabled": True, "depart_time": "18:00"}
trip, _, T, _ = carpool.plan_trip(cfg, FakeAmap())
return trip.back_plans, T, trip
def test_option_is_read_and_defaults_to_30(self):
self.assertEqual(carpool.DEFAULTS["ride_extra_min"], 30)
self.assertEqual(carpool.load_trip(config([person("小陈", "114.0,34.0")]), FakeAmap()).ride_extra, 30)
self.assertEqual(carpool.load_trip(config([person("小陈", "114.0,34.0")], ride_extra_min=12), FakeAmap()).ride_extra, 12)
def test_outbound_slow_car_to_far_station_means_taxi(self):
# 小陈坐老王的车去西站,比自己打车去近站多花约 10 分钟:上限 5 不搭,30 搭
people = [person("老王", WANG, car_seats=3), person("小陈", "114.0,34.0")]
plans, *_ = self.out(people, ride_extra_min=5)
self.assertEqual((plans[0].rides, plans[0].taxi), ({}, {"小陈": "st:近站"}))
plans, *_ = self.out(people, ride_extra_min=30)
self.assertEqual(plans[0].rides, {"小陈": ("老王", "st:西站")})