Method and system for generating coverage loop boundary test case based on program slices

By generating loop boundary test cases through program slicing and path analysis, this technology solves the problems of low accuracy and automation in generating loop boundary test cases in existing technologies, and achieves efficient and accurate loop boundary testing, which is suitable for complex loop structures in modern software development.

CN121187952APending Publication Date: 2025-12-23NANJING UNIV OF AERONAUTICS & ASTRONAUTICS
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202511317441.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-09-16
Publication Date
2025-12-23

AI Technical Summary

Technical Problem

Existing technologies struggle to accurately cover the loop structures of complex programs when generating loop boundary test cases, leading to problems such as infinite loops, array out-of-bounds errors, and resource leaks. Furthermore, they suffer from low automation and efficiency.

Method used

By employing program slicing technology combined with path analysis and symbolic execution, test cases covering loop boundaries are generated. The source code is parsed through abstract syntax trees to construct a program dependency graph, locate loop structures, simulate the loop execution process, capture condition judgment nodes, generate candidate test cases, and iteratively adjust them.

Benefits of technology

It improves the accuracy and automation of loop boundary testing, reduces manual intervention, and enhances testing efficiency and coverage, especially in complex loop scenarios where efficiency is improved by more than 10 times and coverage by more than 30%.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121187952A_ABST
    Figure CN121187952A_ABST
Patent Text Reader

Abstract

The invention discloses a method and a system for generating a test case for covering a loop boundary based on program slices. The method comprises the following steps of: inputting a source code to be tested and a target loop line number; the method comprises the following steps: analyzing a to-be-tested source code based on an abstract syntax tree technology, and extracting key node information to construct a program dependency graph; collecting related code lines through graph traversal by taking a loop structure needing to be analyzed as a criterion, and generating a minimum executable loop slice; performing symbolic execution on the minimum executable loop slice, simulating a loop execution process, capturing condition judgment nodes, and forming a track dictionary; determining a strategy based on the trajectory dictionary and the variable state, and when the strategy is numerical search, performing parameter space exploration; when the strategy is symbolic analysis, analyzing the cyclic condition expression and solving the optimal parameter; generating candidate test cases based on the analysis result; executing the candidate test case, calculating the number of loop iterations, and determining whether an expected state is reached; and if the expected state is reached, outputting a final test case.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The application belongs to the technical field of computer science, and particularly relates to a loop boundary test case generation method and system based on program slicing. TECHNICAL BACKGROUND

[0002] In modern software development, as the software scale is continuously expanded and the complexity is continuously increased, software testing becomes a key link for guaranteeing software quality. The goal is to design appropriate test cases to discover potential software defects as early as possible. Loop structure is an important component in programs and is widely used in various business logic, data processing and algorithm implementation. However, loop statements are also most prone to program defects, especially under loop boundary conditions, which can easily cause problems such as dead loop, array out-of-bounds, resource leakage and the like. About 20% to 30% of program defects are related to loop structure.

[0003] In order to obtain relatively accurate loop boundary test cases, the industry has developed various analysis techniques. The following are several existing implementation schemes most similar to the present application:

[0004] 1. Equivalence class partitioning method

[0005] The equivalence class partitioning method is based on the assumption that "test cases with the same input characteristics often have consistent execution results". All possible input data are divided into several mutually exclusive subsets (equivalence classes). Selecting representative data in each equivalence class as test cases can cover a large number of potential input scenarios with a small number of tests, reducing redundant tests.

[0006] 2. Boundary value analysis method

[0007] The boundary value analysis method is based on the experience rule that "program defects are often concentrated near the boundaries of input data". It focuses on designing test cases for the boundary values of input equivalence classes. Boundary values are usually critical points or values near critical points of equivalence classes (such as minimum value, maximum value, slightly less than minimum value, slightly greater than maximum value, etc.).

[0008] 3. Symbolic execution

[0009] Symbolic execution is a program analysis technique that simulates program execution by using symbolic values (rather than specific numerical values), thereby systematically exploring all possible execution paths of the program, deriving path constraints, and generating test cases that meet specific conditions. It has important applications in software testing, vulnerability detection, program verification and the like, and particularly exhibits unique advantages in path coverage of complex logic (such as loops, branch nesting).

[0010] 4. Program slicing technology

[0011] Program slicing is an analysis technique that extracts code fragments related to a specific variable or condition from the code. It can effectively narrow down the scope of debugging and exception detection. This method has been widely used in debugging and fault localization by filtering code related to exceptions to reduce debugging time. However, in complex programs, program slicing techniques often cannot accurately distinguish between code unrelated to exceptions, resulting in redundant slicing results. In addition, program slicing mostly relies on static analysis, making it difficult to capture dynamic behavior and runtime data flow, resulting in insufficient detection of certain exception paths.

[0012] In view of the implementation schemes in the above background art, although they have achieved certain results in analyzing loop boundaries and generating test cases, there are still the following problems and shortcomings:

[0013] 1. Strong dependence of equivalence class partitioning method on requirements and insufficient coverage of complex scenarios

