A python automation test script generation method and system

CN123011742APending Publication Date: 2026-10-30GHOSTCLOUD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611510833.1
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-09-28
Publication Date
2026-10-30

AI Technical Summary

Technical Problem

[0005]场景适配性差:接口测试、UI测试、性能测试等不同场景的脚本结构、依赖库差异巨大

Benefits of technology

[0049]1)利用特征解析模型对自然语言需求进行语义理解与结构化提取,实现了对非专业开发背景测试人员的友好支持,使其无需掌握复杂编程语法即可描述测试需求;

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123011742A_ABST
    Figure CN123011742A_ABST
Patent Text Reader

Abstract

The application discloses a Python automatic test script generation method and system, relates to the technical field of software test automation, and receives a natural language or a structured test requirement, extracts a test scene type, technical parameters and an expected result by using a feature analysis model, and forms a structured requirement feature vector; according to the scene type, a preset Python test script template is matched, and the technical parameters are automatically filled into a template placeholder to generate an initial script; syntax checking, logic integrity detection and compatibility optimization are performed on the initial script, and an executable script is output. The application further provides three mechanisms of intelligent assertion logic code synthesis, incremental training and business process test intelligent arrangement, can automatically generate complex verification logic, continuously optimize the feature analysis model according to execution feedback, and automatically arrange an end-to-end test process.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of software test automation technology, specifically to a method and system for generating Python automated test scripts. Background Technology

[0002] In the software development lifecycle, automated testing is a crucial step in ensuring software quality and improving testing efficiency. Python, with its concise syntax and rich ecosystem (offering mature testing frameworks such as Pytest, Selenium, and Locust), has become the mainstream choice for developing automated test scripts.

[0003] However, the current Python-based automated test script development model still has significant bottlenecks:

[0004] High development threshold: Testers need to be proficient in Python syntax and APIs of various testing frameworks, which is extremely unfriendly to non-professional developers and results in a long script development cycle.

[0005] Poor scenario adaptability: The script structure and dependency libraries vary greatly across different scenarios such as interface testing, UI testing, and performance testing. Existing tools mostly focus on single scenarios and lack a unified multi-scenario script generation solution, forcing testers to master multiple tools, resulting in high learning costs.

[0006] Low script reusability: Traditional scripts are mostly "one-off" code for specific needs, lacking parameterized and templated design. When the test object or requirements change slightly, a large amount of code often needs to be rewritten, resulting in high maintenance costs.

[0007] Compatibility issues are prominent: Python versions and various testing frameworks iterate rapidly, and manually written scripts often face version compatibility problems, requiring additional time for debugging and adaptation. Summary of the Invention

[0008] The purpose of this invention is to overcome the shortcomings of the prior art and provide a Python automated test script generation method and system, which realizes the automated conversion from natural language or structured testing requirements to high-quality, executable Python test scripts, supports multiple testing scenarios such as interface, UI, and performance, reduces the development threshold, and improves script development efficiency, intelligence level and reusability.

[0009] The objective of this invention is achieved through the following technical solution:

[0010] In a first aspect, this invention discloses a method for generating automated test scripts using Python, comprising:

[0011] Receive test requirements, perform feature parsing on the test requirements, extract test scenario type, test object, test action, technical parameters and expected results, and generate a structured requirement feature vector;

[0012] Based on the test scenario type in the structured requirement feature vector, a hybrid matching strategy combining keyword matching and semantic similarity is adopted to match the corresponding Python test script template from the pre-set scenario template library. The Python test script template contains a fixed syntax framework and parameter placeholders.

[0013] The technical parameters in the structured requirement feature vector are filled into the corresponding parameter placeholders of the matched template to generate the initial Python test script;

[0014] The initial Python test script is subjected to syntax validation, logical integrity checks, and runtime environment compatibility optimization to obtain an executable Python test script.

[0015] Based on the first aspect, the test requirements include natural language text or structured documents;

[0016] If the test requirement is natural language text, a feature parsing model is used for semantic understanding and named entity recognition to extract structured features;

[0017] If the test requirement is a structured document, the Pandas library is used for data parsing to extract the feature vector of the structured requirement.

