A high-loop-complexity embedded software unit test case automatic generation method, system, electronic device and storage medium
Patent Information
- Application Number
- CN202611244339.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-17
- Publication Date
- 2026-10-16
AI Technical Summary
[0005]本发明提出一种高圈复杂度的嵌入式软件单元测试用例自动生成方法的技术方案,旨在解决现有技术在对高圈复杂度嵌入式代码进行测试时,因追求全路径覆盖而导致路径爆炸、或因采用随机方式而导致覆盖不稳定的技术问题
1、本发明通过引入圈复杂度计算,实现了对测试场景的精准过滤,过滤掉复杂度过低或过高的场景,提高了测试用例生成的投入产出比。
Smart Images

Figure CN122925239A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of embedded software testing technology, and particularly relates to a method, system, electronic device and storage medium for automatically generating embedded software unit test cases with high cyclomatic complexity. Background Technology
[0002] In the field of industrial control, the reliability and security of embedded software are paramount. Unit testing, as an important means of verifying the smallest testable unit of software, is widely used for early defect detection during the development phase. However, due to the complexity of functional logic, many functions in embedded software have high cyclomatic complexity. When unit testing functions with excessively high cyclomatic complexity, the sheer number of paths due to their numerous branches, loops, and complex logical operators significantly increases the design difficulty.
[0003] Traditional testing methods rely on developers' experience to manually write test cases, which is inefficient and often misses some expected results or generates a large number of repetitive test cases, failing to cover all paths. Although there are some automatic generation methods (such as random testing, symbolic execution, and full path enumeration), they still suffer from unstable coverage, path explosion, insufficient engineering applicability, and exponential growth of test cases in high cyclomatic complexity scenarios.
[0004] Therefore, how to effectively control the size of test cases while ensuring test coverage, and adapt to the complex logical structure of high cyclomatic complexity functions in embedded software, is a technical problem that urgently needs to be solved. Summary of the Invention
[0005] This invention proposes a technical solution for automatically generating unit test cases for embedded software with high cyclomatic complexity. It aims to solve the technical problems of path explosion caused by pursuing full path coverage or unstable coverage caused by using random methods when testing embedded code with high cyclomatic complexity.
[0006] The first aspect of this invention discloses a method for automatically generating unit test cases for embedded software with high cyclomatic complexity; the method includes: Step S1: Obtain the code to be tested, construct a control flow graph, and bind the conditional expression of the decision node to the exit edge of the control flow graph. The exit edge carries an edge label indicating the direction of the branch. Step S2: Calculate the cyclomatic complexity of the code to be tested, and determine whether to enable automatic path analysis and set an upper limit on the number of representative paths based on the cyclomatic complexity. Step S3: Traverse the control flow graph and construct a decision vector for each execution path that reaches the exit. The decision vector is an ordered sequence composed of the identifiers of the decision nodes and the labels of the selected edges. The decision vector is used to remove duplicates and retain one representative path. The remaining logically equivalent paths are pruned and a set of representative paths is output. Step S4: For each representative path in the representative path set, extract the corresponding condition expression according to each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge label: take the original condition expression for the true branch, and take the negation of the original condition expression for the false branch, to obtain the constraint list of the representative path. Step S5: Parse the variables, operators and boundary constants from the constraint list, perform interval intersection on each variable to obtain the legal value interval, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path; Step S6: Output a set of unit test cases based on the input parameter combination. Each test case shall contain at least a test case identifier and the input parameter combination.
[0007] Furthermore, in step S1, before constructing the control flow graph, the code under test is preprocessed; the preprocessing includes: using a preset fake header file to convert type definitions and macro definitions in the code under test that are not recognized by the parser into constant or standard variable types.
[0008] Furthermore, in step S1, for the composite conditional expression, based on the short-circuit evaluation characteristic of logical operators, the composite conditional expression is reconstructed into cascaded atomic decision nodes, and the conditional expressions of the decomposed atomic decision nodes are respectively bound to the corresponding exit edges.
[0009] Furthermore, in step S3, the control flow graph is traversed using a depth-first search algorithm; during the traversal, the system maintains a set of seen decision vectors; when a new path is generated during traversal, the hash value of its decision vector is calculated; if the hash value does not exist in the set of seen decision vectors, the new path is retained as a representative path; if it already exists, pruning is performed on the new path.
[0010] Furthermore, when traversing the control flow graph, when encountering a loop structure node, a maximum consecutive TRUE threshold is set for each loop decision node; when the number of consecutive TRUE outputs by the loop decision node reaches the maximum consecutive TRUE threshold, the next decision result of the node is forcibly corrected to FALSE to break out of the loop, and the forced breakout decision is added as a feature dimension to the decision vector.
[0011] Furthermore, in step S5, the interval intersection convergence includes: establishing a dynamic boundary interval {min: -∞, max: +∞} for each variable; and gradually tightening the dynamic boundary interval according to the parsed operator to obtain the intersection interval that satisfies all constraints.
[0012] Furthermore, during the tightening of the dynamic boundary interval, consistency verification is performed in real time; when the min is greater than the max, the representative path is determined to be an unreachable path, the parameter solution for the path is terminated, and a marker record containing the failure reason is generated.
[0013] Furthermore, for conditional expressions involving comparisons between variables, they are transformed into relative constraints based on relative offsets, and variable dependency logic is instantiated according to a preset offset increment when selecting the representative value.
[0014] Furthermore, in step S6, the set of output unit test cases further includes: injecting the input parameter combination into the code under test for execution, capturing the runtime state through instrumentation to obtain the expected output, wherein the expected output includes the return value and the state of global variables.
[0015] Furthermore, in step S2, the rule for determining the cyclomatic complexity is as follows: if the cyclomatic complexity is less than or equal to the first threshold or greater than or equal to the second threshold, then the subsequent steps are not executed and a prompt is given; if the cyclomatic complexity is between the first threshold and the second threshold, then step S3 is executed.
[0016] A second aspect of this invention discloses an automatic generation system for embedded software unit test cases with high cyclomatic complexity; the system includes: The input code module is configured to acquire the code to be tested, construct a control flow graph, and bind the conditional expression of the decision node to the exit edge of the control flow graph, which carries an edge label indicating the direction of the branch. The cyclomatic complexity calculation module is configured to calculate the cyclomatic complexity of the code under test, and determine whether to enable automatic path analysis and set an upper limit on the number of representative paths based on the cyclomatic complexity. The path analysis module is configured to traverse the control flow graph, construct a decision vector for each execution path leading to the exit, the decision vector being an ordered sequence of decision node identifiers and selected edge labels, and retain one representative path by equivalent deduplication of the decision vector, pruning the remaining logically equivalent paths, and outputting a set of representative paths. The parameter constraint analysis module is configured to, for each representative path in the representative path set, extract the corresponding condition expression according to each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge label: take the original condition expression for a true branch, and take the negation of the original condition expression for a false branch, to obtain the constraint list of the representative path. The parameter combination generation module is configured to parse variables, operators and boundary constants from the constraint list, perform interval intersection convergence on each variable to obtain a valid value range, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path. The output test case module is configured to output a set of unit test cases based on the combination of the input parameters, and each test case contains at least a test case identifier and the combination of the input parameters.
[0017] A third aspect of this invention discloses an electronic device. The electronic device includes a memory and a processor. The memory stores a computer program, and when the processor executes the computer program, it implements the steps of the high-cyclomatic-complexity embedded software unit test case automatic generation method according to any one of the first aspects of this disclosure.
[0018] A fourth aspect of this invention discloses a computer-readable storage medium. The computer-readable storage medium stores a computer program, which, when executed by a processor, implements the steps of the high-cyclomatic-complexity embedded software unit test case automatic generation method according to any one of the first aspects of this disclosure.
[0019] The beneficial effects of this invention are: 1. This invention introduces cyclomatic complexity calculation to achieve precise filtering of test scenarios, filtering out scenarios with too low or too high complexity, thereby improving the return on investment in test case generation.
[0020] 2. By introducing a decision vector and a hash-based deduplication pruning mechanism, this invention can proactively identify and prune logically equivalent redundant paths, compressing the path size from exponential to linear, and effectively suppressing "path explosion".
[0021] 3. This invention replaces traditional heavy symbolic execution with arithmetic boundary calculation by using a constraint-guided interval convergence strategy, thereby avoiding the timeout risk of complex constraint solvers and reducing the dependence on hardware resources. It is very suitable for resource-constrained embedded environments. Attached Figure Description
[0022] To more clearly illustrate the specific embodiments of the present invention or the technical solutions in the prior art, the drawings used in the description of the specific embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.
[0023] Figure 1 A flowchart illustrating an automatic generation method for embedded software unit test cases with high cyclomatic complexity according to an embodiment of the present invention; Figure 2 Generate a system block diagram for unit test cases in embodiments of the present invention; Figure 3 A flowchart for the module that calculates cyclomatic complexity; Figure 4 A flowchart for analyzing the path module; Figure 5 A flowchart for the parameter constraint analysis module; Figure 6 A flowchart for generating the parameter combination module; Figure 7 A flowchart for outputting test case modules; Figure 8 This is a structural diagram of an electronic device according to an embodiment of the present invention. Detailed Implementation
[0024] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. 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.
[0025] This invention aims to address the technical problems of path explosion and unstable coverage caused by pursuing full path coverage when testing embedded code with high cyclomatic complexity in existing technologies. It provides a solution that controls path size and is compatible with lightweight constraint generation. The key difference between this invention and existing technologies lies in its approach: instead of solving all paths, it introduces decision vectors (BlockID, EdgeLabel) and a hash deduplication mechanism to actively prune logically equivalent paths during DFS traversal, retaining only a limited number of representative paths. Then, lightweight interval-convergent constraint analysis (based on boundary values / equivalence classes) is performed on these pruned paths to generate single-point parameter combinations, rather than complex symbolic solutions. This "subtraction and substitution" approach solves the dual problems of "path explosion" and "solution difficulty."
[0026] One example is an automated test case generation system for embedded software with high cyclomatic complexity, comprising an input code module, a cyclomatic complexity calculation module, a path analysis module, a parameter constraint analysis module, a parameter combination generation module, and an output test case module. The entire automated test case generation system uses automated testing tools to complete code evaluation and test case generation, requiring no manual intervention throughout the process.
[0027] The first aspect of this invention discloses a method for automatically generating unit test cases for embedded software with high cyclomatic complexity.
[0028] Example 1: Figure 1 This is a flowchart illustrating an automatic generation method for embedded software unit test cases with high cyclomatic complexity according to an embodiment of the present invention, such as... Figure 1 As shown, the method includes: Step S1: Obtain the code to be tested, construct a control flow graph, and bind the conditional expression of the decision node to the exit edge of the control flow graph. The exit edge carries an edge label indicating the direction of the branch. Before constructing the control flow graph, the code under test is preprocessed; the preprocessing includes: using a preset fake header file to convert type definitions and macro definitions in the code under test that are not recognized by the parser into constant or standard variable types.
[0029] For compound conditional expressions, based on the short-circuit evaluation characteristic of logical operators, the compound conditional expressions are reconstructed into cascaded atomic decision nodes, and the conditional expressions of the decomposed atomic decision nodes are bound to the corresponding exit edges.
[0030] Step S2: Calculate the cyclomatic complexity of the code to be tested, and determine whether to enable automatic path analysis and set an upper limit on the number of representative paths based on the cyclomatic complexity. The rule for determining cyclomatic complexity is as follows: if the cyclomatic complexity is less than or equal to a first threshold or greater than or equal to a second threshold, then subsequent steps are not executed and a prompt is given; if the cyclomatic complexity is between the first threshold and the second threshold, then step S3 is executed. Figure 3 As shown.
[0031] Step S3: Traverse the control flow graph and construct a decision vector for each execution path that reaches the exit. The decision vector is an ordered sequence composed of the identifiers of the decision nodes and the labels of the selected edges. The decision vector is used to remove duplicates and retain one representative path. The remaining logically equivalent paths are pruned and a set of representative paths is output. The control flow graph is traversed using a depth-first search algorithm. During the traversal, the system maintains a set of seen decision vectors. When a new path is generated during traversal, the hash value of its decision vector is calculated. If the hash value does not exist in the set of seen decision vectors, the new path is retained as a representative path. If it already exists, pruning is performed on the new path. When traversing the control flow graph, upon encountering a loop structure node, a maximum consecutive TRUE threshold is set for each loop decision node. When the number of consecutive TRUE outputs by the loop decision node reaches the maximum consecutive TRUE threshold, the next decision result of the node is forcibly corrected to FALSE to break out of the loop, and the forced exit decision is added as a feature dimension to the decision vector. Figure 4 As shown.
[0032] Step S4: For each representative path in the representative path set, extract the corresponding condition expression for each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge label: for true branches, take the original condition expression; for false branches, take the negation of the original condition expression, thus obtaining the constraint list of the representative path; such as Figure 5 As shown.
[0033] Step S5: Parse the variables, operators and boundary constants from the constraint list, perform interval intersection on each variable to obtain the legal value interval, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path; In step S5, the interval intersection convergence includes: establishing a dynamic boundary interval {min: -∞, max: +∞} for each variable; and gradually tightening the dynamic boundary interval according to the parsed operator to obtain the intersection interval that satisfies all constraints. During the tightening of the dynamic boundary interval, consistency verification is performed in real time; when the min is greater than the max, the representative path is determined to be an unreachable path, the parameter solution of the path is terminated and a flag record containing the failure reason is generated. For conditional expressions involving comparisons between variables, they are transformed into relative constraints based on relative offsets. When selecting the representative value, the variable dependency logic is instantiated according to a preset offset increment, such as... Figure 6 As shown.
[0034] Step S6: Output a set of unit test cases based on the input parameter combination. Each test case shall contain at least a test case identifier and the input parameter combination.
[0035] In step S6, the output unit test case set further includes: injecting the input parameter combination into the code under test for execution, capturing the runtime state through instrumentation to obtain the expected output, wherein the expected output includes return values and global variable states, such as... Figure 7 As shown.
[0036] Example 2: Suppose the embedded code function to be tested is as follows: void fun(int x, int y) { if (x>0) { if (y<10) { / / Path P0 covers this area: x>0 and y<10 printf("P0 Path\n"); } else { / / Path P1 covers this area: x>0 and y>=10 printf("P1 Path\n"); } } else { / / Path P2 covers this area: x<=0 printf("P2 Path\n"); } }
[0037] For the code to be tested mentioned above, this system automatically performs the following steps: Step S1: Obtain the code to be tested and construct the control flow graph (CFG): The system acquires the code to be tested, constructs a control flow graph, and binds the conditional expressions of decision nodes to the exit edges of the control flow graph, with each exit edge carrying an edge label indicating the direction of a branch. The system then parses the code to be tested and reconstructs it into basic blocks with decision labels. For example, decision node B1 (condition "x>0") and decision node B2 (condition "y<10") are extracted.
[0038] The system physically binds the conditional expression to the exit edge: The TRUE edge of B1 is bound to "x>0" and flows to B2; the FALSE edge of B1 flows to the exit B4.
[0039] The TRUE edge of B2 is bound to "y<10" and flows to the internal execution block B3; the FALSE edge of B2 flows to the exit B4.
[0040] Step S2: Calculate cyclomatic complexity and preprocess: The system calculates the cyclomatic complexity of the code under test, and determines whether to enable automatic path analysis and sets an upper limit on the number of representative paths based on the cyclomatic complexity. The system also calculates the cyclomatic complexity of the function `fun`. If the complexity is within a set range (e.g., between 5 and 20), the automatic path analysis mechanism is triggered.
[0041] Step S3: Path traversal and representative path clipping based on decision vectors: Traverse the control flow graph, construct a decision vector for each execution path leading to the exit, the decision vector being an ordered sequence of decision node identifiers and selected edge labels, and use the decision vector to remove duplicates and retain one representative path, pruning the remaining logically equivalent paths, and outputting a set of representative paths; use labeled depth-first search (DFS) to traverse the control flow graph, recording the (BlockID, EdgeLabel) along the way: 1) When traversing the TRUE branches of B1 and B2, construct the decision vector: (('B1','TRUE'),('B2','TRUE')). Calculate its hash value and store it in the known set, retaining it as the representative path P0.
[0042] 2) Then iterate through the results to obtain the decision vector of P1: (('B1','TRUE'),('B2','FALSE')), and keep it as the representative path P1.
[0043] 3) Finally, iterate through the path to obtain the decision vector of P2: (('B1','FALSE'),), and keep it as the representative path P2.
[0044] Through this deduplication mechanism, DFS actively prunes all redundant execution paths, strictly outputting only the three logically equivalent representative paths mentioned above.
[0045] Step S4, Parameter Constraint Analysis: For each representative path in the representative path set, extract the corresponding condition expression for each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge labels: for true branches, take the original condition expression; for false branches, take the negation of the original condition expression, thus obtaining the constraint list for the representative path. The system iterates through the decision vector of each representative path and performs polarity conversion and restoration logic in conjunction with the basic block conditions. For path P0: the vector contains ('B1', 'TRUE'), extract the constraint x>0; it contains ('B2', 'TRUE'), extract the constraint y<10. The constraint list of P0 is ['x>0', 'y<10'].
[0046] For path P1: extract the constraints as ['x>0', 'not(y<10)'].
[0047] For path P2: extract the constraint as ['not(x>0)'].
[0048] Step S5, Dynamic Interval Convergence and Input Parameter Generation: Parse the variables, operators and boundary constants from the constraint list, perform interval intersection convergence on each variable to obtain a valid value interval, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path. The system parses the above constraint list, abandons the traditional symbolic solver, and adopts a lightweight interval intersection convergence algorithm: Process P0 (x>0, y<10): Establish dynamic boundary intervals {min:1,max:+∞} for variable x; and {min:-∞,max:9} for y. Based on the boundary convergence strategy, the system prioritizes integers close to the conditional extrema to generate a single-point parameter combination: combo={'x':1,'y':9}.
[0049] Process P1(x>0, not(y<10)): Operator inversion: not(y<10) is equivalent to y>=10.
[0050] The interval converges to x∈[1,+∞), y∈[10,+∞). Generate a single-point parameter combination: combo={'x':1,'y':10}.
[0051] Process P2 (not (x>0)): The interval converges to x∈(-∞,0). y is unconstrained (using the default value of 0). Generate parameter combination: combo={'x':0,'y':0}.
[0052] Step S6: Output structured unit test cases The set of unit test cases is output based on the combination of input parameters, and each test case contains at least a test case identifier and the combination of input parameters.
[0053] The system uses instrumentation techniques to capture runtime state (or simulate stubs), automatically converting the final path-parameter mapping into executable unit test cases. The structured output test suite is as follows: Use Case 1 (corresponding to P0): Input {"x":1,"y":9}, expected output standard stream capture "P0 Path\n".
[0054] Use Case 2 (corresponding to P1): Input {"x":1,"y":10}, expected output standard stream capture "P1 Path\n".
[0055] Use Case 3 (corresponding to P2): Input {"x":0,"y":0}, expected output standard stream capture "P2 Path\n".
[0056] As can be seen from the above embodiments, this solution greatly constrains the path enumeration space through "path determination vector extraction", and then avoids the timeout problem of SMT solver by "lightweight interval single point value", taking into account the test completeness (100% branch coverage) and execution efficiency under embedded high cyclic complexity functions, and completely eliminating the exponential explosion of paths and test cases.
[0057] Comparative Example 1: To verify the technical effectiveness of this invention, an embedded communication processing function with multiple nested decisions and a cyclomatic complexity of 15 was selected as the object of theoretical analysis. Based on the multi-layer abstraction strategy of "cyclomatic complexity filtering - decision vector pruning - lightweight solution" proposed in this invention, the test case generation process was simulated and deduced. Under the same hardware environment benchmark, the theoretical performance curves of the traditional symbolic execution tool (KLEE v3.0) were compared with the solution of this invention. The deduction results are shown in Table 1: Table 1
[0058] As shown in Table 1, although the traditional symbolic execution method can achieve 100% decision coverage, it will theoretically produce an exponential path explosion when dealing with functions with a cyclomatic complexity of 15 and containing loops. Due to the solver bottleneck, the actual execution time is usually over a second (~5000ms), and the memory usage increases linearly with the number of paths.
[0059] In contrast, this invention, through topological similarity merging, can theoretically prune 128 syntactic paths into 8 semantic path clusters. Since the pruning process avoids the expensive SMT solution and only involves linear-time vector comparison, combined with lightweight offset instantiation, the theoretical processing time can be reduced to milliseconds (~200ms), and memory consumption is also significantly reduced.
[0060] As shown in Table 1 and the derivation process, this invention achieves a balance between "high coverage and low consumption" while maintaining 100% decision coverage. This path pruning mechanism based on topological abstraction demonstrates the significant superiority of the present invention in handling highly complex embedded code, which cannot be easily achieved by conventional techniques in this field.
[0061] In practical applications, those skilled in the art will understand that the present invention is not limited to the specific embodiments described above, but also includes the following equivalents or alternatives: (1) Dynamic adjustment of cyclomatic complexity threshold: This invention presets a fixed range of cyclomatic complexity thresholds (e.g., 5-20). Based on this, the system also supports an adaptive adjustment mechanism based on hardware resources or time budget: when the system detects a risk of memory overflow, it automatically lowers the upper limit of the number of paths (Max_Paths). This kind of dynamic threshold adjustment based on the operating environment is still technically based on controlling resource consumption by limiting complexity, and is an equivalent substitution for the engineering applicability of this invention.
[0062] (2) Variations of the constraint generation strategy: The core solution of this invention uses the method of "interval intersection + single point value" to generate parameters. In other embodiments, the "random sampling method" can also be used, that is, a value is randomly selected within the calculated legal interval [min, max] to meet the randomness requirements of specific tests.
[0063] (3) Variations of path deduplication structure: The core solution of this invention uses a hash set to store the seen vectors. In scenarios with more limited resources, a Bloom filter or a trie tree can also be used to store the decision vectors. Although the Bloom filter has a certain false positive rate, in embedded testing scenarios, it can further compress memory usage and achieve the same function as "deduplication and pruning".
[0064] (4) Extension to non-embedded code: The application scenarios of this invention are not limited to embedded software, but can also be extended to non-embedded software. In the cyclomatic complexity calculation module, it is only necessary to configure the variable conversion and function definition conversion rules of non-embedded software accordingly to identify and parse non-embedded code.
[0065] In summary, the solution proposed in this invention can: 1) Avoid path explosion from the source: Replace full path enumeration with decision vector deduplication and pruning. The path size and decision points are in a controlled relationship, rather than exponentially expanding. 2) Avoid heavy-duty solutions: For finite representative paths, use single-point solutions with boundary / equivalence interval convergence to avoid symbolic execution solution overhead and unsolvable risks; 3) More suitable for embedded scenarios: The whole process does not rely on heavyweight solvers and can stably output deterministic use cases in resource-constrained environments.
[0066] The second aspect of this invention discloses an automatic generation system for embedded software unit test cases with high cyclomatic complexity. Figure 2 This is a structural diagram of an automatic generation system for high cyclomatic complexity embedded software unit test cases according to an embodiment of the present invention; the system adopts the automatic generation method for high cyclomatic complexity embedded software unit test cases as described in any one of embodiments 1-2, such as... Figure 2 As shown, the system 100 includes: The input code module 101 is configured to acquire the code to be tested, construct a control flow graph, and bind the conditional expression of the decision node to the exit edge of the control flow graph, wherein the exit edge carries an edge label indicating the direction of the branch. The cyclomatic complexity calculation module 102 is configured to calculate the cyclomatic complexity of the code under test, and determine whether to enable automatic path analysis and set an upper limit on the number of representative paths based on the cyclomatic complexity. The path analysis module 103 is configured to traverse the control flow graph, construct a decision vector for each execution path that reaches the exit, the decision vector is an ordered sequence composed of the identifiers of the decision nodes passed through and the labels of the selected edges, and retain one representative path by equivalent deduplication through the decision vector, prune the remaining logically equivalent paths, and output a set of representative paths. The parameter constraint analysis module 104 is configured to, for each representative path in the representative path set, extract the corresponding condition expression according to each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge label: take the original condition expression for a true branch, and take the negation of the original condition expression for a false branch, to obtain the constraint list of the representative path. The parameter combination generation module 105 is configured to parse variables, operators and boundary constants from the constraint list, perform interval intersection convergence on each variable to obtain a valid value range, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path. The output test case module 106 is configured to output a set of unit test cases based on the combination of input parameters, wherein each test case contains at least a test case identifier and the combination of input parameters.
[0067] Traditional software testing typically treats "paths" from a discretized perspective: either attempting to exhaustively list all paths, leading to path explosion, or random sampling, resulting in unstable coverage. Furthermore, a long-standing technical bias exists in this field—the belief that "discarding any potential path will reduce coverage integrity"—leading technical personnel to naturally resist "active deduplication / reduction."
[0068] This invention overcomes the aforementioned biases by creatively applying the abstract thinking of "clustering / feature selection" in machine learning to the control flow path analysis of deterministic software: it uses a "decision vector" for each execution path. V= (B_id1,L1),(B_id2,L2),…
[0069] The path is represented as a logical feature fingerprint, thus elevating the "path" from a pure syntactic object to an analytical object that can be merged according to equivalence. By merging equivalent fingerprints using the existing vector set, logically equivalent paths naturally form a "cluster", and only one representative path is retained, which is equivalent to "clustering / feature equivalence" in effect; Because the path size is compressed to a manageable representative set, it becomes possible to replace heavy constraint solutions with lightweight boundary value / equivalence class interval convergence, forming a causal chain of "one reduction and one exchange".
[0070] Compared with the prior art, the present invention has the following significant advantages: 1. Precise scene adaptation and resource optimization – cyclomatic complexity calculation This invention achieves precise filtering of test scenarios by introducing cyclomatic complexity calculation. Unlike the blind activation of existing technologies, this invention filters out scenarios with excessively low complexity (no need for automation) or excessively high complexity (prone to system crashes) by setting thresholds. This feature ensures that the automated process runs only within the most efficient and necessary range, thereby avoiding the waste of computing resources in low-value scenarios at the source and significantly improving the return on investment of test case generation.
[0071] 2. Controllable path size and fundamental suppression of "path explosion"—representative path pruning This invention breaks away from the traditional testing bias of pursuing "full path coverage" by introducing a decision vector and a hash-based deduplication pruning mechanism. By defining path signatures as an ordered sequence of (BlockID, EdgeLabel), this invention can proactively identify and prune logically equivalent redundant paths. This "reduction instead of full coverage" strategy forcibly compresses the path size from exponential to linear, fundamentally dismantling the physical basis of "path explosion" and making subsequent analysis possible.
[0072] 3. Low-cost and high-efficiency parameter solving and embedded environment adaptation—lightweight interval convergence This invention successfully achieves a technological transformation of "replacing heavy burden with heavy burden" through a "constraint-guided interval convergence strategy." Because the number of paths has been reduced to a very small amount, this invention replaces traditional heavy symbolic execution SMT (Simplified Methods of Measuring and Mapping) solutions with simple arithmetic boundary calculations. This strategy not only completely avoids the timeout risk of complex constraint solvers but also greatly reduces dependence on hardware resources, making it particularly suitable for resource-constrained embedded software testing environments, achieving unexpected low power consumption and high efficiency.
[0073] 4. Balancing Test Completeness and Engineering Feasibility: This invention employs a multi-level progressive processing mechanism of "cyclomatic complexity filtering—decision vector pruning—lightweight solution," achieving deep collaboration and tight coupling among various technical features. Compared to the shortcomings of existing technologies that struggle to balance high coverage and low computational overhead, this invention focuses on the Boolean logic (TRUE / FALSE) of key decision nodes, achieving millisecond-level test case generation efficiency while ensuring representative path coverage.
[0074] Furthermore, this invention solves the technical problem of difficult parsing of composite constraints by introducing a composite condition decomposition mechanism based on short-circuit evaluation, which transforms complex logical expressions into atomic decision nodes. At the same time, by adopting a relative offset abstraction strategy to handle comparisons between variables, the space complexity of constraint solving is significantly reduced while ensuring coverage of key logic, achieving compatibility between high path representativeness and low resource consumption.
[0075] A third aspect of this invention discloses an electronic device. The electronic device includes a memory and a processor. The memory stores a computer program, and when the processor executes the computer program, it implements the steps of the high-cyclomatic-complexity embedded software unit test case automatic generation method according to any one of the first aspects of this invention.
[0076] Figure 8 This is a structural diagram of an electronic device according to an embodiment of the present invention, such as... Figure 8As shown, the electronic device includes a processor, memory, network interface, display screen, and input devices connected via a system bus. The processor provides computing and control capabilities. The memory includes non-volatile storage media and internal memory. The non-volatile storage media stores the operating system and computer programs. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used for wired or wireless communication with external terminals; wireless communication can be achieved through Wi-Fi, carrier networks, Near Field Communication (NFC), or other technologies. The display screen can be an LCD screen or an e-ink screen. The input devices can be a touch layer covering the display screen, buttons, a trackball, or a touchpad mounted on the device's casing, or an external keyboard, touchpad, or mouse.
[0077] Those skilled in the art will understand that Figure 8 The structure shown is merely a structural diagram of the part related to the technical solution of this disclosure and does not constitute a limitation on the electronic device to which the solution of this application is applied. The specific electronic device may include more or fewer components than shown in the figure, or combine certain components, or have different component arrangements.
[0078] A fourth aspect of this invention discloses a computer-readable storage medium. The computer-readable storage medium stores a computer program, which, when executed by a processor, implements the steps of the method for automatically generating high-cyclomatic complexity embedded software unit test cases according to any one of the first aspects of this invention.
[0079] Please note that the technical features of the above embodiments can be combined arbitrarily. For the sake of brevity, not all possible combinations of the technical features in the above embodiments have been described. However, as long as the combination of these technical features does not contradict each other, it should be considered within the scope of this specification. The above embodiments only illustrate several implementation methods of this application, and their descriptions are relatively specific and detailed, but they should not be construed as limiting the scope of the invention patent. It should be pointed out that for those skilled in the art, several modifications and improvements can be made without departing from the concept of this application, and these all fall within the protection scope of this application. Therefore, the protection scope of this patent application should be determined by the appended claims.
Claims
1. A method for automatically generating unit test cases for embedded software with high cyclomatic complexity, characterized in that, The method includes: Step S1: Obtain the code to be tested, construct a control flow graph, and bind the conditional expression of the decision node to the exit edge of the control flow graph. The exit edge carries an edge label indicating the direction of the branch. Step S2: Calculate the cyclomatic complexity of the code to be tested, and determine whether to enable automatic path analysis and set an upper limit on the number of representative paths based on the cyclomatic complexity. Step S3: Traverse the control flow graph and construct a decision vector for each execution path that reaches the exit. The decision vector is an ordered sequence composed of the identifiers of the decision nodes and the labels of the selected edges. The decision vector is used to remove duplicates and retain one representative path. The remaining logically equivalent paths are pruned and a set of representative paths is output. Step S4: For each representative path in the representative path set, extract the corresponding condition expression according to each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge label: take the original condition expression for the true branch, and take the negation of the original condition expression for the false branch, to obtain the constraint list of the representative path. Step S5: Parse the variables, operators and boundary constants from the constraint list, perform interval intersection on each variable to obtain the legal value interval, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path; Step S6: Output a set of unit test cases based on the input parameter combination. Each test case shall contain at least a test case identifier and the input parameter combination.
2. The method for automatically generating unit test cases for embedded software with high cyclomatic complexity according to claim 1, characterized in that, In step S1, before constructing the control flow graph, the code under test is preprocessed; the preprocessing includes: using a preset fake header file to convert type definitions and macro definitions in the code under test that are not recognized by the parser into constant or standard variable types.
3. The method for automatically generating unit test cases for embedded software with high cyclomatic complexity according to claim 1, characterized in that, In step S1, for the composite conditional expression, based on the short-circuit evaluation characteristic of logical operators, the composite conditional expression is reconstructed into cascaded atomic decision nodes, and the conditional expressions of the decomposed atomic decision nodes are respectively bound to the corresponding exit edges.
4. The method for automatically generating unit test cases for embedded software with high cyclomatic complexity according to claim 1, characterized in that, In step S3, the control flow graph is traversed using a depth-first search algorithm. During the traversal, the system maintains a set of seen decision vectors. When a new path is generated during traversal, the hash value of its decision vector is calculated. If the hash value does not exist in the set of seen decision vectors, the new path is retained as a representative path. If it already exists, prune the new path; When traversing the control flow graph, when a loop structure node is encountered, a maximum consecutive TRUE threshold is set for each loop decision node. When the number of consecutive TRUE outputs by the loop decision node reaches the maximum consecutive TRUE threshold, the next decision result of the node is forcibly corrected to FALSE to break out of the loop, and the forced exit decision is added as a feature dimension to the decision vector.
5. The method for automatically generating unit test cases for embedded software with high cyclomatic complexity according to claim 1, characterized in that, In step S5, the interval intersection convergence includes: establishing a dynamic boundary interval {min: -∞, max: +∞} for each variable; and gradually tightening the dynamic boundary interval according to the parsed operator to obtain the intersection interval that satisfies all constraints. During the tightening of the dynamic boundary interval, consistency verification is performed in real time; when the min is greater than the max, the representative path is determined to be an unreachable path, the parameter solution of the path is terminated and a flag record containing the failure reason is generated. For conditional expressions that include comparisons between variables, they are transformed into relative constraints based on relative offsets, and variable dependency logic is instantiated according to a preset offset increment when selecting the representative value.
6. The method for automatically generating unit test cases for embedded software with high cyclomatic complexity according to claim 1, characterized in that, In step S6, the set of output unit test cases further includes: injecting the input parameter combination into the code under test for execution, capturing the runtime state through instrumentation to obtain the expected output, the expected output including return value and global variable state.
7. The method for automatically generating unit test cases for embedded software with high cyclomatic complexity according to claim 1, characterized in that, In step S2, the rule for determining the cyclomatic complexity is as follows: if the cyclomatic complexity is less than or equal to the first threshold or greater than or equal to the second threshold, then the subsequent steps are not executed and a prompt is given; if the cyclomatic complexity is between the first threshold and the second threshold, then step S3 is executed.
8. A system for automatically generating unit test cases for embedded software with high cyclomatic complexity, characterized in that, The system includes: The input code module is configured to acquire the code to be tested, construct a control flow graph, and bind the conditional expression of the decision node to the exit edge of the control flow graph, which carries an edge label indicating the direction of the branch. The cyclomatic complexity calculation module is configured to calculate the cyclomatic complexity of the code under test, and determine whether to enable automatic path analysis and set an upper limit on the number of representative paths based on the cyclomatic complexity. The path analysis module is configured to traverse the control flow graph, construct a decision vector for each execution path leading to the exit, the decision vector being an ordered sequence of decision node identifiers and selected edge labels, and retain one representative path by equivalent deduplication of the decision vector, pruning the remaining logically equivalent paths, and outputting a set of representative paths. The parameter constraint analysis module is configured to, for each representative path in the representative path set, extract the corresponding condition expression according to each decision node and edge label in its decision vector, and generate constraint terms according to the direction of the edge label: take the original condition expression for a true branch, and take the negation of the original condition expression for a false branch, to obtain the constraint list of the representative path. The parameter combination generation module is configured to parse variables, operators and boundary constants from the constraint list, perform interval intersection convergence on each variable to obtain a valid value range, and select a representative value according to the boundary value or the midpoint of the equivalence class to generate a set of input parameter combinations for the representative path. The output test case module is configured to output a set of unit test cases based on the combination of the input parameters, and each test case contains at least a test case identifier and the combination of the input parameters.
9. An electronic device, characterized in that, The electronic device includes a memory and a processor. The memory stores a computer program. When the processor executes the computer program, it implements the steps in the method for automatically generating embedded software unit test cases with high cyclomatic complexity as described in any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program, which, when executed by a processor, implements the steps of the method for automatically generating high cyclomatic complexity embedded software unit test cases according to any one of claims 1 to 7.