-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathAutoBeTest.ts
More file actions
3173 lines (3052 loc) · 119 KB
/
AutoBeTest.ts
File metadata and controls
3173 lines (3052 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { tags } from "typia";
import { AutoBeOpenApi } from "../openapi/AutoBeOpenApi";
import { CamelCasePattern } from "../typings/CamelCasePattern";
/**
* AST type system for programmatic E2E test function generation through AI
* function calling.
*
* This namespace defines a comprehensive Abstract Syntax Tree structure that
* enables AI agents to construct complete E2E test functions at the AST level.
* Each type corresponds to specific TypeScript language constructs, allowing
* precise control over generated test code while maintaining type safety and
* business logic accuracy.
*
* ## Core Purpose
*
* The system is designed for systematic generation where AI function calls
* build test scenarios step-by-step, mapping business requirements to
* executable code. Instead of generating raw TypeScript strings, AI agents
* construct structured AST objects that represent:
*
* - Complete test function flows with proper data dependencies
* - Realistic API call sequences with captured responses
* - Comprehensive validation using TestValidator assertions
* - Complex business logic with conditional flows and error handling
*
* ## Architecture Overview
*
* - **IFunction**: Root container representing complete test functions
* - **Statements**: Building blocks for test logic (API operations, expressions,
* conditionals)
* - **Expressions**: Value computations, API calls, data access, and validations
* - **Literals**: Direct values for realistic business data
* - **Random Generators**: Dynamic test data creation with business constraints
* - **Predicates**: TestValidator assertions for comprehensive validation
*
* ## Business Context
*
* In E2E testing, this typically maps to complete business scenarios like:
*
* - Customer purchase workflows (registration → product selection → payment →
* confirmation)
* - Seller product management (authentication → product creation → inventory
* management)
* - Multi-role interactions (seller creates product → customer purchases → admin
* processes)
*
* Each generated function represents a realistic business workflow with proper
* data flow, where API responses from earlier steps provide inputs for
* subsequent operations, creating authentic test scenarios that mirror
* real-world application usage.
*
* @author Samchon
* @note This namespace documentation is excluded from AI function calling schemas
*/
export namespace AutoBeTest {
/**
* Root interface representing a complete E2E test function.
*
* This serves as the top-level container for all statements that comprise a
* test function. Each statement in the array represents a logical step in the
* test scenario, enabling systematic construction of complex business
* workflows through AI function calling.
*
* The generation process follows a three-stage approach: planning, drafting,
* and AST construction. This ensures that AI agents create well-structured,
* comprehensive test functions through deliberate design phases.
*
* In the context of E2E testing, this typically maps to complete business
* scenarios like "customer purchase flow" or "seller product management",
* where each statement handles one aspect of the workflow.
*/
export interface IFunction {
/**
* Strategic plan for implementing the test scenario.
*
* This field requires AI agents to think through the test implementation
* strategy before generating actual statements. It should analyze the given
* scenario and determine the optimal approach for creating a comprehensive
* test function.
*
* The plan should address:
*
* - Key business entities and their relationships that need to be tested
* - Sequence of operations required to achieve the test scenario
* - Data dependencies between different test steps
* - Validation points where business rules should be verified
* - Error conditions and edge cases that should be tested
* - Overall test structure and organization
*
* This planning step ensures that the generated statements follow a logical
* progression and create a realistic, comprehensive test scenario that
* properly validates the business workflow.
*/
plan: string;
/**
* Draft TypeScript code implementation of the test function.
*
* This field contains a preliminary TypeScript implementation of the test
* function based on the strategic plan. The draft serves as an intermediate
* step between planning and AST construction, allowing AI agents to:
*
* - Visualize the actual code structure before AST generation
* - Ensure proper TypeScript syntax and API usage patterns
* - Validate the logical flow and data dependencies
* - Identify any missing components or validation steps
* - Refine the approach before committing to AST statements
*
* The draft should be complete, executable TypeScript code that represents
* the full test function implementation. This code will then be analyzed
* and converted into the corresponding AST statements structure.
*
* **⚠️ CRITICAL: Avoid TypeScript features that complicate AST conversion!
* ⚠️**
*
* **❌ AVOID**: Template literals, destructuring, for/while loops, switch
* statements, try/catch blocks, spread operators, arrow functions without
* blocks
*
* **✅ USE**: Simple property access, explicit API operations, array methods
* (arrayMap, arrayForEach), predicate functions, clear if/else chains
*/
draft: string;
/**
* Array of statements that comprise the test function body.
*
* Each statement represents a discrete step in the test scenario, typically
* corresponding to business actions like API calls, validations, or state
* transitions. The order is significant as it reflects the logical flow of
* the business process.
*
* These statements should be generated by analyzing and converting the
* draft TypeScript code into structured AST representations, ensuring that
* the implementation follows the predetermined approach and creates a
* complete data flow chain representing the business scenario.
*
* **⚠️ CRITICAL: Convert unsupported TypeScript features to AutoBeTest AST
* equivalents! ⚠️**
*
* - Template literals → String concatenation with IBinaryExpression
* - Destructuring → Separate IPropertyAccessExpression statements
* - Loops → IArrayForEachExpression/IArrayMapExpression
* - Switch statements → Nested IIfStatement chains
* - Try/catch → IErrorPredicate for error testing
*
* **🚨 CRITICAL: DO NOT PUT EXPRESSIONS DIRECTLY IN STATEMENTS ARRAY! 🚨**
*
* This array ONLY accepts `IStatement` types. If you need to execute an
* expression (like predicates, function calls, etc.), you MUST wrap it in
* `IExpressionStatement`:
*
* **❌ WRONG - Expression directly in statements array**:
*
* ```typescript
* statements: [
* { type: "apiOperateStatement", ... },
* { type: "equalPredicate", ... } // ❌ This is IExpression, not IStatement!
* ]
* ```
*
* **✅ CORRECT - Expression wrapped in IExpressionStatement**:
*
* ```typescript
* statements: [
* { type: "apiOperateStatement", ... },
* {
* type: "expressionStatement", // ✅ Statement wrapper
* expression: {
* type: "equalPredicate", ... // ✅ Expression properly contained
* }
* }
* ]
* ```
*
* **Statement Types (can go directly in array)**:
*
* - `IApiOperateStatement`
* - `IExpressionStatement`
* - `IIfStatement`
* - `IReturnStatement`
* - `IThrowStatement`
*
* **Expression Types (must be wrapped in IExpressionStatement)**:
*
* - `IEqualPredicate`, `IConditionalPredicate`, `IErrorPredicate`, etc.
* - `ICallExpression`
* - All literal types and random generators
* - Any other `IExpression` type
*
* AI function calling strategy: Build statements by parsing the draft code
* and converting each logical operation into appropriate AST statement
* types, maintaining the data dependencies and business logic flow
* established in the draft. Always verify that you're using statement
* types, not expression types directly.
*/
statements: IStatement[] & tags.MinItems<1>;
}
/* -----------------------------------------------------------
STATEMENTS
----------------------------------------------------------- */
/**
* Union type representing all possible statement types in test functions.
*
* Statements are the building blocks of test function logic, each serving
* specific purposes in the E2E testing context:
*
* - IApiOperateStatement: Primary mechanism for all SDK API operations with
* automatic response handling and data capture
* - IExpressionStatement: Execute utility functions and validations without
* value capture
* - IIfStatement: Handle conditional business logic (prefer predicates for
* validation)
* - IReturnStatement: Function termination (rarely used in tests)
* - IThrowStatement: Explicit error scenarios
*
* Note: IBlockStatement is intentionally excluded from this union as it
* should only be used in special contexts (like if/else branches) rather than
* as a general statement type in the main function flow.
*
* AI selection strategy: Choose statement type based on the business action
* being performed. Use IApiOperateStatement for all API operations with
* automatic data capture, predicates for validations, and other statement
* types for specific non-API needs.
*/
export type IStatement =
| IApiOperateStatement
| IExpressionStatement
| IIfStatement
| IReturnStatement
| IThrowStatement;
/**
* Block for grouping statements in specific structural contexts.
*
* **SPECIAL USE ONLY**: This type represents a block of statements and should
* only be used in specific contexts where statement grouping is structurally
* required:
*
* - If/else statement branches
*
* - {@link IIfStatement.thenStatement}
* - {@link IIfStatement.elseStatement}
* - Arrow function bodies: {@link IArrowFunction.body}
* - Other contexts requiring explicit block scoping
*
* Unlike a block statement, this is not a statement itself but a structural
* container for statements. For normal test function flow, use individual
* statements directly rather than wrapping them in blocks.
*
* **Updated for API-first workflow**: Blocks can now contain
* `IApiOperateStatement` for API operations with automatic data capture,
* predicate expressions for validations, and other statement types as needed
* within conditional logic or function bodies.
*
* AI function calling restriction: Do not use for general statement grouping
* in main function flow. Reserve for structural requirements only
* (conditional branches, function bodies).
*/
export interface IBlock {
/** Type discriminator. */
type: "block";
/**
* Nested statements within this block.
*
* Each statement represents a step within the grouped operation. Can
* include any valid statement type:
*
* - `IApiOperateStatement` for API operations with automatic data capture
* within conditional logic
* - Predicate expressions for validations within blocks
* - Other statement types as needed for the block's purpose
*
* Maintains the same ordering significance as the root function's
* statements array.
*
* **🚨 CRITICAL: DO NOT PUT EXPRESSIONS DIRECTLY IN STATEMENTS ARRAY! 🚨**
*
* This array ONLY accepts `IStatement` types. If you need to execute an
* expression (like predicates, function calls, etc.), you MUST wrap it in
* `IExpressionStatement`:
*
* **❌ WRONG - Expression directly in statements array**:
*
* ```typescript
* statements: [
* { type: "apiOperateStatement", ... },
* { type: "conditionalPredicate", ... } // ❌ This is IExpression, not IStatement!
* ]
* ```
*
* **✅ CORRECT - Expression wrapped in IExpressionStatement**:
*
* ```typescript
* statements: [
* { type: "apiOperateStatement", ... },
* {
* type: "expressionStatement", // ✅ Statement wrapper
* expression: {
* type: "conditionalPredicate", ... // ✅ Expression properly contained
* }
* }
* ]
* ```
*
* **Statement Types (can go directly in array)**:
*
* - `IApiOperateStatement`
* - `IExpressionStatement`
* - `IIfStatement`
* - `IReturnStatement`
* - `IThrowStatement`
*
* **Expression Types (must be wrapped in IExpressionStatement)**:
*
* - `IEqualPredicate`, `IConditionalPredicate`, etc.
* - `ICallExpression`
* - All literal types and random generators
* - Any other `IExpression` type
*
* Example business context - Block: "Premium Customer Workflow"
*
* - API operation: Verify premium status (with automatic data capture)
* - API operation: Access exclusive content (with automatic data capture)
* - Predicate: Validate premium features are available (wrapped in
* expressionStatement)
* - API operation: Log premium usage (with automatic data capture)
*/
statements: IStatement[] & tags.MinItems<1>;
}
/**
* API operation statement for SDK function calls with automatic response
* handling and data capture.
*
* This statement type handles the complete lifecycle of API operations
* including:
*
* 1. Executing API function calls through the SDK
* 2. Automatically capturing the response in a variable (when variableName is
* provided)
* 3. Performing runtime type assertion using typia.assert<T>() for type safety
*
* This is the primary mechanism for all API interactions in E2E test
* scenarios, providing integrated data capture that eliminates the need for
* separate variable declarations.
*
* The statement automatically handles the complex pattern of API calling,
* response capturing, and type validation that is essential for robust E2E
* testing.
*
* AI function calling importance: Use this for ALL SDK API operations to
* ensure proper response handling, automatic data capture, and type safety in
* business test scenarios.
*/
export interface IApiOperateStatement {
/** Type discriminator. */
type: "apiOperateStatement";
/**
* API endpoint specification defining the operation to be called.
*
* Contains the HTTP method and path information that identifies which
* specific API operation from the OpenAPI specification should be invoked.
* This corresponds to operations defined in the AutoBeOpenApi.IDocument.
*
* The endpoint determines the expected parameter types, request body
* schema, and response body schema for proper type validation.
*/
endpoint: AutoBeOpenApi.IEndpoint;
/**
* Single argument object for the API function call.
*
* **CRITICAL**: All API functions accept exactly one object parameter that
* contains all necessary data for the operation. This argument object is
* constructed based on the API operation's specification and follows a
* standardized structure.
*
* **⚠️ CRITICAL AI RESTRICTION: This MUST be an AST expression, NOT a JSON
* value! ⚠️** **❌ WRONG: { "name": "John", "age": 30 } (raw JSON object)**
* **✅ CORRECT: IObjectLiteralExpression with proper AST structure**
*
* **Object Structure Rules:**
*
* The argument object is constructed by combining path parameters and
* request body data according to the following rules based on the target
* {@link AutoBeOpenApi.IOperation}:
*
* 1. **Path Parameters**: Each parameter from
* `AutoBeOpenApi.IOperation.parameters` becomes a property in the
* argument object, where:
*
* - Property name: `AutoBeOpenApi.IParameter.name`
* - Property value: Expression matching `AutoBeOpenApi.IParameter.schema`
* - Example: `{ saleId: "uuid-string", customerId: "another-uuid" }`
* 2. **Request Body**: If `AutoBeOpenApi.IOperation.requestBody` exists:
*
* - Add a `body` property containing the request body data
* - Value type: Object literal matching the requestBody's typeName schema
* - Example: `{ body: { name: "Product Name", price: 99.99 } }`
* 3. **Combined Structure**: When both path parameters and request body exist:
*
* ```typescript
* {
* // Path parameters as individual properties
* "saleId": "uuid-value",
* "customerId": "another-uuid",
* // Request body as 'body' property
* "body": {
* "name": "Updated Product",
* "price": 149.99,
* "description": "Enhanced product description"
* }
* }
* ```
*
* **Special Cases:**
*
* - **No Parameters**: When `parameters` is empty array AND `requestBody` is
* null, set this to `null` (the API function requires no arguments)
* - **Only Path Parameters**: When `requestBody` is null but `parameters`
* exist, create object with only path parameter properties
* - **Only Request Body**: When `parameters` is empty but `requestBody`
* exists, create object with only the `body` property
*
* **AI Construction Strategy:**
*
* 1. Analyze the target `AutoBeOpenApi.IOperation` specification
* 2. Extract all path parameters and create corresponding object properties
* 3. If request body exists, add it as the `body` property
* 4. Ensure all property values match the expected types from OpenAPI schema
* 5. Use realistic business data that reflects actual API usage patterns
*
* **Type Safety Requirements:**
*
* - Path parameter values must match their schema types (string, integer,
* etc.)
* - Request body structure must exactly match the referenced schema type
* - All required properties must be included with valid values
* - Optional properties can be omitted or included based on test scenario
* needs
*
* **Business Context Examples:**
*
* ```typescript
* // GET /customers/{customerId}/orders/{orderId} (no request body)
* {
* customerId: "cust-123",
* orderId: "order-456"
* }
*
* // POST /customers (only request body)
* {
* body: {
* name: "John Doe",
* email: "john@example.com",
* phone: "+1-555-0123"
* }
* }
*
* // PUT /customers/{customerId}/orders/{orderId} (both path params and body)
* {
* customerId: "cust-123",
* orderId: "order-456",
* body: {
* status: "shipped",
* trackingNumber: "TRACK123",
* estimatedDelivery: "2024-12-25"
* }
* }
*
* // GET /health (no parameters or body)
* null
* ```
*/
argument?: IObjectLiteralExpression | null;
/**
* Optional variable name for capturing the API response with automatic data
* handling.
*
* **Conditional Usage:**
*
* - `string`: When API operation returns data that needs to be captured
*
* - Creates: `const variableName: ApiResponseType =
* typia.assert<ResponseType>(await api.operation(...))`
* - The response is automatically type-validated using typia.assert
* - Variable can be referenced in subsequent test steps for data flow
* - `null`: When API operation returns void or response is not needed
*
* - Creates: `await api.operation(...)`
* - No variable assignment or type assertion is performed
* - Typically used for operations like delete, logout, or fire-and-forget
* calls
*
* **AI Decision Logic:**
*
* - Set to meaningful variable name when the response contains business data
* needed for subsequent operations
* - Set to null when the operation is void or side-effect only
* - Consider if subsequent test steps need to reference the response data for
* business logic or validations
*
* Variable naming should follow business domain conventions (e.g.,
* "customer", "order", "product") rather than technical naming. This
* automatic data capture eliminates the need for separate variable
* declaration statements.
*/
variableName?: (string & CamelCasePattern) | null;
}
/**
* Expression statement for executing utility operations without value
* capture.
*
* **IMPORTANT: For API operations, use `IApiOperateStatement` instead.** This
* statement type is primarily for utility operations that don't require
* capturing return values, and where the operation's side effect or
* validation is more important than its return value.
*
* Common E2E testing scenarios:
*
* - Validation assertions using TestValidator predicates (when not using
* predicate expressions)
* - Utility function calls (console.log, debugging functions)
* - Non-API side-effect operations
* - Cleanup operations that don't involve API calls
*
* **Note**: For most validation cases, prefer using predicate expressions
* (IEqualPredicate, IConditionalPredicate, etc.) instead of expression
* statements with TestValidator calls.
*
* AI function calling usage: Select when the business action's execution is
* the goal, not data capture, and when the operation is NOT an API call.
*/
export interface IExpressionStatement {
/** Type discriminator. */
type: "expressionStatement";
/**
* The expression to be executed as a statement.
*
* **Should NOT contain API function calls** - use `IApiOperateStatement`
* for those instead.
*
* Typically represents utility operations:
*
* - TestValidator function calls (though predicates are preferred)
* - Console operations for debugging
* - Non-API utility function invocations
* - Side-effect operations that don't involve the API
*
* The expression's result is discarded, making this suitable for
* void-returning operations or when return values are not needed for
* subsequent test steps.
*
* Most commonly contains ICallExpression for utility invocations.
*/
expression: IExpression;
}
/**
* Conditional statement for business rule-based test flow control.
*
* Enables test scenarios to branch based on runtime conditions or business
* rules. This should be used for genuine business logic branching where
* different test paths are needed based on data state or business
* conditions.
*
* **IMPORTANT: For validation purposes, prefer predicate expressions
* instead:**
*
* - Use `IEqualPredicate` instead of `if (x === y) throw new Error(...)`
* - Use `INotEqualPredicate` instead of `if (x !== y) throw new Error(...)`
* - Use `IConditionalPredicate` instead of `if (!condition) throw new
* Error(...)`
* - Use `IErrorPredicate` instead of `if` blocks that only contain error
* throwing
*
* **Only use IIfStatement when:**
*
* - Different business logic paths are needed (not just validation)
* - Complex conditional workflows that can't be expressed as simple predicates
* - Actor-based or feature-flag dependent test scenarios
* - Multi-step conditional operations where predicates are insufficient
*
* Business scenarios requiring conditional logic:
*
* - Actor-based test flows (premium vs regular customers)
* - Feature availability testing with different user journeys
* - Optional business process steps based on entity state
* - Complex workflow branching that involves multiple operations per branch
*
* AI function calling strategy: First consider if the validation can be
* handled by predicate expressions. Use IIfStatement only when genuine
* business logic branching is required that cannot be expressed through
* predicates.
*/
export interface IIfStatement {
/** Type discriminator. */
type: "ifStatement";
/**
* Boolean expression determining which branch to execute.
*
* Typically evaluates business conditions like user roles, feature flags,
* data states, or validation results. Should represent meaningful business
* logic rather than arbitrary technical conditions.
*
* Examples:
*
* - Customer.role === "premium"
* - Product.status === "available"
* - Order.payment_status === "completed"
*/
condition: IExpression;
/**
* Block to execute when condition is true.
*
* Contains the primary business flow for the conditional scenario. Should
* represent the main path or expected behavior when the business condition
* is met.
*/
thenStatement: IBlock;
/**
* Optional alternative block for when condition is false.
*
* Can be another IIfStatement for chained conditions (else-if) or IBlock
* for alternative business flow. May be null when no alternative action is
* needed.
*
* Business context: Represents fallback behavior, alternative user
* journeys, or error handling paths.
*/
elseStatement?: IBlock | IIfStatement | null;
}
/**
* Return statement for function termination.
*
* Rarely used in E2E test functions since they typically return void. May be
* used in helper functions or when test functions need to return specific
* data for chaining or validation purposes.
*
* **Note**: Most E2E test functions should complete naturally without
* explicit return statements, as they represent complete business workflow
* testing rather than value-returning operations.
*
* AI function calling usage: Generally avoid in main test functions. Consider
* only for special cases where test result data needs to be returned to
* calling context, such as helper functions within arrow function
* expressions.
*/
export interface IReturnStatement {
/** Type discriminator. */
type: "returnStatement";
/**
* Expression representing the value to be returned.
*
* Should evaluate to the appropriate return type expected by the function
* signature. In test contexts, typically void or validation result
* objects.
*
* Can reference previously captured data from API operations or computed
* values, but should not contain direct API calls.
*/
expression: IExpression;
}
/**
* Explicit error throwing for test failure scenarios.
*
* Used for custom error conditions or when specific business rule violations
* should cause immediate test termination with descriptive error messages.
*
* **IMPORTANT: For most validation scenarios, prefer predicate expressions:**
*
* - Use `IEqualPredicate` instead of manual equality checks with throw
* - Use `IConditionalPredicate` instead of condition checks with throw
* - Use `IErrorPredicate` for testing expected error conditions
*
* **Only use IThrowStatement when:**
*
* - Custom error handling logic that can't be expressed as predicates
* - Complex business rule violations requiring custom error messages
* - Exceptional cases where predicate expressions are insufficient
*
* E2E testing scenarios:
*
* - Custom validation failures with specific business context
* - Unexpected state conditions that should halt test execution
* - Complex error conditions requiring detailed diagnostic information
*
* AI function calling usage: Use sparingly, primarily for business logic
* violations that require explicit error reporting and cannot be handled by
* the standard predicate validation system.
*/
export interface IThrowStatement {
/** Type discriminator. */
type: "throwStatement";
/**
* Expression that evaluates to the error to be thrown.
*
* Typically an Error object construction with descriptive message
* explaining the business context of the failure. Should provide clear
* information about what business condition caused the error.
*
* Should NOT involve API calls - use IApiOperateStatement for API
* operations that are expected to throw errors, and IErrorPredicate for
* testing expected API error conditions.
*
* Example: new Error("Customer verification failed: invalid email format")
*/
expression: IExpression;
}
/* -----------------------------------------------------------
THE EXPRESSION
----------------------------------------------------------- */
/**
* Union type encompassing all possible expressions in test scenarios.
*
* Expressions represent values, computations, and operations that can be used
* within statements. This comprehensive set covers all necessary constructs
* for building complex E2E test scenarios:
*
* **Basic constructs:**
*
* - Identifiers: Variable references
* - Property/Element access: Object navigation
* - Function calls: Utility invocations (NOT API calls - use
* IApiOperateStatement)
* - Literals: Direct values
*
* **Advanced constructs:**
*
* - Random generators: Test data creation
* - Operators: Logical and arithmetic operations
* - Arrow functions: Callback definitions
* - Predicates: TestValidator validation operations (preferred over manual
* validation)
*
* **Note**: API function calls should NOT be represented as expressions. Use
* `IApiOperateStatement` for all SDK API operations instead.
*
* AI selection strategy: Choose expression type based on the specific
* operation needed in the business scenario. For API calls, always use the
* dedicated statement type rather than call expressions.
*/
export type IExpression =
// LITERALS
| IBooleanLiteral
| INumericLiteral
| IStringLiteral
| IArrayLiteralExpression
| IObjectLiteralExpression
| INullLiteral
| IUndefinedKeyword
// ACCESSORS
| IIdentifier
| IPropertyAccessExpression
| IElementAccessExpression
// OPERATORS
| ITypeOfExpression
| IPrefixUnaryExpression
| IPostfixUnaryExpression
| IBinaryExpression
// FUNCTIONAL
| IArrowFunction
| ICallExpression
| INewExpression
| IArrayFilterExpression
| IArrayForEachExpression
| IArrayMapExpression
| IArrayRepeatExpression
// RANDOM GENERATORS
| IPickRandom
| ISampleRandom
| IBooleanRandom
| IIntegerRandom
| INumberRandom
| IStringRandom
| IPatternRandom
| IFormatRandom
| IKeywordRandom
// PREDICATORS
| IEqualPredicate
| INotEqualPredicate
| IConditionalPredicate
| IErrorPredicate;
/* -----------------------------------------------------------
LITERALS
----------------------------------------------------------- */
/**
* Boolean literal for true/false values.
*
* Represents direct boolean values used in conditions, flags, and business
* rule specifications. Common in test scenarios for setting feature flags,
* validation states, and binary business decisions.
*
* E2E testing usage:
*
* - Feature flags (enabled: true/false)
* - Business state flags (active, verified, completed)
* - Validation parameters for API operations
* - Configuration options for test scenarios
*
* **Note**: Often used as arguments in `IApiOperateStatement` for boolean
* parameters, or in conditional expressions for business logic.
*/
export interface IBooleanLiteral {
/** Type discriminator. */
type: "booleanLiteral";
/**
* The boolean value (true or false).
*
* Should represent meaningful business states rather than arbitrary
* true/false values. Consider the business context when selecting the value
* based on the intended test scenario.
*/
value: boolean;
}
/**
* Numeric literal for number values.
*
* Represents direct numeric values including integers, decimals, and
* floating-point numbers. Essential for business data like quantities,
* prices, scores, and identifiers used in test scenarios.
*
* E2E testing scenarios:
*
* - Product quantities and prices for API operation parameters
* - Score values and ratings in business validations
* - Pagination parameters (page, limit) for API calls
* - Business thresholds and limits for conditional logic
* - Mathematical calculations with captured data
*
* **Note**: Commonly used as arguments in `IApiOperateStatement` for numeric
* parameters, or in comparisons with captured API response data.
*/
export interface INumericLiteral {
/** Type discriminator. */
type: "numericLiteral";
/**
* The numeric value.
*
* Can be integer or floating-point number. Should represent realistic
* business values appropriate for the test scenario context (e.g.,
* reasonable prices, quantities, scores).
*
* AI consideration: Use business-appropriate values rather than arbitrary
* numbers (e.g., 10000 for price instead of 12345.67).
*/
value: number;
}
/**
* String literal for text values.
*
* Represents direct string values including business names, descriptions,
* identifiers, and formatted data. One of the most commonly used literal
* types in E2E testing for realistic business data.
*
* E2E testing importance: Critical for providing realistic business data that
* reflects actual user input and system behavior, especially as parameters
* for API operations and in comparisons with captured response data.
*/
export interface IStringLiteral {
/** Type discriminator. */
type: "stringLiteral";
/**
* The string value.
*
* Should contain realistic business data appropriate for the context:
*
* - Names: "John Doe", "Acme Corporation"
* - Emails: "john@example.com"
* - Descriptions: "High-quality wireless headphones"
* - Codes: "PROMO2024", "SKU-12345"
* - Status values: "pending", "approved", "completed"
*
* **Usage context**: Commonly used as arguments in `IApiOperateStatement`
* for string parameters, in predicate validations for expected values, or
* in conditional expressions for business logic.
*
* AI content strategy: Use meaningful, realistic values that reflect actual
* business scenarios rather than placeholder text like "string" or "test".
*/
value: string;
}
/**
* Array literal for creating array values directly.
*
* Represents direct array construction with explicit elements. Essential for
* providing list data in test scenarios such as multiple products, user
* lists, or configuration arrays, particularly as parameters for API
* operations.
*
* E2E testing scenarios:
*
* - Product lists for bulk API operations
* - Tag arrays for categorization in API requests
* - Multiple item selections for API parameters
* - Configuration option lists for test setup
* - Multiple entity references for relationship testing
*
* **Note**: Commonly used as arguments in `IApiOperateStatement` when API
* operations require array parameters, or for constructing test data to be
* used in business logic.
*
* AI function calling usage: Use when business scenarios require explicit
* list data rather than dynamic array generation from captured API
* responses.
*/
export interface IArrayLiteralExpression {
/** Type discriminator. */
type: "arrayLiteralExpression";
/**
* Array of expressions representing the array elements.
*
* Each element can be any valid expression (literals, identifiers
* referencing captured data, function calls, etc.). Elements should
* represent meaningful business data appropriate for the array's purpose.
*
* **⚠️ CRITICAL AI RESTRICTION: Each element MUST be an AST expression, NOT
* raw JSON values! ⚠️** **❌ WRONG: ["item1", "item2", 123] (raw JSON
* values)** **✅ CORRECT: [IStringLiteral, IStringLiteral, INumericLiteral]
* (AST expressions)**
*
* Examples:
*
* - [product1, product2, product3] for entity arrays (referencing captured
* data)
* - ["electronics", "gadgets"] for category tags
* - [{ name: "file1.jpg" }, { name: "file2.jpg" }] for file lists
* - [seller.id, customer.id] for ID arrays (mixing captured data)
*
* AI content strategy: Populate with realistic business data that reflects
* actual usage patterns, mixing literals and references to captured data as
* appropriate.
*/
elements: IExpression[];
}
/**
* Object literal for creating object values directly.
*
* Represents direct object construction with explicit properties. The primary
* mechanism for creating request bodies, configuration objects, and
* structured data in E2E test scenarios, particularly as parameters for API
* operations.
*
* E2E testing importance: Critical for API request bodies in
* `IApiOperateStatement` calls and configuration objects that drive business
* operations.
*/
export interface IObjectLiteralExpression {
/** Type discriminator. */
type: "objectLiteralExpression";
/**
* Array of property assignments defining the object structure.
*
* Each property represents a key-value pair in the object. Properties
* should correspond to actual DTO structure requirements and business data
* needs when used as API request bodies.
*
* **For API operations**: Must align with API schema requirements when used
* as arguments in `IApiOperateStatement`. Property names and value types
* should match expected DTO interfaces.
*
* **For test data**: Can mix literal values with references to captured
* data from previous API operations to create realistic business
* scenarios.
*
* AI validation requirement: Ensure properties match the target schema
* definition exactly when used for API operations, including required
* fields and types.
*/
properties: IPropertyAssignment[];
}
/**