[0018] Based on the first aspect, the feature parsing model includes an embedding layer, a sequence encoding layer, and a label decoding layer;

[0019] The embedding layer uses a pre-trained BERT model to convert the input natural language test requirement text into a sequence of word vectors carrying contextual semantic information;

[0020] The sequence encoding layer employs a bidirectional long short-term memory network to encode the word vector sequence from both the forward and reverse directions, and concatenates the hidden states from both directions as the context representation of each word to capture long-distance dependencies in the text.

[0021] The label decoding layer uses a conditional random field to decode the hidden state sequence output by the bidirectional long short-term memory network, and combines it with preset label transition constraints to output the globally optimal label sequence, thereby achieving joint recognition of test scenario type, test object, test action, technical parameters, and expected results.

[0022] Based on the first aspect, the scenario template library includes at least one of the following: an interface test template built on the Requests library, a UI test template built on the Selenium library, and a performance test template built on the Locust library.

[0023] Based on the first aspect, the hybrid matching strategy that combines keyword matching and semantic similarity specifically includes:

[0024] The test scenario type field is matched with the preset keyword library of each template in the scenario template library, and the matching score is calculated. The keyword library of the interface test template includes interface, API, request and HTTP; the keyword library of the UI test template includes page, element, click and input; and the keyword library of the performance test template includes performance, concurrency, load test and throughput.

[0025] The semantic vector of the test scenario type field is similar to the semantic vector of each template identifier. The keyword matching score and semantic similarity are weighted and summed according to a preset weight, and the template with the highest score is used as the target template. When the highest score is lower than the preset threshold, the scenario matching is determined to be unsuccessful, the default interface test template is output and manual confirmation is prompted. When there are multiple candidate templates with similar scores, the user is prompted to confirm the selection.

[0026] Based on the first aspect, the syntax verification includes calling Python's ast module to parse the initial Python test script, detect and automatically correct syntax errors; the logical integrity detection includes determining whether the initial Python test script contains assertion logic code and exception handling structure through static code analysis, and automatically supplementing the corresponding code blocks if they are missing.

[0027] Based on the first aspect, it also includes analyzing the description of the expected result and generating verification code using an intelligent assertion logic code synthesis mechanism; wherein, the intelligent assertion logic code synthesis mechanism specifically includes:

[0028] Analyze the description of expected results in the structured requirement feature vector, and combine it with the historical response data structure of the target interface or a predefined data pattern to identify verifiable fields, determine the data type and constraints of the fields, and infer the legal business rules or value ranges.

[0029] Based on the analysis of the expected results described in the structured requirement feature vector, multi-dimensional assertion logic code that exceeds the explicitly specified range of the technical parameters is synthesized. The assertion logic code includes code for checking the existence of fields, data types, and compliance with business rules in the response data.

[0030] The synthesized multi-dimensional assertion logic code is inserted or generated at the corresponding logic location in the initial Python test script.

[0031] Based on the first aspect, it also includes using an incremental training mechanism to adaptively optimize the script and iterate the model; the incremental training mechanism includes:

[0032] Execute the executable Python test script and monitor its execution process, collecting execution performance data and results;

[0033] In response to execution failures caused by missing parameters or semantic misunderstandings, training samples are constructed by combining the current test requirements with the error messages and input data from the execution failure.

[0034] The feature parsing model is incrementally trained using the training samples to optimize the accuracy of the required feature parsing.

[0035] Based on the first aspect, if the test requirement describes an end-to-end business process containing multiple atomic steps, then the test requirement is parsed and scripts are synthesized using a business process test intelligent orchestration mechanism; wherein, the business process test intelligent orchestration mechanism specifically includes:

[0036] Analyze the test requirements and identify the atomic test scenarios and the data dependencies between them;

[0037] Based on the data dependencies, generate test scripts for each atomic test scenario;

[0038] Arrange the execution order of the test scripts and the data transfer logic across scripts to generate an executable full-process test suite.

[0039] Secondly, this invention discloses a Python automated test script generation system for executing the Python automated test script generation method described in the first aspect, comprising:

[0040] The requirement feature parsing module is used to parse the features of received natural language or structured test requirements and generate a structured requirement feature vector containing test scenario type, technical parameters and expected results.

