helpers.ts
2.95 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
/** 离线测试辅助:假客户端、假时钟与临时目录。不访问高德、不消耗额度。 */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { QueryError, StopRun, extractFields } from '../src/client.ts';
import type { Clock, LookupClient, ResultFields, StopHandle } from '../src/client.ts';
export const HEADER = ['案件号', '出险地点', '报案时间', '经度', '纬度', '行政区', '街道', '道路'];
export const FIRST = ['00000000000000000001', '虚构地址,测试"引号"\n换行',
'46023.1234567890', '113.936672', '22.7405', '', '', ''];
export const RESPONSE = {
status: '1', info: 'OK', infocode: '10000',
regeocode: {
formatted_address: '广东省深圳市光明区凤凰街道光源四路',
addressComponent: {
district: '光明区', township: '凤凰街道',
streetNumber: { street: '观光路', distance: '160.034' },
},
roads: [{ name: '光源六路', distance: '106.121' },
{ name: '光源四路', distance: '14.788' },
{ name: '光源二路', distance: '49.5397' }],
},
};
export const RESPONSE_BODY = JSON.stringify(RESPONSE);
export const NEAREST = extractFields(RESPONSE.regeocode);
export type Behavior = (lng: string, lat: string) => ResultFields | Promise<ResultFields>;
export class FakeClient implements LookupClient {
calls: [string, string][] = [];
requests = 0;
stopEvent: StopHandle = {
isSet: () => this.flagged,
set: () => { this.flagged = true; },
wait: async () => true,
};
flagged = false;
behavior: Behavior;
constructor(behavior?: Behavior) {
this.behavior = behavior ?? ((): ResultFields => NEAREST);
}
async lookup(lng: string, lat: string): Promise<ResultFields> {
this.requests += 1;
this.calls.push([lng, lat]);
return this.behavior(lng, lat);
}
}
export function failBehavior(message: string): Behavior {
return (): never => {
throw new QueryError(message);
};
}
export function stopBehavior(message: string): Behavior {
return (): never => {
throw new StopRun(message);
};
}
/** 虚拟时钟:退避与限速立即返回,并记录每次等待秒数。 */
export class FakeClock implements Clock {
sleeps: number[] = [];
private time = 0;
now(): number {
return this.time;
}
async sleep(seconds: number): Promise<void> {
this.sleeps.push(seconds);
this.time += seconds * 1000;
}
}
/** 一次测试跑几十个临时目录,不清理会把人机的临时文件夹堆满;退出时尽力删掉。 */
const tempDirs = new Set<string>();
process.on('exit', () => {
for (const dir of tempDirs) {
try {
fs.rmSync(dir, { recursive: true, force: true, maxRetries: 2 });
} catch {
// 句柄还没放开的留给系统清理,不能让清理动作把测试结果带成失败
}
}
});
export function tempRoot(prefix = 'amap test '): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.add(dir);
return dir;
}