[0014] The core limitation of equivalence class partitioning method lies in its "black box" nature and "equivalence within class" assumption. It only focuses on the surface relationship between input and output, ignores the internal logic and boundary details of the program, and relies on manual interpretation of requirements. In actual testing, methods such as boundary value analysis, cause-effect graph (handling multiple parameter combinations), path coverage (combined with white box techniques), especially in complex loop structures and multi-branch logic scenarios, need to be supplemented with techniques such as symbolic execution and program slicing to make up for the inherent defects of equivalence class partitioning.

[0015] 2. Strong dependence of boundary value analysis method on boundary definition

[0016] The core limitation of boundary value analysis method lies in its "input-oriented" and "quantitative dependence" characteristics. It can only cover defects directly related to input boundaries, and cannot handle complex scenarios such as internal logic, multiple parameter dependencies, and non-numeric input. It relies on manual definition and selection of boundaries. In actual testing, methods such as path coverage (white box testing), state transition testing (for internal states), and cause-effect graph (handling multiple parameter combinations) need to be combined, especially in scenarios such as loop boundaries and branch nesting, which require techniques such as symbolic execution and program slicing to achieve comprehensive coverage from input boundaries to code logic boundaries.

[0017] 3. Complexity and limitations of constraint solving in symbolic execution

[0018] The limitations of symbolic execution are essentially due to its pursuit of "full path coverage" and "precise constraint solving", which inherently contradict the complexity of the program and the dynamic nature of the environment. In practical applications, techniques such as hybrid execution (symbolic execution + concrete execution), program slicing (narrowing down the analysis scope), and machine learning-assisted path pruning can be used to alleviate these problems.

[0019] 4. Strong dependence of program slicing on slicing criteria and difficulty in analyzing complex program structures

[0020] Although program slicing technology can narrow down the debugging range and improve the efficiency of exception positioning, the results often contain a large number of redundant code fragments, increasing the workload of subsequent analysis. In particular, in programs containing complex control flow and exception handling logic, the slicing results may be mixed with code unrelated to the exception. In addition, program slicing is mainly based on static analysis, and it is difficult to capture the dynamic behavior of the program, such as concurrent processing, asynchronous calls, or external input dependencies. This makes it not comprehensive enough for exception detection in some complex scenarios. SUMMARY

[0021] The present application aims to solve the problems existing in the prior art loop boundary test case generation technology, and provides a loop boundary test case generation method based on program slicing. The method comprehensively uses program slicing, path analysis, and symbolic execution techniques, designs and implements an automatic test case generation framework and tool chain, realizes the automatic generation of loop boundary test cases, and improves the automation, efficiency and accuracy of software testing, providing strong support for loop boundary testing.

[0022] TECHNICAL SOLUTION: In a first aspect, the present application provides a loop boundary test case generation method based on program slicing, comprising the following steps:

[0023] Step 1: input the source code to be tested and the target loop line number;

[0024] Step 2: parse the source code to be tested based on the abstract syntax tree technology, extract key node information, and build a program dependency graph based on the extracted key node information; the key node information includes function definition, class definition, variable reference, and loop structure;

[0025] Step 3: locate the loop structure to be analyzed according to the target loop line number, collect related code lines by graph traversal based on the loop structure to be analyzed as the criterion, and generate the minimum executable loop slice after sorting and removing duplicates;

[0026] Step 4: perform symbolic execution on the minimum executable loop slice, simulate the loop execution process, capture the condition judgment nodes, record the judgment type, expression, result and variable state, and form a trajectory dictionary;

[0027] Step 5: collect the trajectory dictionary and variable state, determine the strategy based on the trajectory dictionary and variable state, perform parameter space exploration when the strategy is numerical search; and when the strategy is symbolic analysis, analyze the loop condition expression and solve the optimal parameters;

[0028] Step 6: generate candidate test cases based on the analysis results obtained based on the strategy;

[0029] Step 7: execute the candidate test case, calculate the number of loop iterations, and confirm whether the expected state is reached; if the expected state is not reached, iterate the input parameters according to the verification result and execute step 5 for repeated analysis and verification; if the expected state is reached, output the final test case.

[0030] Further, in step 2, the source code to be tested is parsed based on the abstract syntax tree technology, key node information is extracted, and a program dependency graph is constructed based on the extracted key node information; specifically including:

[0031] Follow the principle of depth-first search, use abstract syntax tree technology to convert the source code text to be tested into AST nodes;

[0032] Abstract the source code through tree structure, extract the program structure of the source code to be tested, and obtain key node information;

[0033] The program dependency graph is used to control the logical relationship of the key node information by controlling the dependency and data dependency relationship, and the program dependency graph is composed of a control flow graph and control dependency edges and data dependency edges, where the nodes represent functions or classes, and the edges represent call or dependency relationship.

[0034] Further, in step 3, the target loop line number is used to locate the loop structure to be analyzed, and the related code lines are collected through graph traversal based on the loop structure to be analyzed as a criterion to generate a minimum executable loop slice after sorting and deduplication; specifically including:

[0035] According to the target loop line number, find the corresponding For or While loop structure in the abstract syntax tree, use the For or While loop structure as the slice criterion, collect all function, class and variable definition code lines related to the target loop based on the program dependency graph, sort and deduplicate the collected code lines, and form a minimum executable loop slice.

[0036] Further, in step 4, the minimum executable loop slice is subjected to symbolic execution, the loop execution process is simulated, the condition judgment nodes are captured, the judgment type, expression, result and variable state are recorded, and a trajectory dictionary is formed, specifically including:

[0037] Take the minimum executable loop slice as input, perform abstract syntax tree analysis again, simulate the execution process of the loop slice through the interpretation execution mechanism, and process the execution of assignment, increment, and custom expression;

[0038] During the execution simulation process, the visit_if and visit_while methods in the abstract syntax tree accessor are rewritten to capture the condition judgment nodes in the loop execution process;

[0039] For each condition judgment node, use ast.unparse() to get the source code expression of the judgment condition, execute the expression in the current environment to get the Boolean result, and build a track dictionary to record the judgment type, condition expression, result, and current variable state, forming a list containing multiple judgment records;

[0040] The judgment sequence in the list is segmented, and the judgment records from the start to the exit of each loop are divided into a loop track segment. Each loop track segment contains multiple condition judgment nodes and their variable states in the execution process of the loop.

[0041] Further, in step 5, when the strategy is numerical search, the parameter space exploration includes:

[0042] The termination condition of the loop is extracted from the list, including the judgment node whose loop condition result is False;

[0043] By comparing the variable differences between the last time the state is true before the loop terminates and the termination state, the critical variables affecting the loop boundary are identified. At the same time, the loop condition expression is converted into a sympy expression;

[0044] Taking the initial parameter value as the reference, set the search interval, and generate a series of candidate parameter values using linear sampling; call the verification function for each candidate parameter value to perform the minimum executable loop slicing operation and record the actual loop count;

[0045] If a better parameter value is found in the preliminary search, reduce the search range in its adjacent area for secondary sampling;

[0046] Repeat the above verification process to continuously update the optimal parameter value.

[0047] Further, in step 5, when the strategy is symbolic analysis, the loop condition expression is parsed and the optimal parameter is solved;

[0048] For loop conditions with explicit mathematical expressions, convert the condition expression to a symbolic expression, determine the solving strategy according to the comparison operator, find the critical points of the expression by differentiation, and evaluate these points to determine the parameter value that maximizes the number of loop executions.

[0049] In a second aspect, an embodiment of the present application provides a loop boundary test case generation system based on program slicing, comprising:

[0050] An input module for inputting source code to be tested and target loop line number;

[0051] A program slicing module is configured to parse source code to be tested based on an abstract syntax tree technique, extract key node information, and construct a program dependency graph based on the extracted key node information; the key node information includes function definitions, class definitions, variable references, and loop structures; a target loop line number is used to locate a loop structure to be analyzed, and relevant code lines are collected through graph traversal based on the loop structure to be analyzed as a criterion, and a minimum executable loop slice is generated after being sorted and deduplicated;

[0052] A path analysis module is configured to perform symbolic execution on the minimum executable loop slice, simulate a loop execution process, capture condition judgment nodes, record judgment types, expressions, results, and variable states, and form a trace dictionary;

[0053] A test case generation module is configured to collect the trace dictionary and the variable states, determine a strategy based on the trace dictionary and the variable states, perform parameter space exploration when the strategy is numerical search, analyze a loop condition expression and solve an optimal parameter when the strategy is symbolic analysis, generate a candidate test case based on an analysis result obtained based on the strategy, execute the candidate test case, calculate a loop iteration number, and confirm whether an expected state is reached; if the expected state is not reached, input parameters are iteratively adjusted and repeated analysis and verification are performed according to a verification result; and if the expected state is reached, a final test case is output.

[0054] Further, the source code to be tested is parsed based on the abstract syntax tree technique, the key node information is extracted, and the program dependency graph is constructed based on the extracted key node information; specifically including:

[0055] An abstract syntax tree technique is used to convert the source code text to be tested into an AST node in accordance with a depth-first search principle;

[0056] The source code is abstracted through a tree structure, the program structure of the source code to be tested is extracted, and key node information is obtained;

[0057] A program dependency graph is used to describe logical relationships of the key node information in terms of control dependency and data dependency relationships; the program dependency graph is composed of a control flow graph, control dependency edges, and data dependency edges; in the program dependency graph, a node represents a function or a class, and an edge represents a call or a dependency relationship;

[0058] The target loop line number is used to locate the loop structure to be analyzed, and relevant code lines are collected through graph traversal based on the loop structure to be analyzed as a criterion, and a minimum executable loop slice is generated after being sorted and deduplicated; specifically including:

[0059] According to the target loop line number, a corresponding For or While loop structure is found in the abstract syntax tree, and based on the program dependency graph, all function, class and variable definition code lines related to the target loop are collected as the For or While loop structure, the collected code lines are sorted, de-duplicated and sorted to form a minimum executable loop slice.