[0041] A scenario template library is used to store Python test script templates categorized by test scenario. The Python test script templates contain a fixed syntax framework and parameter placeholders.

[0042] A dynamic parameter configuration engine connects the requirement feature parsing module and the scene template library. It is used to match the corresponding template according to the structured requirement feature vector and automatically fill the technical parameters into the template placeholders to generate the initial script.

[0043] The dynamic parameter configuration engine also includes an intelligent assertion logic code synthesis unit, which is used to perform in-depth analysis on the expected result description and automatically synthesize multi-dimensional assertion logic code to insert into the initial Python test script.

[0044] The script verification and optimization component is used to perform syntax verification, logical integrity checks, and runtime environment compatibility optimization on the initial Python test script, and output an executable script.

[0045] The business process orchestration engine is used to parse the test requirement when the test requirement is an end-to-end business process, identify the atomic test scenarios and their data dependencies, generate test scripts for each scenario, and orchestrate their execution order and data transmission logic to form a full-process test suite.

[0046] The script execution and feedback analysis module is used to execute the executable script and monitor its process, compare the execution results with the expected results, and construct training samples when it is determined that the failure is caused by the deviation in the requirement analysis.

[0047] The model iteration management module is used to incrementally train the feature parsing model in the requirement feature parsing module using the training samples.

[0048] The beneficial effects of this invention are:

[0049] 1) By using a feature parsing model to perform semantic understanding and structured extraction of natural language requirements, it provides friendly support for testers without professional development backgrounds, enabling them to describe test requirements without mastering complex programming syntax;

[0050] 2) Based on a pre-built multi-scenario template library and parameter mapping and automatic filling, it realizes unified adaptation to different test scenarios such as interface, UI, and performance, and rapid script generation. When the requirements change, only the parameters need to be adjusted, which solves the problems of poor scenario adaptability, low script reusability and high maintenance cost of traditional methods. Attached Figure Description

[0051] Figure 1 This is a flowchart of the Python automated test script generation method provided in this embodiment of the invention;

[0052] Figure 2 This is a schematic diagram of the intelligent assertion logic code synthesis mechanism provided in this embodiment of the invention;

[0053] Figure 3 This is a schematic diagram of the incremental training mechanism provided in an embodiment of the present invention;

[0054] Figure 4 This is a schematic diagram of the intelligent orchestration mechanism for business process testing provided in this embodiment of the invention. Detailed Implementation

[0055] The technical solution of the present invention will be clearly and completely described below with reference to the embodiments. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0056] Example 1

[0057] Please refer to Figure 1 This embodiment provides a method for generating Python automated test scripts, including:

[0058] Receive test requirements, perform feature parsing on the test requirements, extract test scenario type, test object, test action, technical parameters and expected results, and generate structured requirement feature vectors. The test requirements include natural language text or structured documents.

[0059] Based on the test scenario type in the structured requirement feature vector, a hybrid matching strategy combining keyword matching and semantic similarity is adopted to match the corresponding Python test script template from the pre-set scenario template library. The Python test script template contains a fixed syntax framework and parameter placeholders.

[0060] The technical parameters in the structured requirement feature vector are filled into the corresponding parameter placeholders of the matched template to generate the initial Python test script;

[0061] The initial Python test script is subjected to syntax validation, logical integrity checks, and runtime environment compatibility optimization to obtain an executable Python test script.

[0062] As one possible implementation, when the test requirement is natural language text, a feature parsing model is used for semantic understanding and named entity recognition to extract structured features; the feature parsing model is preferably a hybrid model based on BERT-BiLSTM-CRF.

[0063] Furthermore, the feature parsing model includes an embedding layer, a sequence encoding layer, and a label decoding layer: the embedding layer uses a pre-trained BERT model to convert the input natural language test requirement text into a sequence of word vectors carrying contextual semantic information; the sequence encoding layer uses a bidirectional long short-term memory network (BiLSTM) to encode the word vector sequence from both the forward and reverse directions, and concatenates the hidden states from both directions as the contextual representation of each word to capture long-distance dependencies in the text; the label decoding layer uses a conditional random field (CRF) to decode the hidden state sequence output by the BiLSTM, and combines it with preset label transition constraints (e.g., under the BIO labeling system, the "B-technical parameters" label is not allowed to be directly followed by the "I-test object" label) to output the globally optimal label sequence, thereby achieving joint recognition of test scenario type (text classification task) and test object, test action, technical parameters, and expected result (sequence labeling task).

