amap-fill.test.ts 17.5 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
/**
 * 离线回归测试。运行:npm test
 * 使用临时文件与模拟网络,不调用高德、不消耗接口额度。
 */
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { describe, test } from 'node:test';
import {
  AmapClient, Cache, QueryError, RateLimiter, RequestCancelled, StopRun, StopSignal, extractFields,
} from '../src/client.ts';
import type { LookupClient, ResultFields, Transport } from '../src/client.ts';
import { atomicCsv, readCsv } from '../src/csv-store.ts';
import { normalizeCoordinates } from '../src/coords.ts';
import { runJob } from '../src/fill.ts';
import type { RunOptions } from '../src/fill.ts';
import { CONSISTENCY } from '../src/consistency.ts';
import { CONSISTENCY_COLUMN, REVIEW_NOTE_COLUMN, STANDARD_ADDRESS_COLUMN } from '../src/targets.ts';
import {
  FIRST, HEADER, NEAREST, RESPONSE, RESPONSE_BODY, FakeClient, FakeClock, failBehavior, tempRoot,
} from './helpers.ts';

describe('坐标与字段', () => {
  test('坐标按十进制取整,原字符串无需可表示为双精度', () => {
    assert.deepEqual(normalizeCoordinates('113.94113800000002', '22.51217'), ['113.941138', '22.512170']);
    assert.deepEqual(normalizeCoordinates('113.0000005', '22.1234565'), ['113.000001', '22.123457']);
    assert.deepEqual(normalizeCoordinates('-0', '0'), ['0.000000', '0.000000']);
  });

  test('无效坐标不会被当成 0', () => {
    for (const [lng, lat] of [['', '22'], ['abc', '22'], ['NaN', '22'], ['Infinity', '22'],
      ['181', '22'], ['114', '-91'], ['114', ''], ['1e9999999', '22']] as [string, string][]) {
      assert.throws(() => normalizeCoordinates(lng, lat), { name: 'UserError' }, `${lng}/${lat} 应被拒绝`);
    }
  });

  test('真实首点选择最近道路,而不是门牌道路或第一条', () => {
    const result = extractFields(RESPONSE.regeocode);
    assert.deepEqual([result.district, result.township, result.road], ['光明区', '凤凰街道', '光源四路']);
    assert.deepEqual([result.road_source, result.road_distance], ['nearest_road', '14.788']);
    assert.equal(result.street_road, '观光路');
    assert.deepEqual(result.candidates.map((item) => item.name),
      ['光源六路', '光源四路', '光源二路']);
  });

  test('无效道路候选被忽略,距离 0 有效', () => {
    const result = extractFields({
      roads: [
        { name: '坏路1', distance: '-1' }, { name: '坏路2', distance: 'NaN' },
        { name: '', distance: '0' }, { name: '坏路3', distance: [] },
        { name: '远路', distance: '2' }, { name: '近路', distance: '0' }],
    });
    assert.equal(result.road, '近路');
    assert.equal(result.road_distance, '0');
  });

  test('缺失数组与门牌回退', () => {
    const result = extractFields({
      addressComponent: { district: [], township: null, streetNumber: { street: '门牌路', distance: '12' } },
      roads: [],
    });
    assert.deepEqual([result.district, result.township, result.road], ['', '', '门牌路']);
    assert.equal(result.road_source, 'street_number');
    assert.equal(extractFields({}).road, '');
  });
});

describe('限速', () => {
  test('限速时段使用精确耗时', async () => {
    const clock = new FakeClock();
    const limiter = new RateLimiter(100, new StopSignal(clock), clock);
    await limiter.acquire();
    const first = clock.now();
    await limiter.acquire();
    assert.ok(clock.now() - first >= 10, '100 QPS 的第二个时段至少间隔 10 毫秒');
  });

  test('限速对全部并发请求生效', async () => {
    const limiter = new RateLimiter(100, new StopSignal());
    const stamps = await Promise.all(Array.from({ length: 8 }, async () => {
      await limiter.acquire();
      return performance.now();
    }));
    const ordered = [...stamps].sort((a, b) => a - b);
    assert.ok(ordered[7] - ordered[0] >= 60, `并发间隔不足:${ordered[7] - ordered[0]}`);
  });
});

function workspace() {
  const root = tempRoot('amap-files ');
  const src = path.join(root, 'input.csv');
  const out = path.join(root, 'out.csv');
  const cache = path.join(root, 'cache.sqlite3');
  const lines = (file = out): string[][] => {
    const { header, rows } = readCsv(file, null);
    return [header, ...rows];
  };
  return {
    root,
    src,
    out,
    cache,
    log: path.join(root, '.temp', 'out.处理日志.csv'),
    write: (rows: string[][], header: string[] = HEADER) => atomicCsv(src, header, rows),
    lines,
    run: (client: LookupClient = new FakeClient(), options: RunOptions = {}) =>
      runJob(src, out, cache, { client, workers: 1, ...options }),
  };
}