[0060] Further, the minimum executable loop slice is symbolically executed to simulate the loop execution process, capture the condition judgment nodes, record the judgment type, expression, result and variable state, and form a track dictionary, specifically including:

[0061] The minimum executable loop slice is taken as input, and the abstract syntax tree is parsed again to simulate the execution process of the loop slice through the interpretation execution mechanism to process the execution of assignment, increment and custom expression.

[0062] During the execution simulation process, the visit_if and visit_while methods in the abstract syntax tree accessor are rewritten to capture the condition judgment nodes in the loop execution process.

[0063] For each condition judgment node, the source code expression of the judgment condition is obtained using ast.unparse(), the expression is executed in the current environment to obtain a Boolean result, and a track dictionary is constructed to record the judgment type, condition expression, result and current variable state to form a list containing multiple judgment records.

[0064] The judgment sequence in the list is segmented, and the judgment records from the start to the exit of each loop are divided into a loop track segment, and each loop track segment contains multiple condition judgment nodes and their variable states in the loop execution process.

[0065] Further, when the strategy is numerical search, parameter space exploration is performed, including:

[0066] The termination condition of the loop is extracted from the list, including the judgment node whose loop condition result is False.

[0067] By comparing the variable differences between the last time the loop termination condition is true and the termination state, the critical variables affecting the loop boundary are identified, and the loop condition expression is converted into a sympy expression.

[0068] Taking the initial parameter value as a reference, a search interval is set, and a series of candidate parameter values are generated using linear sampling; for each candidate parameter value, a verification function is called to execute the minimum executable loop slice operation and record the actual loop count.

[0069] If a better parameter value is found in the preliminary search, the search range is narrowed in its adjacent area for secondary sampling.

[0070] The above verification process is repeated, and the optimal parameter value is constantly updated.

[0071] The loop condition expression is parsed and the optimal parameter is solved when the strategy is symbolic analysis.

[0072] For the loop condition with a clear mathematical expression, the condition expression is converted into a symbolic expression, the solving strategy is determined according to the comparison operator, the critical points of the expression are found by derivation, and the parameter value that can maximize the number of loop executions is determined by evaluating these points.

[0073] Advantages: Compared with the prior art, the present application has the following advantages:

[0074] 1. Reduce the defects of loop structure: Loop structure is the core component of the program, but it is also a high-defect area. The primary purpose of the present application is to accurately locate the scene covering the loop boundary, and to reduce the problems of dead loop, array out-of-bounds, resource leakage and the like generated in the control of the number of loop iterations and the judgment of boundary conditions.

[0075] 2. Realize the generation of test cases covering the loop boundary: The present application designs a complete tool chain, including slicing tools, path generation tools and test case generation algorithms, which are specially adapted to the analysis needs of loop structure, and can automatically generate test cases covering the loop structure boundary.

[0076] 3. Improve test efficiency and coverage: The present application uses an automated tool chain, and the test case generation time is shortened from several minutes required by manual debugging to seconds, and the efficiency is improved by more than 10 times in complex loop scenarios; the multi-strategy integrated framework reduces more than 90% of manual intervention, supports agile development and continuous integration process. And the system's ability to explore the parameter space breaks through the limitations of human experience, and can find the boundary scenarios that traditional methods easily ignore. Experimental data shows that for loops containing quadratic function boundary conditions, the coverage is improved by more than 30% compared with manual testing, and the test results can be reproduced stably, providing a feasible solution for large-scale software testing.

[0077] 4. Improve the degree of software testing automation: Modern software development has an increasingly urgent need for automated testing, especially in agile development and continuous integration scenarios. The present application provides reusable technical framework and tools to provide core support for software testing automation, promotes the integration of testing into the whole development process, and realizes the automatic discovery of program defects.

[0078] 5. Improve the accuracy of loop boundary testing: Focus on loop-related core code through program slicing technology, exclude irrelevant code interference, and make boundary analysis more targeted; Critical variable dynamic identification mechanism can accurately locate the key factors affecting the termination of the loop, reducing more than 80% of invalid test cases compared with traditional boundary value analysis method.

[0079] 6. Enhance the adaptability of complex scenarios: Design complementary strategies for different types of loop conditions, adapt mathematical expressions with symbolic analysis, handle non-formal conditions with numerical search, and use machine learning to deal with complex nonlinear relationships, solving the applicability limitations of single methods in complex loop structures.

[0080] 7. Preserve code readability and reusability: Slice reconstruction mechanism based on line numbers avoids direct manipulation of AST structure, and the output of the smallest executable slice preserves the original code style and logical integrity, facilitating manual verification and secondary development; Modular tool design supports function extension and multi-language adaptation.

[0081] 8. Reduce the technical threshold of testing: Visual trajectory output and automated process simplify the technical complexity of loop boundary testing, allowing developers to conduct efficient testing without deep understanding of symbolic execution or program slicing theory, reducing the cost and technical threshold of software testing. BRIEF DESCRIPTION OF DRAWINGS

[0082] Figure 1 A basic framework diagram of a loop boundary test case generation method based on program slicing is provided for the embodiments of the application. DETAILED DESCRIPTION