[0064] The training process of the feature parsing model is as follows: collect historical test requirement texts and their manual annotation results to form a training sample set. The annotation content of each training sample includes a test scenario type label, as well as the entity boundary and entity category corresponding to the test object, test action, technical parameters, and expected result (using the BIO annotation system); use the cross-entropy loss function (the CRF loss function is used for the sequence annotation part) as the optimization objective, use the Adam optimizer to fine-tune the pre-trained BERT model, and use the F1 value on the validation set to select the model and stop early, thus obtaining the trained feature parsing model.

[0065] The above structure is adopted because: the BERT model, pre-trained on a large-scale corpus, possesses strong semantic understanding capabilities, enabling it to map semantically similar texts into similar vector representations; BiLSTM can model the semantic role of each word by incorporating contextual information; and the CRF decoding layer ensures the legality of entity boundaries and entity categories through label transfer constraints. The combination of these three elements allows the feature parsing model to accurately identify test scenario types from natural language testing requirements and extract structured features such as test objects, test actions, technical parameters, and expected results, thereby generating structured requirement feature vectors.

[0066] As one possible implementation, when the test requirement is a structured document, the Pandas library is used for data parsing to extract the feature vector of the structured requirement.

[0067] As one possible implementation, the scenario template library includes at least one of the following: an interface test template built on the Requests library, a UI test template built on the Selenium library, and a performance test template built on the Locust library.

[0068] As one possible implementation, the method for generating the initial Python test script is as follows: based on a pre-set parameter mapping rule library, the technical parameters in the structured requirement feature vector are matched with the parameter placeholders in the template, and automatic replacement and filling are performed.

[0069] Furthermore, the technical parameters are specific configuration values ​​directly related to test execution, including: interface test parameters, such as interface address, request method, request headers, request body, expected status code, etc.; UI test parameters, such as browser type, element location method, input text, etc.; and performance test parameters, such as concurrent users, startup rate, test duration, etc. These technical parameters correspond to the placeholders {api_url}, {request_method}, {headers}, and {expected_status_code} in the interface test template, the placeholders {browser_type}, {element_locator}, and {input_text} in the UI test template, and the placeholders {user_count}, {spawn_rate}, and {test_duration} in the performance test template, respectively.

[0070] Furthermore, the parameter mapping rule library contains multiple pre-defined parameter mapping rules. Each rule establishes a correspondence between technical parameters and template placeholders, and its form is {technical parameter name, template placeholder, type conversion rule, default value}. The type conversion rule converts the technical parameter value to the data type required by the placeholder before filling, for example, converting a string value to an integer. The default value is used to fill in the missing technical parameter for a placeholder if it is not specified in the requirements. After filling, the generated initial script undergoes an integrity check to verify that all required placeholders have been filled. If any required placeholders are not filled, a prompt message is output or the default value is used to complete the field.

[0071] One possible approach to syntax validation is to call Python's ast module to parse the initial script, detect and automatically correct syntax errors.

[0072] As one possible implementation, the method for performing logical integrity checks is as follows: determine whether the initial script contains assertion logic code and exception handling structure through static code analysis; if missing, automatically supplement the corresponding code block.

[0073] The method for detecting missing assertion logic code is as follows: search for the existence of an Assert node within the function body of the test function. Simultaneously, the test scenario type is considered for further judgment.

[0074] In API testing scenarios, if there are no Assert nodes in the function body, it is determined that the assertion logic code is missing.

[0075] For UI testing scenarios, if there is no Assert node in the function body to validate page elements, titles, or text, it is determined that the assertion logic code is missing.

[0076] When a missing assertion logic code is detected, a standard assertion code block is generated based on the scenario type and template preset, and inserted as a new Assert node into the corresponding position of the function body.

[0077] The method for detecting missing exception handling structures is as follows: check whether the top-level node of the test function body is wrapped by the TryExcept node. If it is not wrapped, it is determined that the exception handling structure is missing.

