Python test case generation method based on combination of big language model and type information
By combining the large language model with type information, high-coverage Python test cases are generated, which solves the limitations of test case generation in the dynamic language Python and achieves comprehensive coverage of Python program units.
Patent Information
- Application Number
- CN202410422104.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-04-09
- Publication Date
- 2024-10-01
AI Technical Summary
Existing Python unit testing tools have limitations when generating test cases with high coverage. Especially for Python, which is a dynamic language, it cannot accurately generate type information, resulting in branch conditions that are difficult to satisfy and low coverage.
Using a large language model combined with type information, the environment configuration module, syntax analysis module and test generation module are used to generate an abstract syntax tree, build a control dependency graph, use the large language model to drive test case generation, and calculate cross-mutation and branch distances. Optimize test cases to achieve high coverage for each branch.
It realizes high-coverage test case generation for Python program units, reduces tool limitations, improves code coverage and readability, adapts to the characteristics of the Python language, and generates test cases with higher coverage and readability. sex.
Smart Images

Figure CN118733432A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of software analysis and testing, and in particular to a Python test case generation method combining a large language model with type information. Background Art
[0002] Software testing refers to running a program under specified conditions to find errors in the program, measure the quality of the software, and evaluate whether it can meet the design requirements. The purpose is to ensure the reliability, stability and maintainability of the program. The evaluation of test cases mainly uses coverage to quantify the extent to which the test cases can run the program under test. Commonly used methods include code line coverage and branch coverage. Branch coverage is generally used in current research. Software testing is carried out in parallel with development and is divided into several different stages, including unit testing, integration testing, system testing, and regression testing. Unit testing refers to testing the units that make up the software, that is, functions. It can not only verify the correctness of the unit, but the assertions added during the test process can also improve the readability of the code and provide assistance for regression testing in the software maintenance phase. In addition, compared with the tedious manual writing of test cases that requires a lot of mechanical labor, the automatic generation of test cases is undoubtedly more concerned by researchers and developers. There are also several major categories of unit test automatic generation tools for static languages such as Java, such as Randoop based on random generation and EvoSuite based on genetic algorithms and evolutionary algorithms. With the rise of artificial intelligence technology, AthenaTest based on deep learning technology has also emerged.
[0003] In recent years, researchers and developers in program analysis have begun to focus on the Python language, which has become popular due to the AI boom, and related results have gradually been promoted in the Python community. Taking Python's unit test automatic generation tool as an example, new tools have been continuously launched at relevant conferences in recent years. For example, Pynguin has successfully applied the unit test automatic generation algorithm for statically typed languages such as Java to Python. The goal of these tools is to generate test cases with the highest possible coverage for Python programs, but their implementation methods are somewhat different from the actual applicable scenarios.
[0004] As more and more tools are launched, tool evaluation has become an important task. Both users and developers need to have a detailed understanding of the performance and limitations of the tools. On the one hand, Python, as a dynamic language, is different from static languages in many aspects. These factors may cause trouble for the automatic generation of test cases. For example, the characteristic of dynamically determining the type at runtime makes it impossible for the tool to accurately generate the corresponding type of test input before running without other type information prompts; on the other hand, the Python language ecosystem is very rich, which is directly reflected in the huge number of Python third-party libraries. General Python tools need to be able to provide test case generation capabilities for different types of third-party library units, but existing Python tools are often only targeted at specific third-party libraries, or the selected data sets are not universal, and the effectiveness of use in general large-scale projects is questionable.
[0005] In fact, existing research has found that the tool has certain limitations, mainly manifested in the fact that some branch conditions are extremely difficult to meet, and the parameters of the test cases are randomly generated, and the dynamic language has no provisions for parameter types, which makes these branches almost impossible to cover. Existing work has not further explored the reasons for this finding. However, this is very important for improving program coverage. For example, in a function, after the input is passed in, it is usually checked to ensure that its format, type, etc. meet the requirements of the function. Randomly generated test inputs are difficult to pass such checks, resulting in low coverage of such functions. Therefore, it is necessary to minimize this limitation. Summary of the invention
[0006] The purpose of the present invention is to provide a Python test case generation method that combines a large language model with type information, so as to effectively and automatically generate test cases for Python program units, and provide detailed feedback so that users can understand information such as the generation time and the specific coverage of the generated test cases.
[0007] In order to solve the above technical problems, the present invention provides the following technical solutions:
[0008] The Python test case generation method combining a large language model with type information includes:
[0009] The environment configuration module uses open source projects as test data sets to perform environment assessment configuration;
[0010] The syntax analysis module uses the abstract syntax tree to perform syntax analysis on the unit under test of the open source project and construct the control dependency graph G;
[0011] A large language model driving module is used to form prompt words of the large language model and specify the test generation plan through the prompt words;
[0012] The test generation module uses prompt words to drive the large language model based on the control dependency graph G to automatically generate and iterate test cases, scores and screens each test case to obtain the optimal test case set.
[0013] Furthermore, the environment configuration module uses the git clone command to obtain the project to be tested from its Github repository, independently generates a virtual Python environment for each project to be tested, configures the dependencies required for the operation of the project to be tested, configures the operating framework of the Python test case generation method that combines a large language model with type information, and performs environment configuration. The project to be tested includes project source code and test cases.
[0014] Among them, in order to ensure the normal progress of the test, git reset--hard is used to roll back the project code to the commit corresponding to the project version in the current environment; Git is an open source distributed version control system; GitHub is a software source code hosting service platform that uses Git for version control; git clone is an instruction to copy the project from a remote repository to a local one; git reset--hard is an instruction to roll back the status of the current repository to a specific commit.
[0015] Furthermore, the specific steps of the syntax analysis module include:
[0016] Read the source code of the program to be tested, use the ast module provided by the standard library to traverse the abstract syntax tree to generate an abstract syntax tree for each unit to be tested, and traverse it to obtain branch control nodes;
[0017] For branch control nodes, such as if-else, while and other statements, they are added to the set U as the coverage target branches of the current unit to be tested, and a control dependency graph G is established for the control dependency relationship between all coverage target branches in the current unit to be tested.
[0018] Among them, the abstract syntax tree is an abstract representation of the syntax structure of the source code, which expresses the syntax structure of the programming language in a tree form, and each node on the tree represents a structure in the source code.
[0019] Furthermore, the control dependency graph is a flow graph used to represent the dominance relationship between program branch nodes, where the nodes represent program branches and the directed edges represent the dominance of the pointing node over the pointed node.
[0020] Furthermore, the prompt words are combined in the form of "few-shot+set plan", and the prompt words are composed of "unit to be tested+natural language description+test case function signature". The "few-shot+set plan" step includes: taking out the callable object with the lowest coverage in the offspring population Q, adding an example unit to be tested-test case pair before the callable object with the lowest coverage, and setting a natural language description to help the large language model formulate a test generation plan, the example unit to be tested-test case pair refers to a unit to be tested for example, and an example test case generated for it; the "set plan" in the "few-shot+set plan" refers to formulating a test generation plan, and the "few-shot" in the "few-shot+set plan" belongs to the prior art and is not described in detail here. The callable object refers to the fact that there may be multiple classes, functions, etc. in the unit to be tested.
[0021] Furthermore, the specific steps of the test generation module include:
[0022] Take a test case as an individual, the test case set as a population, the branch to be covered in the unit under test as the target u, and perform initialization work;
[0023] Perform crossover mutation based on the current population P to obtain the offspring population Q;
[0024] If the difference between the maximum coverage of individuals in the offspring population Q and the maximum coverage of individuals in the parent population P is less than the threshold τ, and the stagnation iteration round Len has reached the maximum stagnation iteration round LenMax, then the prompt word is input into the large language model Model to obtain a new offspring individual Q`, and Q` is used as the new offspring population Q;
[0025] Use the branch distance calculation method to calculate the score of each individual in the offspring population Q on each target u in U*, update U*, if the score is 1, remove the target in U*, and add the target's successor in the control dependency graph G to U*, and greedily update the candidate population A according to the score, while keeping the maximum number of candidate population A no more than M; if the current target a in the control dependency graph G points to target b, then target b becomes the successor of target a in the control dependency graph G; the purpose of updating U* is to make the score calculated by the population only related to the current incompletely covered target. Use the updated U* as the incompletely covered target set for the next iteration;
[0026] Take the union of the current population P and the offspring population Q, sort them according to the dominance relationship between individuals, and sort the dominance relationship between each individual, and take the first M in the sorting as the new generation population P;
[0027] Update the stalled iteration round Len and the maximum stalled iteration round LenMax. If the iteration calls the large language model Model and the coverage rate still does not change, it means that the large language model has limited effect on the unit to be tested. Double the maximum stalled iteration round LenMax to reduce the call; if the iteration does not call the large language model Model and the coverage rate does not change, then increase the stalled iteration round Len count;
[0028] If the total running time does not exceed the timeout period t, a new round of iteration will continue;
[0029] After the iteration, the first individual in each target set in the candidate population A is taken out, representing the individual with the highest score in the current target, and added to the optimal test case set T, and the optimal test case set T is returned as the output.
[0030] Furthermore, a maximum population size M and a timeout time t are set; the timeout time t refers to the maximum time used for test generation;
[0031] The target set U* that is not fully covered is initialized to the points with in-degree 0 in the control dependency graph G;
[0032] The output optimal test case set T is initialized to an empty set;
[0033] The current population P is initialized to N randomly generated test cases;
[0034] The candidate population A of each target is initialized according to the population P. If there are individuals in the population P that completely cover the target, the candidate population A is initialized to a set that only contains individuals that completely cover the target. Otherwise, the branch distance calculation method between each individual in the population P and the target is used to calculate the score, and the candidate population A is initialized to the population P and sorted in reverse order according to the score.
[0035] Set the large language model Model used by the algorithm and synchronously set the parameters of the large model, as well as the stagnation iteration round Len at which the algorithm coverage remains unchanged when Model is not called, and the maximum stagnation iteration round LenMax.
[0036] Furthermore, the crossover mutation refers to cutting two individuals into two fragments at random positions and recombining them into two new individuals, which is called crossover; for a certain individual, there is a 1 / 3 probability of adding, deleting or changing a code, which is called mutation.
[0037] Furthermore, the score s of individual t on target u is calculated as follows: if individual t completely covers target u, score s is 1; if individual t does not cover target u at all, score s is 0; otherwise, a score s between 0 and 1 is calculated by the branch distance calculation method, and the closer the score s is to 1, the more likely individual t is to completely cover target u. The branch distance calculation method belongs to the prior art and will not be described in detail herein.
[0038] Furthermore, the dominance relationship between the individuals refers to that for two individuals t1 and t2, if the score of t1 on each target u on the target set U* that is not currently fully covered is greater than or equal to t2, and there is at least one target u whose score is greater than t2, then t1 is said to dominate t2.
[0039] Compared with the prior art, the beneficial effects achieved by the present invention are as follows: the present invention combines a large language model with control dependencies to automatically generate test cases for a given Python program unit; before generating test cases, Python type annotation information is pre-extracted, and the generation range of random input is narrowed according to the type annotation information; the score calculation for each branch is realized, and the candidate optimal individual of each branch is maintained, so that the test case with the highest coverage rate for each branch can be obtained; when the algorithm falls into coverage stagnation, the large language model is called by combining prompt words in a "few-shot+set plan" manner, and new test cases are generated to try to cover the currently uncovered code; the current set of branches to be covered is updated according to the coverage of the test cases, and the probability of generating individuals with higher scores for these branches in the next iteration is greater; when the individual scores are the same, individuals with fewer lines of code are preferentially selected to reduce the redundancy of the generated test cases and improve readability; finally, for each branch target, a set of individual test cases with the highest score is obtained as an output result set, which can achieve as much coverage as possible for all branches in the unit to be tested. The present invention improves the problem of low coverage of some codes in current Python program automatic unit testing tools, and can reflect the degree of support of the tool for Python language features, can help users better utilize the information of the unit to be tested, and can also provide developers with test cases with higher coverage and better readability. BRIEF DESCRIPTION OF THE DRAWINGS
[0040] The accompanying drawings are used to provide a further understanding of the present invention and constitute a part of the specification. Together with the embodiments of the present invention, they are used to explain the present invention and do not constitute a limitation of the present invention. In the accompanying drawings:
[0041] Figure 1 It is the overall architecture diagram of the Python test case generation method of the present invention combining a large language model with type information;
[0042] Figure 2It is a flow chart of the Python test case generation method of the present invention combining a large language model with type information. DETAILED DESCRIPTION
[0043] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0044] The present invention provides a technical solution: a Python test case generation method combining a large language model with type information, comprising:
[0045] The environment configuration module uses open source projects as test data sets for environment assessment configuration. Specifically, the open source projects to be tested are determined according to needs, and the project source code is obtained from its Github repository using the git clone command. A virtual Python environment is generated for each project, and its required dependencies are installed. In order to ensure the normal progress of the test, the project code is rolled back to the commit corresponding to the project version in the current environment using git reset--hard. Finally, a virtual environment is generated for the framework tool of the Python test case generation method for large language models combined with type information, and the environment is configured for it.
[0046] The syntax analysis module uses the abstract syntax tree to perform syntax analysis on the unit to be tested of the open source project, obtains the type annotation and control dependency graph G of the unit to be tested, specifically inputs the unit to be tested specified in the open source project, performs syntax analysis on the unit, uses the ast module provided by the standard library to generate and traverse the abstract syntax tree, and records the required information during the traversal process. For each branch statement structure in the unit to be tested, it is recorded as the coverage target branch of the unit; for all coverage target branches in the unit to be tested, a control dependency graph G is established to represent the control dependency relationship between branches.
[0047] The large language model driving module composes prompt words according to the type annotation of the unit to be tested and the control dependency graph G information obtained by the syntax analysis module; the prompt words are composed of "unit to be tested + natural language description + test case function signature".
[0048] The test generation module uses a large language model to automatically generate and iterate test cases based on the prompt words, scores and screens each test case, and obtains the optimal test case set, specifically:
[0049] S401 regards a test case as an individual, a test case set as a population, and a branch to be covered in the unit to be tested as a target u. The maximum population number M and the timeout time t are set; the timeout time t refers to the maximum time used for test generation; the current outermost target U* covered is initialized to a target in U that is not controlled by any other target, that is, a point with an in-degree of 0 in G; the output optimal test case set T is initialized to an empty set; the current population P is initialized to N randomly generated test cases; the candidate population A of each target is initialized according to the population P, and if there is a When the individual completely covers the target, the candidate population A is initialized to a set that only contains individuals that completely cover the target. Otherwise, the branch distance calculation method between each individual in the population P and the target is used to calculate the score, and the candidate population A is initialized to the population P and arranged in reverse order according to the score, that is, the individuals are sorted from high to low according to the scores obtained on the target; the large language model Model used by the algorithm is set and the parameters of the large model are set synchronously, as well as the stagnation iteration round Len at which the algorithm coverage remains unchanged when the Model is not called, and the maximum stagnation iteration round LenMax.
[0050] S402. At the beginning of each iteration, crossover mutation is performed based on the current population P to obtain a descendant population Q. The descendant population Q represents a set of new test cases generated. Specifically, for two individuals, they are cut into two fragments at random positions and recombined to form two new individuals, which is called crossover. For a certain individual, there is a 1 / 3 probability of performing an operation of adding, deleting or changing a code on it, which is called mutation.
[0051] S403, calculate the coverage data of each individual in the offspring population. If the difference between the maximum coverage obtained by individuals in the offspring population Q and the maximum coverage obtained by individuals in the parent population P is less than the threshold τ, and the stagnant iteration round Len has reached the maximum stagnant iteration round LenMax, it is said that it has fallen into coverage stagnation. At this time, select the callable object with the lowest coverage from the unit to be tested, add an example unit to be tested-test case pair before the object, and set the natural language description as "#figure out all the paths of the above unit, then generate new unit test cases to cover as many paths as possible." Help the large language model to formulate a test generation plan, combine prompt words in the way of "few-shot+set plan", input the prompt words into the large language model Model to obtain a new offspring individual Q', and use Q' as the new offspring population Q.
[0052] S404. Calculate the score of each individual in the offspring population Q on each target u in U*, and greedily update the candidate population A based on the score, while keeping the maximum number of candidate population A not exceeding M. Specifically: calculate the score s of individual t on the target u to be covered: if individual t completely covers the target u, s is 1; if individual t does not cover the target u at all, s is 0; otherwise, calculate an s between 0 and 1 through the branch distance calculation method. The closer s is to 1, the more likely t is to completely cover the target u. Then try to add individual t to the optimal individual candidate population A of u: if s is 1, it means that t completely covers u, then A is updated to a set containing only individual t; otherwise, insert t into the corresponding position in A based on s and the number of lines of code of individual t, and keep the size of A not exceeding the specified maximum population number. If the population number is already greater than the specified maximum number at this time, the population number is controlled to the specified maximum number;
[0053] Update U* according to the score of each individual in the offspring population Q on each target u in U*. If the score is 1, remove the target from U* and add the successor target in the control dependency graph G to U*.
[0054] S405, taking the union of the current population P and the offspring population Q, sorting them according to the dominance relationship between individuals, and sorting the dominance relationship between each individual, and taking the first M individuals in the sorting as the new generation population P.
[0055] S406, updating the stagnant iteration round Len and the maximum stagnant iteration round LenMax. If the large language model is called in this round of iteration and the coverage is not improved, it means that the large language model has limited effect on the unit under test, and LenMax is doubled to reduce the call; if the large language model is not called in this round of iteration and the coverage is not improved, Len is incremented. After that, if the timeout is not reached, a new round of iteration is performed.
[0056] S407, after the timeout period is reached, for each target maintained optimal individual candidate population, select the first individual, add it to the result individual set, and form the final output test case set. Finally, a set of optimal test case sets for the input unit under test and the specific coverage information of these test cases can be obtained.
[0057] It should be noted that, in this article, relational terms such as first and second, etc. are only used to distinguish one entity or operation from another entity or operation, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Moreover, the terms "include", "comprise" or any other variants thereof are intended to cover non-exclusive inclusion, so that a process, method, article or device including a series of elements includes not only those elements, but also other elements not explicitly listed, or also includes elements inherent to such process, method, article or device.
[0058] Finally, it should be noted that the above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. Although the present invention has been described in detail with reference to the aforementioned embodiments, those skilled in the art can still modify the technical solutions described in the aforementioned embodiments or replace some of the technical features therein by equivalents. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.
Claims
1. Python test case generation method combining large language model with type information, It is characterized in that include: The environment configuration module uses open source projects as test data sets to perform environment assessment configuration; The syntax analysis module uses the abstract syntax tree to perform syntax analysis on the unit under test of the open source project and construct the control dependency graph G; A large language model driving module is used to form prompt words of the large language model and specify the test generation plan through the prompt words; The test generation module uses prompt words to drive the large language model based on the control dependency graph G to automatically generate and iterate test cases, scores and screens each test case to obtain the optimal test case set.
2. The Python test case generation method combining a large language model with type information according to claim 1, It is characterized in that The environment configuration module uses the git clone command to obtain the project to be tested from its Github repository, independently generates a virtual Python environment for each project to be tested, configures the dependencies required for the operation of the project to be tested, configures the operating framework of the Python test case generation method that combines a large language model with type information, and performs environment configuration.
3. The Python test case generation method combining a large language model with type information according to claim 1, It is characterized in that The specific steps of the grammar analysis module include: Read the program source code of the project to be tested, generate an abstract syntax tree for each unit to be tested, and traverse it to obtain branch control nodes; The branch control node is taken as the coverage target branch of the current unit under test and added to the set U, and a control dependency graph G is established for the control dependency relationship between all coverage target branches in the current unit under test.
4. The Python test case generation method combining a large language model with type information according to claim 3, It is characterized in that The control dependency graph is a flow graph used to represent the dominance relationship between program branch nodes, where the nodes represent program branches and the directed edges represent the dominance of the pointing node over the pointed node.
5. The Python test case generation method combining a large language model with type information according to claim 1, It is characterized in that The prompt word is composed of "unit to be tested + natural language description + test case function signature".
6. The Python test case generation method combining a large language model with type information according to claim 1, It is characterized in that The specific steps of the test generation module include: Take a test case as an individual, the test case set as a population, the branch to be covered in the unit under test as the target, and perform initialization work; Perform crossover mutation based on the current population P to obtain the offspring population Q; If the difference between the maximum coverage of individuals in the offspring population Q and the maximum coverage of individuals in the parent population P is less than the threshold τ, and the stagnation iteration round Len has reached the maximum stagnation iteration round LenMax, then the prompt word is input into the large language model Model to obtain a new offspring individual Q`, and Q` is used as the new offspring population Q; Calculate the score of each individual in the offspring population Q on each target u in the target set U* that is not fully covered by the current method using the branch distance calculation method, update U*, and use the score greedily to update the candidate population A, while keeping the maximum number of candidate population A no more than M; Take the union of the current population P and the offspring population Q, sort them according to the dominance relationship between individuals, and sort the dominance relationship between each individual, and take the first M in the sorting as the new generation population P; Update the stalled iteration round Len and the maximum stalled iteration round LenMax. If the iteration calls the large language model Model and the coverage rate still does not change, it means that the large language model has limited effect on the unit to be tested. Double the maximum stalled iteration round LenMax to reduce the call; if the iteration does not call the large language model Model and the coverage rate does not change, then increase the stalled iteration round Len count; If the total running time does not exceed the timeout period t, a new round of iteration will continue; After the iteration, the first individual in each target set in the candidate population A is taken out, representing the individual with the highest score in the current target, and added to the optimal test case set T, and the optimal test case set T is returned as the output.
7. The Python test case generation method combining a large language model with type information according to claim 6, It is characterized in that The initialization work includes: Set the maximum population size M and the timeout time t; the timeout time t refers to the maximum time used for test generation; The currently incompletely covered target set U* is initialized to the points with in-degree 0 in the control dependency graph G; The output optimal test case set T is initialized to an empty set; The current population P is initialized to N randomly generated test cases; The candidate population A of each target is initialized according to the population P. If there are individuals in the population P that completely cover the target, the candidate population A is initialized to a set that only contains individuals that completely cover the target. Otherwise, the branch distance calculation method between each individual in the population P and the target is used to calculate the score, and the candidate population A is initialized to the population P and sorted in reverse order according to the score. Set the large language model Model used by the algorithm and synchronously set the parameters of the large language model Model, as well as the stagnation iteration round Len at which the algorithm coverage remains unchanged when Model is not called, and the maximum stagnation iteration round LenMax.
8. The Python test case generation method combining a large language model with type information according to claim 6, It is characterized in that The crossover mutation refers to cutting two individuals into two fragments at random positions and recombining them into two new individuals, which is called crossover; for a certain individual, there is a 1 / 3 probability of adding, deleting or changing a code, which is called mutation.
9. The Python test case generation method combining a large language model with type information according to claim 6, It is characterized in that The score s of individual t on target u is calculated as follows: if individual t completely covers target u, the score s is 1; if individual t does not cover target u at all, the score s is 0; otherwise, a score s between 0 and 1 is calculated by the branch distance calculation method. The closer the score s is to 1, the more likely it is that individual t will completely cover target u.
10. The Python test case generation method combining a large language model with type information according to claim 6, It is characterized in that The dominance relationship between individuals means that for two individuals t1 and t2, if the score of t1 on each target u on the target set U* that is not currently fully covered is greater than or equal to t2, and there is at least one target u whose score is greater than t2, then t1 is said to dominate t2.
Citation Information
Cited By
High-quality micro-benchmark performance test automatic generation method and device based on large language model
CN119440992A
A method and apparatus for automatically generating high-quality micro-benchmark performance tests based on large language models
CN119440992B
Dynamic language test case automatic generation method based on large language model
CN119576799A
Automatic generation method of dynamic language test cases based on large language model
CN119576799B
ROS 2 defect detection method based on large language model and differential test
CN119597654A