[0083] The present application proposes an integrated framework for generating test cases based on program slicing results for loop path analysis, which is used to automatically generate test cases covering loop boundaries. The framework combines program slicing, path analysis based on loop body execution process, and loop boundary test case generation to generate test cases covering loop boundaries in the program. The technical implementation scheme of the framework will be described in detail below, and the workflow will be illustrated through specific cases.

[0084] I. Overall structure of the framework

[0085] 1. Program slicing phase: A static program slicing tool is designed to automatically extract the smallest executable code segment related to the target loop given the source code and the target loop line number, providing support for subsequent path analysis and test case generation.

[0086] 2. Path analysis phase: Before generating loop boundary test cases, the execution path of the loop body must be completely analyzed and modeled to capture the changes in conditions and states in each iteration.

[0087] 3. Test case generation phase: Use loop slicing to execute the path information of the process, iteratively adjust the test case, and let the number of loop executions in the test process increase and the execution path extend, and finally get the test case covering the loop boundary.

[0088] The specific steps include:

[0089] Step 1: Input the source code to be tested and the target loop line number, accurately locate the loop structure to be analyzed, and define the scope for the subsequent process.

[0090] Step 2: Call the program slicing tool, parse the source code based on the abstract syntax tree (AST) technology, extract function, variable, loop and other key node information, and then use the networkx tool to build the program dependency graph (PDG).

[0091] Step 3: According to the target loop line number, locate the loop structure, and collect the relevant code lines through graph traversal based on it, and generate the smallest executable loop slice after sorting and removing duplicates.

[0092] Step 4: The path generation tool performs symbolic execution on the slice, simulates the loop execution process, captures the condition judgment nodes through AST accessor rewriting, records the judgment type, expression, result and variable state, and forms the trace dictionary (trace_log).

[0093] Step 5: The loop boundary test case generation algorithm starts multi-strategy analysis, numerical search system explores the parameter space, symbolic analysis converts the loop condition into sympy expression and solves the optimal parameters. Based on the analysis results, generate candidate test cases.

[0094] Step 6: Execute the candidate cases through the verification function, calculate the number of loop iterations, and confirm whether the expected state is reached. If the boundary is not reached, adjust the input parameters according to the verification results and repeat the analysis and verification; if the boundary is reached, output the final test case covering the loop boundary.

[0095] II. Further explanation of the program slicing phase

[0096] The main goal of the program slicing phase is to narrow the analysis scope and only keep the key code related to the loop path, so as to reduce unnecessary code interference and improve the accuracy and efficiency of path analysis. The specific steps are to first use the abstract syntax tree (AST) technology to extract the syntax analysis and structure of the target program, and then use the networkx tool to build the internal dependency graph of the program. After that, all the dependency structures related to the target loop are identified through graph traversal algorithm, and finally the corresponding code fragments are extracted and output.

[0097] 1. AST parsing: The ast module is used to convert the code text into AST nodes. The source code is highly abstracted through a tree structure, stripping away syntax details unrelated to logic, and extracting program structure, including function definitions, class definitions, variable references, loop structures, and other node information.

[0098] AST traversal follows the depth-first search (DFS) principle, and the ast.NodeVisitor class implements traversal control through the Visitor Pattern. This algorithm implements automated recursive traversal, and developers only need to rewrite the visit_NodeType method for specific node types based on their own needs to easily implement custom analysis and achieve the desired functionality.

[0099] 2. Building dependency graphs: Program dependency graphs (PDGs) describe the logical relationships between elements in the code based on control and data dependencies. They are composed of control flow graphs (CFGs) with control dependency edges and data dependency edges. Based on the aforementioned AST, the DependencyVisitor class traverses the AST to identify function calls, class method references, and variable definition and reference relationships. Then, the networkx tool is used to build function and variable dependency graphs, where nodes represent functions or classes, and edges represent "call" or "dependency" relationships.

[0100] First is the generation of control flow graphs (CFGs), which divide the code into basic blocks (BasicBlock) and build directed edges to represent execution order. For example:

[0101]

[0102] The CFG corresponding to this code is: [B0]→[B1 / B2]→[B3]. Its control dependency relationship is: B3 dominates B1 and B2, and B1 is control dependent on the B0 branch where the condition x>0 is located.

[0103] Second is data dependency analysis, which is based on Def-Use chain tracking variable life cycle, for example:

[0104]

[0105] The data dependency relationship in this code is: variable c is data dependent on b in line 3 and the assignment in line 4.

[0106] 3. Locating target loop and slice extraction: According to the input target loop line number, find the corresponding For or While loop structure in AST, take the loop as the slice criterion, collect all function, class and variable definition code lines related to the target loop based on the dependency graph, sort and remove duplicates, form a minimum executable code slice, i.e. loop slice, and save it to the output file.

[0107] III. Further explanation of the current path analysis stage.