[0078] When a missing exception handling structure is detected, all nodes of the original function body are moved to the body property of a newly created TryExcept node. At least one ExceptHandler child node is created for this TryExcept node to catch common exceptions. In the body of the ExceptHandler node, a statement calling the test framework's failed method is inserted. Finally, the function body of the original test function is replaced with this newly created TryExcept node.

[0079] For example, this embodiment demonstrates the generation of a user login interface test script:

[0080] Test requirement input: Users can input test requirements in natural language through the text box on the system's web interface, or upload a structured requirement document in Excel format through the "file upload" function. The system supports batch import of multiple sets of test requirements.

[0081] Demand Feature Analysis: The format of the input demand is judged. If it is natural language, features are extracted using the BERT-BiLSTM-CRF hybrid model. If it is a structured document, the data is parsed using Pandas. Finally, a unified structured demand feature vector is generated and stored in the system database.

[0082] Scenario template matching: Read the "Scenario Type" field from the requirement feature vector, traverse the scenario template library, and determine the target template through keyword matching algorithms (such as "interface" matching interface test templates, "performance" matching performance test templates);

[0083] Furthermore, to improve matching accuracy, the scenario matching adopts a hybrid matching strategy combining keyword matching and semantic similarity: On the one hand, the test scenario type field is matched with the preset keyword library of each template in the scenario template library and a matching score is calculated. The keyword library of the interface test template includes "interface, API, request, HTTP", etc.; the keyword library of the UI test template includes "page, element, click, input", etc.; and the keyword library of the performance test template includes "performance, concurrency, load testing, throughput", etc. On the other hand, the semantic vector of the test scenario type field is similar to the semantic vector of each template identifier. The keyword matching score and semantic similarity are weighted and summed according to preset weights, and the template with the highest score is used as the target template. When the highest score is lower than a preset threshold, the scenario matching is determined to be unsuccessful, the default interface test template is output and manual confirmation is prompted. When there are multiple candidate templates with similar scores, the user is prompted to confirm the selection.

[0084] Automatic parameter filling: The engine calls the parameter mapping rule library to match the technical parameters in the requirement feature vector with the placeholders in the target template one by one, and automatically replaces the placeholders; for example, in the interface test requirement, "api_url:https: / / api.example.com / login" and "expected_status_code:200" will replace {api_url} and {expected_status_code} in the template respectively to generate the initial script;

[0085] Script validation optimization: The script validation optimization component performs syntax verification, logic detection, and compatibility optimization in sequence: Syntax verification detects and corrects syntax errors using the ast module; Logic detection supplements missing assertions and exception handling logic; Compatibility optimization adjusts the script syntax based on the user-selected Python version and test framework version to ensure compatibility.

[0086] Example 2

[0087] Please refer to Figure 2 This embodiment further optimizes upon embodiment 1 by utilizing an intelligent assertion logic code synthesis mechanism to analyze the description of the expected result and generate verification code; wherein, the intelligent assertion logic code synthesis mechanism includes:

[0088] Analyze the description of expected results in the structured requirement feature vector, and combine it with the historical response data structure of the target interface or a predefined data pattern to identify verifiable fields, determine the data type and constraints of the fields, and infer the legal business rules or value ranges.

[0089] As one possible implementation, this invention uses dependency parsing to identify the subject, quantity constraints, attribute constraints, and logical relationships in the description, and extracts key verification dimensions, existence, quantity range, content inclusion, type matching, and business rules.

[0090] Based on the analysis of the expected results described in the structured requirement feature vector, multi-dimensional assertion logic code that exceeds the explicitly specified range of the technical parameters is synthesized. The assertion logic code includes code for checking the existence of fields, data types, and compliance with business rules in the response data.

[0091] As one possible implementation, when generating multi-dimensional assertion logic code, if it is an interface test scenario, it is generated in combination with the response data structure pattern of the interface; if it is a UI test scenario, it is generated in combination with the page DOM structure and element positioning information.

[0092] The synthesized multi-dimensional assertion logic code is inserted or generated at the corresponding logical location in the initial Python test script; for interface tests, it is inserted after obtaining the response object and before the TryExcept block ends; for UI tests, it is inserted after the page operation is completed and before the browser is closed.