describe('文件与续跑', () => {
  test('CSV 保留每个非空原字段并按坐标去重', async () => {
    const files = workspace();
    const second = [...FIRST];
    second[0] = '00000000000000000002';
    second[3] = '113.93667200000002';
    second[4] = '22.740500';
    second[6] = '原街道';
    files.write([FIRST, second]);
    const original = fs.readFileSync(files.src);
    const client = new FakeClient();
    const report = await files.run(client);
    const actual = files.lines();
    assert.deepEqual(actual[0], [...HEADER, CONSISTENCY_COLUMN, REVIEW_NOTE_COLUMN, STANDARD_ADDRESS_COLUMN]);
    assert.deepEqual(actual[1].slice(0, 5), FIRST.slice(0, 5));
    assert.deepEqual(actual[2].slice(0, 5), second.slice(0, 5));
    assert.equal(actual[2][6], '原街道');
    assert.deepEqual(actual[1].slice(5), ['光明区', '凤凰街道', '光源四路', CONSISTENCY.same, '', '广东省-深圳市-光明区-凤凰街道-光源四路']);
    assert.deepEqual(client.calls, [['113.936672', '22.740500']]);
    assert.equal(report.exit_code, 0);
    assert.deepEqual(fs.readFileSync(files.src), original);
    assert.equal(fs.readFileSync(files.out).subarray(0, 3).toString('hex'), 'efbbbf');
    assert.ok(fs.existsSync(files.log));
  });

  test('缺少补全列时自动追加空列,结果写进追加列', async () => {
    const files = workspace();
    const header = HEADER.slice(0, 5);
    files.write([FIRST.slice(0, 5),
      ['00000000000000000002', '另一虚构地址', '46023.5', '114.1', '22.6']], header);
    const messages: string[] = [];
    const report = await files.run(new FakeClient(), { progress: (m) => messages.push(m) });
    const actual = files.lines();
    assert.deepEqual(actual[0], [...header, '行政区', '街道', '道路', CONSISTENCY_COLUMN, REVIEW_NOTE_COLUMN, STANDARD_ADDRESS_COLUMN]);
    assert.deepEqual(actual[1], [...FIRST.slice(0, 5), '光明区', '凤凰街道', '光源四路', CONSISTENCY.same, '', '广东省-深圳市-光明区-凤凰街道-光源四路']);
    assert.deepEqual(actual[2], ['00000000000000000002', '另一虚构地址', '46023.5', '114.1', '22.6',
      '光明区', '凤凰街道', '光源四路', CONSISTENCY.same, '', '广东省-深圳市-光明区-凤凰街道-光源四路']);
    assert.equal(report.exit_code, 0);
    assert.match(messages[0], /行政区、街道、道路.*追加空列/);
  });

  test('已完整行不查询也不改动坐标', async () => {
    const files = workspace();
    const row = [...FIRST];
    row[3] = 'invalid';
    row[5] = '区';
    row[6] = '街道';
    row[7] = '路';
    files.write([row]);
    const client = new FakeClient();
    assert.equal((await files.run(client)).exit_code, 0);
    assert.deepEqual(client.calls, []);
    assert.deepEqual(files.lines()[1], [...row, CONSISTENCY.noBasis, '', '虚构地址,测试"引号"\n换行-区-街道-路']);
  });

  test('无效坐标原样保留且不请求', async () => {
    const files = workspace();
    const row = [...FIRST];
    row[3] = 'NaN';
    files.write([row]);
    const client = new FakeClient();
    assert.equal((await files.run(client)).exit_code, 2);
    assert.deepEqual(client.calls, []);
    assert.deepEqual(files.lines()[1], [...row, CONSISTENCY.notApplicable, '', '']);
  });

  test('缓存续跑:空结果成功也不重复请求', async () => {
    const files = workspace();
    files.write([FIRST]);
    const client = new FakeClient(() => extractFields({}));
    assert.equal((await files.run(client)).exit_code, 2);
    const second = new FakeClient();
    assert.equal((await files.run(second)).exit_code, 2);
    assert.deepEqual(second.calls, []);
  });

  test('失败请求在下次运行时重试', async () => {
    const files = workspace();
    files.write([FIRST]);
    assert.equal((await files.run(new FakeClient(failBehavior('temporary')))).exit_code, 2);
    assert.equal((await files.run()).exit_code, 0);
  });

  test('配额停止保存已完成行且只续跑剩余坐标', async () => {
    const files = workspace();
    const rows = [0, 1, 2].map(() => [...FIRST]);
    rows.forEach((row, i) => { row[3] = `114.${String(i).padStart(6, '0')}`; });
    files.write(rows);
    const limited = (lng: string): ResultFields => {
      if (lng === '114.000001') throw new StopRun('quota');
      return NEAREST;
    };
    assert.equal((await files.run(new FakeClient(limited))).exit_code, 2);
    assert.equal(files.lines().length, 4);
    assert.equal(files.lines()[1][5], '光明区');
    const client = new FakeClient();
    assert.equal((await files.run(client)).exit_code, 0);
    assert.deepEqual(client.calls, [['114.000001', '22.740500'], ['114.000002', '22.740500']]);
  });

  test('缓存分批提交,关闭时不足一批的结果也落盘', () => {
    const file = path.join(tempRoot('amap cache batch '), 'cache/test.sqlite3');
    const coords = Array.from({ length: 250 }, (_, i): [string, string] =>
      [`114.${String(i).padStart(6, '0')}`, '22.740500']);
    const cache = new Cache(file);
    coords.forEach((coord, i) => cache.put(coord, { ...NEAREST, road: `路${i}` }));
    cache.close();
    const again = new Cache(file);
    const read = coords.map((coord) => again.get(coord)?.road);
    again.close();
    assert.deepEqual(read, coords.map((_, i) => `路${i}`), '200 条整批与余下 50 条都应已提交');
  });

  test('中断后保存并可续跑', async () => {
    const files = workspace();
    files.write([FIRST]);
    const controller = new AbortController();
    const client = new FakeClient(() => {
      controller.abort();
      throw new RequestCancelled('用户中断');
    });
    assert.equal((await files.run(client, { signal: controller.signal })).exit_code, 130);
    assert.equal(files.lines().length, 2);
    assert.equal((await files.run()).exit_code, 0);
  });

  test('limit 只输出前 N 行', async () => {
    const files = workspace();
    files.write([FIRST, FIRST, FIRST]);
    await files.run(undefined, { limit: 2 });
    assert.equal(files.lines().length, 3);
  });

  test('并行完成仍保持原始行序', async () => {
    const files = workspace();
    const rows = Array.from({ length: 20 }, () => [...FIRST]);
    rows.forEach((row, i) => { row[3] = `114.${String(i).padStart(6, '0')}`; });
    files.write(rows);
    let active = 0;
    let peak = 0;
    const reversedOrder = async (lng: string): Promise<ResultFields> => {
      active += 1;
      peak = Math.max(peak, active);
      await new Promise((resolve) => { setTimeout(resolve, (20 - Number(lng.slice(-6))) * 2); });
      active -= 1;
      return { ...NEAREST, road: lng };
    };
    await files.run(new FakeClient(reversedOrder), { workers: 20 });
    assert.ok(peak > 1, `并发峰值应大于 1,实际 ${peak}`);
    assert.deepEqual(files.lines().slice(1).map((row) => row[7]), rows.map((row) => row[3]));
  });

  test('拒绝把输出、缓存或日志指向源文件', async () => {
    const files = workspace();
    files.write([FIRST]);
    const cases: [string, string][] = [
      [files.src, files.cache],
      [files.out, files.src],
      [path.join(files.root, 'input.csv'), files.cache],
    ];
    for (const [output, cache] of cases) {
      await assert.rejects(() => runJob(files.src, output, cache, { client: new FakeClient() }),
        { name: 'UserError' }, `${output} 不应覆盖源文件`);
    }
  });

  test('格式错误的输入在联网前停止', async () => {
    const cases: [string[], string[][]][] = [
      [HEADER, [FIRST.slice(0, -1)]],
      [HEADER.slice(0, 4), [FIRST.slice(0, 4)]],
      [[...HEADER, '道路'], [[...FIRST, '']]],
    ];
    for (const [header, rows] of cases) {
      const files = workspace();
      files.write(rows, header);
      const client = new FakeClient();
      await assert.rejects(() => files.run(client), { name: 'UserError' },
        `表头 ${header.join('/')} 应被拒绝`);
      assert.deepEqual(client.calls, []);
    }
  });
});

