Skip to content

Commit b55b450

Browse files
revert refactoring
1 parent b1f34ea commit b55b450

2 files changed

Lines changed: 17 additions & 137 deletions

File tree

lib/lib.ts

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
11
import { fileURLToPath } from 'node:url';
22

3+
import type { Actor, ActorRun, ActorRunListItem, ActorStandby, Task } from 'apify-client';
34
import { ApifyClient } from 'apify-client';
45
import type { SuiteFactory, TestContext, TestFunction } from 'vitest';
56
import { describe as vitestDescribe, ExpectStatic, test as vitestTest } from 'vitest';
67

78
import { DEFAULT_DESCRIBE_OPTIONS, DEFAULT_TEST_ACTOR_OPTIONS, DEFAULT_TRIGGERS } from './consts.js';
89
import { extendExpect } from './extend-expect.js';
10+
import { RunTestResult } from './run-test-result.js';
911
import { shouldRunForTrigger } from './trigger.js';
10-
import type { ActorBuild, ActorTestOptions, DescribeConfig, TestActorConfig, TriggerConfig } from './types.js';
11-
import { createStandbyTask, createStartRunFn, createStartStandbyFn, generateRunLink } from './utils.js';
12+
import type {
13+
ActorBuild,
14+
ActorTestOptions,
15+
DescribeConfig,
16+
RunOptions,
17+
TestActorConfig,
18+
TriggerConfig,
19+
} from './types.js';
20+
import { getActorPrefilledInput, sleep } from './utils.js';
1221

1322
export { getCurrentTrigger, TRIGGER_ENV_VAR } from './trigger.js';
1423
export { ExpectStatic };
@@ -30,7 +39,7 @@ try {
3039
throw new Error(`Failed to parse actor builds: ${err}`);
3140
}
3241