[0093] Preferably, the generated assertion code can also be wrapped in a TryExcept block to provide meaningful failure information.

[0094] Example 3

[0095] Please refer to Figure 3 This embodiment further optimizes upon embodiment 1 or 2 by utilizing an incremental training mechanism for adaptive optimization of the script and model iteration. Specifically, the incremental training mechanism is a closed-loop learning system that continuously optimizes the feature parsing model by analyzing script execution failure cases. The incremental training mechanism includes:

[0096] Execute the executable Python test script and monitor its execution process, collecting execution performance data and results;

[0097] As one possible implementation, during script execution, key nodes can be monitored through decorators or hook functions: request sending, response receiving, element operations, and assertion verification.

[0098] In response to execution failure due to missing parameters or semantic misunderstanding, training samples are constructed using the current test requirements, error messages from the execution failure, and input data. These training samples must include the original requirement semantics, the error messages from the execution failure, the input data, and environment variables. The training samples are generated by correcting labels.

[0099] For missing parameters, the missing parameter name is extracted from the error message and the correct value is inferred by combining it with the semantics of the original requirement; for semantic misunderstandings, correction is made based on the correct value pattern library.

[0100] The feature parsing model is incrementally trained using the training samples to optimize the accuracy of the required feature parsing;

[0101] As one possible implementation, the incremental training employs an elastic weight solidification strategy to prevent catastrophic forgetting. The elastic weight solidification strategy specifically includes: calculating the importance of each parameter in the old samples and limiting the magnitude of change of important parameters during updates.

[0102] Example 4

[0103] Please refer to Figure 4 This embodiment further optimizes any one of embodiments 1-3. When the test requirement describes an end-to-end business process containing multiple atomic steps, it also includes using a business process test intelligent orchestration mechanism to parse the test requirement and synthesize scripts. The business process test intelligent orchestration mechanism includes the following steps:

[0104] Analyze the test requirements and identify the atomic test scenarios and the data dependencies between them;

[0105] As one possible implementation, atomic test scenarios are identified through semantic parsing and scenario graph construction. Specifically, this includes: identifying step boundary markers in the requirement text using a sequence labeling model to segment long requirements into atomic test scenarios; and for each atomic step sequence, calling a feature parsing model to extract the step type, input / output signatures, and resource requirements. The data dependencies include parameter name matching relationships, semantic similarity matching relationships, and type consistency relationships between scenarios.

[0106] Based on the data dependencies, generate test scripts for each atomic test scenario;

[0107] The execution order of the test scripts and the cross-script data transfer logic are arranged to generate an executable full-process test suite. Specifically, the data transfer logic is implemented through a global context manager, which stores global key-value pairs to enable data sharing between steps. The global context manager is configured as follows:

[0108] 1. Upstream output is environment variables, which are then read by downstream scripts;

[0109] 2. Write the structured data to a temporary file and specify the file path to the downstream.

[0110] Example 5

[0111] This embodiment provides a Python automated test script generation system for executing the method described in any one of embodiments 1-4, including:

[0112] The requirement feature parsing module is used to parse the features of received natural language or structured test requirements and generate a structured requirement feature vector containing test scenario type, technical parameters and expected results.

[0113] The scenario template library stores Python test script templates categorized by test scenario. Each template includes a fixed syntax framework and parameter placeholders. The library includes: an API test template, built on the Requests library, containing a fixed syntax framework for request sending, request header configuration, parameter passing, API assertions, and exception handling, with reserved parameter placeholders such as {api_url}, {request_method}, {headers}, and {expected_status_code}; a UI test template, built on the Selenium library, containing logic for browser initialization, element location, page operations, result assertions, and browser closure, with reserved placeholders such as {browser_type}, {element_locator}, and {input_text}; and a performance test template, built on the Locust library, containing logic for user behavior definition, concurrent user configuration, test duration setting, and performance metric monitoring, with reserved placeholders such as {user_count}, {spawn_rate}, and {test_duration}.

