UNPKG

@autobe/agent

Version:

AI backend server code generator

156 lines (124 loc) 174 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformTestWriteHistory = transformTestWriteHistory; const utils_1 = require("@autobe/utils"); const openapi_1 = require("@samchon/openapi"); const tstl_1 = require("tstl"); const typia_1 = __importDefault(require("typia")); const uuid_1 = require("uuid"); const getTestExternalDeclarations_1 = require("../compile/getTestExternalDeclarations"); function transformTestWriteHistory(ctx, props) { return __awaiter(this, void 0, void 0, function* () { return { histories: [ { id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), type: "systemMessage", text: systemPrompt.get(), }, { id: (0, uuid_1.v7)(), created_at: new Date().toISOString(), type: "assistantMessage", text: utils_1.StringUtil.trim ` Here is the list of input material composition. Make e2e test functions based on the following information. ## Instructions The following e2e-test-specific instructions were extracted from the user's requirements and conversations. These instructions focus exclusively on test-related aspects such as test data generation strategies, assertion patterns, error handling approaches, and specific validation logic that should be implemented in the test code. Follow these instructions when implementing the e2e test function. Carefully distinguish between: - Suggestions or recommendations (consider these as guidance) - Direct specifications or explicit commands (these must be followed exactly) When instructions contain direct specifications or explicit design decisions, follow them precisely even if you believe you have better alternatives. ${props.instruction} ## Function Name The e2e test function name must be ${JSON.stringify(props.scenario.functionName)}. ## Scenario Plan Here is the scenario plan what you have to implement. \`\`\`json ${JSON.stringify(props.scenario)} \`\`\` ## DTO Definitions You can use these DTO definitions. Never use the DTO definitions that are not listed here. ${transformTestWriteHistory.structures(props.artifacts)} ## API (SDK) Functions You can use these API functions. Never use the functions that are not listed here. ${transformTestWriteHistory.functional(props.artifacts)} ## E2E Mockup Functions Just reference, and never follow this code as it is. \`\`\`json ${JSON.stringify(props.artifacts.e2e)} \`\`\` ## External Definitions Here is the external declaration files (d.ts) you can reference. \`\`\`json ${JSON.stringify(yield (0, getTestExternalDeclarations_1.getTestExternalDeclarations)(ctx))} \`\`\` ## Template Code Here is the template e2e test code what you must follow. You're only allowed to modify the "<SCENARIO DESCRIPTION HERE>" and code inside the function block marked as "// <E2E TEST CODE HERE>". Change the template code by writing your scenario description to the comment, and filling your implementation logic into the function. Note that, you don't need to add any "import" statement more than this template code. Everything you need is already imported, so make your implementation code in the import scope. \`\`\`typescript ${props.artifacts.template} \`\`\` `, }, ], userMessage: `Write e2e test function ${props.scenario.functionName} please`, }; }); } (function (transformTestWriteHistory) { function structures(artifacts) { return utils_1.StringUtil.trim ` ${Object.keys(artifacts.document.components.schemas) .map((k) => `- ${k}`) .join("\n")} \`\`\`json ${JSON.stringify(artifacts.dto)} \`\`\` `; } transformTestWriteHistory.structures = structures; function functional(artifacts) { const document = (0, utils_1.transformOpenApiDocument)(artifacts.document); const app = openapi_1.HttpMigration.application(document); return utils_1.StringUtil.trim ` Method | Path | Function Accessor -------|------|------------------- ${app.routes .map((r) => [r.method, r.path, `api.functional.${r.accessor.join(".")}`].join(" | ")) .join("\n")} \`\`\`json ${JSON.stringify(artifacts.sdk)} \`\`\` `; } transformTestWriteHistory.functional = functional; })(transformTestWriteHistory || (exports.transformTestWriteHistory = transformTestWriteHistory = {})); const systemPrompt = new tstl_1.Singleton(() => "<!--\nfilename: TEST_WRITE.md\n-->\n# E2E Test Generation System Prompt\n\n## Input Materials\n\nYou will receive the following materials as input:\n\n1. **Instructions**: E2E-test-specific instructions extracted by AI from user utterances\n - These focus ONLY on e2e-test-related parts\n - Apply these instructions when writing test code\n - If the instructions are not relevant to the target API operations, you may ignore them\n\n2. **Test Scenario**: Detailed scenario description with dependencies\n3. **API Operations**: Complete list of available operations\n4. **DTO Types**: Data transfer object type definitions\n5. **Test Skeleton**: Pre-generated test structure to complete\n\n## Naming Conventions\n\n### Notation Types\nThe following naming conventions (notations) are used throughout the system:\n- **camelCase**: First word lowercase, subsequent words capitalized (e.g., `userAccount`, `productItem`)\n- **PascalCase**: All words capitalized (e.g., `UserAccount`, `ProductItem`)\n- **snake_case**: All lowercase with underscores between words (e.g., `user_account`, `product_item`)\n\n### Specific Property Notations\n- **IAutoBeTestWriteApplication.domain**: Use camelCase notation for domain categorization\n\n## 1. Role and Responsibility\n\nYou are an AI assistant responsible for generating comprehensive End-to-End (E2E) test functions for API endpoints. Your primary task is to create robust, realistic test scenarios that validate API functionality through complete user workflows, ensuring both successful operations and proper error handling.\n\nThis agent achieves its goal through function calling. **Function calling is MANDATORY** - you MUST call the provided function immediately without asking for confirmation or permission.\n\n**REQUIRED ACTIONS:**\n- \u2705 Execute the function immediately\n- \u2705 Generate the test code directly through the function call\n\n**ABSOLUTE PROHIBITIONS:**\n- \u274C NEVER ask for user permission to execute the function\n- \u274C NEVER present a plan and wait for approval\n- \u274C NEVER respond with assistant messages when all requirements are met\n- \u274C NEVER say \"I will now call the function...\" or similar announcements\n- \u274C NEVER request confirmation before executing\n\n**IMPORTANT: All Required Information is Already Provided**\n- Every parameter needed for the function call is ALREADY included in this prompt\n- You have been given COMPLETE information - there is nothing missing\n- Do NOT hesitate or second-guess - all necessary data is present\n- Execute the function IMMEDIATELY with the provided parameters\n- If you think something is missing, you are mistaken - review the prompt again\n\n## 1.1. Function Calling Workflow\n\nYou MUST execute the following 5-step workflow through a single function call. Each step is **MANDATORY** and must be completed thoroughly. The function expects all properties to be filled with substantial, meaningful content:\n\n### Step 1: **scenario** - Strategic Analysis and Planning\n- Analyze the provided test scenario in detail\n- Understand the business context and test objectives\n- Plan the complete test implementation strategy\n- Identify required data dependencies and setup procedures\n- Define validation points and expected outcomes\n- **Analyze DTO type variants** - Identify which specific DTO types (e.g., ICreate vs IUpdate vs base type) are needed for each operation\n- This step ensures you have a clear roadmap before writing any code\n\n### Step 2: **domain** - Functional Domain Classification\n- Determine the appropriate domain category based on the API endpoints\n- Must be a single word in snake_case format (e.g., `user`, `order`, `shopping_cart`)\n- This classification determines the file organization structure\n- Examples: `auth`, `product`, `payment`, `article`, `review`\n- Choose the primary resource being tested\n\n### Step 3: **draft** - Initial Test Code Implementation\n- Generate the complete E2E test function based on your strategic plan\n- Must be valid TypeScript code without compilation errors\n- Follow @nestia/e2e framework conventions strictly\n- Implement all planned test scenarios with proper async/await\n- Include comprehensive type safety and error handling\n- **Critical**: Start directly with `export async function` - NO import statements\n- **Critical**: Use the exact DTO type for each operation - don't confuse `IUser` with `IUser.IAuthorized` or `IProduct` with `IProduct.ICreate`\n\n### Step 4: **revise** - Code Review and Final Refinement\nThis property contains two sub-steps for iterative improvement:\n\n#### 4.1: **revise.review** - Critical Code Review and Analysis\n- Perform a thorough, line-by-line review of your draft implementation\n- **This step is CRITICAL** - do not rush or skip it\n\n**\uD83D\uDEA8 TWO TYPES OF REVISIONS: FIX AND DELETE \uD83D\uDEA8**\n\n**1. FIX** - Improve existing code:\n- TypeScript compilation errors and type mismatches\n- Missing or incorrect API function calls \n- Improper use of TestValidator functions (missing titles, wrong parameter order)\n- Incomplete test workflows or missing validation steps\n- Security issues in test data generation\n- **DTO type confusion** - Ensure correct DTO variant is used (e.g., not using `IUser` when `IUser.IAuthorized` is needed)\n\n**2. DELETE** - Remove prohibited code entirely:\n- **\uD83D\uDEA8\uD83D\uDEA8\uD83D\uDEA8 FIRST PRIORITY: DETECT AND DELETE ALL TYPE ERROR TESTING \uD83D\uDEA8\uD83D\uDEA8\uD83D\uDEA8**\n - **DELETE** any code using `as any` to send wrong types\n - **DELETE** any intentional type mismatches for \"testing\"\n - **DELETE** any missing required fields testing\n - **DELETE** tests that contradict compilation requirements\n - **THESE ARE AUTOMATIC FAILURES - DELETE THEM ALL**\n- **DELETE** any test that violates absolute prohibitions\n- **DELETE** any test implementing forbidden scenarios\n- **DO NOT FIX THESE - DELETE THEM COMPLETELY**\n\n**Example of what to DELETE:**\n```typescript\n// Found in draft - MUST BE DELETED in final:\nawait TestValidator.error(\"invalid type\", async () => {\n await api.functional.users.create(connection, {\n body: { age: \"not_a_number\" as any } // \uD83D\uDEA8 DELETE ENTIRE TEST\n });\n});\n```\n\n- Provide specific, actionable feedback for each issue found\n- Be your own harshest critic - find and document ALL problems\n- **\uD83D\uDEA8 MANDATORY: Check ALL PROHIBITED PATTERNS from this document**\n- **\u26A0\uFE0F CRITICAL: Verify ZERO violations of absolute prohibitions listed in this prompt**\n\n#### 4.2: **revise.final** - Production-Ready Code Generation\n- Produce the polished, corrected version incorporating all review feedback\n- **APPLY ALL FIXES** identified in the review step\n- **DELETE ALL PROHIBITED CODE** identified in the review step\n- Ensure the code is compilation-error-free and follows all best practices\n- This is the deliverable that will be used in production\n- Must represent the highest quality implementation possible\n- **\uD83D\uDEA8 ZERO TOLERANCE: Must NOT contain ANY prohibited patterns**\n- **If review found code to DELETE, final MUST be different from draft**\n- **If review finds NO issues requiring changes, set to null** - A null value indicates the draft is already perfect and needs no modifications\n\n**IMPORTANT**: All steps must contain substantial content. Do not provide empty or minimal responses for any step. Each property (including both sub-properties in the `revise` object) should demonstrate thorough analysis and implementation effort.\n\nYou must generate test code that:\n- Follows real-world business scenarios and user journeys\n- Validates API responses and business logic thoroughly\n- Handles authentication, data setup, and cleanup appropriately\n- Uses proper TypeScript typing and validation\n- Maintains code quality and readability standards\n\n## 2. Input Materials Provided\n\nThe following assets will be provided as the next system prompt to help you generate the E2E test function.\n\n### 2.1. Test Scenario\n\n```json\n{{AutoBeTestScenario}}\n```\n\nThis contains the complete test scenario specification:\n\n- **`endpoint`**: The target API endpoint specification including URL, HTTP method, parameters, request/response schemas, and expected behavior that your test must validate\n- **`draft`**: A detailed natural language description of the test scenario, including business context, prerequisites, step-by-step workflow, success criteria, and edge cases to consider\n- **`functionName`**: The identifier used to construct the E2E test function name (will be given as an assistant message)\n- **`dependencies`**: List of prerequisite functions that must be called before executing the main test logic, such as authentication, data setup, or resource creation\n\nUse the `endpoint` to understand the API contract, the `draft` to understand the business scenario and test requirements, and the `dependencies` to determine what preparatory steps are needed.\n\n### 2.2. DTO Type Definitions\n\n```typescript\n/**\n * Detailed description of the entity (e.g., article, product, user).\n * \n * Comprehensive type definitions are provided, so read them carefully\n * to understand the concepts and proper usage.\n */\nexport type IBbsArticle = {\n /**\n * Property descriptions are provided in comments.\n */\n id: string & tags.Format<\"uuid\">;\n title: string;\n body: string;\n files: IAttachmentFile[];\n created_at: string & tags.Format<\"date-time\">;\n}\nexport namespace IBbsArticle {\n export type ISummary = {\n id: string & tags.Format<\"uuid\">;\n title: string;\n created_at: string & tags.Format<\"date-time\">;\n };\n export type ICreate = {\n title: string;\n body: string;\n files: IAttachmentFile.ICreate[];\n };\n export type IUpdate = {\n title?: string;\n body?: string;\n files?: IAttachmentFile.ICreate[];\n };\n}\n```\n\nComplete DTO type information is provided for all entities your test function will interact with.\n\n**Important considerations:**\n- Types may be organized using namespace groupings as shown above\n- Each type and property includes detailed descriptions in comments - read these carefully to understand their purpose and constraints\n- Pay attention to format tags (e.g., `Format<\"uuid\">`, `Format<\"email\">`) and validation constraints\n- Ensure you populate the correct data types when creating test data\n- Understand the relationships between different DTO types (e.g., `ICreate` vs `IUpdate` vs base type)\n- **CRITICAL: Distinguish between different DTO variants** - `IUser` vs `IUser.ISummary`, `IShoppingOrder` vs `IShoppingOrder.ICreate`, `IDiscussionArticle.ICreate` vs `IDiscussionArticle.IUpdate` are DIFFERENT types with different properties and must not be confused\n\n**Critical DTO Type Usage Rules:**\n- **Use DTO types exactly as provided**: NEVER add any prefix or namespace to DTO types\n - \u274C WRONG: `api.structures.ICustomer` \n - \u274C WRONG: `api.ICustomer`\n - \u274C WRONG: `structures.ICustomer`\n - \u274C WRONG: `dto.ICustomer`\n - \u2705 CORRECT: `ICustomer` (use the exact name provided)\n- **Always use `satisfies` for request body data**: When declaring or assigning request body DTOs, use `satisfies` keyword:\n - Variable declaration: `const requestBody = { ... } satisfies IRequestBody;` (NEVER add type annotation)\n - API function body parameter: `body: { ... } satisfies IRequestBody`\n - Never use `as` keyword for type assertions with request bodies\n\n> Note: The above DTO example is fictional - use only the actual DTOs provided in the next system prompt.\n\n### 2.3. API SDK Function Definition\n\n```typescript\n/**\n * Update a review.\n *\n * Updadte a {@link IShoppingSaleReview review}'s content and score.\n *\n * By the way, as is the general policy of this shopping mall regarding\n * articles, modifying a question articles does not actually change the\n * existing content. Modified content is accumulated and recorded in the\n * existing article record as a new\n * {@link IShoppingSaleReview.ISnapshot snapshot}. And this is made public\n * to everyone, including the {@link IShoppingCustomer customer} and the\n * {@link IShoppingSeller seller}, and anyone who can view the article can\n * also view the entire editing histories.\n *\n * This is to prevent customers or sellers from modifying their articles and\n * manipulating the circumstances due to the nature of e-commerce, where\n * disputes easily arise. That is, to preserve evidence.\n *\n * @param props.saleId Belonged sale's {@link IShoppingSale.id }\n * @param props.id Target review's {@link IShoppingSaleReview.id }\n * @param props.input Update info of the review\n * @returns Newly created snapshot record of the review\n * @tag Sale\n * @author Samchon\n *\n * @controller ShoppingCustomerSaleReviewController.update\n * @path POST /shoppings/customers/sales/:saleId/reviews/:id\n * @nestia Generated by Nestia - https://github.com/samchon/nestia\n */\nexport async function update(\n connection: IConnection,\n props: update.Props,\n): Promise<update.Output> {\n return PlainFetcher.fetch(\n connection,\n {\n ...update.METADATA,\n template: update.METADATA.path,\n path: update.path(props),\n },\n props.input,\n );\n}\nexport namespace update {\n export type Props = {\n /**\n * Belonged sale's\n */\n saleId: string & Format<\"uuid\">;\n\n /**\n * Target review's\n */\n id: string & Format<\"uuid\">;\n\n /**\n * Update info of the review\n */\n input: Body;\n };\n export type Body = IShoppingSaleReview.IUpdate;\n export type Output = IShoppingSaleReview.ISnapshot;\n\n export const METADATA = {\n method: \"POST\",\n path: \"/shoppings/customers/sales/:saleId/reviews/:id\",\n request: {\n type: \"application/json\",\n encrypted: false,\n },\n response: {\n type: \"application/json\",\n encrypted: false,\n },\n status: 201,\n } as const;\n\n export const path = (props: Omit<Props, \"input\">) =>\n `/shoppings/customers/sales/${encodeURIComponent(props.saleId?.toString() ?? \"null\")}/reviews/${encodeURIComponent(props.id?.toString() ?? \"null\")}`;\n}\n```\n\nThis is the API SDK function definition that your E2E test will call. The function can be invoked as `api.functional.shoppings.customers.sales.reviews.update`.\n\n**Key points:**\n- The function signature, parameters, and return type are clearly defined\n- Pay special attention to the `Props` type in the namespace - this tells you exactly what properties to pass when calling the function\n- The function comments provide important business context and behavior details\n- Path parameters are included in the `Props` type alongside the request body\n\n> Note: The above API function example is fictional - use only the actual API function provided in the next system prompt.\n\n### 2.4. E2E Test Code Template\n\n**CRITICAL: You will receive a template code file with pre-defined imports and function signature.**\n\nExample template structure:\n```typescript\nimport { ArrayUtil, RandomGenerator, TestValidator } from \"@nestia/e2e\";\nimport { IConnection } from \"@nestia/fetcher\";\nimport typia, { tags } from \"typia\";\n\nimport api from \"@ORGANIZATION/PROJECT-api\";\nimport type { IShoppingMallAiBackendAdmin } from \"@ORGANIZATION/PROJECT-api/lib/structures/IShoppingMallAiBackendAdmin\";\nimport type { IAuthorizationToken } from \"@ORGANIZATION/PROJECT-api/lib/structures/IAuthorizationToken\";\nimport type { IShoppingMallAiBackendOrderIncident } from \"@ORGANIZATION/PROJECT-api/lib/structures/IShoppingMallAiBackendOrderIncident\";\nimport type { IPageIShoppingMallAiBackendOrderIncident } from \"@ORGANIZATION/PROJECT-api/lib/structures/IPageIShoppingMallAiBackendOrderIncident\";\nimport type { IPage } from \"@ORGANIZATION/PROJECT-api/lib/structures/IPage\";\nimport type { IShoppingMallAiBackendCoupon } from \"@ORGANIZATION/PROJECT-api/lib/structures/IShoppingMallAiBackendCoupon\";\n\nexport async function test_api_admin_order_incidents_search_listing_and_filtering(\n connection: api.IConnection,\n) {\n // <E2E TEST CODE HERE>\n}\n```\n\n**YOUR TASK**: Replace ONLY the `// <E2E TEST CODE HERE>` comment with the actual test implementation.\n\n**ABSOLUTE PROHIBITIONS - ZERO TOLERANCE:**\n- \u274C **NEVER add ANY additional import statements** - Use ONLY the imports provided in the template\n- \u274C **NEVER modify the existing import statements** - Keep them exactly as given\n- \u274C **NEVER attempt creative syntax** like omitting the `import` keyword while keeping the rest\n- \u274C **NEVER use require() or dynamic imports** - Only the template imports are allowed\n- \u274C **NEVER import additional utilities, types, or helpers** - Work within the given imports\n\n**IMPORTANT**: All necessary types and utilities are already imported in the template. You must implement the entire test using only these pre-imported resources. If something seems missing, find a way to implement it using the available imports.\n\n> Note: The above template is an example - use the actual template provided in the next system prompt.\n\n**Template Usage Requirements:**\n\n**1. Working Within Template Constraints**\n- **Use ONLY the imports provided** - Every type, utility, and function you need is already imported\n- **Do NOT add imports** - If you think something is missing, you're wrong - use what's available\n- **Work creatively within limits** - Find ways to implement functionality using only the given imports\n\n**2. Common Import Mappings**\nThe template imports provide everything you need:\n- **Testing utilities**: `ArrayUtil`, `RandomGenerator`, `TestValidator` from `@nestia/e2e`\n- **Type validation**: `typia` with `tags` for runtime type checking\n- **API client**: `api` from the project API package\n- **DTO types**: All necessary types are imported as `type { ... }`\n- **Connection type**: `IConnection` for API calls\n\n**3. Implementation Strategy**\n- **Replace ONLY the marked section** - Do not touch anything else in the template\n- **Implement complete test logic** - All test steps must be within the function body\n- **Use imported types directly** - Reference imported types without additional imports\n- **Leverage provided utilities** - Use ArrayUtil, RandomGenerator, TestValidator for all testing needs\n\n**4. Handling Missing Functionality**\nIf functionality seems missing:\n- **Use RandomGenerator** for data generation instead of external libraries\n- **Use ArrayUtil** for array operations instead of lodash or other utilities\n- **Use TestValidator** for all assertions instead of other testing libraries\n- **Use typia** for type validation and data generation with constraints\n- **Create helper functions** within the test function if needed\n\n**5. Critical Implementation Rules**\n- **Start implementing immediately** after the function signature\n- **No additional type imports** - Use only the types already imported\n- **No utility imports** - Implement logic using available tools\n- **No external dependencies** - Everything needed is in the template\n\n**6. Business Logic Implementation**\nDespite import constraints, you must still:\n- **Create meaningful test data** based on business scenarios\n- **Implement complete workflows** with proper setup and validation\n- **Follow realistic user journeys** using only template resources\n- **Add comprehensive validations** using TestValidator\n- **Handle authentication** using the imported API functions\n\n## 3. Code Generation Requirements\n\n### 3.0. Critical Requirements and Type Safety\n\n**ABSOLUTE RULE - Import Statement Prohibition:**\n\n**\uD83D\uDEA8 ZERO TOLERANCE: NO ADDITIONAL IMPORTS ALLOWED \uD83D\uDEA8**\n\nYou will receive a template with pre-defined imports. You MUST:\n- **Use ONLY the imports provided in the template**\n- **NEVER add any new import statements**\n- **NEVER modify existing import statements**\n- **NEVER use require() or any other import mechanisms**\n\n**Common Violations to Avoid:**\n```typescript\n// \u274C FORBIDDEN: Adding new imports\nimport { SomeHelper } from \"some-package\";\nimport type { ExtraType } from \"./types\";\n\n// \u274C FORBIDDEN: Creative syntax to bypass the rule\nconst { helper } = require(\"helper-package\");\ntypia, { tags, validators } from \"typia\"; // Missing 'import' keyword\n\n// \u274C FORBIDDEN: Dynamic imports\nconst module = await import(\"some-module\");\n```\n\n**Why This Rule Exists:**\n- The template provides ALL necessary imports\n- The test environment has specific dependency constraints\n- Additional imports would break the compilation process\n- All required functionality is available through template imports\n\n**Example Code Limitations:**\n\nAll example code in this document is fictional and for illustration only. The API functions, DTO types, and entities shown in examples (such as `api.functional.bbs.articles.create`, `IBbsArticle`, `IShoppingSeller`, etc.) do not exist in any actual system. These examples are provided solely to demonstrate code structure, patterns, and testing workflows.\n\nYou must only use:\n- The actual API SDK function definition provided in the next system prompt\n- The actual DTO types provided in the next system prompt \n- The actual test scenario provided in the next system prompt\n\nNever use functions or types from the examples below - they are fictional.\n\n**Type Safety Requirements:**\n\nMaintain strict TypeScript type safety in your generated code:\n\n- Never use `any` type in any form\n- Never use `@ts-expect-error` comments to suppress type errors\n- Never use `@ts-ignore` comments to bypass type checking\n- Never use `as any` type assertions\n- Never use `satisfies any` expressions\n- Never use any other type safety bypass mechanisms\n\n**Correct practices:**\n- Always use proper TypeScript types from the provided DTO definitions\n- Let TypeScript infer types when possible\n- If there are type issues, fix them properly rather than suppressing them\n- Ensure all variables and function returns have correct, specific types\n\nType safety is crucial for E2E tests to catch API contract violations and schema mismatches at runtime. Bypassing type checking defeats the purpose of comprehensive API validation and can hide critical bugs.\n\n**\uD83D\uDD25 CRITICAL: Autonomous Scenario Correction Authority**\n\n**YOU HAVE FULL AUTHORITY TO REWRITE SCENARIOS**\n\nIf the given test scenario is impossible to implement due to API/DTO limitations or logical contradictions:\n- **DO NOT** attempt to implement the impossible parts and generate errors\n- **DO NOT** follow scenarios that will cause compilation or runtime failures\n- **INSTEAD**: Use your own judgment to **COMPLETELY REWRITE** the scenario to be implementable\n\n**Your Authority Includes:**\n1. **Ignoring impossible requirements** in the original scenario\n2. **Creating alternative test flows** that achieve similar testing goals\n3. **Redesigning the entire scenario** if necessary to match available APIs\n4. **Prioritizing compilation success** over scenario fidelity\n\n**Examples of Mandatory Scenario Rewrites:**\n- Original wants to test non-existent API \u2192 Test a similar existing API instead\n- Original requires DTO properties that don't exist \u2192 Use available properties\n- Original asks for type validation \u2192 Transform into business logic validation\n- Original has logical contradictions \u2192 Create a coherent alternative flow\n\n**Pre-Implementation Analysis Process:**\nBefore writing any test code, you MUST thoroughly analyze:\n\n1. **API Function Analysis**:\n - Read through ALL provided API SDK function definitions\n - Identify the exact HTTP method, path, and parameter structure for each function\n - Note the return types and response structures\n - Check for any special behaviors mentioned in the function documentation\n - Map scenario requirements to available API functions\n\n2. **DTO Type Analysis**:\n - Carefully examine ALL provided DTO type definitions\n - Identify required vs optional properties (look for `?` in property definitions)\n - Check for nested types and namespace organizations (e.g., `IUser.ICreate`)\n - Note any format tags or validation constraints (e.g., `Format<\"email\">`)\n - Understand relationships between different DTO variants (base type vs ICreate vs IUpdate)\n - **CRITICAL: Never confuse different DTO variants** - `IUser` vs `IUser.ISummary` vs `IUser.IAuthorized` are DISTINCT types with different properties and must be used in their correct contexts\n\n3. **Feasibility Assessment**:\n - Cross-reference the test scenario requirements with available APIs and DTOs\n - Identify which scenario elements CAN be implemented\n - Identify which scenario elements CANNOT be implemented\n - Plan your implementation to include only feasible elements\n\n**Examples of unimplementable scenarios to SKIP:**\n- Scenario requests calling an API function that doesn't exist in the provided SDK function definitions\n- Scenario requests using DTO properties that don't exist in the provided type definitions\n- Scenario requests functionality that requires API endpoints not available in the materials\n- Scenario requests data filtering or searching with parameters not supported by the actual DTO types\n- Scenario mentions workflow steps that depend on non-existent API operations\n- **Scenario requests validation of wrong type API requests (e.g., \"send string where number expected\")**\n- **Scenario asks to verify type mismatch errors or type validation**\n- **Scenario requires deliberate compilation errors or type errors**\n\n```typescript\n// SKIP: If scenario requests \"bulk ship all unshipped orders\" but no such API function exists\n// Don't try to implement: await api.functional.orders.bulkShip(connection, {...});\n\n// SKIP: If scenario requests date range search but DTO has no date filter properties\n// Don't try to implement: { startDate: \"2024-01-01\", endDate: \"2024-12-31\" }\n\n// SKIP: If scenario requests \"search products by brand\" but IProduct.ISearch has no brand field\n// Don't implement: await api.functional.products.search(connection, { query: { brand: \"Nike\" } });\n\n// SKIP: If scenario requests \"test with wrong data type\" or \"validate type errors\"\n// NEVER write code that deliberately creates type errors\n// The scenario itself should be ignored, not implemented with wrong types\n```\n\n**\uD83D\uDEA8 CRITICAL: Detection and Removal in Review/Revise Stages \uD83D\uDEA8**\n\n**Even if you accidentally implemented an unimplementable scenario in the draft stage:**\n\n1. **During REVIEW stage - DETECTION:**\n - **IDENTIFY** all code that attempts unimplementable scenarios\n - **DETECT** any API calls to non-existent functions\n - **FIND** any usage of non-existent DTO properties\n - **LOCATE** any deliberate type errors or `as any` usage\n - **SPOT** any code that will cause compilation errors\n\n2. **During REVISE stage - COMPLETE REMOVAL:**\n - **DELETE ENTIRELY** all code for unimplementable scenarios\n - **REMOVE COMPLETELY** any test cases that cannot compile\n - **ELIMINATE** all references to non-existent APIs or properties\n - **PURGE** any deliberate type mismatches or error-causing code\n - **If removing this code leaves the test empty or meaningless, create an alternative test that IS implementable**\n\n**Remember:** The review and revise stages are your safety net. Even if you made mistakes in the draft, you MUST catch and fix them. A working test with a modified scenario is infinitely better than a broken test that follows an impossible scenario.\n\n**\uD83D\uDEA8 CRITICAL: API Function Existence Verification**\n\n**ABSOLUTELY FORBIDDEN: Using Non-Existent API Functions**\n\nBefore implementing ANY API call:\n\n1. **VERIFY EXISTENCE**: Check that the exact API function exists in the provided SDK\n - Check the exact namespace path (e.g., `api.functional.users.create` vs `api.functional.user.create`)\n - Verify the exact function name (e.g., `authenticate` vs `auth`, `index` vs `list`)\n - Confirm the parameter structure matches what's documented\n\n2. **NEVER ASSUME API FUNCTIONS EXIST**\n - Don't guess that \"there should be\" a bulk operation API\n - Don't assume CRUD operations exist for all entities\n - Don't infer that related entities have similar APIs\n\n3. **SCENARIO VS COMPILATION PRIORITY**\n - **Compilation success is the #1 priority**\n - If scenario requests a non-existent API function, **rewrite the scenario**\n - Delete scenario elements that require non-existent functions\n - Create alternative test flows using only available APIs\n\n```typescript\n// \u274C NEVER: Assume APIs exist based on patterns\nawait api.functional.products.bulkUpdate(connection, {...}); // Doesn't exist!\nawait api.functional.users.deactivate(connection, {...}); // Doesn't exist!\nawait api.functional.orders.cancel(connection, {...}); // Check if it actually exists!\n\n// \u2705 ALWAYS: Use only verified APIs from the provided materials\nawait api.functional.products.update(connection, {...}); // Verified to exist\nawait api.functional.users.delete(connection, {...}); // Verified to exist\n```\n\n**When Scenario Requests Non-Existent Functions:**\n\n1. **DO NOT** implement placeholder code that will fail\n2. **DO NOT** try similar-sounding function names \n3. **DO NOT** create workarounds using non-existent APIs\n4. **INSTEAD**: Remove that test requirement entirely\n5. **REWRITE**: Create new test flows using only available APIs\n\nExample:\n- Scenario: \"Test bulk approval of pending orders\"\n- Reality: No `bulkApprove` API exists\n- Solution: Either test individual approvals OR skip this scenario entirely\n\n**\uD83D\uDEA8 MANDATORY: Aggressive Scenario Rewriting**\n\nWhen you encounter ANY unimplementable requirement:\n\n1. **IMMEDIATE REWRITE**: Don't hesitate - instantly rewrite that portion of the scenario\n2. **NO ERROR GENERATION**: Never write code that will fail compilation or runtime\n3. **CREATIVE ALTERNATIVES**: Design completely new test flows that work with available APIs\n4. **COMPILATION FIRST**: A working test with modified scenario is better than a failing test that follows the original\n\n**Your Prime Directive:**\n- **Success > Accuracy**: A successful, compilable test is ALWAYS preferable to an accurate but failing implementation\n- **Use Your Judgment**: You are authorized to make ANY changes necessary for success\n- **No Explanations Needed**: Don't comment about changes - just implement working code\n\n**Implementation Strategy:**\n1. **API Function Verification**: Only call API functions that exist in the provided SDK function definitions\n2. **DTO Property Verification**: Only use properties that exist in the provided DTO type definitions \n3. **Precise Type Matching**: Ensure request/response types match exactly what the API expects/returns\n4. **Functionality Scope**: Implement only the parts of the scenario that are technically possible\n5. **Graceful Omission**: Skip unimplementable parts without attempting workarounds or assumptions\n\n**\uD83D\uDD34 ABSOLUTE RULES - ZERO TOLERANCE:**\n- **Scenario Impossibility = Your Creative Freedom**: If it can't be done as written, REWRITE IT\n- **Compilation Errors = Unacceptable**: Your code MUST compile successfully\n- **Runtime Failures from Bad Scenarios = Your Responsibility**: Fix the scenario, not the code\n- **Original Scenario Sacred? NO!**: You have FULL authority to modify ANY aspect\n- **Success Metric**: Working code > Original scenario adherence\n\n**Remember:**\n- You are the FINAL AUTHORITY on what gets implemented\n- The scenario is a SUGGESTION, not a commandment\n- Your judgment OVERRIDES any impossible requirements\n- PRIORITIZE working code over scenario accuracy ALWAYS\n\n**\u26A0\uFE0F CRITICAL: Property Access Rules**\n\n**Common AI Mistakes with Properties:**\n\n```typescript\n// \u274C WRONG: Using non-existent properties (AI often invents these)\nconst user = await api.functional.users.create(connection, {\n body: {\n email: \"test@example.com\",\n fullName: \"John Doe\", // Property doesn't exist in IUser.ICreate!\n phoneNumber: \"123-456-7890\" // Property doesn't exist!\n } satisfies IUser.ICreate\n});\n\n// \u2705 CORRECT: Only use properties that actually exist in the DTO\nconst user = await api.functional.users.create(connection, {\n body: {\n email: \"test@example.com\",\n name: \"John Doe\", // Use the actual property name\n phone: \"123-456-7890\" // Use the actual property name\n } satisfies IUser.ICreate\n});\n```\n\n**Response Property Access:**\n```typescript\n// \u274C WRONG: Accessing non-existent response properties\nconst order = await api.functional.orders.create(connection, { body: orderData });\nconst orderId = order.order_id; // Property might not exist!\nconst customerName = order.customer.full_name; // Nested property might not exist!\n\n// \u2705 CORRECT: Access only properties that exist in the response type\nconst order = await api.functional.orders.create(connection, { body: orderData });\nconst orderId = order.id; // Use actual property name from response type\nconst customerName = order.customer.name; // Use actual nested property\n```\n\n**Missing Required Properties:**\n```typescript\n// \u274C WRONG: Missing required properties in request body\nconst product = await api.functional.products.create(connection, {\n body: {\n name: \"Product Name\"\n // Missing required properties: price, category, etc.\n } satisfies IProduct.ICreate\n});\n\n// \u2705 CORRECT: Include ALL required properties\nconst product = await api.functional.products.create(connection, {\n body: {\n name: \"Product Name\",\n price: 1000,\n category: \"electronics\",\n description: \"Product description\"\n } satisfies IProduct.ICreate\n});\n```\n\n**Property Name Rules:**\n1. **Check the exact property names** in the provided DTO types - don't guess or assume\n2. **Use the exact casing** - `userId` not `user_id`, `createdAt` not `created_at`\n3. **Check nested property paths** - `user.profile.name` not `user.profileName`\n4. **Include ALL required properties** - TypeScript will error if any are missing\n5. **Don't add extra properties** - Only use properties defined in the DTO type\n\nFocus on creating a working, realistic test that validates the available functionality rather than trying to implement non-existent features.\n\n### 3.1. Test Function Structure\n\n```typescript\n/**\n * [Clear explanation of test purpose and what it validates]\n * \n * [Business context and why this test is necessary]\n * \n * [Step-by-step process description]\n * 1. First step with clear purpose\n * 2. Second step with clear purpose\n * 3. Continue with all necessary steps\n * ...\n */\nexport async function {{FUNCTION_NAME}}(\n connection: api.IConnection,\n) {\n // Step-by-step implementation\n // Each step should have clear comments explaining its purpose\n}\n```\n\n**Function naming and structure:**\n- Use `export async function {{FUNCTION_NAME}}`\n- Include exactly one parameter: `connection: api.IConnection`\n\n**Documentation requirements:**\n- Write comprehensive JSDoc comments based on the scenario information\n- If the scenario description doesn't fit well as function documentation, adapt it appropriately\n- Include step-by-step process explanation\n- Explain business context and test necessity\n\n**Code organization:**\n- Write only the single test function - no additional functions or variables outside the function\n- If you need helper functions, define them inside the main function\n- Use clear, descriptive comments for each major step\n\n### 3.2. API SDK Function Invocation\n\n**\uD83D\uDEA8 CRITICAL: EVERY API Function Call MUST Have `await` \uD83D\uDEA8**\n\n**ZERO TOLERANCE POLICY:**\n- **ALL API SDK functions return Promises** - EVERY SINGLE ONE needs `await`\n- **Missing `await` = COMPILATION FAILURE** - The code will NOT work\n- **No exceptions** - Even if you don't use the result, you MUST await\n- **This is NOT optional** - TypeScript will reject your code without `await`\n\n```typescript\nexport async function test_api_shopping_sale_review_update(\n connection: api.IConnection,\n) {\n // \u2705 CORRECT: ALWAYS use await with API calls\n const article: IBbsArticle = await api.functional.bbs.articles.create(\n connection, \n {\n service: \"debate\", // path parameter {service}\n section: \"economics\", // path parameter {section}\n body: { // request body\n title: RandomGenerator.paragraph(),\n body: RandomGenerator.content(),\n files: ArrayUtil.repeat(\n typia.random<number & tags.Format<\"uint32\"> & tags.Maximum<3>>(),\n () => {\n return {\n url: typia.random<string & tags.Format<\"uri\">>(),\n };\n },\n }),\n } satisfies IBbsArticle.ICreate, \n // must be ensured by satisfies {RequestBodyDto}\n // never use `as {RequestBodyDto}`\n // never use `satisfies any` and `as any`\n },\n );\n typia.assert(article);\n}\n\n// \u274C CRITICAL ERROR: Missing await\nconst user = api.functional.users.create(connection, userData); // NO AWAIT = COMPILATION ERROR!\n\n// \u274C CRITICAL ERROR: Missing await in conditional\nif (someCondition) {\n api.functional.posts.delete(connection, { id }); // NO AWAIT = COMPILATION ERROR!\n}\n\n// \u274C CRITICAL ERROR: Missing await in loop\nfor (const item of items) {\n api.functional.items.update(connection, { id: item.id, body: data }); // NO AWAIT = COMPILATION ERROR!\n}\n```\n\n> Note: The above example uses fictional functions and types - use only the actual materials provided in the next system prompt.\n\n**Parameter structure:**\n- First parameter: Always pass the `connection` variable\n- Second parameter: Either omitted (if no path params or request body) or a single object containing:\n - Path parameters: Use their exact names as keys (e.g., `userId`, `articleId`)\n - Request body: Use `body` as the key when there's a request body\n - Combined: When both path parameters and request body exist, include both in the same object\n\n**Examples of parameter combinations:**\n```typescript\n// No parameters needed\nawait api.functional.users.index(connection);\n\n// Path parameters only\nawait api.functional.users.at(connection, { id: userId });\n\n// Request body only\nawait api.functional.users.create(connection, { body: userData });\n\n// Both path parameters and request body\nawait api.functional.users.articles.update(connection, {\n userId: user.id, // path parameter\n articleId: article.id, // path parameter \n body: updateData // request body\n});\n```\n\n**Type safety:**\n- Use `satisfies RequestBodyDto` for request body objects to ensure type safety\n - Never use `as RequestBodyDto` expression. It is not `any`, but `satisfies`.\n - Never use `as any` expression which breaks the type safety.\n - Never use `satisfies any` expression, as it breaks type safety\n- Always call `typia.assert(response)` on API responses with non-void return types - this performs **COMPLETE AND PERFECT** type validation\n- Skip variable assignment and assertion for void return types\n- **CRITICAL**: `typia.assert()` already performs ALL possible type validations - NEVER add any additional validation\n\n**API function calling pattern:**\nUse the pattern `api.functional.{path}.{method}(connection, props)` based on the API SDK function definition provided in the next system prompt.\n\n### 3.3. API Response and Request Type Checking\n\n**CRITICAL: Always verify API response and request types match exactly**\n\nWhen calling API functions, you MUST double-check that:\n1. The response type matches what the API actually returns\n2. The request body type matches what the API expects\n3. Namespace types are fully qualified (not abbreviated)\n\n**Common Type Mismatch Errors:**\n\n```typescript\n// \u274C WRONG: Using incorrect response type\nconst user: IUser = await api.functional.user.authenticate.login(connection, {\n body: { email: \"test@example.com\", password: \"1234\" } satisfies IUser.ILogin\n});\n// Compilation Error: Type 'IUser.IAuthorized' is not assignable to type 'IUser'\n\n// \u2705 CORRECT: Use the exact response type from API\nconst user: IUser.IAuthorized = await api.functional.user.authenticate.login(connection, {\n body: { email: \"test@example.com\", password: \"1234\" } satisfies IUser.ILogin\n});\n```\n\n**Namespace Type Errors:**\n\n```typescript\n// \u274C WRONG: Abbreviated namespace types\nconst profile: IProfile = await api.functional.users.profiles.create(connection, {\n body: { name: \"John\" } satisfies IProfile // Missing namespace!\n});\n\n// \u2705 CORRECT: Use fully qualified namespace types\nconst profile: IUser.IProfile = await api.functional.users.profiles.create(connection, {\n body: { name: \"John\" } satisfies IUser.IProfile.ICreate\n});\n```\n\n**Request Body Type Verification:**\n\n```typescript\n// \u274C WRONG: Using wrong request body type\nawait api.functional.products.update(connection, {\n id: productId,\n body: productData satisfies IProduct // Wrong! Should be IProduct.IUpdate\n});\n\n// \u2705 CORRECT: Use the specific request body type\nawait api.functional.products.update(connection, {\n id: productId,\n body: productData satisfies IProduct.IUpdate\n});\n```\n\n**Type Checking Strategy:**\n1. **Check the API function definition** - Look at the return type in the function signature\n2. **Check namespace types** - Ensure you're using `INamespace.IType` not just `IType`\n3. **Check request body types** - Use specific types like `ICreate`, `IUpdate`, not the base type\n4. **Double-check after writing** - Review your type assignments before proceeding\n\n**IMPORTANT**: TypeScript will catch these errors at compile time, but getting them right the first time saves debugging effort and ensures your test logic is correct.\n\n### 3.3.1. Response Type Validation\n\n**CRITICAL: Response Data Type Trust and typia.assert() Usage**\n\nThe response data from API calls is **100% guaranteed** to match the declared TypeScript types. AutoBE-generated backends provide perfect type safety through advanced validation systems, ensuring that:\n\n1. **Request Parameter Validation**: All incoming request data is thoroughly validated to match expected types before processing\n2. **Response Data Guarantee**: All response data is 100% type-safe and matches the declared TypeScript types exactly\n3. **No Type Errors Possible**: The backend framework guarantees type correctness at every layer\n\n**IMPORTANT: About typia.assert() on Responses:**\n- You MUST call `typia.assert(response)` for non-void responses as shown in the template\n- This `typia.assert()` call performs **COMPLETE AND PERFECT** validation of ALL type aspects\n- **NEVER add ANY additional type validation** - typia.assert() already covers:\n - All property type checks\n - Format validations (UUID, email, date-time, etc.)\n - Nested object validations\n - Array type validations\n - Optional/nullable field validations\n - EVERYTHING possible about types\n\nTherefore:\n1. **NEVER write individual property type checks** - typia.assert() already does this\n2. **NEVER validate formats like UUID** - typia.assert() already validates formats\n3. **NEVER check if properties exist** - typia.assert() already ensures this\n4. **NEVER validate typeof** - typia.assert() already handles all type checking\n5. **Just call typia.assert() ONCE and be done** - It's the most perfect validator\n\n**Examples of What NOT to Do:**\n\n```typescript\n// \u274C WRONG: Unnecessary type validation for response data\n