helpers.ts 2.87 KB
/** 离线测试辅助:假客户端、假时钟与临时目录。不访问高德、不消耗额度。 */
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: {
    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;
}