[0108] The path analysis stage performs a complete analysis and modeling of the execution path of the loop body, capturing the changes in conditions and states in each iteration. Symbolic execution technology is used to abstract program inputs into symbolic variables, and the constraints of the path are derived at the logical level. Based on the abstract syntax tree (AST), a tool is constructed to track the execution process of the path, which records the path trajectory, models the state, and reconstructs the trajectory without modifying the original code logic, providing technical support for subsequent boundary determination and test case design.

[0109] 1. AST parsing and execution simulation: Take the loop slice obtained by the slicing tool as input, and perform AST parsing again. The execution process of the loop slice is simulated through the interpretation execution mechanism, and statements such as assignment, increment, and custom expressions are processed.

[0110] 2. Judgment node capture and trajectory recording: During the execution simulation process, the visit_if and visit_while methods in the AST accessor are rewritten to capture the condition judgment nodes in the loop execution process. For each judgment node, the source code expression of the judgment condition is obtained using ast.unparse(), the expression is executed in the current environment to get the Boolean result, and a trajectory dictionary is constructed to record the judgment type (while or if), condition expression, result, and current variable state (environment snapshot), forming a list trace_log containing multiple judgment records. For example, for the code:

[0111]

[0112] The execution path and corresponding judgment trajectory are as follows:

[0113]

[0114] 3. Trajectory structured processing: The judgment sequence in trace_log is segmented, and the judgment records from the start to the exit of each loop are divided into a "loop trajectory segment". Each trajectory segment contains multiple judgment points and variable states in the loop execution process, and can be visualized and output in a specified format.

[0115] IV. Further explanation of the test case generation phase.

[0116] In the test case generation phase, the termination condition of the loop is extracted from the trace_log, that is, the judgment node whose loop condition result is False. By comparing the variable differences between the last true state before loop termination (critical point state) and the termination state (termination point state), the critical variables affecting the loop boundary are identified. At the same time, the loop condition expression is converted into a sympy expression for mathematical analysis. A multi-strategy integration method is used to iteratively adjust the test case.

[0117] 1. Symbolic analysis method: For loop conditions with clear mathematical expressions, the condition expression is converted into a symbolic expression, the solving strategy is determined according to the comparison operator, and the critical points of the expression are found by differentiation. These points are evaluated to determine the parameter values that maximize the number of loop executions. The specific method is as follows:

[0118]

[0119] 2. Numerical search method: In cases where symbolic processing is difficult to implement, a numerical search method will be used. With the initial parameter value as the benchmark, set the search interval (e.g. initial_value-search_range to initial_value+search_range), and use linear sampling to generate a series of candidate parameter values (such as generating uniformly distributed test points by np.linspace). Then, call the verification function (_verify_param_value) for each candidate parameter value, perform loop slicing operation, and record the actual number of iterations. If a better parameter value is found in the preliminary search, reduce the search range in its adjacent area for secondary sampling. Repeat the above verification process and continuously update the optimal parameter value. At the same time, store the tested parameter values and their corresponding iteration numbers to avoid repeated calculations. The specific method is as follows:

[0120]

[0121] 3. Verification and iterative adjustment: To ensure that the generated test case indeed reaches the expected loop boundary, verification and iterative adjustment are performed as follows:

[0122]

[0123] Through this verification mechanism, each time a new test case is generated, the code is actually executed to confirm the number of iterations, and the results are stored in the cache for subsequent optimization. This iterative feedback ensures that the algorithm can gradually converge to the true loop boundary.

[0124] The technical solutions provided by the embodiments of the present application are described in detail below with an example.

[0125] The source code is as follows:

[0126]

[0127] Stage one: program slicing