[0114] A dynamic parameter configuration engine connects the requirement feature parsing module and the scenario template library. It matches corresponding templates based on the structured requirement feature vector and automatically fills technical parameters into template placeholders to generate an initial script. The dynamic parameter configuration engine performs the following steps: scenario matching, filtering target templates from the scenario template library based on the scenario type field in the requirement feature vector; parameter matching, traversing the technical parameters in the requirement feature vector, calling the parameter mapping rule library, and finding the corresponding template placeholders; and automatic filling, replacing the placeholders with technical parameter values, such as replacing {request_method} in the template with “request_method:POST”, to generate an initial executable Python test script.

[0115] The dynamic parameter configuration engine also includes an intelligent assertion logic code synthesis unit, which is used to perform in-depth analysis on the expected result description and automatically synthesize multi-dimensional assertion logic code to insert into the initial script;

[0116] The script verification and optimization component is used to perform syntax verification, logical integrity detection, and runtime environment compatibility optimization on the initial Python test script, and output an executable script.

[0117] The business process orchestration engine is used to parse the test requirement when the test requirement is an end-to-end business process, identify the atomic test scenarios and their data dependencies, generate test scripts for each scenario, and orchestrate their execution order and data transmission logic to form a full-process test suite.

[0118] The script execution and feedback analysis module is used to execute the executable script and monitor its process, compare the execution results with the expected results, and construct training samples when it is determined that the failure is caused by the deviation in the requirement analysis.

[0119] The model iteration management module is used to incrementally train the feature parsing model in the requirement feature parsing module using the training samples.

[0120] The above description is merely a preferred embodiment of the present invention. It should be understood that the present invention is not limited to the forms disclosed herein and should not be construed as excluding other embodiments. It can be used in various other combinations, modifications, and environments, and can be altered within the scope of the concept described herein through the above teachings or related technologies or knowledge. Modifications and variations made by those skilled in the art that do not depart from the spirit and scope of the present invention should be within the protection scope of the appended claims.

Claims

1. A method for generating Python automated test scripts, characterized in that, include: Receive test requirements, perform feature parsing on the test requirements, extract test scenario type, test object, test action, technical parameters and expected results, and generate a structured requirement feature vector; Based on the test scenario type in the structured requirement feature vector, a hybrid matching strategy combining keyword matching and semantic similarity is adopted to match the corresponding Python test script template from the pre-set scenario template library. The Python test script template contains a fixed syntax framework and parameter placeholders. The technical parameters in the structured requirement feature vector are filled into the corresponding parameter placeholders of the matched template to generate the initial Python test script; The initial Python test script is subjected to syntax validation, logical integrity checks, and runtime environment compatibility optimization to obtain an executable Python test script.

2. The Python automated test script generation method according to claim 1, characterized in that: The test requirements include natural language text or structured documents; If the test requirement is natural language text, a feature parsing model is used for semantic understanding and named entity recognition to extract structured features; If the test requirement is a structured document, the Pandas library is used for data parsing to extract the feature vector of the structured requirement.

3. The Python automated test script generation method according to claim 2, characterized in that: The feature parsing model includes an embedding layer, a sequence encoding layer, and a label decoding layer; The embedding layer uses a pre-trained BERT model to convert the input natural language test requirement text into a sequence of word vectors carrying contextual semantic information; The sequence encoding layer employs a bidirectional long short-term memory network to encode the word vector sequence from both the forward and reverse directions, and concatenates the hidden states from both directions as the context representation of each word to capture long-distance dependencies in the text. The label decoding layer uses a conditional random field to decode the hidden state sequence output by the bidirectional long short-term memory network, and combines it with preset label transition constraints to output the globally optimal label sequence, thereby achieving joint recognition of test scenario type, test object, test action, technical parameters, and expected results.

4. The Python automated test script generation method according to claim 1, characterized in that, The scenario template library includes at least one of the following: an interface test template built on the Requests library, a UI test template built on the Selenium library, and a performance test template built on the Locust library.