type QueueItem = string | Error;

function queueTransport(items: QueueItem[]) {
  const urls: string[] = [];
  const timeouts: number[] = [];
  const transport: Transport = async (url, timeoutSeconds) => {
    if (items.length === 0) throw new Error('测试队列已空');
    urls.push(url);
    timeouts.push(timeoutSeconds);
    const item = items.shift() as QueueItem;
    if (item instanceof Error) throw item;
    return { body: item };
  };
  return { transport, urls, timeouts };
}

describe('HTTP 客户端', () => {
  test('只发送坐标与接口参数,结果不含 Key', async () => {
    const queue = queueTransport([RESPONSE_BODY]);
    const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport });
    const result = await client.lookup('113.936672', '22.740500');
    const url = new URL(queue.urls[0]);
    assert.deepEqual([...url.searchParams.keys()].sort(),
      ['extensions', 'key', 'location', 'output', 'radius', 'roadlevel']);
    assert.equal(url.searchParams.get('location'), '113.936672,22.740500');
    assert.equal(queue.timeouts[0], 20);
    assert.equal(JSON.stringify(result).includes('TEST_SECRET'), false);
    assert.equal(result.road, '光源四路');
  });

  test('限速与超时先重试后成功', async () => {
    const clock = new FakeClock();
    const queue = queueTransport([new Error('secret must not be logged'),
      JSON.stringify({ status: '0', infocode: '10021' }), RESPONSE_BODY]);
    const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport, clock });
    const result = await client.lookup('114.000000', '22.000000');
    assert.equal(result.road, '光源四路');
    assert.equal(client.requests, 3);
    assert.deepEqual(clock.sleeps, [1, 2]);
  });

  test('重试耗尽后使用四次尝试并隐藏底层异常', async () => {
    const clock = new FakeClock();
    const queue = queueTransport(Array.from({ length: 4 },
      () => new Error('connect https://x?key=TEST_SECRET failed')));
    const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport, clock });
    await assert.rejects(() => client.lookup('114.000000', '22.000000'), (exc: unknown) => {
      assert.ok(exc instanceof QueryError);
      assert.equal(String(exc).includes('TEST_SECRET'), false);
      return true;
    });
    assert.equal(client.requests, 4);
    assert.deepEqual(clock.sleeps, [1, 2, 4]);
  });

  test('权限与配额错误立即停止且不重试', async () => {
    for (const code of ['10001', '10002', '10003', '10009', '10012', '10041', '10044', '40000']) {
      const queue = queueTransport([JSON.stringify({ status: '0', infocode: code })]);
      const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport });
      await assert.rejects(() => client.lookup('114.000000', '22.000000'), StopRun, `${code} 应停止运行`);
      assert.equal(client.requests, 1);
    }
  });

  test('无效域名与封禁账号立即停止', async () => {
    for (const code of ['10006', '10026']) {
      const queue = queueTransport([JSON.stringify({ status: '0', infocode: code })]);
      const clock = new FakeClock();
      const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport, clock });
      await assert.rejects(() => client.lookup('114.000000', '22.000000'), StopRun);
      assert.equal(client.requests, 1);
    }
  });

  test('其他已记录限流码选择重试而不是停止', async () => {
    for (const code of ['10014', '10029']) {
      const queue = queueTransport([JSON.stringify({ status: '0', infocode: code }), RESPONSE_BODY]);
      const clock = new FakeClock();
      const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport, clock });
      const result = await client.lookup('114.000000', '22.000000');
      assert.equal(result.road, '光源四路');
      assert.equal(client.requests, 2);
    }
  });

  test('无效 JSON 不会被当作空结果缓存', async () => {
    const clock = new FakeClock();
    const queue = queueTransport(Array.from({ length: 4 }, () => 'not json'));
    const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport, clock });
    await assert.rejects(() => client.lookup('114.000000', '22.000000'), QueryError);
  });

  test('请求都走同一已验证的 HTTPS 连接配置', async () => {
    const queue = queueTransport([RESPONSE_BODY, RESPONSE_BODY]);
    const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport });
    await client.lookup('114.000000', '22.000000');
    await client.lookup('114.000001', '22.000001');
    assert.equal(queue.urls.length, 2);
    for (const url of queue.urls) {
      const parsed = new URL(url);
      assert.equal(parsed.protocol, 'https:');
      assert.equal(parsed.host, 'restapi.amap.com');
    }
  });

  test('截断的响应体被重试而不中止运行', async () => {
    const clock = new FakeClock();
    const queue = queueTransport([new Error('premature close'), RESPONSE_BODY]);
    const client = new AmapClient('TEST_SECRET', 0, { transport: queue.transport, clock });
    const result = await client.lookup('114.000000', '22.000000');
    assert.equal(result.road, '光源四路');
    assert.equal(client.requests, 2);
  });
});