@nestia/e2e 7.0.0-dev.20250608 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,347 +1,594 @@
1
- import { RandomGenerator } from "./RandomGenerator";
2
- import { json_equal_to } from "./internal/json_equal_to";
3
-
4
- /**
5
- * Test validator.
6
- *
7
- * `TestValidator` is a collection gathering E2E validation functions.
8
- *
9
- * @author Jeongho Nam - https://github.com/samchon
10
- */
11
- export namespace TestValidator {
12
- /**
13
- * Test whether condition is satisfied.
14
- *
15
- * @param title Title of error message when condition is not satisfied
16
- * @return Currying function
17
- */
18
- export const predicate =
19
- (title: string) =>
20
- <T extends boolean | (() => boolean) | (() => Promise<boolean>)>(
21
- condition: T,
22
- ): T extends () => Promise<boolean> ? Promise<void> : void => {
23
- const message = () =>
24
- `Bug on ${title}: expected condition is not satisfied.`;
25
-
26
- // SCALAR
27
- if (typeof condition === "boolean") {
28
- if (condition !== true) throw new Error(message());
29
- return undefined as any;
30
- }
31
-
32
- // CLOSURE
33
- const output: boolean | Promise<boolean> = condition();
34
- if (typeof output === "boolean") {
35
- if (output !== true) throw new Error(message());
36
- return undefined as any;
37
- }
38
-
39
- // ASYNCHRONOUS
40
- return new Promise<void>((resolve, reject) => {
41
- output
42
- .then((flag) => {
43
- if (flag === true) resolve();
44
- else reject(message());
45
- })
46
- .catch(reject);
47
- }) as any;
48
- };
49
-
50
- /**
51
- * Test whether two values are equal.
52
- *
53
- * If you want to validate `covers` relationship,
54
- * call smaller first and then larger.
55
- *
56
- * Otherwise you wanna non equals validator, combine with {@link error}.
57
- *
58
- * @param title Title of error message when different
59
- * @param exception Exception filter for ignoring some keys
60
- * @returns Currying function
61
- */
62
- export const equals =
63
- (title: string, exception: (key: string) => boolean = () => false) =>
64
- <T>(x: T) =>
65
- (y: T) => {
66
- const diff: string[] = json_equal_to(exception)(x)(y);
67
- if (diff.length)
68
- throw new Error(
69
- [
70
- `Bug on ${title}: found different values - [${diff.join(", ")}]:`,
71
- "\n",
72
- JSON.stringify({ x, y }, null, 2),
73
- ].join("\n"),
74
- );
75
- };
76
-
77
- /**
78
- * Test whether error occurs.
79
- *
80
- * If error occurs, nothing would be happened.
81
- *
82
- * However, no error exists, then exception would be thrown.
83
- *
84
- * @param title Title of exception because of no error exists
85
- */
86
- export const error =
87
- (title: string) =>
88
- <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
89
- const message = () => `Bug on ${title}: exception must be thrown.`;
90
- try {
91
- const output: T = task();
92
- if (is_promise(output))
93
- return new Promise<void>((resolve, reject) =>
94
- output.catch(() => resolve()).then(() => reject(message())),
95
- ) as any;
96
- else throw new Error(message());
97
- } catch {
98
- return undefined as any;
99
- }
100
- };
101
-
102
- export const httpError =
103
- (title: string) =>
104
- (...statuses: number[]) =>
105
- <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
106
- const message = (actual?: number) =>
107
- typeof actual === "number"
108
- ? `Bug on ${title}: status code must be ${statuses.join(
109
- " or ",
110
- )}, but ${actual}.`
111
- : `Bug on ${title}: status code must be ${statuses.join(
112
- " or ",
113
- )}, but succeeded.`;
114
- const predicate = (exp: any): Error | null =>
115
- typeof exp === "object" &&
116
- exp.constructor.name === "HttpError" &&
117
- statuses.some((val) => val === exp.status)
118
- ? null
119
- : new Error(
120
- message(
121
- typeof exp === "object" && exp.constructor.name === "HttpError"
122
- ? exp.status
123
- : undefined,
124
- ),
125
- );
126
- try {
127
- const output: T = task();
128
- if (is_promise(output))
129
- return new Promise<void>((resolve, reject) =>
130
- output
131
- .catch((exp) => {
132
- const res: Error | null = predicate(exp);
133
- if (res) reject(res);
134
- else resolve();
135
- })
136
- .then(() => reject(new Error(message()))),
137
- ) as any;
138
- else throw new Error(message());
139
- } catch (exp) {
140
- const res: Error | null = predicate(exp);
141
- if (res) throw res;
142
- return undefined!;
143
- }
144
- };
145
-
146
- export function proceed(task: () => Promise<any>): Promise<Error | null>;
147
- export function proceed(task: () => any): Error | null;
148
- export function proceed(
149
- task: () => any,
150
- ): Promise<Error | null> | (Error | null) {
151
- try {
152
- const output: any = task();
153
- if (is_promise(output))
154
- return new Promise<Error | null>((resolve) =>
155
- output
156
- .catch((exp) => resolve(exp as Error))
157
- .then(() => resolve(null)),
158
- );
159
- } catch (exp) {
160
- return exp as Error;
161
- }
162
- return null;
163
- }
164
-
165
- /**
166
- * Validate index API.
167
- *
168
- * Test whether two indexed values are equal.
169
- *
170
- * If two values are different, then exception would be thrown.
171
- *
172
- * @param title Title of error message when different
173
- * @return Currying function
174
- *
175
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
176
- */
177
- export const index =
178
- (title: string) =>
179
- <Solution extends IEntity<any>>(expected: Solution[]) =>
180
- <Summary extends IEntity<any>>(
181
- gotten: Summary[],
182
- trace: boolean = false,
183
- ): void => {
184
- const length: number = Math.min(expected.length, gotten.length);
185
- expected = expected.slice(0, length);
186
- gotten = gotten.slice(0, length);
187
-
188
- const xIds: string[] = get_ids(expected).slice(0, length);
189
- const yIds: string[] = get_ids(gotten)
190
- .filter((id) => id >= xIds[0])
191
- .slice(0, length);
192
-
193
- const equals: boolean = xIds.every((x, i) => x === yIds[i]);
194
- if (equals === true) return;
195
- else if (trace === true)
196
- console.log({
197
- expected: xIds,
198
- gotten: yIds,
199
- });
200
- throw new Error(
201
- `Bug on ${title}: result of the index is different with manual aggregation.`,
202
- );
203
- };
204
-
205
- /**
206
- * Valiate search options.
207
- *
208
- * Test a pagination API supporting search options.
209
- *
210
- * @param title Title of error message when searching is invalid
211
- * @returns Currying function
212
- *
213
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
214
- */
215
- export const search =
216
- (title: string) =>
217
- /**
218
- * @param getter A pagination API function to be called
219
- */
220
- <Entity extends IEntity<any>, Request>(
221
- getter: (input: Request) => Promise<Entity[]>,
222
- ) =>
223
- /**
224
- * @param total Total entity records for comparison
225
- * @param sampleCount Sampling count. Default is 1
226
- */
227
- (total: Entity[], sampleCount: number = 1) =>
228
- /**
229
- * @param props Search properties
230
- */
231
- async <Values extends any[]>(
232
- props: ISearchProps<Entity, Values, Request>,
233
- ): Promise<void> => {
234
- const samples: Entity[] = RandomGenerator.sample(total)(sampleCount);
235
- for (const s of samples) {
236
- const values: Values = props.values(s);
237
- const filtered: Entity[] = total.filter((entity) =>
238
- props.filter(entity, values),
239
- );
240
- const gotten: Entity[] = await getter(props.request(values));
241
-
242
- TestValidator.index(`${title} (${props.fields.join(", ")})`)(filtered)(
243
- gotten,
244
- );
245
- }
246
- };
247
-
248
- export interface ISearchProps<
249
- Entity extends IEntity<any>,
250
- Values extends any[],
251
- Request,
252
- > {
253
- fields: string[];
254
- values(entity: Entity): Values;
255
- filter(entity: Entity, values: Values): boolean;
256
- request(values: Values): Request;
257
- }
258
-
259
- /**
260
- * Validate sorting options.
261
- *
262
- * Test a pagination API supporting sorting options.
263
- *
264
- * You can validate detailed sorting options both ascending and descending orders
265
- * with multiple fields. However, as it forms a complicate currying function,
266
- * I recommend you to see below example code before using.
267
- *
268
- * @param title Title of error message when sorting is invalid
269
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_sort.ts
270
- */
271
- export const sort =
272
- (title: string) =>
273
- /**
274
- * @param getter A pagination API function to be called
275
- */
276
- <
277
- T extends object,
278
- Fields extends string,
279
- Sortable extends Array<`-${Fields}` | `+${Fields}`> = Array<
280
- `-${Fields}` | `+${Fields}`
281
- >,
282
- >(
283
- getter: (sortable: Sortable) => Promise<T[]>,
284
- ) =>
285
- /**
286
- * @param fields List of fields to be sorted
287
- */
288
- (...fields: Fields[]) =>
289
- /**
290
- * @param comp Comparator function for validation
291
- * @param filter Filter function for data if required
292
- */
293
- (comp: (x: T, y: T) => number, filter?: (elem: T) => boolean) =>
294
- /**
295
- * @param direction "+" means ascending order, and "-" means descending order
296
- */
297
- async (direction: "+" | "-", trace: boolean = false) => {
298
- let data: T[] = await getter(
299
- fields.map((field) => `${direction}${field}` as const) as Sortable,
300
- );
301
- if (filter) data = data.filter(filter);
302
-
303
- const reversed: typeof comp =
304
- direction === "+" ? comp : (x, y) => comp(y, x);
305
- if (is_sorted(data, reversed) === false) {
306
- if (
307
- fields.length === 1 &&
308
- data.length &&
309
- (data as any)[0][fields[0]] !== undefined &&
310
- trace
311
- )
312
- console.log(data.map((elem) => (elem as any)[fields[0]]));
313
- throw new Error(
314
- `Bug on ${title}: wrong sorting on ${direction}(${fields.join(
315
- ", ",
316
- )}).`,
317
- );
318
- }
319
- };
320
-
321
- export type Sortable<Literal extends string> = Array<
322
- `-${Literal}` | `+${Literal}`
323
- >;
324
- }
325
-
326
- interface IEntity<Type extends string | number | bigint> {
327
- id: Type;
328
- }
329
-
330
- function get_ids<Entity extends IEntity<any>>(entities: Entity[]): string[] {
331
- return entities.map((entity) => entity.id).sort((x, y) => (x < y ? -1 : 1));
332
- }
333
-
334
- function is_promise(input: any): input is Promise<any> {
335
- return (
336
- typeof input === "object" &&
337
- input !== null &&
338
- typeof (input as any).then === "function" &&
339
- typeof (input as any).catch === "function"
340
- );
341
- }
342
-
343
- function is_sorted<T>(data: T[], comp: (x: T, y: T) => number): boolean {
344
- for (let i: number = 1; i < data.length; ++i)
345
- if (comp(data[i - 1], data[i]) > 0) return false;
346
- return true;
347
- }
1
+ import { RandomGenerator } from "./RandomGenerator";
2
+ import { json_equal_to } from "./internal/json_equal_to";
3
+
4
+ /**
5
+ * A comprehensive collection of E2E validation utilities for testing
6
+ * applications.
7
+ *
8
+ * TestValidator provides type-safe validation functions for common testing
9
+ * scenarios including condition checking, equality validation, error testing,
10
+ * HTTP error validation, pagination testing, search functionality validation,
11
+ * and sorting validation.
12
+ *
13
+ * All functions follow a currying pattern to enable reusable test
14
+ * configurations and provide detailed error messages for debugging failed
15
+ * assertions.
16
+ *
17
+ * @author Jeongho Nam - https://github.com/samchon
18
+ * @example
19
+ * ```typescript
20
+ * // Basic condition testing
21
+ * TestValidator.predicate("user should be authenticated")(user.isAuthenticated);
22
+ *
23
+ * // Equality validation
24
+ * TestValidator.equals("API response should match expected")(expected)(actual);
25
+ *
26
+ * // Error validation
27
+ * TestValidator.error("should throw on invalid input")(() => validateInput(""));
28
+ * ```;
29
+ */
30
+ export namespace TestValidator {
31
+ /**
32
+ * Validates that a given condition evaluates to true.
33
+ *
34
+ * Supports synchronous boolean values, synchronous functions returning
35
+ * boolean, and asynchronous functions returning Promise<boolean>. The return
36
+ * type is automatically inferred based on the input type.
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Synchronous boolean
41
+ * TestValidator.predicate("user should exist")(user !== null);
42
+ *
43
+ * // Synchronous function
44
+ * TestValidator.predicate("array should be empty")(() => arr.length === 0);
45
+ *
46
+ * // Asynchronous function
47
+ * await TestValidator.predicate("database should be connected")(
48
+ * async () => await db.ping()
49
+ * );
50
+ * ```;
51
+ *
52
+ * @param title - Descriptive title used in error messages when validation
53
+ * fails
54
+ * @returns A currying function that accepts the condition to validate
55
+ * @throws Error with descriptive message when condition is not satisfied
56
+ */
57
+ export const predicate =
58
+ (title: string) =>
59
+ <T extends boolean | (() => boolean) | (() => Promise<boolean>)>(
60
+ condition: T,
61
+ ): T extends () => Promise<boolean> ? Promise<void> : void => {
62
+ const message = () =>
63
+ `Bug on ${title}: expected condition is not satisfied.`;
64
+
65
+ // SCALAR
66
+ if (typeof condition === "boolean") {
67
+ if (condition !== true) throw new Error(message());
68
+ return undefined as any;
69
+ }
70
+
71
+ // CLOSURE
72
+ const output: boolean | Promise<boolean> = condition();
73
+ if (typeof output === "boolean") {
74
+ if (output !== true) throw new Error(message());
75
+ return undefined as any;
76
+ }
77
+
78
+ // ASYNCHRONOUS
79
+ return new Promise<void>((resolve, reject) => {
80
+ output
81
+ .then((flag) => {
82
+ if (flag === true) resolve();
83
+ else reject(message());
84
+ })
85
+ .catch(reject);
86
+ }) as any;
87
+ };
88
+
89
+ /**
90
+ * Validates deep equality between two values using JSON comparison.
91
+ *
92
+ * Performs recursive comparison of objects and arrays. Supports an optional
93
+ * exception filter to ignore specific keys during comparison. Useful for
94
+ * validating API responses, data transformations, and object state changes.
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * // Basic equality
99
+ * TestValidator.equals("response should match expected")(expectedUser)(actualUser);
100
+ *
101
+ * // Ignore timestamps in comparison
102
+ * TestValidator.equals("user data should match", (key) => key === "updatedAt")(
103
+ * expectedUser
104
+ * )(actualUser);
105
+ *
106
+ * // Validate API response structure
107
+ * const validateResponse = TestValidator.equals("API response structure");
108
+ * validateResponse({ id: 1, name: "John" })({ id: 1, name: "John" });
109
+ * ```;
110
+ *
111
+ * @param title - Descriptive title used in error messages when values differ
112
+ * @param exception - Optional filter function to exclude specific keys from
113
+ * comparison
114
+ * @returns A currying function chain: first accepts expected value, then
115
+ * actual value
116
+ * @throws Error with detailed diff information when values are not equal
117
+ */
118
+ export const equals =
119
+ (title: string, exception: (key: string) => boolean = () => false) =>
120
+ <T>(x: T) =>
121
+ (y: T) => {
122
+ const diff: string[] = json_equal_to(exception)(x)(y);
123
+ if (diff.length)
124
+ throw new Error(
125
+ [
126
+ `Bug on ${title}: found different values - [${diff.join(", ")}]:`,
127
+ "\n",
128
+ JSON.stringify({ x, y }, null, 2),
129
+ ].join("\n"),
130
+ );
131
+ };
132
+
133
+ /**
134
+ * Validates that a function throws an error or rejects when executed.
135
+ *
136
+ * Expects the provided function to fail. If the function executes
137
+ * successfully without throwing an error or rejecting, this validator will
138
+ * throw an exception. Supports both synchronous and asynchronous functions.
139
+ *
140
+ * @example
141
+ * ```typescript
142
+ * // Synchronous error validation
143
+ * TestValidator.error("should reject invalid email")(
144
+ * () => validateEmail("invalid-email")
145
+ * );
146
+ *
147
+ * // Asynchronous error validation
148
+ * await TestValidator.error("should reject unauthorized access")(
149
+ * async () => await api.functional.getSecretData()
150
+ * );
151
+ *
152
+ * // Validate input validation
153
+ * TestValidator.error("should throw on empty string")(
154
+ * () => processRequiredInput("")
155
+ * );
156
+ * ```;
157
+ *
158
+ * @param title - Descriptive title used in error messages when no error
159
+ * occurs
160
+ * @returns A currying function that accepts the task function to validate
161
+ * @throws Error when the task function does not throw an error or reject
162
+ */
163
+ export const error =
164
+ (title: string) =>
165
+ <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
166
+ const message = () => `Bug on ${title}: exception must be thrown.`;
167
+ try {
168
+ const output: T = task();
169
+ if (is_promise(output))
170
+ return new Promise<void>((resolve, reject) =>
171
+ output.catch(() => resolve()).then(() => reject(message())),
172
+ ) as any;
173
+ else throw new Error(message());
174
+ } catch {
175
+ return undefined as any;
176
+ }
177
+ };
178
+
179
+ /**
180
+ * Validates that a function throws an HTTP error with specific status codes.
181
+ *
182
+ * Specialized error validator for HTTP operations. Validates that the
183
+ * function throws an HttpError with one of the specified status codes. Useful
184
+ * for testing API endpoints, authentication, and authorization logic.
185
+ *
186
+ * @example
187
+ * ```typescript
188
+ * // Validate 401 Unauthorized
189
+ * await TestValidator.httpError("should return 401 for invalid token")(401)(
190
+ * async () => await api.functional.getProtectedResource("invalid-token")
191
+ * );
192
+ *
193
+ * // Validate multiple possible error codes
194
+ * await TestValidator.httpError("should return client error")(400, 404, 422)(
195
+ * async () => await api.functional.updateNonexistentResource(data)
196
+ * );
197
+ *
198
+ * // Validate server errors
199
+ * TestValidator.httpError("should handle server errors")(500, 502, 503)(
200
+ * () => callFaultyEndpoint()
201
+ * );
202
+ * ```;
203
+ *
204
+ * @param title - Descriptive title used in error messages
205
+ * @returns A currying function that accepts status codes, then the task
206
+ * function
207
+ * @throws Error when function doesn't throw HttpError or status code doesn't
208
+ * match
209
+ */
210
+ export const httpError =
211
+ (title: string) =>
212
+ (...statuses: number[]) =>
213
+ <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
214
+ const message = (actual?: number) =>
215
+ typeof actual === "number"
216
+ ? `Bug on ${title}: status code must be ${statuses.join(
217
+ " or ",
218
+ )}, but ${actual}.`
219
+ : `Bug on ${title}: status code must be ${statuses.join(
220
+ " or ",
221
+ )}, but succeeded.`;
222
+ const predicate = (exp: any): Error | null =>
223
+ typeof exp === "object" &&
224
+ exp.constructor.name === "HttpError" &&
225
+ statuses.some((val) => val === exp.status)
226
+ ? null
227
+ : new Error(
228
+ message(
229
+ typeof exp === "object" && exp.constructor.name === "HttpError"
230
+ ? exp.status
231
+ : undefined,
232
+ ),
233
+ );
234
+ try {
235
+ const output: T = task();
236
+ if (is_promise(output))
237
+ return new Promise<void>((resolve, reject) =>
238
+ output
239
+ .catch((exp) => {
240
+ const res: Error | null = predicate(exp);
241
+ if (res) reject(res);
242
+ else resolve();
243
+ })
244
+ .then(() => reject(new Error(message()))),
245
+ ) as any;
246
+ else throw new Error(message());
247
+ } catch (exp) {
248
+ const res: Error | null = predicate(exp);
249
+ if (res) throw res;
250
+ return undefined!;
251
+ }
252
+ };
253
+
254
+ /**
255
+ * Safely executes a function and captures any errors without throwing.
256
+ *
257
+ * Utility function for error handling in tests. Executes the provided
258
+ * function and returns any error that occurs, or null if successful. Supports
259
+ * both synchronous and asynchronous functions. Useful for testing error
260
+ * conditions without stopping test execution.
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * // Synchronous error capture
265
+ * const error = TestValidator.proceed(() => {
266
+ * throw new Error("Something went wrong");
267
+ * });
268
+ * console.log(error?.message); // "Something went wrong"
269
+ *
270
+ * // Asynchronous error capture
271
+ * const asyncError = await TestValidator.proceed(async () => {
272
+ * await failingAsyncOperation();
273
+ * });
274
+ *
275
+ * // Success case
276
+ * const noError = TestValidator.proceed(() => {
277
+ * return "success";
278
+ * });
279
+ * console.log(noError); // null
280
+ * ```;
281
+ *
282
+ * @param task - Function to execute safely
283
+ * @returns Error object if function throws/rejects, null if successful
284
+ */
285
+ export function proceed(task: () => Promise<any>): Promise<Error | null>;
286
+ export function proceed(task: () => any): Error | null;
287
+ export function proceed(
288
+ task: () => any,
289
+ ): Promise<Error | null> | (Error | null) {
290
+ try {
291
+ const output: any = task();
292
+ if (is_promise(output))
293
+ return new Promise<Error | null>((resolve) =>
294
+ output
295
+ .catch((exp) => resolve(exp as Error))
296
+ .then(() => resolve(null)),
297
+ );
298
+ } catch (exp) {
299
+ return exp as Error;
300
+ }
301
+ return null;
302
+ }
303
+
304
+ /**
305
+ * Validates pagination index API results against expected entity order.
306
+ *
307
+ * Compares the order of entities returned by a pagination API with manually
308
+ * sorted expected results. Validates that entity IDs appear in the correct
309
+ * sequence. Commonly used for testing database queries, search results, and
310
+ * any paginated data APIs.
311
+ *
312
+ * @example
313
+ * ```typescript
314
+ * // Test article pagination
315
+ * const expectedArticles = await db.articles.findAll({ order: 'created_at DESC' });
316
+ * const actualArticles = await api.functional.getArticles({ page: 1, limit: 10 });
317
+ *
318
+ * TestValidator.index("article pagination order")(expectedArticles)(
319
+ * actualArticles,
320
+ * true // enable trace logging
321
+ * );
322
+ *
323
+ * // Test user search results
324
+ * const manuallyFilteredUsers = allUsers.filter(u => u.name.includes("John"));
325
+ * const apiSearchResults = await api.functional.searchUsers({ query: "John" });
326
+ *
327
+ * TestValidator.index("user search results")(manuallyFilteredUsers)(
328
+ * apiSearchResults
329
+ * );
330
+ * ```;
331
+ *
332
+ * @param title - Descriptive title used in error messages when order differs
333
+ * @returns A currying function chain: expected entities, then actual entities
334
+ * @throws Error when entity order differs between expected and actual results
335
+ */
336
+ export const index =
337
+ (title: string) =>
338
+ <Solution extends IEntity<any>>(expected: Solution[]) =>
339
+ <Summary extends IEntity<any>>(
340
+ gotten: Summary[],
341
+ trace: boolean = false,
342
+ ): void => {
343
+ const length: number = Math.min(expected.length, gotten.length);
344
+ expected = expected.slice(0, length);
345
+ gotten = gotten.slice(0, length);
346
+
347
+ const xIds: string[] = get_ids(expected).slice(0, length);
348
+ const yIds: string[] = get_ids(gotten)
349
+ .filter((id) => id >= xIds[0])
350
+ .slice(0, length);
351
+
352
+ const equals: boolean = xIds.every((x, i) => x === yIds[i]);
353
+ if (equals === true) return;
354
+ else if (trace === true)
355
+ console.log({
356
+ expected: xIds,
357
+ gotten: yIds,
358
+ });
359
+ throw new Error(
360
+ `Bug on ${title}: result of the index is different with manual aggregation.`,
361
+ );
362
+ };
363
+
364
+ /**
365
+ * Validates search functionality by testing API results against manual
366
+ * filtering.
367
+ *
368
+ * Comprehensive search validation that samples entities from a complete
369
+ * dataset, extracts search values, applies manual filtering, calls the search
370
+ * API, and compares results. Validates that search APIs return the correct
371
+ * subset of data matching the search criteria.
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * // Test article search functionality
376
+ * const allArticles = await db.articles.findAll();
377
+ * const searchValidator = TestValidator.search("article search API")(
378
+ * (req) => api.searchArticles(req)
379
+ * )(allArticles, 5); // test with 5 random samples
380
+ *
381
+ * await searchValidator({
382
+ * fields: ["title", "content"],
383
+ * values: (article) => [article.title.split(" ")[0]], // first word
384
+ * filter: (article, [keyword]) =>
385
+ * article.title.includes(keyword) || article.content.includes(keyword),
386
+ * request: ([keyword]) => ({ q: keyword })
387
+ * });
388
+ *
389
+ * // Test user search with multiple criteria
390
+ * await TestValidator.search("user search with filters")(
391
+ * (req) => api.getUsers(req)
392
+ * )(allUsers, 3)({
393
+ * fields: ["status", "role"],
394
+ * values: (user) => [user.status, user.role],
395
+ * filter: (user, [status, role]) =>
396
+ * user.status === status && user.role === role,
397
+ * request: ([status, role]) => ({ status, role })
398
+ * });
399
+ * ```;
400
+ *
401
+ * @param title - Descriptive title used in error messages when search fails
402
+ * @returns A currying function chain: API getter function, then dataset and
403
+ * sample count
404
+ * @throws Error when API search results don't match manual filtering results
405
+ */
406
+ export const search =
407
+ (title: string) =>
408
+ <Entity extends IEntity<any>, Request>(
409
+ getter: (input: Request) => Promise<Entity[]>,
410
+ ) =>
411
+ (total: Entity[], sampleCount: number = 1) =>
412
+ async <Values extends any[]>(
413
+ props: ISearchProps<Entity, Values, Request>,
414
+ ): Promise<void> => {
415
+ const samples: Entity[] = RandomGenerator.sample(total)(sampleCount);
416
+ for (const s of samples) {
417
+ const values: Values = props.values(s);
418
+ const filtered: Entity[] = total.filter((entity) =>
419
+ props.filter(entity, values),
420
+ );
421
+ const gotten: Entity[] = await getter(props.request(values));
422
+
423
+ TestValidator.index(`${title} (${props.fields.join(", ")})`)(filtered)(
424
+ gotten,
425
+ );
426
+ }
427
+ };
428
+
429
+ /**
430
+ * Configuration interface for search validation functionality.
431
+ *
432
+ * Defines the structure needed to validate search operations by specifying
433
+ * how to extract search values from entities, filter the dataset manually,
434
+ * and construct API requests.
435
+ *
436
+ * @template Entity - Type of entities being searched, must have an ID field
437
+ * @template Values - Tuple type representing the search values extracted from
438
+ * entities
439
+ * @template Request - Type of the API request object
440
+ */
441
+ export interface ISearchProps<
442
+ Entity extends IEntity<any>,
443
+ Values extends any[],
444
+ Request,
445
+ > {
446
+ /** Field names being searched, used in error messages for identification */
447
+ fields: string[];
448
+
449
+ /**
450
+ * Extracts search values from a sample entity
451
+ *
452
+ * @param entity - The entity to extract search values from
453
+ * @returns Tuple of values used for searching
454
+ */
455
+ values(entity: Entity): Values;
456
+
457
+ /**
458
+ * Manual filter function to determine if an entity matches search criteria
459
+ *
460
+ * @param entity - Entity to test against criteria
461
+ * @param values - Search values to match against
462
+ * @returns True if entity matches the search criteria
463
+ */
464
+ filter(entity: Entity, values: Values): boolean;
465
+
466
+ /**
467
+ * Constructs API request object from search values
468
+ *
469
+ * @param values - Search values to include in request
470
+ * @returns Request object for the search API
471
+ */
472
+ request(values: Values): Request;
473
+ }
474
+
475
+ /**
476
+ * Validates sorting functionality of pagination APIs.
477
+ *
478
+ * Tests sorting operations by calling the API with sort parameters and
479
+ * validating that results are correctly ordered. Supports multiple fields,
480
+ * ascending/descending order, and optional filtering. Provides detailed error
481
+ * reporting for sorting failures.
482
+ *
483
+ * @example
484
+ * ```typescript
485
+ * // Test single field sorting
486
+ * const sortValidator = TestValidator.sort("article sorting")(
487
+ * (sortable) => api.getArticles({ sort: sortable })
488
+ * )("created_at")(
489
+ * (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
490
+ * );
491
+ *
492
+ * await sortValidator("+"); // ascending
493
+ * await sortValidator("-"); // descending
494
+ *
495
+ * // Test multi-field sorting with filtering
496
+ * const userSortValidator = TestValidator.sort("user sorting")(
497
+ * (sortable) => api.getUsers({ sort: sortable })
498
+ * )("status", "created_at")(
499
+ * (a, b) => {
500
+ * if (a.status !== b.status) return a.status.localeCompare(b.status);
501
+ * return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
502
+ * },
503
+ * (user) => user.isActive // only test active users
504
+ * );
505
+ *
506
+ * await userSortValidator("+", true); // ascending with trace logging
507
+ * ```;
508
+ *
509
+ * @param title - Descriptive title used in error messages when sorting fails
510
+ * @returns A currying function chain: API getter, field names, comparator,
511
+ * then direction
512
+ * @throws Error when API results are not properly sorted according to
513
+ * specification
514
+ */
515
+ export const sort =
516
+ (title: string) =>
517
+ <
518
+ T extends object,
519
+ Fields extends string,
520
+ Sortable extends Array<`-${Fields}` | `+${Fields}`> = Array<
521
+ `-${Fields}` | `+${Fields}`
522
+ >,
523
+ >(
524
+ getter: (sortable: Sortable) => Promise<T[]>,
525
+ ) =>
526
+ (...fields: Fields[]) =>
527
+ (comp: (x: T, y: T) => number, filter?: (elem: T) => boolean) =>
528
+ async (direction: "+" | "-", trace: boolean = false) => {
529
+ let data: T[] = await getter(
530
+ fields.map((field) => `${direction}${field}` as const) as Sortable,
531
+ );
532
+ if (filter) data = data.filter(filter);
533
+
534
+ const reversed: typeof comp =
535
+ direction === "+" ? comp : (x, y) => comp(y, x);
536
+ if (is_sorted(data, reversed) === false) {
537
+ if (
538
+ fields.length === 1 &&
539
+ data.length &&
540
+ (data as any)[0][fields[0]] !== undefined &&
541
+ trace
542
+ )
543
+ console.log(data.map((elem) => (elem as any)[fields[0]]));
544
+ throw new Error(
545
+ `Bug on ${title}: wrong sorting on ${direction}(${fields.join(
546
+ ", ",
547
+ )}).`,
548
+ );
549
+ }
550
+ };
551
+
552
+ /**
553
+ * Type alias for sortable field specifications.
554
+ *
555
+ * Represents an array of sort field specifications where each field can be
556
+ * prefixed with '+' for ascending order or '-' for descending order.
557
+ *
558
+ * @example
559
+ * ```typescript
560
+ * type UserSortable = TestValidator.Sortable<"name" | "email" | "created_at">;
561
+ * // Results in: Array<"-name" | "+name" | "-email" | "+email" | "-created_at" | "+created_at">
562
+ *
563
+ * const userSort: UserSortable = ["+name", "-created_at"];
564
+ * ```;
565
+ *
566
+ * @template Literal - String literal type representing available field names
567
+ */
568
+ export type Sortable<Literal extends string> = Array<
569
+ `-${Literal}` | `+${Literal}`
570
+ >;
571
+ }
572
+
573
+ interface IEntity<Type extends string | number | bigint> {
574
+ id: Type;
575
+ }
576
+
577
+ function get_ids<Entity extends IEntity<any>>(entities: Entity[]): string[] {
578
+ return entities.map((entity) => entity.id).sort((x, y) => (x < y ? -1 : 1));
579
+ }
580
+
581
+ function is_promise(input: any): input is Promise<any> {
582
+ return (
583
+ typeof input === "object" &&
584
+ input !== null &&
585
+ typeof (input as any).then === "function" &&
586
+ typeof (input as any).catch === "function"
587
+ );
588
+ }
589
+
590
+ function is_sorted<T>(data: T[], comp: (x: T, y: T) => number): boolean {
591
+ for (let i: number = 1; i < data.length; ++i)
592
+ if (comp(data[i - 1], data[i]) > 0) return false;
593
+ return true;
594
+ }