5. The Python automated test script generation method according to claim 4, characterized in that, The hybrid matching strategy that combines keyword matching and semantic similarity specifically includes: The test scenario type field is matched with the preset keyword library of each template in the scenario template library, and the matching score is calculated. The keyword library of the interface test template includes interface, API, request and HTTP; the keyword library of the UI test template includes page, element, click and input; and the keyword library of the performance test template includes performance, concurrency, load test and throughput. The semantic vector of the test scenario type field is similar to the semantic vector of each template identifier. The keyword matching score and semantic similarity are weighted and summed according to a preset weight, and the template with the highest score is used as the target template. When the highest score is lower than the preset threshold, the scenario matching is determined to be unsuccessful, the default interface test template is output and manual confirmation is prompted. When there are multiple candidate templates with similar scores, the user is prompted to confirm the selection.

6. The Python automated test script generation method according to claim 1, characterized in that: The syntax verification includes calling Python's ast module to parse the initial Python test script, detect and automatically correct syntax errors; the logical integrity verification includes using static code analysis to determine whether the initial Python test script contains assertion logic code and exception handling structure, and automatically supplementing the corresponding code blocks if they are missing.

7. The Python automated test script generation method according to claim 1, characterized in that, It also includes using an intelligent assertion logic code synthesis mechanism to analyze the description of the expected result and generate verification code; wherein, the intelligent assertion logic code synthesis mechanism specifically includes: Analyze the description of expected results in the structured requirement feature vector, and combine it with the historical response data structure of the target interface or a predefined data pattern to identify verifiable fields, determine the data type and constraints of the fields, and infer the legal business rules or value ranges. Based on the analysis of the expected results described in the structured requirement feature vector, multi-dimensional assertion logic code that exceeds the explicitly specified range of the technical parameters is synthesized. The assertion logic code includes code for checking the existence of fields, data types, and compliance with business rules in the response data. The synthesized multi-dimensional assertion logic code is inserted or generated at the corresponding logic location in the initial Python test script.

8. The Python automated test script generation method according to claim 2, characterized in that, It also includes using an incremental training mechanism to adaptively optimize the script and iterate the model; the incremental training mechanism includes: Execute the executable Python test script and monitor its execution process, collecting execution performance data and results; In response to execution failures caused by missing parameters or semantic misunderstandings, training samples are constructed by combining the current test requirements with the error messages and input data from the execution failure. The feature parsing model is incrementally trained using the training samples to optimize the accuracy of the required feature parsing.

9. The Python automated test script generation method according to claim 1, characterized in that: If the test requirement describes an end-to-end business process containing multiple atomic steps, then the test requirement is parsed and scripts are synthesized using a business process test intelligent orchestration mechanism; wherein, the business process test intelligent orchestration mechanism specifically includes: Analyze the test requirements and identify the atomic test scenarios and the data dependencies between them; Based on the data dependencies, generate test scripts for each atomic test scenario; Arrange the execution order of the test scripts and the data transfer logic across scripts to generate an executable full-process test suite.

10. A Python automated test script generation system, characterized in that, A method for generating a Python automated test script according to any one of claims 1-9, comprising: The requirement feature parsing module is used to parse the features of received natural language or structured test requirements and generate a structured requirement feature vector containing test scenario type, technical parameters and expected results. A scenario template library is used to store Python test script templates categorized by test scenario. The Python test script templates contain a fixed syntax framework and parameter placeholders. A dynamic parameter configuration engine connects the requirement feature parsing module and the scene template library. It is used to match the corresponding template according to the structured requirement feature vector and automatically fill the technical parameters into the template placeholders to generate the initial script. The dynamic parameter configuration engine also includes an intelligent assertion logic code synthesis unit, which is used to perform in-depth analysis on the expected result description and automatically synthesize multi-dimensional assertion logic code to insert into the initial Python test script. The script verification and optimization component is used to perform syntax verification, logical integrity checks, and runtime environment compatibility optimization on the initial Python test script, and output an executable script. The business process orchestration engine is used to parse the test requirement when the test requirement is an end-to-end business process, identify the atomic test scenarios and their data dependencies, generate test scripts for each scenario, and orchestrate their execution order and data transmission logic to form a full-process test suite. The script execution and feedback analysis module is used to execute the executable script and monitor its process, compare the execution results with the expected results, and construct training samples when it is determined that the failure is caused by the deviation in the requirement analysis. The model iteration management module is used to incrementally train the feature parsing model in the requirement feature parsing module using the training samples.