33-
const actorConfig = actorBuilds.reduce<Map<string, ActorBuild>>((map, cfg) => {
42+
const config = actorBuilds.reduce<Map<string, ActorBuild>>((map, cfg) => {
3443
map.set(cfg.actorName, cfg);
3544
map.set(cfg.actorId, cfg);
3645
return map;
@@ -166,7 +175,7 @@ function resolveActorTestConfig(
166175
...(triggers !== undefined ? [triggers] : []),
167176
]);
168177
const shouldRun =
169-
(!!RUN_ALL_PLATFORM_TESTS || actorConfig.has(actorName)) && shouldRunForTrigger(effectiveTriggers.runWhen);
178+
(!!RUN_ALL_PLATFORM_TESTS || config.has(actorName)) && shouldRunForTrigger(effectiveTriggers.runWhen);
170179

171180
return { fullName: `${actorName}: ${name}`, effectiveTriggers, vitestOptions: options ?? {}, shouldRun };
172181
}
@@ -209,7 +218,7 @@ export const testActor = <T>(
209218
const { expect, ...rest } = context;
210219
await fn({
211220
expect: extendExpect(expect),
212-
run: createStartRunFn(apifyClient, actorConfig, actorName, context),
221+
run: createStartRunFn(actorName, context),
213222
...rest,
214223
});
215224
});
@@ -246,15 +255,15 @@ export const testStandbyActor = <I = any, O = any>(
246255
// @ts-expect-error: `TaskMeta` cannot be retyped
247256
context.task.meta = { ...context.task.meta, alerts: effectiveTriggers.alerts };
248257

249-
const standbyTask = await createStandbyTask(apifyClient, actorName, actorConfig.get(actorName)?.buildNumber);
258+
const standbyTask = await createStandbyTask(actorName, config.get(actorName)?.buildNumber);
250259
const { annotate } = context;
251260
const { expect, ...rest } = context;
252261

253262
// NOTE: wrap `fn` in try-catch so the task is always cleaned up afterwards
254263
try {
255264
await fn({
256265
expect: extendExpect(expect),
257-
callStandby: createStartStandbyFn(apifyClient, standbyTask),
266+
callStandby: createStartStandbyFn(standbyTask),
258267
...rest,
259268
});
260269
} catch {

lib/utils.ts

Lines changed: 1 addition & 130 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import type { Actor, ActorRun, ActorRunListItem, ActorStandby, ApifyClient, Task } from 'apify-client';
2-
import type { TestContext } from 'vitest';
3-
4-
import { RunTestResult } from './run-test-result.js';
5-
import type { ActorBuild, RunOptions } from './types.js';
1+
import type { ApifyClient } from 'apify-client';
62

73
/**
84
* Gets prefilled values for a provided build or, if not provided, uses actor's
@@ -60,128 +56,3 @@ export const sleep = async (ms: number) => {
6056
setTimeout(resolve, ms);
6157
});
6258
};
63-
64-
export const generateRunLink = (run: ActorRun | ActorRunListItem): string =>
65-
`https://console.apify.com/view/runs/${run.id}`;
66-
67-
export const createStartRunFn = <T>(
68-
apifyClient: ApifyClient,
69-
config: Map<string, ActorBuild>,
70-
actorNameOrId: string,
71-
testContext: TestContext,
72-
) => {
73-
const { annotate, task } = testContext;
74-
const actorConfig = config.get(actorNameOrId);
75-
const build = actorConfig?.buildNumber;
76-
const buildId = actorConfig?.buildId;
77-
78-
return async (runOptions: RunOptions<T>) => {
79-
const { input, options, prefilledInput, runId } = runOptions;
80-
81-
if (runId) {
82-
const run = await apifyClient.run(runId).get();
83-
if (!run) {
84-
throw new Error(`Run with id "${runId}" doesn't exist`);
85-
}
86-
return new RunTestResult(apifyClient, run);
87-
}
88-
89-
const actor = apifyClient.actor(actorNameOrId);
90-
91-
const actorInput = {
92-
...(prefilledInput && (await getActorPrefilledInput(apifyClient, actorNameOrId, buildId))),
93-
...input,
94-
};
95-
const run = await actor.call(actorInput, { build, log: null, ...options });
96-
97-
const runLink = generateRunLink(run);
98-
await annotate(`${task.name} - ${runLink}`, 'run_link');
99-
// @ts-expect-error: `TaskMeta` cannot be retyped
100-
task.meta = {
101-
runId: run.id,
102-
runLink,
103-
actorName: actorNameOrId,
104-
};
105-
106-
// waiting for datasetItemCount and chargedEventCounts to sync
107-
await sleep(10_000);
108-
109-
return new RunTestResult(apifyClient, run);
110-
};
111-
};
112-
113-
export interface StandbyTask {
114-
standbyUrl: string;
115-
taskId: string;
116-
}
117-
118-
/**
119-
* Creates a function that accepts input for a standby actor and sends a request
120-
* containing that input to the task's standby URL.
121-
*/
122-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
123-
export const createStartStandbyFn = <I = any, O = any>(apifyClient: ApifyClient, standbyTask: StandbyTask) => {
124-
const { standbyUrl } = standbyTask;
125-
return async ({ input }: Pick<RunOptions<I>, 'input'>) => {
126-
const response = await fetch(standbyUrl, {
127-
headers: { Authorization: `Bearer ${apifyClient.token}` },
128-
method: 'POST',
129-
body: JSON.stringify(input),
130-
});
131-
132-
const data = (await response.json()) as O;
133-
return { data, status: response.status, headers: response.headers };
134-
};
135-
};
136-
137-
/**
138-
* Creates a task with a specific `build` — either `buildNumber` or the actor default.
139-
*
140-
* @throws if the actor doesn't exist or doesn't support standby mode.
141-
*/
142-
export const createStandbyTask = async (
143-
apifyClient: ApifyClient,
144-
actorNameOrId: string,
145-
buildNumber?: string,
146-
): Promise<StandbyTask> => {
147-
const actor = apifyClient.actor(actorNameOrId);
148-
149-
const actorInfo = (await actor.get()) as Actor & { standbyUrl?: string };
150-
if (!actorInfo) throw new Error(`Actor "${actorNameOrId}" not found`);
151-
if (!actorInfo.standbyUrl) throw new Error(`Actor "${actorNameOrId}" doesn't support standby mode`);
152-
if (!actorInfo.actorStandby) throw new Error(`Actor "${actorNameOrId}" doesn't contain actorStandby options`);
153-
154-
const { isEnabled, ...defaultActorStandby } = actorInfo.actorStandby;
155-
delete defaultActorStandby.disableStandbyFieldsOverride;
156-
157-
const actorStandbyOptions: ActorStandby = {
158-
...defaultActorStandby,
159-
build: buildNumber ?? defaultActorStandby.build,
160-
};
161-
162-
try {
163-
const { build } = actorStandbyOptions;
164-
const title = `Test task - ${build}:${actorNameOrId}`.slice(0, 62);
165-
// Unique task name: only `a-z0-9-` chars, at most 63 chars long
166-
const randomPrefix = Math.floor(Math.random() * 1_000_000);
167-
const name = `${randomPrefix}${title
168-
.toLowerCase()
169-
.replaceAll(/\s+/g, '')
170-
.replaceAll(/[^a-z0-9-]+/g, '-')}`.slice(0, 62);
171-
172-
const newTask = (await apifyClient.tasks().create({
173-
actId: actorNameOrId,
174-
actorStandby: actorStandbyOptions,
175-
description: `Task for testing standby version ${build}`,
176-
title,
177-
name,
178-
})) as Task & { standbyUrl?: string };
179-
180-
const { id, standbyUrl } = newTask;
181-
if (!standbyUrl) throw new Error(`Task "${id}" doesn't contain standbyUrl property`);
182-
183-
return { standbyUrl, taskId: id };
184-
} catch (error) {
185-
throw new Error(`Failed to create task: ${error}`);
186-
}
187-
};

0 commit comments

Comments
 (0)