TestTraits.ts
75 lines
| 2.1 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r22 | import { IObservable, ICancellation, IDestroyable } from "@implab/core/interfaces"; | ||
| import { Cancellation } from "@implab/core/Cancellation"; | ||||
| import { TraceEvent, LogLevel, WarnLevel } from "@implab/core/log/TraceSource"; | ||||
|
|
r40 | import * as tape from "tape"; | ||
|
|
r22 | import { argumentNotNull } from "@implab/core/safe"; | ||
|
|
r15 | |||
| export class TapeWriter implements IDestroyable { | ||||
|
|
r40 | readonly _tape: tape.Test; | ||
|
|
r15 | |||
| _subscriptions = new Array<IDestroyable>(); | ||||
|
|
r40 | constructor(t: tape.Test) { | ||
| argumentNotNull(t, "tape"); | ||||
| this._tape = t; | ||||
|
|
r15 | } | ||
| writeEvents(source: IObservable<TraceEvent>, ct: ICancellation = Cancellation.none) { | ||||
|
|
r40 | const subscription = source.on(this.writeEvent.bind(this)); | ||
|
|
r15 | if (ct.isSupported()) { | ||
| ct.register(subscription.destroy.bind(subscription)); | ||||
| } | ||||
| this._subscriptions.push(subscription); | ||||
| } | ||||
| writeEvent(next: TraceEvent) { | ||||
|
|
r22 | if (next.level >= LogLevel) { | ||
|
|
r15 | this._tape.comment("LOG " + next.arg); | ||
|
|
r22 | } else if (next.level >= WarnLevel) { | ||
|
|
r15 | this._tape.comment("WARN " + next.arg); | ||
| } else { | ||||
| this._tape.comment("ERROR " + next.arg); | ||||
| } | ||||
| } | ||||
| destroy() { | ||||
| this._subscriptions.forEach(x => x.destroy()); | ||||
| } | ||||
|
|
r18 | } | ||
| export async function delay(timeout: number, ct: ICancellation = Cancellation.none) { | ||||
| let un: IDestroyable; | ||||
|
|
r40 | |||
|
|
r18 | try { | ||
|
|
r40 | await new Promise((resolve, reject) => { | ||
|
|
r18 | if (ct.isRequested()) { | ||
|
|
r40 | un = ct.register(reject); | ||
| } else { | ||||
| const ht = setTimeout(() => { | ||||
| resolve(); | ||||
| }, timeout); | ||||
| un = ct.register(e => { | ||||
| clearTimeout(ht); | ||||
| reject(e); | ||||
| }); | ||||
| } | ||||
| }); | ||||
|
|
r18 | } finally { | ||
|
|
r40 | if (un) | ||
| un.destroy(); | ||||
| } | ||||
| } | ||||
| export function test(name: string, cb: (t: tape.Test) => any) { | ||||
| tape(name, async t => { | ||||
| try { | ||||
| await cb(t); | ||||
| } catch (e) { | ||||
| console.error(e); | ||||
| t.fail(e); | ||||
| } finally { | ||||
| t.end(); | ||||
| } | ||||
| }); | ||||
| } | ||||