[0128] Input: target loop line number: 7 (while (i < loopLimit) { line where it is located)

[0129] Execution:

[0130] Extract program structure by AST analysis and identify while loop node

[0131] Construct program dependence graph (PDG) and analyze data dependence relationship of variables loopLimit, i and count

[0132] Slicing result:

[0133]

[0134] The code directly related to the loop condition is retained, and irrelevant statements such as sum are removed.

[0135] Stage two: path analysis

[0136] Input: program slicing result, initial test parameter: inputvalue = 30

[0137] Execution:

[0138] Perform AST secondary analysis on the sliced code to simulate the loop execution process

[0139] Capture the condition judgment node (i < loopLimit) of each loop

[0140] Record the judgment result and variable state snapshot to generate a trace log

[0141] Path analysis result:

[0142]

[0143] Stage three: test case generation

[0144] Input: path analysis trace log, loop condition expression: i < loopLimit (where loopLimit = 100n-n 2 )

[0145] Execution: Utilize symbolic analysis techniques

[0146] Extract loop termination condition, identify critical variable n (input parameter)

[0147] Convert loop condition to symbolic expression: loopLimit = 100n - n 2

[0148] Find parameter value that maximizes loop count through derivative analysis (n = 50)

[0149] Iteratively verify parameter value, confirm peak loop count

[0150] Test case generation results:

[0151]

[0152] When symbolic analysis is difficult, employ numerical search methods to generate test cases, example as follows:

[0153] Code as follows:

[0154]

[0155] In this example, the loop condition contains square root (x**0.5), absolute value (abs()), symbolic analysis is difficult to accurately handle non-linear operations and floating-point precision issues. Step calculation involves modulo (x%7) and type conversion (int()), symbolic analysis cannot effectively model the interaction between condition branching and integer truncation. Therefore, symbolic analysis is difficult to derive a unified boundary constraint formula, numerical search method is adopted.

[0156]

Claims

1. A method for generating test cases covering loop boundaries based on program slicing, characterized in that: Includes the following steps: Step 1: Enter the source code to be tested and the target loop line number; Step 2: Parse the source code to be tested using abstract syntax tree technology, extract key node information, and construct a program dependency graph based on the extracted key node information; The key node information includes: function definition, class definition, variable reference, and loop structure; Step 3: Locate the loop structure to be analyzed based on the target loop line number, collect relevant code lines through graph traversal based on the loop structure to be analyzed, and generate the minimum executable loop slice after sorting and deduplication; Step 4: Perform symbolic execution on the minimum executable loop slice to simulate the loop execution process, capture condition judgment nodes, record the judgment type, expression, result and variable state, and form a trajectory dictionary; Step 5: Collect the trajectory dictionary and variable states, and determine the strategy based on the trajectory dictionary and variable states. When the strategy is numerical search, explore the parameter space; when the strategy is symbolic analysis, parse the loop condition expression and solve for the optimal parameters. Step 6: Based on the analysis results obtained from the strategy, generate candidate test cases; Step 7: Execute candidate test cases, calculate the number of loop iterations, and confirm whether the expected state has been achieved. If the expected state has not been achieved, adjust the input parameters iteratively based on the verification results and execute step 5 for repeated analysis and verification. If the expected state has been achieved, output the final test cases.

2. The method for generating test cases covering loop boundaries based on program slicing according to claim 1, characterized in that: In step 2, the abstract syntax tree (AST) technique is used to parse the source code to be tested, extract key node information, and construct a program dependency graph based on the extracted key node information. Specifically, it includes: Following the depth-first search principle, the abstract syntax tree technique is used to convert the source code text to be tested into AST nodes; By abstracting the source code using a tree structure, the program structure of the source code to be tested can be extracted to obtain key node information; A program dependency graph is used to describe the logical relationships of key node information using control dependencies and data dependencies. The program dependency graph is composed of a control flow graph plus control dependency edges and data dependency edges. In the program dependency graph, nodes represent functions or classes, and edges represent calls or dependencies.

3. The method for generating test cases covering loop boundaries based on program slicing according to claim 2, characterized in that: Step 3, which involves locating the loop structure to be analyzed based on the target loop line number, collecting relevant code lines through graph traversal based on the loop structure to be analyzed, and generating the minimum executable loop slice after deduplication, specifically includes: Based on the target loop line number, the corresponding For or While loop structure is found in the abstract syntax tree. Using the For or While loop structure as the slicing criterion, the code lines of all function, class, and variable definitions related to the target loop are collected based on the program dependency graph. The collected code lines are organized, deduplicated, and sorted to form the minimum executable loop slice.

4. The method for generating test cases covering loop boundaries based on program slicing according to claim 1, characterized in that: Step 4, which involves symbolic execution of the minimum executable loop slice to simulate the loop execution process, captures condition judgment nodes, records the judgment type, expression, result, and variable state, and forms a trajectory dictionary, specifically includes: Taking the minimum executable loop slice as input, the abstract syntax tree is parsed again. The execution process of the loop slice is simulated through the interpretation execution mechanism to handle the execution of assignment, increment, and user-defined expressions. During the simulation, the condition judgment nodes in the loop execution process are captured by overriding the visit_if and visit_while methods in the abstract syntax tree accessor; For each condition judgment node, use ast.unparse() to obtain the source code expression of the judgment condition, execute the expression in the current environment to obtain a boolean result, and build a trajectory dictionary to record the judgment type, condition expression, result and current variable state, forming a list containing multiple judgment records; The judgment sequence in the list is segmented, and the judgment record from the beginning to the end of each loop is divided into a loop trajectory segment. Each loop trajectory segment contains multiple condition judgment nodes and their variable states during the execution of the loop.

5. The method for generating test cases covering loop boundaries based on program slicing according to claim 4, characterized in that: In step 5, when the strategy is numerical search, the parameter space exploration includes: Extract the loop termination condition from the list, including the condition node where the loop condition result is False; By comparing the differences between the variables in the last true state before loop termination and the termination state, the critical variables affecting the loop boundary are identified; at the same time, the loop condition expression is converted into a sympy expression. Based on the initial parameter values, a search interval is set, and a series of candidate parameter values ​​are generated using linear sampling; for each candidate parameter value, a verification function is called to perform the minimum executable loop slice operation and record the actual number of loops. If a better parameter value is found in the initial search, the search range is narrowed down in the neighborhood and a second sampling is performed; Repeat the above verification process to continuously update the optimal parameter values.

6. The method for generating test cases covering loop boundaries based on program slicing according to claim 4, characterized in that: In step 5, when the strategy is symbolic analysis, the loop condition expression is parsed and the optimal parameters are solved; For loop conditions with explicit mathematical expressions, the condition expression is converted into a symbolic expression, the solution strategy is determined based on the comparison operator, the critical point of the expression is found by differentiation, and these points are evaluated to determine the parameter values ​​that maximize the number of loop executions.

7. A system for generating test cases covering loop boundaries based on program slicing, characterized in that: include: The input module is used to input the source code to be tested and the target loop line number; The program slicing module is used to parse the source code to be tested based on abstract syntax tree technology, extract key node information, and build a program dependency graph based on the extracted key node information. The key node information includes: function definition, class definition, variable reference, and loop structure; the loop structure to be analyzed is located according to the target loop line number, and relevant code lines are collected by graph traversal based on the loop structure to be analyzed, and after sorting and deduplication, the minimum executable loop slice is generated; The path analysis module is used to perform symbolic execution on the minimum executable loop slice, simulate the loop execution process, capture condition judgment nodes, record the judgment type, expression, result and variable state, and form a trajectory dictionary; The test case generation module collects trajectory dictionaries and variable states, determines strategies based on these dictionaries and states, explores the parameter space when the strategy is numerical search, and parses loop condition expressions and solves for optimal parameters when the strategy is symbolic analysis. Based on the analysis results obtained from the strategy, candidate test cases are generated. These candidate test cases are executed, the number of loop iterations is calculated, and it is confirmed whether the expected state has been reached. If the expected state has not been reached, the input parameters are iteratively adjusted based on the verification results, and repeated analysis and verification are performed. If the expected state has been reached, the final test cases are output.

8. The test case generation system for covering loop boundaries based on program slicing according to claim 7, characterized in that: The abstract syntax tree (API) technique is used to parse the source code to be tested, extract key node information, and construct a program dependency graph based on the extracted key node information. Specifically, it includes: Following the depth-first search principle, the abstract syntax tree technique is used to convert the source code text to be tested into AST nodes; By abstracting the source code using a tree structure, the program structure of the source code to be tested can be extracted to obtain key node information; A program dependency graph is used to describe the logical relationships of key node information using control dependencies and data dependencies. The program dependency graph is composed of a control flow graph plus control dependency edges and data dependency edges. In the program dependency graph, nodes represent functions or classes, and edges represent calls or dependencies. The process of locating the loop structure to be analyzed based on the target loop line number, collecting relevant code lines through graph traversal based on the loop structure to be analyzed, and generating the minimum executable loop slice after deduplication; specifically includes: Based on the target loop line number, the corresponding For or While loop structure is found in the abstract syntax tree. Using the For or While loop structure as the slicing criterion, the code lines of all function, class, and variable definitions related to the target loop are collected based on the program dependency graph. The collected code lines are organized, deduplicated, and sorted to form the minimum executable loop slice.

9. A test case generation system for covering loop boundaries based on program slicing according to claim 8, characterized in that: The aforementioned symbolic execution of the minimum executable loop slice, simulating the loop execution process, capturing condition judgment nodes, recording the judgment type, expression, result, and variable state, and forming a trajectory dictionary, specifically includes: Taking the minimum executable loop slice as input, the abstract syntax tree is parsed again. The execution process of the loop slice is simulated through the interpretation execution mechanism to handle the execution of assignment, increment, and user-defined expressions. During the simulation, the condition judgment nodes in the loop execution process are captured by overriding the visit_if and visit_while methods in the abstract syntax tree accessor; For each condition judgment node, use ast.unparse() to obtain the source code expression of the judgment condition, execute the expression in the current environment to obtain a boolean result, and build a trajectory dictionary to record the judgment type, condition expression, result and current variable state, forming a list containing multiple judgment records; The judgment sequence in the list is segmented, and the judgment record from the beginning to the end of each loop is divided into a loop trajectory segment. Each loop trajectory segment contains multiple condition judgment nodes and their variable states during the execution of the loop.

10. A test case generation system for covering loop boundaries based on program slicing according to claim 9, characterized in that: When the strategy is numerical search, the parameter space exploration includes: Extract the loop termination condition from the list, including the condition node where the loop condition result is False; By comparing the differences between the variables in the last true state before loop termination and the termination state, the critical variables affecting the loop boundary are identified; at the same time, the loop condition expression is converted into a sympy expression. Based on the initial parameter values, a search interval is set, and a series of candidate parameter values ​​are generated using linear sampling; for each candidate parameter value, a verification function is called to perform the minimum executable loop slice operation and record the actual number of loops. If a better parameter value is found in the initial search, the search range is narrowed down in the neighborhood and a second sampling is performed; Repeat the above verification process to continuously update the optimal parameter values; When the strategy is symbolic analysis, the loop condition expression is parsed and the optimal parameters are solved. For loop conditions with explicit mathematical expressions, the condition expression is converted into a symbolic expression, the solution strategy is determined based on the comparison operator, the critical point of the expression is found by differentiation, and these points are evaluated to determine the parameter values ​​that maximize the number of loop executions.

Citation Information

Cited By

  • Code verification method, device, equipment and system

    CN122311092A