|
| 1 | +import type { ChannelAccountSnapshot, ChannelGatewayContext } from "openclaw/plugin-sdk/test-utils"; |
| 2 | +import { expect, vi } from "vitest"; |
| 3 | +import { createStartAccountContext } from "./start-account-context.js"; |
| 4 | + |
| 5 | +export function startAccountAndTrackLifecycle<TAccount extends { accountId: string }>(params: { |
| 6 | + startAccount: (ctx: ChannelGatewayContext<TAccount>) => Promise<unknown>; |
| 7 | + account: TAccount; |
| 8 | +}) { |
| 9 | + const patches: ChannelAccountSnapshot[] = []; |
| 10 | + const abort = new AbortController(); |
| 11 | + const task = params.startAccount( |
| 12 | + createStartAccountContext({ |
| 13 | + account: params.account, |
| 14 | + abortSignal: abort.signal, |
| 15 | + statusPatchSink: (next) => patches.push({ ...next }), |
| 16 | + }), |
| 17 | + ); |
| 18 | + let settled = false; |
| 19 | + void task.then(() => { |
| 20 | + settled = true; |
| 21 | + }); |
| 22 | + return { |
| 23 | + abort, |
| 24 | + patches, |
| 25 | + task, |
| 26 | + isSettled: () => settled, |
| 27 | + }; |
| 28 | +} |
| 29 | + |
| 30 | +export async function abortStartedAccount(params: { |
| 31 | + abort: AbortController; |
| 32 | + task: Promise<unknown>; |
| 33 | +}) { |
| 34 | + params.abort.abort(); |
| 35 | + await params.task; |
| 36 | +} |
| 37 | + |
| 38 | +export async function expectPendingUntilAbort(params: { |
| 39 | + waitForStarted: () => Promise<void>; |
| 40 | + isSettled: () => boolean; |
| 41 | + abort: AbortController; |
| 42 | + task: Promise<unknown>; |
| 43 | + assertBeforeAbort?: () => void; |
| 44 | + assertAfterAbort?: () => void; |
| 45 | +}) { |
| 46 | + await params.waitForStarted(); |
| 47 | + expect(params.isSettled()).toBe(false); |
| 48 | + params.assertBeforeAbort?.(); |
| 49 | + await abortStartedAccount({ abort: params.abort, task: params.task }); |
| 50 | + params.assertAfterAbort?.(); |
| 51 | +} |
| 52 | + |
| 53 | +export async function expectStopPendingUntilAbort(params: { |
| 54 | + waitForStarted: () => Promise<void>; |
| 55 | + isSettled: () => boolean; |
| 56 | + abort: AbortController; |
| 57 | + task: Promise<unknown>; |
| 58 | + stop: ReturnType<typeof vi.fn>; |
| 59 | +}) { |
| 60 | + await expectPendingUntilAbort({ |
| 61 | + waitForStarted: params.waitForStarted, |
| 62 | + isSettled: params.isSettled, |
| 63 | + abort: params.abort, |
| 64 | + task: params.task, |
| 65 | + assertBeforeAbort: () => { |
| 66 | + expect(params.stop).not.toHaveBeenCalled(); |
| 67 | + }, |
| 68 | + assertAfterAbort: () => { |
| 69 | + expect(params.stop).toHaveBeenCalledOnce(); |
| 70 | + }, |
| 71 | + }); |
| 72 | +} |
0 commit comments