@nestia/e2e 0.4.2 → 0.5.0-dev.20240617

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,339 +1,343 @@
1
- import { is_sorted } from "tstl/ranges";
2
-
3
- import { RandomGenerator } from "./RandomGenerator";
4
- import { json_equal_to } from "./internal/json_equal_to";
5
-
6
- /**
7
- * Test validator.
8
- *
9
- * `TestValidator` is a collection gathering E2E validation functions.
10
- *
11
- * @author Jeongho Nam - https://github.com/samchon
12
- */
13
- export namespace TestValidator {
14
- /**
15
- * Test whether condition is satisfied.
16
- *
17
- * @param title Title of error message when condition is not satisfied
18
- * @return Currying function
19
- */
20
- export const predicate =
21
- (title: string) =>
22
- <T extends boolean | (() => boolean) | (() => Promise<boolean>)>(
23
- condition: T,
24
- ): T extends () => Promise<boolean> ? Promise<void> : void => {
25
- const message = () =>
26
- `Bug on ${title}: expected condition is not satisfied.`;
27
-
28
- // SCALAR
29
- if (typeof condition === "boolean") {
30
- if (condition !== true) throw new Error(message());
31
- return undefined as any;
32
- }
33
-
34
- // CLOSURE
35
- const output: boolean | Promise<boolean> = condition();
36
- if (typeof output === "boolean") {
37
- if (output !== true) throw new Error(message());
38
- return undefined as any;
39
- }
40
-
41
- // ASYNCHRONOUS
42
- return new Promise<void>((resolve, reject) => {
43
- output
44
- .then((flag) => {
45
- if (flag === true) resolve();
46
- else reject(message());
47
- })
48
- .catch(reject);
49
- }) as any;
50
- };
51
-
52
- /**
53
- * Test whether two values are equal.
54
- *
55
- * If you want to validate `covers` relationship,
56
- * call smaller first and then larger.
57
- *
58
- * Otherwise you wanna non equals validator, combine with {@link error}.
59
- *
60
- * @param title Title of error message when different
61
- * @param exception Exception filter for ignoring some keys
62
- * @returns Currying function
63
- */
64
- export const equals =
65
- (title: string, exception: (key: string) => boolean = () => false) =>
66
- <T>(x: T) =>
67
- (y: T) => {
68
- const diff: string[] = json_equal_to(exception)(x)(y);
69
- if (diff.length)
70
- throw new Error(
71
- `Bug on ${title}: found different values - [${diff.join(", ")}]`,
72
- );
73
- };
74
-
75
- /**
76
- * Test whether error occurs.
77
- *
78
- * If error occurs, nothing would be happened.
79
- *
80
- * However, no error exists, then exception would be thrown.
81
- *
82
- * @param title Title of exception because of no error exists
83
- */
84
- export const error =
85
- (title: string) =>
86
- <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
87
- const message = () => `Bug on ${title}: exception must be thrown.`;
88
- try {
89
- const output: T = task();
90
- if (is_promise(output))
91
- return new Promise<void>((resolve, reject) =>
92
- output.catch(() => resolve()).then(() => reject(message())),
93
- ) as any;
94
- else throw new Error(message());
95
- } catch {
96
- return undefined as any;
97
- }
98
- };
99
-
100
- export const httpError =
101
- (title: string) =>
102
- (...statuses: number[]) =>
103
- <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
104
- const message = (actual?: number) =>
105
- typeof actual === "number"
106
- ? `Bug on ${title}: status code must be ${statuses.join(
107
- " or ",
108
- )}, but ${actual}.`
109
- : `Bug on ${title}: status code must be ${statuses.join(
110
- " or ",
111
- )}, but succeeded.`;
112
- const predicate = (exp: any): Error | null =>
113
- typeof exp === "object" &&
114
- exp.constructor.name === "HttpError" &&
115
- statuses.some((val) => val === exp.status)
116
- ? null
117
- : new Error(
118
- message(
119
- typeof exp === "object" && exp.constructor.name === "HttpError"
120
- ? exp.status
121
- : undefined,
122
- ),
123
- );
124
- try {
125
- const output: T = task();
126
- if (is_promise(output))
127
- return new Promise<void>((resolve, reject) =>
128
- output
129
- .catch((exp) => {
130
- const res: Error | null = predicate(exp);
131
- if (res) reject(res);
132
- else resolve();
133
- })
134
- .then(() => reject(new Error(message()))),
135
- ) as any;
136
- else throw new Error(message());
137
- } catch (exp) {
138
- const res: Error | null = predicate(exp);
139
- if (res) throw res;
140
- return undefined!;
141
- }
142
- };
143
-
144
- export function proceed(task: () => Promise<any>): Promise<Error | null>;
145
- export function proceed(task: () => any): Error | null;
146
- export function proceed(
147
- task: () => any,
148
- ): Promise<Error | null> | (Error | null) {
149
- try {
150
- const output: any = task();
151
- if (is_promise(output))
152
- return new Promise<Error | null>((resolve) =>
153
- output
154
- .catch((exp) => resolve(exp as Error))
155
- .then(() => resolve(null)),
156
- );
157
- } catch (exp) {
158
- return exp as Error;
159
- }
160
- return null;
161
- }
162
-
163
- /**
164
- * Validate index API.
165
- *
166
- * Test whether two indexed values are equal.
167
- *
168
- * If two values are different, then exception would be thrown.
169
- *
170
- * @param title Title of error message when different
171
- * @return Currying function
172
- *
173
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
174
- */
175
- export const index =
176
- (title: string) =>
177
- <Solution extends IEntity<any>>(expected: Solution[]) =>
178
- <Summary extends IEntity<any>>(
179
- gotten: Summary[],
180
- trace: boolean = true,
181
- ): void => {
182
- const length: number = Math.min(expected.length, gotten.length);
183
- expected = expected.slice(0, length);
184
- gotten = gotten.slice(0, length);
185
-
186
- const xIds: string[] = get_ids(expected).slice(0, length);
187
- const yIds: string[] = get_ids(gotten)
188
- .filter((id) => id >= xIds[0])
189
- .slice(0, length);
190
-
191
- const equals: boolean = xIds.every((x, i) => x === yIds[i]);
192
- if (equals === true) return;
193
- else if (trace === true)
194
- console.log({
195
- expected: xIds,
196
- gotten: yIds,
197
- });
198
- throw new Error(
199
- `Bug on ${title}: result of the index is different with manual aggregation.`,
200
- );
201
- };
202
-
203
- /**
204
- * Valiate search options.
205
- *
206
- * Test a pagination API supporting search options.
207
- *
208
- * @param title Title of error message when searching is invalid
209
- * @returns Currying function
210
- *
211
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
212
- */
213
- export const search =
214
- (title: string) =>
215
- /**
216
- * @param getter A pagination API function to be called
217
- */
218
- <Entity extends IEntity<any>, Request>(
219
- getter: (input: Request) => Promise<Entity[]>,
220
- ) =>
221
- /**
222
- * @param total Total entity records for comparison
223
- * @param sampleCount Sampling count. Default is 1
224
- */
225
- (total: Entity[], sampleCount: number = 1) =>
226
- /**
227
- * @param props Search properties
228
- */
229
- async <Values extends any[]>(
230
- props: ISearchProps<Entity, Values, Request>,
231
- ): Promise<void> => {
232
- const samples: Entity[] = RandomGenerator.sample(total)(sampleCount);
233
- for (const s of samples) {
234
- const values: Values = props.values(s);
235
- const filtered: Entity[] = total.filter((entity) =>
236
- props.filter(entity, values),
237
- );
238
- const gotten: Entity[] = await getter(props.request(values));
239
-
240
- TestValidator.index(`${title} (${props.fields.join(", ")})`)(filtered)(
241
- gotten,
242
- );
243
- }
244
- };
245
-
246
- export interface ISearchProps<
247
- Entity extends IEntity<any>,
248
- Values extends any[],
249
- Request,
250
- > {
251
- fields: string[];
252
- values(entity: Entity): Values;
253
- filter(entity: Entity, values: Values): boolean;
254
- request(values: Values): Request;
255
- }
256
-
257
- /**
258
- * Validate sorting options.
259
- *
260
- * Test a pagination API supporting sorting options.
261
- *
262
- * You can validate detailed sorting options both asceding and descending orders
263
- * with multiple fields. However, as it forms a complicate currying function,
264
- * I recomend you to see below example code before using.
265
- *
266
- * @param title Title of error message when sorting is invalid
267
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_sort.ts
268
- */
269
- export const sort =
270
- (title: string) =>
271
- /**
272
- * @param getter A pagination API function to be called
273
- */
274
- <
275
- T extends object,
276
- Fields extends string,
277
- Sortable extends Array<`-${Fields}` | `+${Fields}`> = Array<
278
- `-${Fields}` | `+${Fields}`
279
- >,
280
- >(
281
- getter: (sortable: Sortable) => Promise<T[]>,
282
- ) =>
283
- /**
284
- * @param fields List of fields to be sorted
285
- */
286
- (...fields: Fields[]) =>
287
- /**
288
- * @param comp Comparator function for validation
289
- * @param filter Filter function for data if required
290
- */
291
- (comp: (x: T, y: T) => number, filter?: (elem: T) => boolean) =>
292
- /**
293
- * @param direction "+" means ascending order, and "-" means descending order
294
- */
295
- async (direction: "+" | "-", trace: boolean = true) => {
296
- let data: T[] = await getter(
297
- fields.map((field) => `${direction}${field}` as const) as Sortable,
298
- );
299
- if (filter) data = data.filter(filter);
300
-
301
- const reversed: typeof comp =
302
- direction === "+" ? comp : (x, y) => comp(y, x);
303
- if (is_sorted(data, (x, y) => reversed(x, y) < 0) === false) {
304
- if (
305
- fields.length === 1 &&
306
- data.length &&
307
- (data as any)[0][fields[0]] !== undefined &&
308
- trace
309
- )
310
- console.log(data.map((elem) => (elem as any)[fields[0]]));
311
- throw new Error(
312
- `Bug on ${title}: wrong sorting on ${direction}(${fields.join(
313
- ", ",
314
- )}).`,
315
- );
316
- }
317
- };
318
-
319
- export type Sortable<Literal extends string> = Array<
320
- `-${Literal}` | `+${Literal}`
321
- >;
322
- }
323
-
324
- interface IEntity<Type extends string | number | bigint> {
325
- id: Type;
326
- }
327
-
328
- function get_ids<Entity extends IEntity<any>>(entities: Entity[]): string[] {
329
- return entities.map((entity) => entity.id).sort((x, y) => (x < y ? -1 : 1));
330
- }
331
-
332
- function is_promise(input: any): input is Promise<any> {
333
- return (
334
- typeof input === "object" &&
335
- input !== null &&
336
- typeof (input as any).then === "function" &&
337
- typeof (input as any).catch === "function"
338
- );
339
- }
1
+ import { ranges } from "tstl";
2
+
3
+ import { RandomGenerator } from "./RandomGenerator";
4
+ import { json_equal_to } from "./internal/json_equal_to";
5
+
6
+ /**
7
+ * Test validator.
8
+ *
9
+ * `TestValidator` is a collection gathering E2E validation functions.
10
+ *
11
+ * @author Jeongho Nam - https://github.com/samchon
12
+ */
13
+ export namespace TestValidator {
14
+ /**
15
+ * Test whether condition is satisfied.
16
+ *
17
+ * @param title Title of error message when condition is not satisfied
18
+ * @return Currying function
19
+ */
20
+ export const predicate =
21
+ (title: string) =>
22
+ <T extends boolean | (() => boolean) | (() => Promise<boolean>)>(
23
+ condition: T,
24
+ ): T extends () => Promise<boolean> ? Promise<void> : void => {
25
+ const message = () =>
26
+ `Bug on ${title}: expected condition is not satisfied.`;
27
+
28
+ // SCALAR
29
+ if (typeof condition === "boolean") {
30
+ if (condition !== true) throw new Error(message());
31
+ return undefined as any;
32
+ }
33
+
34
+ // CLOSURE
35
+ const output: boolean | Promise<boolean> = condition();
36
+ if (typeof output === "boolean") {
37
+ if (output !== true) throw new Error(message());
38
+ return undefined as any;
39
+ }
40
+
41
+ // ASYNCHRONOUS
42
+ return new Promise<void>((resolve, reject) => {
43
+ output
44
+ .then((flag) => {
45
+ if (flag === true) resolve();
46
+ else reject(message());
47
+ })
48
+ .catch(reject);
49
+ }) as any;
50
+ };
51
+
52
+ /**
53
+ * Test whether two values are equal.
54
+ *
55
+ * If you want to validate `covers` relationship,
56
+ * call smaller first and then larger.
57
+ *
58
+ * Otherwise you wanna non equals validator, combine with {@link error}.
59
+ *
60
+ * @param title Title of error message when different
61
+ * @param exception Exception filter for ignoring some keys
62
+ * @returns Currying function
63
+ */
64
+ export const equals =
65
+ (title: string, exception: (key: string) => boolean = () => false) =>
66
+ <T>(x: T) =>
67
+ (y: T) => {
68
+ const diff: string[] = json_equal_to(exception)(x)(y);
69
+ if (diff.length)
70
+ throw new Error(
71
+ [
72
+ `Bug on ${title}: found different values - [${diff.join(", ")}]:`,
73
+ "\n",
74
+ JSON.stringify({ x, y }, null, 2),
75
+ ].join("\n"),
76
+ );
77
+ };
78
+
79
+ /**
80
+ * Test whether error occurs.
81
+ *
82
+ * If error occurs, nothing would be happened.
83
+ *
84
+ * However, no error exists, then exception would be thrown.
85
+ *
86
+ * @param title Title of exception because of no error exists
87
+ */
88
+ export const error =
89
+ (title: string) =>
90
+ <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
91
+ const message = () => `Bug on ${title}: exception must be thrown.`;
92
+ try {
93
+ const output: T = task();
94
+ if (is_promise(output))
95
+ return new Promise<void>((resolve, reject) =>
96
+ output.catch(() => resolve()).then(() => reject(message())),
97
+ ) as any;
98
+ else throw new Error(message());
99
+ } catch {
100
+ return undefined as any;
101
+ }
102
+ };
103
+
104
+ export const httpError =
105
+ (title: string) =>
106
+ (...statuses: number[]) =>
107
+ <T>(task: () => T): T extends Promise<any> ? Promise<void> : void => {
108
+ const message = (actual?: number) =>
109
+ typeof actual === "number"
110
+ ? `Bug on ${title}: status code must be ${statuses.join(
111
+ " or ",
112
+ )}, but ${actual}.`
113
+ : `Bug on ${title}: status code must be ${statuses.join(
114
+ " or ",
115
+ )}, but succeeded.`;
116
+ const predicate = (exp: any): Error | null =>
117
+ typeof exp === "object" &&
118
+ exp.constructor.name === "HttpError" &&
119
+ statuses.some((val) => val === exp.status)
120
+ ? null
121
+ : new Error(
122
+ message(
123
+ typeof exp === "object" && exp.constructor.name === "HttpError"
124
+ ? exp.status
125
+ : undefined,
126
+ ),
127
+ );
128
+ try {
129
+ const output: T = task();
130
+ if (is_promise(output))
131
+ return new Promise<void>((resolve, reject) =>
132
+ output
133
+ .catch((exp) => {
134
+ const res: Error | null = predicate(exp);
135
+ if (res) reject(res);
136
+ else resolve();
137
+ })
138
+ .then(() => reject(new Error(message()))),
139
+ ) as any;
140
+ else throw new Error(message());
141
+ } catch (exp) {
142
+ const res: Error | null = predicate(exp);
143
+ if (res) throw res;
144
+ return undefined!;
145
+ }
146
+ };
147
+
148
+ export function proceed(task: () => Promise<any>): Promise<Error | null>;
149
+ export function proceed(task: () => any): Error | null;
150
+ export function proceed(
151
+ task: () => any,
152
+ ): Promise<Error | null> | (Error | null) {
153
+ try {
154
+ const output: any = task();
155
+ if (is_promise(output))
156
+ return new Promise<Error | null>((resolve) =>
157
+ output
158
+ .catch((exp) => resolve(exp as Error))
159
+ .then(() => resolve(null)),
160
+ );
161
+ } catch (exp) {
162
+ return exp as Error;
163
+ }
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * Validate index API.
169
+ *
170
+ * Test whether two indexed values are equal.
171
+ *
172
+ * If two values are different, then exception would be thrown.
173
+ *
174
+ * @param title Title of error message when different
175
+ * @return Currying function
176
+ *
177
+ * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
178
+ */
179
+ export const index =
180
+ (title: string) =>
181
+ <Solution extends IEntity<any>>(expected: Solution[]) =>
182
+ <Summary extends IEntity<any>>(
183
+ gotten: Summary[],
184
+ trace: boolean = true,
185
+ ): void => {
186
+ const length: number = Math.min(expected.length, gotten.length);
187
+ expected = expected.slice(0, length);
188
+ gotten = gotten.slice(0, length);
189
+
190
+ const xIds: string[] = get_ids(expected).slice(0, length);
191
+ const yIds: string[] = get_ids(gotten)
192
+ .filter((id) => id >= xIds[0])
193
+ .slice(0, length);
194
+
195
+ const equals: boolean = xIds.every((x, i) => x === yIds[i]);
196
+ if (equals === true) return;
197
+ else if (trace === true)
198
+ console.log({
199
+ expected: xIds,
200
+ gotten: yIds,
201
+ });
202
+ throw new Error(
203
+ `Bug on ${title}: result of the index is different with manual aggregation.`,
204
+ );
205
+ };
206
+
207
+ /**
208
+ * Valiate search options.
209
+ *
210
+ * Test a pagination API supporting search options.
211
+ *
212
+ * @param title Title of error message when searching is invalid
213
+ * @returns Currying function
214
+ *
215
+ * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
216
+ */
217
+ export const search =
218
+ (title: string) =>
219
+ /**
220
+ * @param getter A pagination API function to be called
221
+ */
222
+ <Entity extends IEntity<any>, Request>(
223
+ getter: (input: Request) => Promise<Entity[]>,
224
+ ) =>
225
+ /**
226
+ * @param total Total entity records for comparison
227
+ * @param sampleCount Sampling count. Default is 1
228
+ */
229
+ (total: Entity[], sampleCount: number = 1) =>
230
+ /**
231
+ * @param props Search properties
232
+ */
233
+ async <Values extends any[]>(
234
+ props: ISearchProps<Entity, Values, Request>,
235
+ ): Promise<void> => {
236
+ const samples: Entity[] = RandomGenerator.sample(total)(sampleCount);
237
+ for (const s of samples) {
238
+ const values: Values = props.values(s);
239
+ const filtered: Entity[] = total.filter((entity) =>
240
+ props.filter(entity, values),
241
+ );
242
+ const gotten: Entity[] = await getter(props.request(values));
243
+
244
+ TestValidator.index(`${title} (${props.fields.join(", ")})`)(filtered)(
245
+ gotten,
246
+ );
247
+ }
248
+ };
249
+
250
+ export interface ISearchProps<
251
+ Entity extends IEntity<any>,
252
+ Values extends any[],
253
+ Request,
254
+ > {
255
+ fields: string[];
256
+ values(entity: Entity): Values;
257
+ filter(entity: Entity, values: Values): boolean;
258
+ request(values: Values): Request;
259
+ }
260
+
261
+ /**
262
+ * Validate sorting options.
263
+ *
264
+ * Test a pagination API supporting sorting options.
265
+ *
266
+ * You can validate detailed sorting options both asceding and descending orders
267
+ * with multiple fields. However, as it forms a complicate currying function,
268
+ * I recomend you to see below example code before using.
269
+ *
270
+ * @param title Title of error message when sorting is invalid
271
+ * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_sort.ts
272
+ */
273
+ export const sort =
274
+ (title: string) =>
275
+ /**
276
+ * @param getter A pagination API function to be called
277
+ */
278
+ <
279
+ T extends object,
280
+ Fields extends string,
281
+ Sortable extends Array<`-${Fields}` | `+${Fields}`> = Array<
282
+ `-${Fields}` | `+${Fields}`
283
+ >,
284
+ >(
285
+ getter: (sortable: Sortable) => Promise<T[]>,
286
+ ) =>
287
+ /**
288
+ * @param fields List of fields to be sorted
289
+ */
290
+ (...fields: Fields[]) =>
291
+ /**
292
+ * @param comp Comparator function for validation
293
+ * @param filter Filter function for data if required
294
+ */
295
+ (comp: (x: T, y: T) => number, filter?: (elem: T) => boolean) =>
296
+ /**
297
+ * @param direction "+" means ascending order, and "-" means descending order
298
+ */
299
+ async (direction: "+" | "-", trace: boolean = true) => {
300
+ let data: T[] = await getter(
301
+ fields.map((field) => `${direction}${field}` as const) as Sortable,
302
+ );
303
+ if (filter) data = data.filter(filter);
304
+
305
+ const reversed: typeof comp =
306
+ direction === "+" ? comp : (x, y) => comp(y, x);
307
+ if (ranges.is_sorted(data, (x, y) => reversed(x, y) < 0) === false) {
308
+ if (
309
+ fields.length === 1 &&
310
+ data.length &&
311
+ (data as any)[0][fields[0]] !== undefined &&
312
+ trace
313
+ )
314
+ console.log(data.map((elem) => (elem as any)[fields[0]]));
315
+ throw new Error(
316
+ `Bug on ${title}: wrong sorting on ${direction}(${fields.join(
317
+ ", ",
318
+ )}).`,
319
+ );
320
+ }
321
+ };
322
+
323
+ export type Sortable<Literal extends string> = Array<
324
+ `-${Literal}` | `+${Literal}`
325
+ >;
326
+ }
327
+
328
+ interface IEntity<Type extends string | number | bigint> {
329
+ id: Type;
330
+ }
331
+
332
+ function get_ids<Entity extends IEntity<any>>(entities: Entity[]): string[] {
333
+ return entities.map((entity) => entity.id).sort((x, y) => (x < y ? -1 : 1));
334
+ }
335
+
336
+ function is_promise(input: any): input is Promise<any> {
337
+ return (
338
+ typeof input === "object" &&
339
+ input !== null &&
340
+ typeof (input as any).then === "function" &&
341
+ typeof (input as any).catch === "function"
342
+ );
343
+ }