Full text
Optimization Techniques for Automated Software Test Data Generation Ph.D. Thesis Dissertation in Computer Sciences Author Francisco Javier Ferrer Urbano Supervisors Dr. Enrique Alba and Dr. Francisco Chicano Department of Lenguajes y Ciencias de la Computación UNIVERSITY OF MALAGA January 2016
AUTOR: Francisco Javier Ferrer Urbano http://orcid.org/0000-0002-1074-0139 EDITA: Publicaciones y Divulgación Científica. Universidad de Málaga Esta obra está bajo una licencia de Creative Commons Reconocimiento-NoComercial- SinObraDerivada 4.0 Internacional: http://creativecommons.org/licenses/by-nc-nd/4.0/legalcode Cualquier parte de esta obra se puede reproducir sin autorización pero con el reconocimiento y atribución de los autores. No se puede hacer uso comercial de la obra y no se puede alterar, transformar o hacer obras derivadas. Esta Tesis Doctoral está depositada en el Repositorio Institucional de la Universidad de Málaga (RIUMA): riuma.uma.es
Departamento de Lenguajes y Ciencias de la Computación Escuela Técnica Superior de Ingeniería Informática Universidad de Málaga El Dr. Enrique Alba Torres y el Dr. Francisco Chicano García pertenecientes al Departamento de Lenguajes y Ciencias de la Computación de la Universidad de Málaga, Certifican que, D. Francisco Javier Ferrer Urbano, Ingeniero en Informática por la Universidad de Málaga, ha realizado en el Departamento de Lenguajes y Ciencias de la Computación de la Universidad de Málaga, bajo su dirección, el trabajo de investigación correspondiente a su Tesis Doctoral titulada: Optimization Techniques for Automated Software Test Data Generation Revisado el presente trabajo, estimamos que puede ser presentado al tribunal que ha de juzgarlo. Y para que conste a efectos de lo establecido en la legislación vigente, autorizamos la presentación de esta Tesis Doctoral en la Universidad de Málaga. En Málaga, Enero de 2016 Fdo: Dr. Enrique Alba Torres y Dr. Francisco Chicano García
A mis padres, Virgilio y Mar´ıa Jos´e, por la educaci´on y el cari˜no que me han dado siempre
Agradecimientos Para comenzar me gustar´ıa agradecer a todas las instituciones e investigadores que han contribuido en mi desarrollo hasta ver plasmada esa evoluci´on en este volumen de tesis doctoral. Agradezco en primer lugar a mis directores Enrique y Francis, que me han guiado de la mejor forma posible para conseguir este objetivo tan deseado. Me alegra mucho haber podido ser capaz de devolver parte de lo que la sociedad me ha brindado en forma de conocimiento cient´ıfico. Han sido muchos los momentos que he vivido junto a ellos en este periodo; por encima de todo me gustar´ıa resaltar su faceta personal, ya que el trabajo siempre se ha realizado en el mejor ambiente posible. Durante este tiempo han sido muchos los compa˜neros que han pasado por el laboratorio desde donde estoy escribiendo estas l´ıneas. Cada uno de ellos me ha aportado lo mejor, y s´olo espero haber podido captar lo m´aximo de ellos, puesto que no existen mejores compa˜neros que los que he tenido. Agradezco a Gabriel, Paco, Guillermo, Juanjo y Jos´e Manuel, siempre dispuestos a ayudarte y de los que he aprendido mucho. A los compa˜neros con los que empec´e esta aventura Briseida, Pablo, y Mart´ın, a los cuales les deseo lo mejor. Tambi´en agradezco a los que nos hemos unido durante este tiempo y compartimos nuestro laboratorio: Jamal, Yesnier, Daniel, Ra´ul y recientemente Christian y Francisco. Con todos ellos este camino recorrido ha sido mucho mejor, y espero que lo siga siendo en esta nueva etapa como doctor. Quisiera mencionar tambi´en a Juan Miguel y Antonio, que me han prestado su ayuda con amabilidad siempre que lo he necesitado. NEO es un grupo donde acogemos cada a˜no a una gran cantidad de investigadores externos, lo que me ha dado la posibilidad de conocer a Sergio, Franco, Mart´ın, Carolina, Andreas, Mauricio, Javier, Sofiene, Karel, Roberto, Darrell, Manuel, Zakaria, David y muchos otros, todos excelentes profesionales y grandes personas. A ellos les doy las gracias por abrirme las puertas de mundo global desde un laboratorio de M´alaga. Mi m´as sincero agradecimiento a Joachim y Peter, que me acogieron en mi estancia en Berlin en lo que ha sido una de las mejores experiencias de mi vida. Esta estancia supuso un crecimiento profesional y sobre todo personal. En estos momentos me acuerdo del sacrificio que hicieron mis padres, Virgilio y Mar´ıa Jos´e, para enviarme a estudiar a M´alaga. Espero haber aprovechado bien la oportunidad y que est´eis orgullosos de m´ı, porque yo no tengo palabras para agradeceros todo lo que hab´eis hecho. Tambi´en agradezco a mis queridos hermanos Eva, Fernando, Alejandro y Virginia, cuyo ejemplo me ha servido desde el d´ıa en que nac´ı. A mis abuelos y t´ıos, en especial a mi abuela Mar´ıa y mi t´ıa Mercedes que son tan importantes para m´ı, gracias por hacerme sentir tan querido. Ahora que cierro una etapa, quiero agradecerle especialmente a una persona que ha estado a mi lado desde que empec´e esta aventura del doctorado, mi prometida Myriam. Voy a emprender un nuevo camino lleno de inc´ognitas en la vida profesional, sin embargo no me preocupa, ya que estando contigo ese camino estar´a lleno de felicidad. Acknowledgements This PhD thesis has been partially funded by the Spanish Ministry of Economy and Competitiveness (MINECO) and the European Regional Development Fund (FEDER), under contract TIN2014-57341-R moveON project (http://moveon.lcc.uma.es). It has been also partially funded by the University of Malaga, under contract UMA/FEDER FC14-TIC36. Finally, the author is supported by a FPI grant with code BES-2012-055967 from MINECO.
Contents Acknowledgements iv 1 Introduction 1 1.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Objectives and Phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 PhD Thesis Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.4 PhD Thesis Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 I Fundamentals of Software Testing and Metaheuristics 7 2 Fundamentals of Software Testing 9 2.1 Structural Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2 Structural Testing Problems Addressed in this Thesis . . . . . . . . . . . . . . . . 11 2.2.1 Test Data Generation Problem . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2.2 Multi-Objective Test Data Generation Problem . . . . . . . . . . . . . . . . 14 2.3 Functional Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.4 Functional Testing Problems Addressed in this Thesis . . . . . . . . . . . . . . . . 17 2.4.1 Prioritized Pairwise Test Data Generation Problem with Classification Tree Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 2.4.2 Test Sequence Generation Problem with Extended Classification Tree Method 20 2.4.3 Pairwise Test Data Generation Problem in SPL . . . . . . . . . . . . . . . . 23 2.4.4 Multi-Objective Test Data Generation Problem in SPL . . . . . . . . . . . 26 2.5 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 3 Fundamentals of Metaheuristics 29 3.1 Formal Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3.2 Classification of Metaheuristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.2.1 Trajectory Based Metaheuristics . . . . . . . . . . . . . . . . . . . . . . . . 33 3.2.2 Population Based Metaheuristics . . . . . . . . . . . . . . . . . . . . . . . . 34 3.3 A Methodology for Evaluating Results . . . . . . . . . . . . . . . . . . . . . . . . . 36 3.3.1 Quality Indicators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 3.3.2 Statistical Analysis Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . 41 v
4 Algorithms 45 4.1 Mono-objective Metaheuristics Used in this PhD Thesis . . . . . . . . . . . . . . . 45 4.1.1 Genetic Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 4.1.2 Evolutionary Strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4.1.3 Ant Colony Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 4.2 Multi-objective Metaheuristics Used in this PhD Thesis . . . . . . . . . . . . . . . 49 4.2.1 Non-dominated Sorting Genetic Algorithm II . . . . . . . . . . . . . . . . . 49 4.2.2 Strength Pareto Evolutionary Algorithm 2 . . . . . . . . . . . . . . . . . . . 49 4.2.3 Multi-Objective Cellular Algorithm . . . . . . . . . . . . . . . . . . . . . . . 50 4.2.4 Pareto Archived Evolution Strategy . . . . . . . . . . . . . . . . . . . . . . 51 4.2.5 Random Multi-Objective Algorithm . . . . . . . . . . . . . . . . . . . . . . 52 II Structural Testing 55 5 Test Data Generation in Object-Oriented Software 57 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 5.2 Test Data Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.2.1 Objective Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 5.2.2 Instrumentation Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 5.3 Distance for instanceof operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 5.4 Experimental Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 5.4.1 Algorithm Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 5.4.2 Mutation Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 5.4.3 Benchmark of Test Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.5 Experimental Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 5.5.1 Preliminary Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 5.5.2 Uniform vs. Distance-based Mutation . . . . . . . . . . . . . . . . . . . . . 66 5.5.3 Adaptive Mutation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 5.6 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 6 Estimating Software Testing Complexity 71 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 6.2 Static Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 6.3 Branch Coverage Expectation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 6.3.1 Markov Chain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 6.3.2 Definition of the Branch Coverage Expectation . . . . . . . . . . . . . . . . 77 6.4 Validation of the Branch Coverage Expectation . . . . . . . . . . . . . . . . . . . . 80 6.5 Empirical Validation Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 6.5.1 Algorithms Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 6.5.2 Program Generator Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 6.5.3 Benchmark of Test Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 85 6.6 Empirical Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 6.6.1 Analysis of the Correlation Between the Static Measures . . . . . . . . . . . 87 6.6.2 Correlation Between Coverage and Static Measures . . . . . . . . . . . . . . 89 6.6.3 Another use of the Branch Coverage Expectation . . . . . . . . . . . . . . . 92 6.6.4 Validation on Real Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 94 6.7 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
7 Multi-Objective Test Data Generation 99 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 7.2 Experimental Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 7.2.1 The MM Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 7.2.2 The mM Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 7.2.3 Benchmark of Test Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 103 7.3 Experimental Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 7.3.1 Evaluation of the MM approach . . . . . . . . . . . . . . . . . . . . . . . . 104 7.3.2 Evaluation of the mM approach . . . . . . . . . . . . . . . . . . . . . . . . 107 7.3.3 MM vs. mM approaches . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.3.4 Validation on Real Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 114 7.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 III Functional Testing 119 8 Combinatorial Interaction Testing using Classification Tree Method 121 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 8.2 Prioritized Pairwise Test Data Generation using CTM . . . . . . . . . . . . . . . . 122 8.2.1 Solution Approaches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 8.2.2 Experimental Benchmark . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 8.2.3 Comparison between GS, PPC and PPS . . . . . . . . . . . . . . . . . . . . 127 8.2.4 Comparison between Genetic Solver and other existing algorithms . . . . . 129 8.3 Test Sequence Generation using ECTM . . . . . . . . . . . . . . . . . . . . . . . . 131 8.3.1 Algorithms Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 8.3.2 Experimental Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 8.3.3 Test Sequences’ Quality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 8.3.4 Test Suite Coverage versus Test Suite Size . . . . . . . . . . . . . . . . . . . 139 8.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 9 Pairwise Testing in Software Product Lines 145 9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 9.2 Parallel Prioritized Pairwise Testing . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.2.1 Algorithm Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 9.2.2 Weight Priority Assignment Methods . . . . . . . . . . . . . . . . . . . . . 147 9.2.3 Experimental Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 9.2.4 Experimental Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9.3 Seeding Strategies for Multi-Objective Pairwise Testing . . . . . . . . . . . . . . . 152 9.3.1 Seeding Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 9.3.2 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 9.3.3 Experimental Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 9.4 Optimal Multi-Objective Pairwise Testing . . . . . . . . . . . . . . . . . . . . . . . 160 9.4.1 Mathematical Linear Program . . . . . . . . . . . . . . . . . . . . . . . . . 161 9.4.2 Algorithm Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 9.4.3 Experimental Setup and Analysis . . . . . . . . . . . . . . . . . . . . . . . . 163 9.5 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
4 1.4. PHD THESIS ORGANIZATION 1.4 PhD Thesis Organization This PhD thesis document is structured in four parts and two appendices. The first part is devoted to present the fundamentals and basis for the work: what is software testing and the software testing problems tackled, an explanation of metaheuristics as resolution techniques, the algorithms used (throughout this PhD dissertation), and the methodology that we have employed for assessing and validate the numerical results. Second and third parts are devoted to the most important testing paradigms that are structural and functional testing, respectively. In the second part we address the automatic test data generation problem, we propose a new complexity measure for estimating the difficulty to test a piece of code, and we solve the bi-objective test data generation problem considering test suite quality and cost as equally important goals, in the context of white-box testing. The third part is devoted to explore the black-box version of the test data generation problem, that is without any information of the source code. In this part we deal with two representations of the system under testing, classification tree method and feature models. The fourth part recaps the main conclusions drawn throughout the work and outlines our future research lines. Finally, the appendices contains the set our related works that have been published during the years in which this PhD thesis has been carried out and a summary in Spanish language In the following we detail the content of each forthcoming chapter: •Part I. Fundamentals of Software Testing and Metaheuristics –Chapter 2 introduces the main concepts of software testing, emphasizing structural and functional testing, the two main paradigms of software testing. After that, the problems addressed in this PhD thesis are formalized in order to provide the reader with the exact details of the problems we are solving. –Chapter 3 provides a generic description of the research field of Optimization and Metaheuristics, including a classification of the main techniques. The last part of this chapter concentrates on how to properly evaluate their results, including quality indicators and the standard statistical validation employed in all our experiments. –Chapter 4 introduces the most important versions of the algorithms used throughout this PhD thesis, including single-objective and multi-objective techniques. The specific implementation details (like the operators for mutation or crossover) which are problemspecific (or representation specific), are deferred to the corresponding chapters. •Part II. Structural Testing –Chapter 5 deals with inheritance for generating test data in Object Oriented source code. This chapter proposes a distance measure to compute the branch distance in the presence of the instanceof operator and two mutation operators that change the candidate solutions based on the distance measure defined. In addition to the proposals we have performed a set of experiments to test our hypotheses comparing against uniform mutation. –Chapter 6 contains the definition of a new complexity measure based on a Markov model of a program, the “Branch Coverage Expectation”. This measure is aimed at providing some knowledge about the difficulty of testing programs. After that, the theoretical and experimental validity of the measure is evaluated using the framework proposed by Kitchenham et al. [120].
CHAPTER 1. INTRODUCTION 5 –Chapter 7 starts by describing two different approaches for tackling the multi-objective test data generation problem. It analyzes the performance of a direct multi-objective approach versus the application of mono-objective algorithms followed by a test case selection. Our approaches consider test suite quality and oracle cost as optimization goals. In contrast to previous results in the literature that have only focused on the coverage of a program, while the oracle cost is a significant cost that has been ignored in most of the previous studies. •Part III. Functional Testing –Chapter 8 explores a series of issues related to the Classification Tree Method. We analyze the prioritization of test data to test first the most important functionalities. After that, we define an entire model (Extended Classification Tree Method) which both industry and academia could use to completely describe all aspects needed to generate sequences of tests for testing a program. Our proposals have been successfully implemented in the CTE XL professional tool, what adds value to our work. –Chapter 9 addresses the application of metaheuristic techniques to Software Product Lines testing. Throughout this chapter we fill several existent gaps in the SPL literature: we compare a parallel genetic solver with an state-of-the-art algorithm with pairwise coverage as adequacy criterion, explore the effect of different seeding strategies, propose classical multi-objective algorithms and a new exact algorithm to compute the true Pareto front considering test suite quality and oracle cost. •Part IV. Conclusions –Chapter 10 contains a global review of the PhD dissertation, and revisits the main conclusions drawn. The research objectives and main contributions are then discussed in view of the results obtained. Lastly, the future lines of research are briefly sketched and discussed. •Appendices –Appendix A presents the set of related works that have been published during the years in which this PhD thesis has been carried out. –Appendix B is a summary of this volume in Spanish.
6 1.4. PHD THESIS ORGANIZATION
Part I Fundamentals of Software Testing and Metaheuristics 7
Chapter 2 Fundamentals of Software Testing Software engineering is a computer science area whose focus is the cost-effective development of high-quality software systems [177]. Contrary to other elements studied in other engineering fields, software is abstract and intangible, which is, on the one hand positive because it is not constrained by physical laws. But, on the other hand, the lack of physical limitations on the potential of the software makes it extremely complex and hence very difficult to understand. Moreover, software is never used on its own but always as a part of some broader system including hardware, people and, often, organizations. Software engineering focuses on the study and application of engineering to the design, development, and maintenance of software. However, nowadays there are many companies that still do not apply software engineering techniques effectively, too many projects produce software that is unreliable. After codification, software products require a test phase with the aim of finding errors and to ensure software correctness. Software testing could be defined from two different points of view [215]. The first defines software testing as the process of evaluating a system or its components with the intent to find whether it satisfies the specified requirements or not - positive view. The second claims that software testing consists in executing a system in order to identify any gaps, errors, or missing requirements in contrast to the actual requirements - negative view. In practice, testing will combine elements of positive and negative testing, not only checking that a system meets the requirements, but also trying to find errors in the source code. Consequently, the testing phase consists in creating a set of test cases to execute the software under test (SUT), then the tester has to check whether the output of the execution is correct or not, follows the specification or not. Testing is not a new concept at all, Romans had already used this concept when evaluating the quality of precious metals in the first century. This concept is still valid, though it is evolving from manual to automatic testing due to the software complexity. Let us draw an example of how difficult is testing even a simple function that classifies triangles1. Suppose the arguments of the function are three integers of 32 bits and the computation execution capacity is 1,000 tests per second, then the exhaustive testing of this function will last 2.5 quintillion years (2.5∗1018 years). Obviously, nobody would test such a function like that, but it is a good example to show that brute force approaches are useless dealing with this problem. The importance of the testing phase and the high economic impact of an inadequate testing infrastructure were detailed in a survey by 1This function uses the lengths of the triangle to classify triangles in types: equilateral, isosceles, scalene, and no-triangle. 9
10 2.1. STRUCTURAL TESTING Tassey [197]. In a software project it is estimated that roughly 60% of costs are development costs and 40% are testing costs. Moreover, for custom software, evolution costs often exceed development costs [192]. Therefore, the automation of test data generation is desirable and could reduce the cost of the whole project. Automatic test data generation (automatic software testing) consists in proposing an adequate set of test data in an automatic way to test a program, thus preventing the engineer from the task of selecting an adequate set of test data to test the SUT. Therefore, this automation of the process requires the automatic selection of adequate test data. This is an optimization problem where the algorithm has to pick the best solution (test suite) among a number of feasible ones, and it can be formulated as a search problem [47] (see Section 3.1). In all types of engineering there are a large number of optimization problems, software engineering is not an exception. In fact, the term Search Based Software Engineering (SBSE) was coined by Harman and Jones [97] to refer to this research field that combines search algorithms with software engineering problems. The automatic generation of test data is the most widely studied topic [95, 147] among SBSE problems and Evolutionary Algorithms (EAs) are the most popular search-based algorithms to face this problem. Then, the research community use the term evolutionary testing to refer to this approach. There are two complementary paradigms for testing a piece of code that rely on the knowledge the tester has of the internal structure of the software: structural testing (white box) and functional testing (black box). On the one hand, structural paradigm uses information about how the SUT is constructed for generating test cases [113]. This structural information generally comes from the control flow graph of the SUT, in particular from the control structures (decisions) that lead to the different branches of the program. This technique is typically used during the early stages of the testing process where the programmer is in charge of executing the test suite [215]. On the other hand, functional tests are designed without any information of the structure of the source code [38,39]. In this paradigm the design of the test cases must be based on the external behavior of the SUT. This technique is typically used when the SUT is implemented by 3rd-party developers, the source code is unavailable, or the entire system is tested. Throughout this PhD thesis we deal with the test data generation problem using structural and functional techniques, so in the rest of this chapter we make a deeper analysis of these two testing paradigms. 2.1 Structural Testing The most relevant techniques for the automatic generation of test data in structural testing include symbolic execution [43], random testing [18], and search-based testing [99]. In symbolic execution the program’s code is analyzed to automatically generate test data. Although this technique has been proven to be useful, it suffers problems that limit its effectiveness on real-world software [14]. Random testing is a competitive testing option only under particular circumstances [18], but it is definitely a good technique to compare with as a sanity check. The problem of automatically generating test inputs is NP-hard [147], so researchers seek to identify test suites that obtain near optimal coverage in reasonable time. For this reason, search-based testing is receiving more and more attention in the last few years [99]. Search-based techniques have revealed that they are the best option to automatically generate test data with a high trade-off between quality and cost. The most popular search-based algorithms for generating test data are EAs [77,147] such as genetic algorithms [8,12,89,168,195,222], evolutionary strategies [5,74], or genetic programming [1, 11, 40, 179, 214]. Other search-based techniques like Tabu Search [60–62], Scatter Search [34, 60, 184], Estimation of Distribution Algorithms [183], Particle Swarm Optimization [140], Simulated
CHAPTER 2. FUNDAMENTALS OF SOFTWARE TESTING 11 Annealing [223], and Hybrid algorithms [213] have been also applied to solve this problem. In structural testing the internal structure of the source code is essential, so different approaches have been presented depending on the particularities of the programming paradigm elements used to develop the SUT. In the related literature there are studies on procedural programming [62,98,128,140], object-oriented programming [19,73,78,179], and even aspect-oriented programming [9]. In particular, different elements of the structure of a program have been studied in detail. Researchers have analyzed different transformations on the source code to make it more testable, namely testability transformations [150]. Occasionally, there are source code elements that may cause inefficiency in the generation of test data, so they require some transformation, for example, the presence of flags in conditions [25], the coverage of loops [61], the existence of internal states [231], the presence of exceptions’ treatment [201], the nesting problem [151], and the use of inheritance [73]. A key idea behind structural testing is the instrumentation of the SUT to measure coverage of some structural criteria. The most popular adequacy criterion for the quality of the generated test suite is branch coverage [44], though other structural criteria have been proposed. For example, loop coverage [61], control-flow coverage [209], data-flow coverage [83], statement coverage [170], or decision coverage [223]. In addition, several objective functions have been suggested [26, 185, 206,224] including the use of penalties [180], normalization [16], approximation distance [216], and branch distance [125] in the so-called fitness function. The solution of the test data generation problem is a set of test data whose execution is able to cover all possible software elements. Most works cited above follow this mono-objective approach. However, real-world engineers deal with the tedious and costly task of checking the system behavior for all the generated test cases. This significant and usually neglected cost is called the oracle cost [152]. Therefore, a reformulation of the problem as multi-objective have been proposed [98, 129] to take into account coverage and oracle cost as equally important objectives. When trying to cover all branches of the SUT, every single branch is a goal. Traditionally, most works focus on only one branch at a time, some others use an aggregated function to deal with all at the same time, namely whole suite approach [77], and more recently, all single branches could be considered as objectives at the same time [169], so it requires a multi-objective optimization technique. This great research effort has led to the development of automatic tools for the generation of test data using a search-based engine. For example, CUTE [188] a concolic unit testing engine for C, DART [87] a directed automated random testing tool, AUSTIN [128] an open source tool for search based software testing of C programs, EvoSuite [80] an automatic test suite generator for Java, and many others. Some of the proposed tools have succeeded in testing safety-critical [202] and real time software [217]. 2.2 Structural Testing Problems Addressed in this Thesis In this section we formally define the structural testing problem addressed in this dissertation. We tackle the Test Data Generation Problem and the Multi-objective Test Data Generation Problem, the multi-objective version of the same problem. 2.2.1 Test Data Generation Problem In software testing the engineer selects an initial set of configurations or inputs for the SUT, called test suite, and s/he checks the SUT behavior with them. In order to ensure the correctness of
12 2.2. STRUCTURAL TESTING PROBLEMS ADDRESSED IN THIS THESIS a program with this technique, it would be necessary to execute the SUT with all the possible configurations, but in practice this is unfeasible. The alternative consists in testing the program with a representative set of test data. Let us define some important concepts related to the test data generation problem. The Control Flow Graph (CFG) of a program P is a directed graph Gp= (I, L) in which I is the set of program’s statements (nodes) and Lis the set of pairs such as (i, j)∈Lif after the execution of statement i, statement jcan be executed. We denote with in(i) and out(i) the in-degree of the node iand the out-degree of the node i, respectively. In this graph there is only one node with entry degree zero which is denoted by i0,in(i0) = 0. This is the initial node of the graph, it represents the first statement of the program. There is also a special node i∗∈Iwith out-degree zero out(i∗) = 0, it represents the end of the program. We denote with VPthe set of variables of the program P. Each variable vi∈VPcan take values in a particular domain Diwith i= 1,...,|VP|. There is a special variable pc ∈VPthat is the program counter, it takes values from the set I. A state ρof the program Pis an application that maps variables to domains: ρ:VP→ |VP| [ i=1 Di(2.1) vi7→ ρ(vi)∈Di(2.2) We say that a state ρis an end state if ρ(pc) = i∗and ρis an initial state if ρ(pc) = i0. Let εp denote the set of all possible states of a program P. We assume the existence of a state converter Sp:εp9εp. This function maps each state ρto the state ρ′obtained after executing statement ρ(pc). An execution of a program Pwith initial state ρ, denoted with ExecP(ρ), is a sequence of states {ρn}where ρ=ρ1and for all i≥1, then ρi+1 =SP(ρi). Each execution {ρn}of the program Pdetermines a path in the control flow graph Gp. This path is formed by a succession of nodes {sn}where each element si∈Iis defined as si=ρi(pc). Let P rojP(ρn) denote the sequence of nodes {sn}determined by the sequence of states {ρn}, that is the projection of the execution in the control flow graph. We denote with StaP({sn}) the set of elements in Ithat are part of the sequence {sn}. Finally, a test datum for a program Pis the initial state of the program and a test suite is a set of test data. Definition 2.2.1 (Statement Coverage).Given a test data set Tfor a program P, we define the statement coverage of T,covStaP(T), as the ratio between the number of statements executed in the executions of the program with initial states given by Tand the total number of statements in the program, that is, covStaP(T) = |Sρ∈TStaP(P rojP(ExecP(ρ)))/{i∗}| |I/{i∗}| (2.3) Now, we can define the Statement Coverage adequacy criterion, which establish that a set of test data Tfor a program Pis adequate when covStaP(T) = 1. Conditional statements (if-then, switch, for, and while) are characterized in the control flow graph by having an out-degree greater than one. We call CCFPto the set of nodes of the control flow graph that represents this kind of statements, that is, CCFP={i∈I|out(i)>1}. An arc of the control flow graph (i, j) is a branch of the program Pif the tail of the arc belongs to the set CCFP. We denote with BPthe set of branches of the program P, i.e.,
CHAPTER 2. FUNDAMENTALS OF SOFTWARE TESTING 13 BP={(i, j)∈L|out(i)>1},(2.4) and with BR({sn}) the set of branches that appear implicitly in the sequence of nodes {sn}: BR({sn}) = {(i, j)∈BP|∃k≥1, i =sk∧j=sk+1}.(2.5) Definition 2.2.2 (Branch Coverage).Given a test data set Tfor a program P, we define the branch coverage of T,covBrP(T), as the ratio between the number of branches taken in the executions of the program with initial states given by Tand the total number of branches in the program, that is, covBrP(T) = |Sρ∈TBRP(ProjP(ExecP(ρ)))| |BP|(2.6) Therefore, the Branch Coverage adequacy criterion establish that a test data set Tfor a program Pis adequate when covBr(T) = 1. Finally, we remark a well-known proposition in the test data generation domain, that is, Proposition 2.2.3. Let Pbe a program and Ta test data set for P. If covBrP(T) = 1 then covStaP(T) = 1. A total branch coverage implies a total statement coverage2. Before we can enunciate the test data generation problem as an optimization problem, we need to formally define an optimization problem. Assuming, without loss of generality, a minimization case, the formal definition of an optimization problem is as follows: Definition 2.2.4 (Optimization problem).An optimization problem is defined as a pair (S, f), where S6=∅is called the solution space (or search space), and fis a function named objective function or fitness function, defined as f:S→R. Solving an optimization problem consists in finding a solution x∗∈Ssuch that: f(x∗)≤f(x),∀x∈S . (2.7) Note that assuming either maximization or minimization does not restrict the generality of the results, since an equivalence can be made between the two cases in the following manner [22,88]: max{f(x)|x∈S} ≡ min{−f(x)|x∈S}.(2.8) Depending on the domain Sbelongs to, we can speak of binary (S⊆B∗), integer (S⊆Z∗), continuous (S⊆R∗), or heterogeneous optimization problems (S⊆(B∪Z∪R)∗). After defining the most important concepts, we formalize the test data generation problem as follows. Definition 2.2.5 (Test data generation problem).Given a program P, the test data generation problem consist in finding a test data set Twhich maximizes covBrP(T). Consequently, a solution3 for this problem is the data set T. 2The proof of this proposition is found in [45]. 3In the testing field this solution is also called test suite.
20 2.4. FUNCTIONAL TESTING PROBLEMS ADDRESSED IN THIS THESIS Definition 2.4.4 (Pairwise Test Data Generation Problem).Given a CTM model M, the combinatorial test data generation problem consists in finding a test data set T which maximizes covPw(T). In order to define the Prioritized Pairwise Test Data Generation problem, we first detail how the priorities are assigned to classification tree elements. These priorities are also called weights. The higher the weight, the higher importance of the element. These weights can be used to guide the test data generation in order to cover first the most important values. Once we have assigned weights to each value (class), we need to define weights for the pair of classes. Definition 2.4.5 (Prioritized Valid Pair).Given a valid pair vp = (ci, cj)with weighted values (ci.w, cj.w), a prioritized valid pair is defined by a couple (vp, wp)where the pair weight wp = ci.w ∗cj.w. We need to define a measure of the quality of a test suite in order to decide which test suite is the best one. We use here a coverage measure which is based on the weights of the class pairs covered. Definition 2.4.6 (Prioritized Test Datum).Aprioritized test datum is a tuple (Q, w), where Q represent a valid test datum, and w its weight. Let VT be the set of all valid pairs in Q, w=Pv∈V T v.w, that is the sum of all valid pairs of the test datum Q. Definition 2.4.7 (Prioritized Test Suite).Aprioritized test suite is a tuple (S, w), where TS is a set of valid test data, and w its weight. Let VTS be the set of all test data in TS, w=Pt∈V T S t.w, that is the sum of the weight of all tests in the test suite. Definition 2.4.8 (Prioritized Pairwise coverage).Given a prioritized test suite PTS for a model M, we define the prioritized pairwise coverage of PTS, covPPw(PTS), as the ratio between the weight value of the test suite PTS and the total weight value of all coverable pairs extracted from all test data generated from the model M. Definition 2.4.9 (The Prioritized Pairwise Test Data Generation Problem).Given a CTM model M, the prioritized combinatorial test data generation problem consists in finding a prioritized test suite PTS which maximizes covPPw(PTS). 2.4.2 Test Sequence Generation Problem with Extended Classification Tree Method The Classification Tree defined above can be used to design test data in isolation. However, the test object can have operations related to transitions between classes in the classification tree and executing these transitions is the only way we can reach a given state (test datum) of the object. Let us continue with the video game example to illustrate new concepts. Imagine we need to execute some code when the user changes the state of the object from starting game to running game. These operations can be modeled by extending the classification tree method with transitions between classes (see Figure 2.3). In a real-world example, these transitions come from the semantics of the software object. We also assume that each classification has a default class that we highlight in the graphical representation by underlining its name. This extension of the classification tree can be seen as a hierarchical concurrent state machine (HCSM) or statechart [94] where classes match states, and classifications match orthogonal regions.
CHAPTER 2. FUNDAMENTALS OF SOFTWARE TESTING 21 Figure 2.3: Video game ECTM example. When the transition information is available we are also interested in covering all the possible transitions in the system. In this case, sequences of test data play a main role rather than the isolated test data. In effect, an isolated test datum does not describe which transitions were executed to get that test datum and, thus, does not determine the transitions executed. For this reason, our goal in this work is to provide test suites composed of sequences of test data that cover not only all the possible classes in the classification tree but also all the transitions by using the minimal number of total test data. In addition to the constraints defined by the classification-classes hierarchy, in the Test Sequence Generation Problem (TSGP) we take dependency rules into account. These are constraints between single test steps i.e., restrictions on the transitions between classes. Within each test sequence, dependency rules must not be violated. Dealing with dependency rules is important since the testing of several states could be combined, resulting in shorter test sequences. In this way, we need fewer amount of resources to test all functionality. In the following we formally define the extension of the CTM (ECTM). Our approach for test sequence generation is based on an idea proposed by Conrad [54], who suggests the interpretation of classification trees as parallel finite state machines. However, we need to extend Conrad’s approach to interpret refined classes of the classification tree. This concept is similar to the refinements of states in UML statecharts. Our approach can be seen as a statechart, because we have concurrent states and we have added hierarchies to the model. The ECTM model can be totally defined by a tuple of four elements, extending the definition of CTM that we made previously (in Section 2.4.1) by adding a set of allowed transitions T: ECT M = (C, V, w, T ),(2.11) where Cis the set of Classes, Vis the set of Classifications, wis a word of the language L(G) generated by the grammar Gand Tis the set of allowed transitions between the classes T⊆C×C. We will use either the notation cs→cdor (cs, cd) to represent a transition between classes csand cd.
22 2.4. FUNCTIONAL TESTING PROBLEMS ADDRESSED IN THIS THESIS As an illustration, the ECTM model shown in Figure 2.3 can be defined by the following quadruple: ECT MEx1= ({V ideoGame, startingGame, runningGame, startup, controlling, gameOver, running, paused}, {Game, Playing, Pause}, w, {startingGame →runningGame, startup →controlling, controlling →gameOver, running →paused, paused →running}) The transition set in an ECTM model can contain any transition except those connecting classes of sibling classifications. Formally, any ECTM model must fulfill: ∀v1, v2∈V, v1∈Siblings(v2) =⇒ ∀c1∈Descendants(v1)∩C, ∀c2∈Descendants(v2)∩C, (c1, c2)/∈T. In order to build a sequence of test data we must define how to navigate from a source test datum Q1to a destination test datum Q2. The initial test datum in a sequence, Qini, is composed by the initial classes of the children classifications under the root of the tree and all their ascendants. Given a transition t= (cs, cd)∈T, the general rule to transit from Q1to Q2is as follows. We must find the deepest common classification of csand cd, say va. If there exists another common classification, then that classification must be an ascendant of the deepest one va. Once we have found va, we must remove from the source test datum Q1all the classes under va, in other words, any class that is descendant of va. Next, we have to add cdand its ascendants which are children of va, and add the initial classes of the classifications of these ascendants, except the siblings of cd. If cdis a refined class, then the initial classes of all classifications of cdand their descendants are also added in order to build a valid test datum. Let us formally define all this procedure. Let Q1be the source test datum, first we must remove from Q1the descendants of va: Q′=Q1−Descendants(va) where {cs, cd} ⊆ Descendants(va) and does not exist vd∈Descendants(va) such that {cs, cd} ⊆ Descendants(vd). Then, we must add some classes to Q′in order to transit to the new test datum Q2. In order to do this, let us define the function Incomplete(Q) as follows: Incomplete(Q) = {v∈V|Parent(v)∈Q∧ ∀c′∈Children(v), c′/∈Q}. Then, we compute Q2iteratively using the next pseudocode: Q2=Q′∪(Ascendants(cd)∩Descendants(va)) ∩C while Incomplete(Q2)6=∅do Q2=Q2∪InitialClass(Incomplete(Q2)) end while We define a test sequence as a sequence of test data T S = (Qi) with 1 ≤i≤n, where the first test datum is the initial one, that is, Q1=Qini. In this work we have chosen two coverage criteria: class and transition coverage. The class coverage criterion consists of covering all the classes of
CHAPTER 2. FUNDAMENTALS OF SOFTWARE TESTING 23 the classification tree with the generated test suite. The transition coverage requires covering all the transitions available between the classes of the ECTM. In our running example of Figure 2.3, we have to cover eight classes for total class coverage (VideoGame, startingGame, runningGame, startup, controlling, gameOver, running, and paused), and five transitions to obtain full transition coverage ({startingGame →runningGame,startup →controlling,controlling →gameOver, running →paused,paused →running})). We formally define the coverage criteria used in this problem as follows: ClassCoverage(sol) = n S i=1 Qi |C|(2.12) T ransitionCoverage(sol) = n−1 S i=1 T ransitions(Qi, Qi+1) |T|(2.13) where T ransitions is defined as: T ransitions(Qi, Qi+1) = (Qi×Qi+1)∩T Given an ECTM model, the objective of the TSGP is the generation of a set of test sequences that maximizes any of the coverage criterion (one each time) defined above (class or transition). Definition 2.4.10 (Test Sequence Generation Problem).Given an ECTM model M, the objective of the TSGP is the generation of a test sequence T S that maximizes any of the coverage criterion (one each time) defined above (ClassCoverage(T S)or T ransitionCoverage(T S)). 2.4.3 Pairwise Test Data Generation Problem in SPL ASoftware Product Line (SPL) is a family of related software systems, which provide different feature combinations [175]. The effective management and realization of variability – the capacity of software artifacts to vary – is crucial to reap the benefits of SPLs such as increased software reuse, faster product customization, and reduced time to market. As we stated before, there is no a common representation for combinatorial testing problem, so in this work we represent SPL with feature models. Feature models have become the de facto standard for modelling the common and variable features of an SPL and their relationships collectively forming a tree-like structure. The nodes of the tree are the features which are depicted as labelled boxes, and the edges represent the relationships among them. Feature models denote the set of feature combinations that the products of an SPL can have [115]. Figure 2.4 shows the feature model of our running example for SPLs, the Graph Product Line (GPL) [134], a standard SPL of basic graph algorithms that has been widely used as a case study in the product line community. In GPL, a product is a collection of algorithms applied to directed or undirected graphs. In a feature model, each feature (except the root) has one parent feature and can have a set of child features. A child feature can only be included in a feature combination of a valid product if its parent is included as well. The root feature is always included. There are four kinds of feature relationships: •Mandatory features are selected whenever their respective parent feature is selected. They are depicted with a filled circle. For example, features Driver and Algorithms,
24 2.4. FUNCTIONAL TESTING PROBLEMS ADDRESSED IN THIS THESIS Figure 2.4: Graph Product Line feature model. •Optional features may or may not be selected if their respective parent feature is selected. An example is feature Search, •Exclusive-or relations indicate that exactly one of the features in the exclusive-or group must be selected whenever the parent feature is selected. They are depicted as empty arcs crossing over a set of lines connecting a parent feature with its child features. For instance, if feature Search is selected, then either feature DFS or feature BFS must be selected, •Inclusive-or relations indicate that at least one of the features in the inclusive-or group must be selected if the parent is selected. They are depicted as filled arcs crossing over a set of lines connecting a parent feature with its child features. As an example, when feature Algorithms is selected then at least one of the features Num,CC,SCC,Cycle,Shortest,Prim, and Kruskal must be selected. Besides the parent-child relations, features can also relate across different branches of the feature model with the so called Cross-Tree Constraints (CTC). Figure 2.4 shows the CTCs of our feature model in textual form. For instance, Num requires Search means that whenever feature Num is selected, feature Search must also be selected. These constraints as well as those implied by the hierarchical relations between features are usually expressed and checked using propositional logic, for further details refer to [29]. Combinatorial Interaction Testing (CIT) is a testing approach that constructs samples to drive the systematic testing of software system configurations [52, 163]. When applied to SPL testing, the idea is to select a representative subset of products where interaction errors are more likely to occur rather than testing the complete product family [52]. In the following we provide the basic terminology of CIT for SPLs4. Definition 2.4.11 (Feature list).Afeature list FL is the list of features in a feature model. 4Definitions based on [29] and [110].
CHAPTER 2. FUNDAMENTALS OF SOFTWARE TESTING 25 Table 2.1: Sample feature sets of GPL feature model. Prod G D B GT DI U W S BF DF A N C SC CY P K SH p0 X X X X X X X X p1 X X X X X X X X X X X X X X p2 X X X X X X X X X X X p3 X X X X X X X Definition 2.4.12 (Feature set).Afeature set fs is a pair (sel, sel)where the first and second components are respectively the set of selected and not-selected features of a SPL product. Let FL be a feature list, thus sel, sel ⊆FL,sel ∩sel =∅, and sel ∪sel =F L. Wherever unambiguous we use the term product as a synonym of feature set. Definition 2.4.13 (Valid feature set).Afeature set fs is valid with respect to a feature model fm iff fs.sel and fs.sel do not violate any constraints described by fm. The set of all valid feature sets represented by fm is denoted as FSfm. An example of valid feature set fs1 is one that computes the algorithm Number, on Directed graphs using BFS search. Thus, the selected features are fs1.sel={GPL, Driver, Benchmark, GraphType, Directed, Search, BFS, Algorithms, Number}5. Consider now another feature set fs2 with selected features BFS and Cycle, meaning {BFS,Cycle} ⊆ fs2.sel. This feature set is invalid because these two features violate the CTC that establishes that whenever Cycle feature is selected then feature DFS must be selected, i.e. Cycle requires DFS. In our running example GPL, the feature model denotes 73 distinct feature sets. Some of them are depicted in Table 2.1, where for any given feature set its selected features are ticked (X) and its unselected features are empty. In this table, we use as column labels the shortest distinguishable prefix of the feature names (e.g. G for feature GPL). The focus of our study is pairwise testing, thus our concern is on the combinations between two features. The coming definitions are consequently presented with that perspective; however, the generalization to combinations of any number of features is straightforward. Definition 2.4.14 (Pair6).Apair ps is a 2-tuple (sel,sel) involving two features from a feature list FL, that is, ps.sel ∪ps.sel ⊆FL ∧ps.sel ∩ps.sel =∅ ∧ |ps.sel ∪ps.sel|= 2. We say pair ps is covered by feature set fs iff ps.sel ⊆fs.sel ∧ps.sel ⊆fs.sel. Definition 2.4.15 (Valid pair).Apair ps is valid in a feature model fm if there exists a valid feature set fs that covers ps. The set of all valid pairs of a feature model fm is denoted with V PSfm. Let us illustrate pairwise testing with the GPL running example. Some samples of pairs are: GPL and Search selected, Weight and Undirected not selected, CC not selected and Driver selected. An example of invalid pair, i.e. not denoted by the feature model, is features Directed and Undirected both selected. Notice that this pair is not valid because they are part of an exclusive-or relation. Definition 2.4.16 (Pairwise test suite).Apairwise test suite pts for a feature model fm is a set of valid feature sets of fm. A pairwise test suite is complete if it covers all the valid pairs in V P Sfm, that is: {fs|∀ps ∈V PSfm ⇒ ∃fs ∈FSfm such that fs covers ps}. 5Unselected features omitted for brevity. 6This definition of pair differs from the mathematical definition of the same term and is specific for SPLs. In particular, it adds more constraints to the traditional definition of pair.
26 2.4. FUNCTIONAL TESTING PROBLEMS ADDRESSED IN THIS THESIS In GPL there is a total of 418 valid pairs, so a complete pairwise test suite for GPL must have all these pairs covered by at least one feature set. Henceforth, because of our focus and for sake of brevity we will refer to pairwise test suites simply as test suites. In the following we provide a formal definition of the priority scheme based on the sketched description provided in [111]. Definition 2.4.17 (Prioritized product).Aprioritized product pp is a 2-tuple (fs, w), where fs represents a valid feature set in feature model fm and w∈Rrepresents its weight. Let ppiand ppj be two prioritized products. We say that ppihas higher priority than ppjfor test-suite generation iff ppi’s weight is greater than ppj’s weight, that is ppi.w >ppj.w. As an example, let us say that we would like to prioritize product p0 with a weight of 17. This would be denoted as pp0=(p1,17). Definition 2.4.18 (Pairwise configuration).Apairwise configuration pc is a 2-tuple (sel, sel) representing a partially configured product, defining the selection of 2 features of feature list FL, i.e. pc.sel ∪pc.sel ⊆FL ∧pc.sel ∩pc.sel =∅ ∧ |pc.sel ∪pc.sel|= 2. We say a pairwise configuration pc is covered by feature set fs iff pc.sel ⊆fs.sel ∧pc.sel ⊆fs.sel. Consider for example the pairwise configuration that indicates that feature Driver is selected while feature Undirected is deselected pc1=({Driver},{Undirected}). Notice that pc1 is covered by products p2 and p3 of Table 2.1. Another example is pairwise configuration pc2=({Directed, Undirected},{})with features Directed and Undirected selected and no feature unselected. This configuration is covered by products p2 and p3 of Table 2.1. Definition 2.4.19 (Weighted pairwise configuration).Aweighted pairwise configuration wpc is a 2-tuple (pc,w) where pc is a pairwise configuration and w ∈Rrepresents its weight computed as follows. Let PP be a set of prioritized products and PPpc be a subset, PPpc ⊆PP, such that PPpc contains all prioritized products in PP that cover pc of wpc, i.e. PPpc ={pp ∈PP|pp.fs covers wpc.pc}. Then w=Pp∈P Ppc p.w Let us consider the following set of prioritized products from Table 2.1. Let PP={(p0,17), (p1,15), (p2,5), (p3,3)}with ppi= (fsi,wi), and assume that the remaining 69 products of our feature model in Figure 2.4 (i.e. 73 minus 4 shown in the table) have priority weight values of 0. The weight of pairwise configuration pc1=({Directed},{Undirected})is then wpc1.w =pp2.w +pp3.w = 5 + 3 = 8, that is, the summation of the weights of the products whose feature sets cover pc1 with weight greater than zero, namely p2 and p3. Similarly, the weight for pc2 (Directed and Undirected selected) is wpc2.w =pp0.w +pp1.w = 17 + 15 = 32. Definition 2.4.20 (Prioritized pairwise covering array).Aprioritized pairwise covering array ppCA for a feature model fm and a set of weighted pairwise configurations WPC is a set of valid feature sets FS that covers all weighted pairwise configurations in WPC whose weight is greater than zero: ∀wpc ∈W P C (wpc.w > 0⇒ ∃fs ∈ppCA such that fs covers wpc.pc). The optimization problem we are interested in consists of finding a prioritized pairwise covering array,ppCA, with the minimum number of feature sets, that is: find ppCA with minimum |ppCA|. What makes the problem far from trivial is the constraints imposed to ppCA by Definition 2.4.20. 2.4.4 Multi-Objective Test Data Generation Problem in SPL Most approaches for SPL pairwise testing have focused on achieving full coverage of all pairwise feature combinations with the minimum number of products to test. Though useful in many
CHAPTER 2. FUNDAMENTALS OF SOFTWARE TESTING 27 contexts, this single-objective perspective does not reflect the prevailing scenario where software engineers do face trade-offs between the objectives of maximizing the coverage or minimizing the number of products to test. In contrast and to address this need, our work proposes a classical multi-objective formalisation where both objectives are equally important. In Section 2.2.2 we have defined the most important concepts related to multi-objective optimisation, then we only highlight the particularities of the Multi-Objective Test Data Generation Problem in SPL, that is, pairwise testing for two objectives. The decision space or solution space is the set of possible solutions to an optimization problem, in our context, it corresponds to the set of all possible sets of valid feature sets represented by a feature model fm, denoted as DSfm =P(FSfm). A decision vector is an element of the decision space, that is x∈DSfm. In our context we consider two objective functions: •Coverage function. We want to maximize the number of pairs covered by a test suite. For simplicity, we use the alternative of minimizing the number of pairs not covered which is defined as follows: ffm 1:DSfm →N,ffm 1(x) = |V PSfm\covers(x)|, where covers computes the pairs covered by the feature sets of test suite x. •Test suite size function. We want to minimize the number of feature sets in the test suite. We define this function as follows: ffm 2:DSfm →N,ffm 2(x) = |x|. Definition 2.4.21 (Multi-Objective SPL pairwise testing problem).Given a feature model fm, a multi-objective pairwise SPL testing problem consists in finding a set of non-dominated solutions X∗⊂DSfm such that it minimizes the objective functions ffm 1and ffm 2. 2.5 Conclusions In this chapter we discuss the fundamentals of software testing from its beginning. Testing is not a new concept at all since it was already used by the Romans to assess the quality of metals. Nevertheless it is still valid since we want to assess the quality of software. In this chapter we formally defined actual testing problems that are addressed in this PhD dissertation. First, we defined the problems related to structural testing: Test Data Generation Problem and Multiobjective Test Data Generation Problem. We are aware that there is a negligible cost not considered in general, the oracle cost. For this reason we have taken into account the quality of the test suite and the oracle cost in the formulation of problems. Second, we define the problems related to functional testing. We can group the addressed problems in those related to Classification Tree Method, that are the Prioritized Pairwise Test Data Generation Problem and the Test Sequence Generation Problem with Extended Classification Tree Method. The other group are the problems related to Software Product Lines, that are the Pairwise Test Data Generation Problem with and without priorities and the Multi-Objective Test Data Generation Problem in SPL. We want to claim the usefulness of this chapter to provide the reader with the exact version of the problems we are going to solve throughout this PhD thesis.
28 2.5. CONCLUSIONS
Chapter 3 Fundamentals of Metaheuristics A heuristic is a simple and intuitive technique that employs a practical methodology to produce close to optimal solutions for a given complex problem using specific information of the problem, not guaranteed to be optimal or perfect, but sufficient for the immediate goals [155]. When finding an optimal solution is impossible or impractical, heuristic methods can be used to speed up the process of finding a satisfactory solution. Heuristics can be seen as mental shortcuts that ease the cognitive load of making a decision. Heuristics are adapted to the problem at hand and they try to take full advantage of the particularities of the problem. However, they can get trapped in a local optimum and thus fail, in general, to obtain the global optimum solution. In addition, they have the drawback of being problem-specific techniques, thus a good heuristic for some given problem will help little when solving a different problem. Consequently, a more general-purpose technique was proposed: Metaheuristics [116]. Metaheuristics, in contrast, are more problem-independent techniques. They are generally conceived as high level heuristics able to employ heuristics methods by guiding them over the search space in order to exploit its best capabilities to achieve better solutions, especially with incomplete or imperfect information or limited computation capacity. The main advantage with respect to a simple heuristic is that they have mechanisms to avoid getting trapped in local optima. This chapter serves as a presentation of metaheuristics, the main techniques used to solve the different variants of the automatic test data generation problem tackled in this PhD thesis. We formally define what is a metaheuristic, we classify the main metaheuristics and we present them for their latter detailed description in the next chapter. Then, we explain the multi-objective paradigm, used when we are interested in optimizing more than one objective at the same time. Finally, we describe the quality indicators and the statistical methods used to measure the quality of the solutions and the practical importance of the results of this research. 3.1 Formal Definition In a first approach, the techniques can be classified into Exact and Approximate. Exact techniques, which are based on the mathematical finding of the optimal solution, or an exhaustive search until the optimum is found, guarantee the optimality of the obtained solution. However, these techniques present some drawbacks. The time they require, though bounded, may be very large, especially for NP-hard problems. Furthermore, it is not always possible to find such an exact technique for every problem. This makes exact techniques not to be a good choice in many occasions, since both their 29
36 3.3. A METHODOLOGY FOR EVALUATING RESULTS foraging for food, prey evading, or colony re-location. The information is typically stored throughout the participating homogeneous agents, or is stored or communicated in the environment itself such as through the use of pheromones in ants, dancing in bees, and proximity in fish and birds. Swarm Intelligence systems are typically made up of a population of simple agents (an entity capable of performing/executing certain operations) interacting locally with one another and with their environment. Although there is normally no centralized control structure dictating how individual agents should behave, local interactions between such agents often lead to the emergence of global behavior. The paradigm consists of two dominant sub-fields: Ant Colony Optimization and Particle Swarm Optimization. We use ACO which will be detailed in next chapter. 3.3 A Methodology for Evaluating Results Metaheuristics are non-deterministic techniques, hence different executions of the same algorithm over the same problem instance can produce different results. This can cause inconveniences to researchers at the time of evaluating and assessing those results, and when comparing different algorithms. Although there are works that tackle the theoretical analysis of many heuristic methods and problems [92], this kind of theoretical analysis still involves a great deal of complexity, therefore the most commonly adopted approach is to establish the comparisons on the basis of empirical data. For this, some indicators have to be defined that enable such comparisons. In a wide sense, there are two kinds of indicators. On the one hand, there are indicators that measure the quality of the obtained solutions. Since both mono-objective and multi-objective problems are solved in this PhD dissertation, specific indicators have to be defined for both approaches. On the other hand, there are indicators that measure the performance of the algorithms in terms of their required computation time or the amount of resources they use. Although the following discussion comments the two types of indicator separately, they are closely related and are often used together for the evaluation of metaheuristics, since the purpose of the latter is twofold: finding high quality solutions within a reasonable time. Once the indicators have been established, a given number of unrelated or independent executions of the experimental configuration (algorithmic configuration and problem instance) are required to obtain statistically consistent results. A value of 30 executions is a commonly adopted and accepted minimum. The mere use of mean value and standard deviation, albeit quite frequent in the literature, is not sufficient and can lead to wrong conclusions. Thus, a global statistical analysis should be applied on the results before stating whether the observed differences are meaningful, and not just the result of the inherent randomness of the techniques. This section contains the discussion of the indicators used in the first place (for quality and performance), then the statistical tests that are used to assess the significance of the results. 3.3.1 Quality Indicators Quality indicators or metrics are of paramount importance when evaluating a metaheuristic. They are defined in many ways depending on whether the optimal solution is known or unknown for the problem at hand (in a benchmark or a classic literature problem the optimum is often known, but for real problems this is hardly the case). As stated before, there are specific indicators for evaluating the solutions of mono-objective and multi-objective problems.
CHAPTER 3. FUNDAMENTALS OF METAHEURISTICS 37 Mono-objective Indicators When the optimum is known beforehand, a simple and intuitive quality indicator for the metaheuristic is the expectancy of actually finding the optimum, or hit rate. This indicator is defined as the ratio or percentage of the number of executions in which the optimum is found over the total number of independent executions that have been performed. Unfortunately, knowing the optimum is not the common case for real problems or, even if they were known, sometimes they are so difficult to obtain that no execution of the experiment achieves it; in fact, experiments with metaheuristics are normally tailored to finish after a given computational effort has been spent (like visiting a maximum number of points of the search space, or running for a given time). For these cases in which the optimum is not known in advance, or that the hit rate cannot be used, other indicators are used. The most popular are the mean and median of the best fitness value found in each independent execution. In general, other statistical data are required, such as the standard deviation, and a corresponding statistical analysis, in order to assess the statistical confidence on the observed results, should be performed. In problems where the optimum is known, both metrics can be combined to offer a wider picture: for instance, a low hit rate with a low mean value speaks for the robustness of the method, and could be preferred over a higher hit rate but with higher median (assuming minimization). Multi-objective Indicators In theory, a Pareto front could contain a large number of points. In practice, a usable approximate solution will only contain a limited number of them; thus, an important goal is that solutions should be as close as possible to the exact Pareto front and uniformly spread, otherwise, they would not be very useful to the decision maker. Besides, closeness to the Pareto front ensures that we are dealing with optimal solutions, while a uniform spread of the solutions means that we have made a good exploration of the objective space and no regions are left unexplored. There exist some well-known density estimators in the literature [50]: niching, adaptive grid, crowding, and the k-nearest neighbour distance. Three different issues are normally considered for assessing the quality of the results computed by a multi-objective optimization algorithm [234]: 1. To minimize the distance of the computed solution set by the proposed algorithm to the optimal Pareto front (convergence towards the optimal Pareto front). 2. To maximize the spread of solutions found, so that we can have a distribution as smooth and uniform as possible (diversity). 3. To maximize the number of elements of the Pareto optimal set found. Figure 3.2 depicts these issues of convergence and diversity. The left front (a) depicts an example of good convergence and bad diversity: the approximation set contains Pareto optimal solutions but there are some unexplored regions of the objective space. The approximation set depicted on the right (b) illustrates poor convergence but good diversity: it has a diverse set of solutions but they are not Pareto optimal. Finally, the lowermost front (c) depicts an approximation front with both good convergence and diversity. A number of quality indicators have been proposed in the literature trying to capture the three issues indicated above, but for the moment, there is not a single metric which captures all of them. Consequently, researchers should use more than one to measure different aspects of the
38 3.3. A METHODOLOGY FOR EVALUATING RESULTS 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 1.2 1.4 f1 f2 Approximation Set Optimal Pareto Front (a) good convergence and bad diversity. 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 1.2 1.4 f1 f2 Approximation Set Optimal Pareto Front (b) bad convergence and good diversity. 0 0.2 0.4 0.6 0.8 1 0 0.2 0.4 0.6 0.8 1 f1 f2 Approximation Set Optimal Pareto Front (c) good convergence and good diversity. Figure 3.2: Examples of Pareto fronts with different behavior of convergence and diversity. solutions generated by the multi-objective techniques. Among them, we can distinguish between Pareto compliant and non Pareto compliant indicators [123]. Given two Pareto fronts, A and B, if A dominates B, the value of a Pareto compliant quality indicator is higher for A than for B; meanwhile, this condition is not fulfilled by the non–compliant indicators. Thus, the use of Pareto compliant indicators should be preferable. To apply these quality indicators, it is usually necessary to know the optimal Pareto front. However, the location of the optimal front is usually unknown. Therefore, the front composed of all the non–dominated solutions computed by all analyzed approaches is used to obtain a reference Pareto front. Many quality indicators have proposed in the literature. Next, we highlight the advantages and disadvantages of some of the most common ones: •Number of Pareto optimal solutions. This non–compliant indicator is very simple, it computes the number of solutions that are included in the optimal Pareto front. Its main advantage lies in the fact that it is very easy to compute. In contrast, the disadvantages are the lack of information about the diversity of solutions and the requirement of knowing the optimal Pareto front.
CHAPTER 3. FUNDAMENTALS OF METAHEURISTICS 39 Figure 3.3: Example of hypervolume. •Hypervolume (HV) [236]. This is a very popular indicator that calculates the volume (in the objective space) covered by members of a non-dominated set of solutions Q(the region enclosed into the discontinuous line in Figure 3.3, Q={A, B, C}) for problems where all objectives are to be minimized. Mathematically, for each solution i∈Q, a hypercube vi is constructed with a reference point Wand the solution ias the diagonal corners of the hypercube. The reference point can simply be found by constructing a vector of the worst objective function values. Thereafter, a union of all hypercubes is found and its hypervolume (HV) is calculated: HV = volume |Q| [ i=1 vi .(3.6) We apply this metric after a normalization of the objective function values to the range [0..1]. A Pareto front with a higher HV than another one could be due to: some solutions in the better front dominate solutions in the other, or, solutions in the better front are more widely distributed than in the other. Since both properties are considered to be good, algorithms with larger values of HV are considered to be desirable. To apply this quality indicator, it is usually necessary to know the optimal Pareto front (from normalization purposes). Of course, typically, we do not know the location of the optimal front. Therefore, we employ as areference Pareto optimal front the front composed of all the non-dominated solutions out of all the executions carried out (i.e., the best front known until now). The main advantages of the hypervolume are that it considers the convergence as well as the diversity of the solutions, and it doesn’t require the optimal Pareto front. A drawback is that it depends on the reference point selected. Different reference points produce different results. This could be critical to compare the results with existing approaches in the literature. •Spread (SD) [57]. It is a diversity non–compliant quality indicator that measures the distribution of individuals over the non-dominated region. This measure is based on the distance between solutions, so Pareto fronts with a smaller value of Spread are more desirable.
40 3.3. A METHODOLOGY FOR EVALUATING RESULTS It takes a zero value for an ideal distribution, denoting a perfect spread of the solutions in the Pareto front. It is defined as follows: ∆ = df+dl+PN−1 i=1 |di−d| df+dl+ (N−1)d,(3.7) where diis the Euclidean distance between consecutive solutions, dis the mean of these distances, and dfand dlare the Euclidean distances of the extreme solutions of the optimal Pareto front in the objective space. The main advantage of this measure is that it summarizes the diversity of a Pareto front in one single scalar value. The main disadvantage is that it does not consider the other quality aspect, i.e., the solution set could be very well distributed, but the solutions could be far from the optimal Pareto front. Other quality indicators should be used to complement the Spread. •Generational Distance (GD) [207]. The generational distance is a non–compliant indicator. It measures how far the elements in the approximated Pareto front are from those in the optimal Pareto front. It considers the distance of the approximated Pareto front obtained to the reference front. Pareto fronts with a smaller value of GD are more desirable, so it takes a zero value for an ideal distribution where all the elements generated are in the reference front; It is defined as: GD =pPn i=1 d2 i n,(3.8) where nis the number of solutions in the approximation front and diis the Euclidean distance (measured in objective space) between each of these solutions and the nearest member in the optimal Pareto front. The advantages of the generational distance are the ease of understanding and calculation, and the possibility to use different kinds of distance functions. In contrast, it does not take into account the diversity of the solutions found, i.e., a front with only one solution in the optimal Pareto front, will obtain an ideal value of generational distance. •Epsilon (Multiplicative) [237]. This Pareto–compliant indicator measures, in one single scalar value, how badly approximated the worst approximated solution of the Pareto front is. The approximation quality of solutions is the ratio between the optimal value and the best value found. This notion is extended to the multi-objective paradigm, resulting in a unary version of the indicator if the optimal Pareto front is known, and a binary version when a reference front is used instead. An approximated Pareto front is an ǫ-approximation if for every point on the optimal Pareto front, the approximated Pareto front contains a point that is at least as good approximately (within a factor ǫ) in all objectives. More formally, given ~ z1= (z1 i, ..., z1 n) and ~ z2= (z2 i, ..., z2 n), where nis the number of objectives: Iǫ+(A) = infǫ∈R|∀ ~ z2∈ PF∗∃~ z1∈A:~ z1≺ǫ~ z2,(3.9) where, ~ z1≺ǫ~ z2if and only if ∀1≤i≤n:z1 i< ǫ ∗z2 i The main advantage of this quality indicator is that it allows us to compare the quality of solutions between different functions, different population sizes, and even different dimensions. In addition, it measures convergence of the algorithm, but it does not depend on a
CHAPTER 3. FUNDAMENTALS OF METAHEURISTICS 41 chosen reference point like the hypervolume. In contrast, its main disadvantage is that it only considers part of the front, namely the worst solution. The previous indicators have the advantage of summarizing an entire front into one single scalar value that allows the performance of different algorithms to be compared. However, from the point of view of a decision maker, knowing about a single number is not enough, because it gives no information about the shape of the front. In the related literature, the trade-off between the different objectives is usually presented by showing one of the approximated Pareto fronts obtained in one single run of a given algorithm. However, if the optimization algorithm used is stochastic there is no warranty that the same result is obtained after a new run of the algorithm. We need a way of representing the results of a multi-objective algorithm that allows us to observe the expected performance and its variability, in the same way as the average and the standard deviation are used in the single-objective case. For this reason, we use the concept of Empirical Attainment Function (EAF) [121]. Empirical Attainment Function: EAF is a function αfrom the objective space Rnto the interval [0,1] that estimates for each vector in the objective space the probability of being dominated by the approximated Pareto front of one single run of the multi-objective algorithm. Given the r approximated Pareto fronts obtained in the different runs, the EAF is defined as: α(z) = 1 r r X i=1 I(Ai {z}) (3.10) where Aiis the i-th approximated Pareto front obtained with the multi-objective algorithm and Iis an indicator function that takes value 1 when the predicate inside it is true, and 0 otherwise. The predicate Ai {z}means Aidominates solution z. Thanks to the attainment function, it is possible to define the concept of k%-attainment surface [121]. The attainment function α is a scalar field in Rnand the k%-attainment surface is the level curve with value k/100 for α. Informally, the 50%-attainment surface in the multi-objective domain is analogous to the median in the single-objective one. In a similar way, the 25%- and 75%-attainment surfaces can be used as the first and third “quartile fronts” and the region between them could be considered a kind of “interquartile region” (see Figure 3.4). The attainment surfaces provide an engineer with a tool for evaluating the variability of an algorithm for the problem at hand. The variability in the results of one multi-objective algorithm is not reduced to a scalar (as in the single-objective case), so the main disadvantage is the visualization of solution with more than three objectives [204]. Using attainment surfaces the engineer can analyze and explore this range of possibilities. From a practical point of view, this tool helps the engineer to decide the more suitable multi-objective algorithm for her/his requirements. 3.3.2 Statistical Analysis Procedure Metaheuristics are stochastic based algorithms, so we always need to perform a series of independent runs for each algorithm’s configuration in order to obtain a distribution of results and quality indicators. Typically, a value of 30 independent executions for each algorithm’s configuration is an accepted minimum. Once we have the results, we must compare the distributions by means of statistical tests, which are indispensable tools to validate and to provide confidence to our empirical analysis. A representation of the statistical procedure carried out in this PhD thesis, which is recommended by the scientific community [81,189], can be seen in Figure 3.5. First, we choose the kind
42 3.3. A METHODOLOGY FOR EVALUATING RESULTS f1 f2 75%-attainment surface 50%-attainment surface 25%-attainment surface Figure 3.4: Examples of attainment surfaces. of test to perform (non-parametric or parametric). To do so, we perform a Kolmogorov-Smirnov test to check whether the samples are distributed according to a normal distribution (Gaussian) or not. After this, the homoskedasticity (i.e., equality of variances) is then checked using the Levene test. If all distributions are normal and the Levene returns a positive value, then we use the parametric procedure. In this case, a t-test for comparing two distributions, and an ANOVA test for comparisons of three or more distributions. Figure 3.5: Statistical validation procedure for experimental results For non-parametric procedure, we use the Wiloxon test to check the significance of the differences between two distributions, and the KruskalWallis test for multiple comparisons. Notice that we use the Bonferroni correction for each particular comparison. If there are no statistical differences, the procedure finishes without rejecting the null hypothesis (equality of distributions). In this study, the tests have been set with a confidence level of 95% or 99%, meaning that statistical differences can be found in distributions when resulted tests are with a p-value<0.05 or p-value <0.001, respectively.
CHAPTER 3. FUNDAMENTALS OF METAHEURISTICS 43 In order to properly interpret the results of statistical tests, it is always advisable to report effect size measures. For that purpose, we have also used the non-parametric effect size measure b A12 statistic proposed by Vargha and Delaney [208]. It tells us how often, on average, one technique outperforms the other. It could be used to determine the probability of yielding higher performance by different algorithms. Given a performance measure M,ˆ A12 measures the probability that running algorithm Ayields higher Mvalues than running another algorithm B. If the two algorithms are equivalent, then ˆ A12 = 0.5. If ˆ A12 = 0.3 then one would obtain higher values for Mwith algorithm A, 30% of the time.
44 3.3. A METHODOLOGY FOR EVALUATING RESULTS
Chapter 4 Algorithms This chapter outlines the main metaheuristic techniques used throughout this PhD thesis. We focus in the particular description of algorithms and operators used to solve the different testing problems tackled here. The specific implementation details (like the operators for mutation or crossover) which are problem specific (or representation specific) are delayed to the corresponding chapters, where the application of the algorithms to solve the problems is discussed. The mono-objective techniques are described in Section 4.1, then the multi-objective techniques in Section 4.2. 4.1 Mono-objective Metaheuristics Used in this PhD Thesis The specific mono-objective algorithms used in this PhD dissertation are described in this section: Genetic Algorithm (Section 4.1.1), Evolutionary Strategy (Section 4.1.2) and Ant Colony Optimization (Section 4.1.3). 4.1.1 Genetic Algorithm Genetic Algorithms [88] belong to the family of EAs (Section 3.2.2). They appear for the first time as a widely recognized optimization method as a result of the work of John Holland in the early 70s, and particularly his 1975 book [106]. Our implementation of the genetic algorithm in this PhD thesis typically uses a ranking method for parent selection and elitist replacement for the next population, that is, the best individual of the current population is included in the next one. Should different operators or replacement policy is used, they will be explicitly described in the corresponding section. In Algorithm 1 we show the general scheme followed by an EA such as the Genetic Algorithm and the Evolutionary Strategy described in this chapter. Initially, the algorithm creates a population of µindividuals randomly or by using a seeding algorithm (Line 2). At each step, the algorithm applies stochastic operators such as selection, recombination, and mutation in order to compute a set of λdescendant individuals Q. The objective of the selection operator is to select some individuals from the population to which the other operators will be applied. In this work the q-tournament method is used. It randomly selects qindividuals from the population, then the best is selected as parent (Line 6). Notice that this method is applied twice to select both parents. The recombination operator generates two new individual from two parents by combining their solution components (Line 7). This operator is able to put together good solution components that are scattered in the population. On the other hand, 45
52 4.2. MULTI-OBJECTIVE METAHEURISTICS USED IN THIS PHD THESIS Algorithm 6 Pseudocode of PAES. 1: proc Input:(paes) //Algorithm parameters in ‘paes’ 2: archive ← ∅ 3: currentSolution ←createSolution(paes) // Creates an initial solution 4: while not termination condition() do 5: mutatedSolution←mutation(currentSolution) 6: evaluate fitness(mutatedSolution) 7: if isDominated(currentSolution, mutatedSolution) then 8: currentSolution ←mutatedSolution 9: else 10: if solutions are nondominated(currentSolution, mutatedSolution) then 11: insert(archive, mutatedSolution) 12: currentSolution ←select(paes, archive) 13: end if 14: end if 15: end while 16: end proc require tuning in order to know that the algorithm is being applied properly (e.g., population size, crossover probability, mutation probability). This technique is used in Chapters 7 and 9. 4.2.5 Random Multi-Objective Algorithm In this thesis dissertation we also use a random search multi-objective algorithm (RNDMulti). We want to check whether the metaheuristic algorithms are capable of outperform random search or not in our proposed testing problems. The pseudocode of the RNDMulti is presented in Algorithm 7. The final result of this random search is the set of all the non-dominated solutions found. This technique is used in Chapters 7 and 9. Algorithm 7 Pseudocode of RNDMulti. 1: proc 2: archive ← ∅ 3: currentSolution ←create solution() // Creates an initial solution 4: while not termination condition() do 5: newSolution ←create solution() 6: insert(archive, newSolution) 7: end while 8: extractParetoFront(archive) 9: end proc
CHAPTER 4. ALGORITHMS 53
54 4.2. MULTI-OBJECTIVE METAHEURISTICS USED IN THIS PHD THESIS
Part II Structural Testing 55
Chapter 5 Test Data Generation in Object-Oriented Software 5.1 Introduction Most of the work found in the literature related to automatic software testing focuses on procedural languages and programs. However, most of the software developed nowadays is object-oriented. Object-Oriented (OO) languages are considered an evolution of procedural languages and they allow developers to design and implement really large software applications more easily than using procedural languages, thanks to their ability for abstracting and modularizing software components. Most of the ideas used for testing procedural programs can be used with no change in the OO software. However, we can find new features in OO languages that do not exist in procedural ones. Some examples of these features are inheritance, polymorphism, overloading, generics, and so on. No doubt these new features solve some common errors found in procedural languages but they also trigger new kinds of errors. Thus, when dealing with OO programs, automatic software testing techniques must include new ideas that are not present in procedural testing. One of the first works in the literature related to OO software was the work by Tonella [199], which used genetic algorithms. Later, Liu et al. [133] proposed the use of ant colony optimization. The work by Wappler and Wegener [213,214] using hybrid algorithms and strongly-typed genetic programming focuses on container classes. More recently, the work by Arcuri and Yao [19] optimizes test cases for covering all the branches at the same time and compares different search strategies. None of the previous work explicitly deals with inheritance for generating test data. The objects used as parameters are generated by calling the constructor and some methods of one class in order to reach a given state of the object. However, no attention is paid to the position of the class in the hierarchy, thus we wish to address this issue in this thesis chapter. We propose new approaches to take into account the position in the class hierarchy of the classes used in the parameters of methods being tested. In particular, this thesis focuses on the Java instanceof operator, which is related to inheritance. It determines if the specified object ‘o’ is assignment-compatible with the object represented by the class ‘c’ (o instanceof c). The operator returns true if the specified object is non-null and can be cast to the reference type represented by the class ‘c’ without raising aClassCastException. It returns false otherwise. The main and motivating research question addressed here is RQ1: what is the guidance for an automatic test data generator if there is a method containing the code in Figure 5.1 and it needs 57
58 5.2. TEST DATA GENERATOR to make the branch condition true? We can use an objective function for this branch that takes value 1 if the condition is true and 0 otherwise. However, this objective function gives no clue on how near a test datum is from making the condition true and an algorithm using this function can behaves like a blind search. This is called the flag problem [96]. Consequently, the fitness landscape consists of two plateaus, corresponding to the two possible values (true or false). One of these plateaus will be super-fit and the other super-unfit. A search-based approach will not be able to locate the super-fit plateau any better than a random search, because the fitness landscape provides no guide to direct the search from unfit to fit regions of the landscape. Where the fit plateau may be very small relative to the unfit plateau, this makes the program hard to test. This issue has been studied by many researchers, however, previous work does not address the issue of a special type of the flag problem that often occurs in the context of object-orientation related to inheritance that occurs when instanceof operators are used. void function (Collection c) { if (c instanceof Set) { ... } } Figure 5.1: Instanceof expression in a sentence. The specific contributions in this thesis chapter are a new branch distance defined for the instanceof operator, and two mutation operators taking into account the class hierarchy. The proposal made in this thesis allows the algorithms to better guide the search for test data in the presence of the instanceof operator. This operator appears in 2,700 of the 13,000 classes of the JDK 1.6 class hierarchy and more than 850 classes include this operator in between 1% and 12% of their source code lines. This means that this operator is used in real software and any contribution that facilitates the testing process when it is present will have an important impact on the OO software testing field. 5.2 Test Data Generator Automatic generation of test data needs to be carried out using a tool to generate test data in an intelligent way, following the global objective of covering all branches of the source code. This problem is formalized in Section 2.2.1 to give the reader precise details of the problem we are coping with. In that section we define the adequacy criterion used to formalize the objective of the generator. In this thesis we use the branch coverage which is the most popular criterion in the literature and was formalized in Eq. (2.6). In the following we describe our test data generator and the complete process of the generation of test data. Our test data generator breaks down the global objective (to cover all the branches) into several partial objectives consisting of dealing with only one branch of the program. Then, each partial objective can be treated as a separate optimization problem in which a solution to the problem is a test datum and the function to be minimized is a distance between the current test datum and one satisfying the partial objective. In order to solve such minimization problem optimization algorithms such EAs are used. The main loop of the test data generator is shown in Figure 5.2.
CHAPTER 5. TEST DATA GENERATION IN OBJECT-ORIENTED SOFTWARE 59 Select a Partial Objective Optimization Algorithm End Continue? yes no Test Case Generator Test case Objective function Program Figure 5.2: The test data generation process. In a loop, the test data generator selects a partial objective (a branch) and uses the optimization algorithm to search for test data taking that branch. When a test datum covers a branch, the test datum is stored in a set associated to that branch. The structure composed of the sets associated to all the branches is called coverage table. After the optimization algorithm stops, the main loop starts again and the test data generator selects a different branch. This scheme is repeated until total branch coverage is obtained or a maximum number of evaluations or consecutive failures of the optimization algorithm is reached. When this happens the test data generator exits the main loop and returns the sets of test data associated to all the branches. In the following two sections we describe two important issues related to the test data generator: the objective function to minimize and the instrumentator used to generate an instrumented equivalent version of the program under test. 5.2.1 Objective Function We have to solve several minimization problems: one for each branch. Now we need to define an objective function (for each branch) to be minimized. This function will be used for evaluating each test datum, and its definition depends on the desired branch and whether the program flow reaches the branching condition associated to the target branch or not. If the condition is reached we can define the objective function on the basis of the logical expression of the branching condition and the values of the program variables when the condition is reached. The resulting expression is called branch distance and can be recursively defined on the structure of the logical expression. That is, for an expression composed of other expressions joined by logical operators the branch distance is computed as an aggregation of the branch distance applied to the component logical expressions. For the Java logical operators && and || we define the branch distance as: bd(a&&b) = bd(a) + bd(b) (5.1) bd(a||b) = min(bd(a), bd(b)) (5.2) where aand bare logical expressions.
60 5.2. TEST DATA GENERATOR In order to completely specify the branch distance we need to define its value in the base case of the recursion, that is, for atomic conditions. The particular expression used for the branch distance in this case depends on the operator of the atomic condition. The operands of the condition appear in the expression. A lot of research has been devoted in the past to the study of appropriate branch distances in software testing. An accurate branch distance considering the value of each atomic condition and the value of its operands can better guide the search. In procedural software testing these accurate functions are well-known and popular in the literature. They are based on distance measures defined for relational operators like <,>, and so on [154]. We use here these distance measures described in the literature. When a test datum does not reach the branching condition of the target branch we cannot use the branch distance as objective function. In this case, we identify the branching condition c whose value must first change in order to cover the target branch (critical branching condition) and we define the objective function as the branch distance of this branching condition plus the approximation level. The approximation level, denoted here with ap(c, b), is defined as the number of branching nodes lying between the critical one (c) and the target branch (b) [216]. We also add a real valued penalty in the objective function to those test data that do not reach the branching condition of the target branch. With this penalty, denoted by p, the objective value of any test datum that does not reach the target branching condition is higher than the one of any test datum that reaches the target branching condition. The exact value of the penalty depends on the target branching condition and it is always an upper bound of the target branch distance. Finally, the expression for the objective function is as follows: fb(x) = bdb(x) if bis reached by x bdc(x) + ap(c, b)∗potherwise (5.3) where cis the critical branching condition, and bdb,bdcare the branch distances of branching conditions band c. The use of the penalty pcould be avoided by normalizing the branch distance to the interval [0,1) (see [16] for example). Nested branches pose a great challenge for the search. For example, if the condition associated to a branch is nested within three conditional statements, all the conditions of these statements must be true in order for the program flow to proceed onto the next one. Therefore, for the purpose of computing the objective function, it is not possible to compute the branch distance for the second and third nested conditions until the first one is true. This gradual release of information might cause efficiency problems for the search (what McMinn calls the nesting problem [149]), which forces us to concentrate on satisfying each predicate sequentially. In order to alleviate the nesting problem, our test data generator selects as objective in each loop one branch whose associated condition has been previously reached by other test data stored in the coverage table. Some of these test data are inserted in the initial population of the algorithm used for solving the optimization problem. The percentage of individuals introduced in this way in the population is called the replacement factor and is denoted by Rf. At the beginning of the generation process some random test data are generated in order to reach some branching conditions. 5.2.2 Instrumentation Tool Instrumentation is the implementation of code instructions that monitors specific components of a software system without modifying the behavior of the original program. In this thesis we are interested in code tracing, that is, receiving information about the execution of an application. Instrumentation approaches can be of two types: source instrumentation and binary instrumenta-
CHAPTER 5. TEST DATA GENERATION IN OBJECT-ORIENTED SOFTWARE 61 tion. Since we have access to the source code of the programs that we want to test, we decided to use source instrumentation in this dissertation. We have developed an instrumentator for Java source code using a Java CC grammar of the Java language structures. The instrumentator adds instrumentation code and transforms the source code to receive information of the program execution. For this purpose, we have implemented the visitor design pattern, which is the best way to analyze and transform the source code related to general structures, control structures, and assignation expressions. Particularly, our instrumentator redefines conditions and decisions associated to control structures (If-then, while, switch, ...). We add some own instrumentation statements that give us the required information to be able to know which branches were traversed in an execution of the program under test. After the execution of our instrumentator over a source code, it returns a new version of the program with the same functionality but annotated with some statements which provide us useful information for computing the branch distance which guide the search to the optimal test data set. 5.3 Distance for instanceof operator In this section we try to answer the main research question of this chapter (RQ1) by presenting our proposal of distance measure for the instanceof operator. This distance will be used in the base case of the branch distance definition (see Section 5.2.1) when the instanceof operator is found. Since our distance is based on the class and interface hierarchy, first we need to present the notation for referring to the classes, interfaces, and their relationship. In Java there is no multiple inheritance among classes, that is, a class can only extend one class. However, this does not hold for interfaces: one interface can extend several interfaces and one class can implement several interfaces. The natural way of representing the class and interface hierarchy is by means of a graph. Following the terminology proposed in the Java language specification [90], we use the term reference type to refer to a class or an interface. Let us denote with GR= (R, ER) the graph representing a hierarchy of reference types, where Ris the set of reference types considered and ER⊆R×Ris the set of arcs. We call this graph the hierarchical graph of R. The set Rcan be composed of all the classes and interfaces accessible from a virtual machine or a subset of them. We will use the notation CRand IRto refer to the set of classes and interfaces in R, respectively. The set of arcs ERis determined by the relationship between classes and interfaces in Rin the following way. Let r1, r2∈Rbe two reference types, then (r1, r2) ∈ERif and only if: •r1, r2∈CRand class r1 is a direct superclass of r2 •r1∈IRand interface r1 is a direct superinterface of reference type r2 We must recall here that there is only one class in Java with no superclass: Object. This fact, together with the lack of multiple inheritance for classes, implies that the subgraph of GR composed only by the set of classes CRis a directed tree with the Object class in the root. We denote this subgraph GCR. At this point we can define the value returned by the instanceof operator based on our definition of hierarchical graph. Let “oinstanceof r” be an instanceof expression where ois an object of class cand ra reference type. This expression evaluates to true if and only if a walk exists in GRfrom rto c. Once we have defined the hierarchical graph for a set of reference types Rwe present now the definition of the distance dbetween one class cand a reference type r. This distance is the one used for comparing the two arguments of an instanceof operator. In this operator, the first argument
68 5.5. EXPERIMENTAL ANALYSIS 5.5.3 Adaptive Mutation Motivated by the results of the previous section we present in this section a new mutation operator that changes its behavior throughout the search. The difference between this adaptive operator, denoted by MDα, and the ones studied in the previous section is the probability distribution used for selecting a class. In MDαthe probability distribution is: p(c, c′) = 1 d(c,c′)α P r∈U,r6=c(1 d(c,r))αif c6=c′ 0 if c=c′ (5.10) In this expression, if α= 0, we have the uniform mutation MU and if α= 1, we have the distance-based mutation MDn. We can use values higher than 1 for α. If the value of αis high, then the mutation only selects classes that are close to the ones in the individual. We can see αas an exploitation-exploration parameter. A low value for αleads to an explorative search. A high value leads to an exploitative search. In order to make it adaptive we must change the value of α throughout the search. We use a linear increase for α, that is: α=λ·step (5.11) where λis a parameter called adaptive speed. With this expression for α, the behavior of the adaptive mutation is the same as the behavior of MU at the beginning and it switches to the behavior of MDn as the search progresses. The higher the value of λ, the higher the speed of this change in the behavior. If λ= 0 we have the uniform mutation, MU. On the other hand, if λ= 1/T , then MDαbehaves like MDn in Tsteps. The adaptive speed λis a new parameter and we must analyze the behavior of the algorithm for different values of λin order to give some guidelines for selecting its value. A low value for λ means a very explorative search. A high value for λmakes the algorithm change very fast from the explorative phase to a very exploitative one. It is well-known in the metaheuristic field that one of the key points in the design of an algorithm is to select the exact balance between exploration and exploitation. Thus, we expect the best value for λto be not too high and not too low: it should be something in between. In order to support this hypothesis we have applied our test data generator using the adaptive mutation to the nine programs presented in Section 5.4.3. We used nine different values for λand performed 100 independent runs for each program and configuration. In all the cases the generator was executed until 100% branch coverage was obtained and we use the number of evaluations for comparison purposes. In Figure 5.7 we show the average number of evaluations for all the programs and the nine values of λ. We have also included the results of MU (λ= 0). As expected, when extreme values for λare used the effort required to reach the total coverage is higher. In particular, when random mutation is used (λ= 0) the effort is higher than for intermediate values of λ(there are statistically significant differences that confirm this observation). On the other hand, when λ= 1/60, the higher value of λ, the effort required is again increased. The reason is that the search reaches a very exploitative stage in a few steps, in which newly generated solutions are similar to the parent solutions. In this situation it is difficult for the algorithm to reach the objective. The best values for λare between 1/100 and 1/200. We have also compared our proposals against a random search. The random search proposes random classes for the vector of objects that is used as test case. The random search is able to reach 100% branch coverage only in obj2 1 with an average of 1302 evaluations. For the other
CHAPTER 5. TEST DATA GENERATION IN OBJECT-ORIENTED SOFTWARE 69 Figure 5.7: Average number of evaluations required for 100% branch coverage in all the test programs for different values of λ. (more complex) programs we stopped the random search after 50,000 evaluations and the average coverage obtained varies from 21% in obj4 3 to 99% in obj3 1. In the results shown in Figure 5.7 the maximum number of average evaluations for a 100% branch coverage is around 8,000. Thus, we conclude that our proposals are much better than a simple random search. The results of Figure 5.7 also show the “difficulty” of the programs for the test data generator. From the results we can sort the programs according to the effort required to reach 100% branch coverage. We can observe that, except in a few cases, this ranking is independent of the value of λand is correlated with the value i+jwhere iis the number of atomic conditions per logical expression, and jis the nesting degree. Furthermore, we can observe that the influence of λon the results is higher in the “most difficult” programs, as we could expect. 5.6 Conclusions In this chapter we have studied one aspect of OO Software, inheritance, to propose some approaches that can help to better guide the search of test data in the context of OO evolutionary testing. In particular, we have answered the RQ1 providing a distance measure to compute the branch distance in the presence of the instanceof operator in Java programs. We have also proposed two mutation operators that change the solutions based on the distance measure defined. In addition to the proposals we have performed a set of experiments to test our hypothesis. First, we have analyzed the most important parameters of the algorithm in order to select the best configuration. After that, we have analyzed and compared one of the proposed mutation operators against a uniform mutation. Finally, we have proposed an adaptive mutation operator that is able to make a better exploration and we have studied its main parameter. One of the main conclusions of this work is that the difficulty to test a program depends on the number of atomic conditions per logical expression, and the nesting degree. Since we are interested in measuring the complexity of testing a program, in the next chapter we analyze the most common static measures and define a testing complexity measure to estimate the effort required to test software.
70 5.6. CONCLUSIONS
Chapter 6 Estimating Software Testing Complexity 6.1 Introduction Since the birth of Software Industry, there has been a high interest in measuring the effort in terms of time and cost required by a task. Nowadays, software applications are essential for Industry, thus software developers need to measure all sort of elements. Tom DeMarco stated [59]: “You can not control what you cannot measure. Measurement is the prerequisite to management control”. The importance of metrics have also been highlighted by the famous physicist Lord Kelvin [198]: “When you can measure what you are speaking about, and express it in numbers, you know something about it; but when you cannot measure it, when you cannot express it in numbers, your knowledge is of a meagre and unsatisfactory kind: it may be the beginning of knowledge, but you have scarcely, in your thoughts, advanced to the state of science”. For these reasons, in this chapter we focus on complexity measures, which quantify the effort required to complete any kind of task. First, it is needed to define what program complexity means. Basili [27] defines complexity as a measure of the resources used by a system while interacting with a piece of software to perform a given task. If the interacting system is a computer, then complexity is defined by the execution time and storage required to perform the computation described by the program. If the interacting system is a programmer then complexity is defined by the difficulty of performing tasks such as coding, debugging, testing or modifying the software. There exist metrics introduced as all-purpose measures of software complexity, however these measures seem to be ineffective in order to measure the testing complexity [107]. The absence of a metric to properly measure the difficulty to test a piece of code encourage us to characterize the testing complexity, and drive us to the following research question RQ1: how difficult is the automated testing of a piece of code? Analyzing the testing complexity, it can be seen as the difficulty for a computer to create a test suite for finding errors in the developed code. Finding errors in early stages of the development is an important task that saves costs of the project. It is estimated that half the time spent on the software project development and more than half its cost, is devoted to testing the product [158]. To this end, in recent years researchers have attempted to predict fault-prone software modules using complexity metrics [228]. In addition, the overall experimental results show that complexity metrics are able to predict fault-prone source code [232]. 71
72 6.2. STATIC MEASURES In most previous works they defined the testing complexity as the number of test cases required [130,227]. Some works try to compute the lower bound [30] of the test cases required, and other works try to provide better understanding on the testing criterion used to generate those test cases [139]. However, they do not focus on the effort to generate these test cases. In a recent work, Nogueira focuses on the correlation between the complexity of the SUT and the complexity of the test cases [164], but the work did not propose any estimation measure. We propose in this thesis dissertation a new complexity measure with the aim of helping the tester to find errors in the code. This measure will predict in a better way the behavior of an automatic test data generator depending on the SUT. This original complexity measure, called “Branch Coverage Expectation” (BCE), is the main contribution of this chapter. The definition of the new measure lies on a Markov model that represents the program. Based on the model of a program, we can also provide an estimation of the number of random test cases that must be generated to obtain a concrete coverage. From these estimations, we can create a theoretical prediction of the evolution of the coverage depending on the number of generated test cases. This second contribution will help the testers to obtain some knowledge about the possible evolution of the testing phase. The validation of the proposed measure is also addressed in this work. For the theoretical validation of the BCE complexity measure we have used the validation framework proposed by Kitchenham et al. [120]. For the experimental validation we have used Evolutionary and Random Testing techniques, which are the most popular search algorithms for automatically generating test cases [10,14,74,128], to compare our estimation with the real value obtained by several test data generators. Finally, we also analyze software complexity measures at program level and we discuss a number of issues associated with these known measures. In addition, we have performed an experimental study of correlations with the aim of highlighting the existing relationships among some static measures. We are especially interested in the existing relationships between the static measures and the branch coverage. In this experimental study we have used two large groups of automatically generated programs and one group of real-world ones to serve as a benchmark. 6.2 Static Measures Quantitative models are frequently used in different engineering disciplines for predicting situations, due dates, required cost, and so on. These quantitative models are based on some kind of measure made on project data or items. Software Engineering is not an exception. A lot of measures are defined in Software Engineering in order to predict software quality [187], task effort [36], etc. We are interested here in measures made on source code pieces. We distinguish two kinds of measures: dynamic, which require the execution of the program, and static, which do not. Some time ago, project managers began to worry about concepts like productivity and quality, then the lines of code (LOC) metric was proposed. Nowadays, the LOC metric is still the primary quantitative measure in use. An examination of the main metrics reveals that most of them confuse the complexity of a program with its size. The underlying idea of these measures are that a program will be much more difficult to work with than a second one if, for example, it is twice the size, has twice as many control paths leading through it, or contains twice as many logical decisions. Unfortunately, these various ways in which a program may increase in complexity tend to move in unison, making it difficult to identify the multiple dimensions of complexity. In this section we present the measures used in this study. In a first group we select the main measures that we selected from the literature:
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 73 •Lines of Code (LOC) •Source Lines of Code (SLOC ) •Lines of Code Equivalent (LOCE) •Total Number of Disjunctions (TNDj) •Total Number of Conjunctions (TNCj) •Total Number of Equalities (TNE) •Total Number of Inequalities (TNI ) •Total Number of Decisions (TND) •Number of Atomic Conditions per Decision (CpD) •Nesting Degree (N) •Halstead’s Complexity (HD) •McCabe’s Cyclomatic Complexity (MC) Let’s have a look at the measures that are directly based on source lines of code (in C-based languages). The LOC measure is a count of the number of semicolons in a method, excluding those within comments and string literals. The SLOC measure counts the source lines that contain executable statements, declarations, and/or compiler directives. However, comments, and blank lines are excluded. The LOCE measure [191] is based on the idea of weighing each source line of code depending on how nested it is. The previous three measures based on the lines of code have several disadvantages: •Depend on the print length •Depend of the programmer’s style for writing source code •Depend on how many statements does one put in one line We have analyzed several measures as the total number of disjunctions (OR operator) and conjunctions (AND operator) that appear in the source code, these operators join atomic conditions. The number of (in)equalities is the number of times that the operator (! =) == is found in atomic conditions of a program. The total number of decisions and the number of atomic conditions per decision do not require any comment. The nesting degree is the maximum number of control flow statements that are nested one inside another. In the following paragraphs we describe the McCabe’s cyclomatic complexity and the Halstead complexity measures in detail. Halstead complexity measures are software metrics [93] introduced by Maurice Howard Halstead in 1977. Halstead’s Metrics are based on arguments derived from common sense, information theory and psychology. The metrics are based on four easily measurable properties of the program, which are: •n1 = the number of distinct operators •n2 = the number of distinct operands •N1 = the total number of operators •N2 = the total number of operands
74 6.2. STATIC MEASURES From these values, six measures can be defined: •Halstead Length (HL): N=N1 + N2 •Halstead Vocabulary (HV): n=n1 + n2 •Halstead Volume (HVL): V=N∗log2n •Halstead Difficulty (HD): HD =n1 2∗N2 n2 •Halstead Level (HLV): L=1 HD •Halstead Effort (HE): E=HD ∗V •Halstead Time (HT): T=E β •Halstead Bugs (HB): B=E2/3 3000 The most basic one is the Halstead Length, which simply totals the number of operators and operands. A small number of statements with a high Halstead Volume would suggest that the individual statements are quite complex. The Halstead Vocabulary gives a clue on the complexity of the statements. For example, it highlights if a small number of operators are used repeatedly (less complex) or if a large number of different operators are used, which will inevitably be more complex. The Halstead Volume uses the length and the vocabulary to give a measure of the amount of code written. The Halstead Difficulty uses a formula to assess the complexity based on the number of unique operators and operands. It suggests how difficult the code is to write and maintain. The Halstead Level is the inverse of the Halstead Difficulty: a low value means the program is prone to errors. The Halstead Effort attempts to estimate the amount of work that it would take to recode a particular method. The Halstead Time is the time to implement or understand a program and it is proportional to the effort. The experiments were used for calibrating this quantity (β= 18). Finally, the Halstead Bugs attempts to estimate the number of bugs that exist in a particular piece of code. McCabe’s cyclomatic complexity is a complexity measure related to the number of ways there exists to traverse a piece of code. This measure determines the minimum number of test cases needed to test all the paths using linearly independent circuits [146]. Cyclomatic complexity is computed using the control flow graph of the program: the nodes of the graph correspond to indivisible groups of sentences of a program (basic blocks), and a directed edge connects two nodes if the second group of sentences might be executed immediately after the first one. Cyclomatic complexity may also be applied to individual functions, modules, methods or classes within a program, and is formally defined as follows: v(G) = E−N+ 2P; (6.1) where Eis the number of edges of the graph, Nis the number of nodes of the graph and Pis the number of connected components. In Figure 6.1, we show an example of control flow graph (G). It is assumed that each node can be reached by the entry node and each node can reach the exit node. The maximum number of linearly independent circuits in G is 9 −6 + 2 ∗1 = 5, so 5 is the cyclomatic complexity of the example. The correlation between the cyclomatic complexity and the number of software faults has been studied in some research articles [28,118]. Most such studies find a strong positive correlation between the cyclomatic complexity and the errors: the higher the complexity the larger the number
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 75 Figure 6.1: The original graph of the McCabe’s article. of faults. For example, a 2008 study by metric-monitoring software supplier Energy [63] analyzed classes of open-source Java applications and divided them into two sets based on how common mistakes were found in them. They found a strong correlation between the cyclomatic complexity and their faultiness, with classes with a combined complexity of 11 having a probability of being fault-prone of just 0.28, rising to 0.98 for classes with a complexity of 74. In addition to this correlation between complexity and errors, a connection has been found between complexity and difficulty to understand software. Nowadays, the subjective reliability of software is expressed in statements such as “I understand this program well enough to know that the tests I have executed are adequate to provide my desired level of confidence on it”. For that reason, we make a close link between complexity and difficulty of discovering errors. Software complexity metrics developed by Halstead and McCabe are related to the difficulty programmers experience in locating errors in code [55]. They can be used in providing feedback to programmers about the complexity of the code they have developed and to managers about the resources that will be necessary to maintain particular sections of code. Since McCabe proposed the cyclomatic complexity, it has received several criticisms. Weyuker concluded that one of the obvious intuitive weaknesses of the cyclomatic complexity is that it makes no provision for distinguishing between programs which perform very little computation and those which perform massive amounts of computation, provided that they have the same decision structure [218]. Piwarski noticed that cyclomatic complexity is the same for Nnested if statements and Nsequential if statements [174]. Moreover, we find the same weaknesses in the group of Halstead’s metrics. No notice is made for the nesting degree, which may increase the effort required by the program severely. The solution of both McCabe’s and Halstead’s weakness is a factor to consider that a nested statement is more complex. For example, we have also studied the LOCE measure that takes into account whether a statement is nested or not. The proposed existing measures of decision complexity tend to be based upon a graph theoretical analysis of a program control structure like McCabe’s complexity. Such measures are meaningful at the program and subprogram level, but metrics computed at those levels will depend on program or subprogram size. However, the values of these metrics primarily depend upon the number of decision points within a program. This suggests that we can compute a size-independent measure of decision complexity by measuring the density of decisions within a program. In addition we have considered making the LOCE measure size-independent. The resulting expression takes into account the nesting degree and the density of the sentences. Following this assumption, we consider in this work two measures derived from some of the first group:
76 6.3. BRANCH COVERAGE EXPECTATION •Density of Decisions (DD) = T ND/LOC. •Density of LOCE (DLOCE) = LOCE/LOC. Finally, we use a dynamic measure called Branch Coverage, which is the percentage of branches of the program that are traversed. This coverage measure is used in most of the related articles in the literature and was formally defined in Section 2.2.1 (Definition 2.6). 6.3 Branch Coverage Expectation This section is aimed at presenting our main contribution in this chapter, a new complexity measure that might help testers to estimate the difficulty of testing a piece of code. The definition of the new measure lies on a Markov chain that represents the program. In this section we briefly explain the characteristics of a Markov chain and the way we generate a model of a given program. The Markov model of the program can be used not only to compute the BCE, but also to estimate the number of random test cases that must be generated to achieve a concrete value of branch coverage. We first introduce the required concepts of Markov chains [124]. 6.3.1 Markov Chain Afirst order Markov chain is a random sequence of states Xtwhere each state depends only on the previous one. That is, P(Xt+1 =j|Xk; 0 ≤k < t) = P(Xt+1 =j|Xt) for all t∈N. We consider here that the set of possible states is finite and, without loss of generality, we label the states using elements of the set [n] = {1, ..., n}. The conditional probabilities of a first order Markov chain P(Xt+1 =j|Xt=i) = Pij (t) are called one-step transition probabilities and the matrix P(t) = [Pij (t)] is the so-called transition probability matrix. We will assume here that these probabilities do not depend on the step t, and thus, Pij (t) = Pij for all t. The Markov chains fulfilling this property are called homogeneous. Two properties of the transition probability matrices are: Pij ≥0,(6.2) n X j=1 Pij = 1.(6.3) Matrices fulfilling the above equations are called stochastic. Let us denote with the column vector q(t) the probability distribution of the states at step t. The component qi(t) is the probability of having state iat step t. A state which is reached infinitely often in a finite Markov chain is called positive-recurrent. If every state in a Markov chain can be reached from every other state, then we say that the Markov chain is irreducible. For irreducible Markov chains having only positive-recurrent states the probability distribution of the states q(t) tends to a given probability distribution πas the time tends to infinite. This probability distribution πis called the stationary distribution and can be computed solving the following linear equations: πTP=πT,(6.4) πT1 = 1.(6.5)
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 77 6.3.2 Definition of the Branch Coverage Expectation In our case the Markov model is built from the control flow graph of the program, where the states of the Markov chain are the basic blocks of the program. A Basic Block (BB) is a portion of the code that is executed sequentially with no interruption. It has one entry point and one exit point, meaning that only the last instruction can be a jump. Whenever the first instruction in a basic block is executed, the rest of the instructions are necessarily executed exactly once, in order. In order to completely characterize a Markov chain we must assign a value to the edges among vertices. The transition probabilities of all branches are computed according to the logical expressions that appear in each condition. We recursively define this probability as follows: P(c1&&c2) = P(c1) ∗P(c2),(6.6) P(c1||c2) = P(c1) + P(c2) −P(c1) ∗P(c2),(6.7) P(¬c1) = 1 −P(c1),(6.8) P(a < b) = 1 2,(6.9) P(a≤b) = 1 2,(6.10) P(a > b) = 1 2,(6.11) P(a≥b) = 1 2,(6.12) P(a== b) = q, (6.13) P(a! = b) = 1 −q, (6.14) where c1, c2 are conditions and a,bare integers. We establish a 1/2 probability when the operators are ordering relational operators (<, ≤, >, ≥). Despite that the actual probability in a random situation is not always 1/2, we have selected the value with the lowest error rate. In the case of equalities and inequalities the probabilities are q and 1 −q, respectively, where qis a parameter of the measure and its value should be adjusted based on the experience. Satisfying an equality is, in general, a hard task and, thus, qshould be close to zero. This parameter could be highly dependent on the data dependencies of the program. The quality of the complexity measure depends on a good election for q. Based on a previous phase for setting parameters, we use q= 1/16 for the experimental analysis. Then, once we have the CFG completed with the transition probabilities, the generation of the transition matrix is automatic. This matrix relates the states and the probability to move from one to another. We assume, without loss of generality, that there is only one entry and exit basic block in the code. Then, in order to obtain a positive-recurrent irreducible Markov chain we add a fictional link from the exit to the entry basic block (labelled as BB1) having probability 1. We then compute the stationary probability πand the frequency of appearance of each basic block in one single execution of the program (E[BBi]). The stationary probability of a basic block is the probability of appearance in infinite program executions starting in any state. On the other hand, the frequency of appearance of a basic block is the mathematical expectation of traversing the basic block in one single execution and is computed as: E[BBi] = πi π1 ,(6.15) where π1is the stationary probability of the entry basic block, BB1.
84 6.5. EMPIRICAL VALIDATION SETUP The program generator is parameterizable, the user can set several parameters of the program under construction (PUC ). Thus, we can assign through several probability distributions the number of sentences of the PUC, the number of variables, the maximum number of atomic conditions in a decision, and the maximum nesting degree by setting these parameters. The user can define the structure of the PUC and, thus, its complexity. Another parameter the user can tune is the percentage of control structures or assignment sentences that will appear in the code. By tuning this parameter the program will contain the desired density of decisions. Once the parameters are set, the program generator builds the general scheme of the PUC. It stores in the used data structure (a general tree) the program structure, the visibility, the modifiers of the program, and creates a main method where the local variables are first declared. Then, the program is built through a sequence of basic blocks of sentences where, according to a probability, the program generator decides which sentence will be added to the program. The creation of the entire program is done in a recursive way. The user can decide whether all the branches of the generated program are reachable (using logic predicates). If total reachability is desired, logic predicates are used to represent the set of possible values that the variables can take at a given point of the PUC. Using these predicates the range of values that a variable can take is known. This range of values is useful to build a new condition that can be true or false. For example, if at a given point of the program we have the predicate x≤100 we know that a forthcoming condition x≤3 will be always true and if this condition appears in an if statement, the else branch will not be reachable. Thus, the predicates are used to guide the program construction to obtain a 100% coverable program. In general, at each point of the program the predicate is different. During the program construction, when a sentence is added to the program, we need to compute the predicate at the point after the new sentence. For this computation we distinguish two cases. First, if the new sentence is an assignment then the new predicate CP′is computed after the previous one CP by updating the values that the assigned variable can take. For example, if the new sentence is x=x+ 7 and CP ≡x≤3, then we have CP ′≡x≤10. Second, if the new sentence is a control statement, an if statement for example, then the program generator creates two new predicates called True-predicate (T P ) and False-predicate (FP). The T P is obtained as the result of the AND operation between CP and the generated condition related to the control statement. The F P is obtained as the result of the AND operation between the CP and the negated condition. In order to ensure that all the branches can be traversed, we check that both, T P and FP are not equivalent to false. If any of them were false, this new predicate is not valid and a new control structure would be generated. Once these predicates are checked, the last control statement is correct and new sentences are generated for the two branches, the predicates are computed inside the branches in the same way. After the control structure is completed, the last predicates of the two branches are combined using the OR operator and the result is the predicate after the control structure. In Figure 6.5 we illustrate the previous explanation with one example. At a certain point of the program’s execution our current predicate (CP1) is x≤3. The new sentence is an if statement with an associated decision x < 0. Then, the program generator creates two new predicates. The first one (CP2) is CP1∧x < 0≡x < 0. The second one is the AND operation between CP1and the negation of x < 0, which is x≥0. The resulting expression is CP4≡0≤x≤3. Next, the program generator modifies the predicates according to the assignment sentences. Finally, the resulting expression after the execution of the if statement is CP6≡x < 0∧y= 5 ∨ −3≤x≤0. This expression is the OR operation between CP3(true branch) and CP5(false branch). Those values that satisfy the logic predicate may participate in the following generated sentences.
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 85 /* CP1≡x≤3*/ if (x < 0) { /* CP2≡T P1≡x≤3∧x < 0≡x < 0*/ y=5; /* CP3≡x < 0∧y= 5 */ } else { /* CP4≡FP1≡x≤3∧x≥0≡0≤x≤3*/ x=x-3; /* CP5≡ −3≤x≤0*/ } /* CP6≡x < 0∧y= 5 ∨ −3≤x≤0*/ Figure 6.5: Illustration of the predicates transformation. 6.5.3 Benchmark of Test Programs The empirical validation is carried out using synthetic programs and real programs. In the following we describe the main characteristics of the programs generated by our program generator and a set of real programs extracted from the literature. Synthetic Programs The program generator can create programs having the same value for the static measures, as well as programs having different values for the measures. The programs we generated for this work can be separated in two groups. One group is characterized by being 100% coverable (called 100%CP), thus all the branches are reachable. The main advantage of these programs is that algorithms can be tested and analyzed on fair way. This kind of programs is not easy to find in the literature. On the other hand, the other group of programs does not guarantee a 100% branch coverage, called ¬100%CP, this fact makes them similar to the real world programs. The methodology applied for the program generation was the following. First, we analyzed a set of Java source files from the JDK 1.6 (java.util.*, java.io.*, java.sql.*, etc.) and we computed the static measures on these files. Next, we used the ranges of the most interesting measures, obtained in this previous analysis as a guide to generate Java source files having values in the same range for the static measures. These values are realistic with respect to the static measures, making the following study meaningful. Our program generator takes into account the desired values for the number of atomic conditions, the nesting degree, the number of sentences and the number of variables. With these parameters our program generator creates a program with a defined control flow graph containing several decisions. The main features of the generated programs are: they deal with integer input parameters, their conditions are joined by whichever logical operator and they are randomly generated. This way, we generated programs with the values in the ranges shown in Table 6.3.
86 6.5. EMPIRICAL VALIDATION SETUP Table 6.3: Range of values for some static measures from the two benchmarks of programs. 100% CP ¬100%CP SLOC 33-150 33-235 Nesting 1-4 1-7 Conditions 1-4 1-7 Decisions 3-50 1-37 McCabe 5-125 3-127 Finally, we generated a total of 2600 (800 in 100%CP and 1800 in ¬100%CP) Java programs1 using our program generator. With the aim of studying the BCE, we applied our test data generator using a GA and an ES as optimization algorithms and a random test data generator (RND). The test data generators proceed by generating test data until total coverage is obtained or a maximum of 150,000 test cases are generated. Since we are working with stochastic algorithms, we perform in all the cases 30 independent runs of the algorithms to obtain a very stable average of the branch coverage. The experimental study requires a total of 2600 ×30 ×3 = 234,000 independent runs of the test data generators. We have followed the statistical analysis procedure described in Section 3.3.2 to analyze the obtained results to compare them with a certain level of confidence. The statistical test that we have carried out is the non-parametric Kruskal-Wallis test used to compare the average of the algorithms. We always consider in this work a confidence level of 95% (i.e., p-value under 0.05) in the statistical tests, which means that the differences are unlikely to have occurred by chance with a confidence of 95%. Real Programs In order to improve the interest of our work we propose an additional benchmark of real programs. It is composed of 10 real programs extracted from the literature [15,113,145]. Some of them have been extracted from the book C Numerical Recipes, available on-line at http://www.nr.com/. They deal with real and integer input values and some of them also contain loops. The programs are listed in Table 6.4, where we inform on the maximum nesting degree, the lines of code (LOC), the number of branches, and the number and type of input arguments. Table 6.4: Characteristics of the real programs. Name ND LOC Branches Arguments Description calday 2 47 22 3 Integer Calculate the day of the week gcd 2 28 8 2 Integer Greatest common denominator line 8 92 36 8 Integer Check if two rectangles overlap numbers 3 71 28 1 Integer Parse a big number from integer to string qformula 2 24 4 3 Double Solve Real Equations qformulas 2 22 6 3 Integer Solve Integer Equations tmichael 5 69 20 3 Integer Classify triangles in 4 types: Michael triangle 4 53 28 3 Integer Classify triangles in 4 types: Our implementation tsthamer 3 76 26 3 Integer Classify triangles in 5 types: Sthamer twegener 3 46 26 3 Double Classify triangles in 5 types: Wegener 1They are available at http://neo.lcc.uma.es/staff/javi/resources.html
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 87 6.6 Empirical Results In this section we describe the experimental analysis performed and we interpret the relationship of the studied measures. We divide the main study in four subsections. In the first one, we analyze the static measures in order to reveal their correlations. In the second subsection, we highlight the existing relationship between the static measures and the code coverage. We analyze which of them are more appropriate for estimating the difficulty for a computer to generate an adequate test suite. In the third subsection, we use the Markov model of programs to predict the relationship between coverage and the number of required test cases. We analyze if our theoretical prediction is similar to a real execution of an automatic test data generator. Finally, we perform the study on the real-world programs. For computing correlations among measures we use the Spearman’s correlation coefficient ρ. This coefficient takes into account the rank of the values of the samples instead of the samples themselves. 6.6.1 Analysis of the Correlation Between the Static Measures In this section we analyze the existing relationship among the static measures of the generated programs. With this previous study we want to clarify the possible similarities and differences of the analyzed static measures in this work. In this study there are three different measures that try to rate the complexity of a program: McCabe’s complexity, the Halstead Difficulty and LOCE. In Tables 6.7 and 6.8 we show a comparison of correlation between these measures, the nesting degree and the group of measures derived from some of the first group (density of decisions and density of LOCE). We show these measures because they are higher correlated with the branch coverage among a number of them. In Tables 6.5 and 6.6 the reader could check all the correlations coefficients for the 100%CP benchmark and the ¬100%CP benchmark, respectively. In addition, we include the BCE measure in order to compare it with the other studied measures. As we can see, the three measures that rate the complexity (MC, HD and LOCE) are highly correlated among them in the 100%CP benchmark and less correlated in the ¬100%CP one. This gives us a clue about the similarities that the complexity measures have among them. On the other hand, the nesting degree is lowly correlated with McCabe’s complexity and Halstead Difficulty. In the case of LOCE, the correlations with the nesting degree are 0.344 in 100%CP and 0.692 in ¬100%CP. This was expected because the LOCE measure weighs the nested statements. In addition, we can remark that the Halstead Difficulty does not correlate with the density of decisions in 100%CP and ¬100%CP (0.052 and 0.023, respectively). We can also observe that the static measures that are highly correlated in one benchmark are highly correlated in the other one too. This is the case of the relationship between nesting, density of decisions and density of LOCE that must be emphasized. All of them are highly correlated, being the correlation between nesting degree and density of LOCE 0.877 in 100%CP and 0.870 in ¬100%CP, nesting degree and density of decisions 0.765 in 100%CP and 0.708 in ¬100%CP and density of decisions and density of LOCE 0.912 in 100%CP and 0.774 in ¬100%CP. Once we have analyzed the other static measures, we report the correlation coefficients of our proposal and the most important static measures studied in this work. The nesting degree must be emphasized because it is the most correlated static measure with the BCE, -0.540 in 100%CP and -0.575 in ¬100%CP, what means that the nesting degree is the most similar measure. In addition, we can see that our proposal is not correlated with McCabe’s and Halstead’s complexities. This analysis of the three rates of complexity is not complete if we do not highlight the static
88 6.6. EMPIRICAL RESULTS Table 6.5: The correlation coefficients among all the measures analyzed in the benchmark 100%CP HD MC LOCE N DD DLOCE BCE LOC SLOC TNDj TNCj TNE TNI TND CpD HL HV HVL HLV HE HT HB ES GA RND HD - 0.796 0.786 -0.108 0.052 -0.035 0.285 0.932 0.853 0.742 0.731 0.644 0.639 0.799 0.454 0.870 0.842 0.864 1.0 0.920 0.920 0.864 0.070 -0.101 0.077 MC 0.796 - 0.965 0.266 0.519 0.408 0.025 0.805 0.962 0.925 0.934 0.829 0.811 0.985 0.524 0.976 0.969 0.977 -0.796 0.954 0.954 0.977 -0.150-0.226-0.074 LOCE 0.786 0.965 - 0.344 0.515 0.474 -0.038 0.796 0.974 0.884 0.882 0.822 0.789 0.976 0.501 0.945 0.938 0.945 -0.786 0.921 0.921 0.945 -0.186-0.251-0.133 N -0.108 0.266 0.344 - 0.765 0.877 -0.540 -0.207 0.180 0.235 0.240 0.311 0.234 0.276 0.136 0.138 0.127 0.139 0.108 0.089 0.089 0.139 -0.543-0.381-0.434 DD 0.052 0.519 0.515 0.765 - 0.912 -0.377 -0.043 0.405 0.449 0.489 0.485 0.437 0.538 0.283 0.368 0.367 0.372 -0.052 0.302 0.302 0.372 -0.439-0.304-0.311 DLOCE-0.035 0.408 0.474 0.877 0.912 - -0.485 -0.132 0.336 0.352 0.380 0.410 0.353 0.418 0.217 0.270 0.258 0.271 0.035 0.208 0.208 0.271 -0.504-0.345-0.397 BCE 0.285 0.025 -0.038 -0.540-0.377 -0.485 - 0.307 0.081 0.065 0.008 -0.124 0.009 0.017 0.078 0.121 0.129 0.120 -0.285 0.159 0.159 0.120 0.510 0.375 0.534 LOC 0.932 0.805 0.796 -0.207-0.043 -0.132 0.307 - 0.879 0.753 0.730 0.634 0.646 0.810 0.419 0.891 0.892 0.890 -0.932 0.910 0.910 0.890 0.136 -0.053 0.120 SLOC 0.853 0.962 0.974 0.180 0.405 0.336 0.081 0.879 - 0.884 0.878 0.794 0.778 0.973 0.492 0.975 0.970 0.975 -0.853 0.960 0.960 0.975 -0.091-0.194-0.050 TNDj 0.742 0.925 0.884 0.235 0.449 0.352 0.065 0.753 0.884 - 0.773 0.813 0.719 0.897 0.515 0.919 0.908 0.919 -0.742 0.900 0.900 0.919 -0.119-0.175-0.036 TNCj 0.731 0.934 0.882 0.240 0.489 0.380 0.008 0.730 0.878 0.773 - 0.734 0.806 0.905 0.497 0.913 0.901 0.913 -0.731 0.895 0.895 0.913 -0.158-0.235-0.072 TNE 0.644 0.829 0.822 0.311 0.485 0.410 -0.124 0.634 0.794 0.813 0.734 - 0.618 0.822 0.435 0.798 0.785 0.797 -0.644 0.779 0.779 0.797 -0.272-0.279-0.207 TNI 0.639 0.811 0.789 0.234 0.437 0.353 0.009 0.646 0.778 0.719 0.806 0.618 - 0.799 0.439 0.794 0.791 0.795 -0.639 0.774 0.774 0.795 -0.121-0.201-0.095 TND 0.799 0.985 0.976 0.276 0.538 0.418 0.017 0.810 0.973 0.897 0.905 0.822 0.799 - 0.503 0.961 0.959 0.962 -0.799 0.935 0.935 0.962 -0.147-0.226-0.082 CpD 0.454 0.524 0.501 0.136 0.283 0.217 0.078 0.419 0.492 0.515 0.497 0.435 0.439 0.503 - 0.524 0.518 0.523 -0.454 0.514 0.514 0.523 -0.089-0.132 0.035 HL 0.870 0.976 0.945 0.138 0.368 0.270 0.121 0.891 0.975 0.919 0.913 0.798 0.794 0.961 0.524 - 0.991 1.0 -0.870 0.989 0.989 1.0 -0.071-0.180-0.012 HV 0.842 0.969 0.938 0.127 0.367 0.258 0.129 0.892 0.970 0.908 0.901 0.785 0.791 0.959 0.518 0.991 - 0.994 -0.842 0.971 0.971 0.994 -0.061-0.172-0.003 HVL 0.864 0.977 0.945 0.139 0.372 0.271 0.120 0.890 0.975 0.919 0.913 0.797 0.795 0.962 0.523 1.0 0.994 - -0.864 0.987 0.987 1.0 -0.072-0.181-0.011 HLV -1.0 -0.796-0.786 0.108 -0.052 0.035 -0.285 -0.932-0.853-0.742-0.731-0.644-0.639-0.799-0.454 -0.870-0.842-0.864 - -0.920-0.920-0.864 -0.070 0.101 -0.077 HE 0.920 0.954 0.921 0.089 0.302 0.208 0.159 0.910 0.960 0.900 0.895 0.779 0.774 0.935 0.514 0.989 0.971 0.987 -0.920 - 1.0 0.987 -0.046-0.168 0.006 HT 0.920 0.954 0.921 0.089 0.302 0.208 0.159 0.910 0.960 0.900 0.895 0.779 0.774 0.935 0.514 0.989 0.971 0.987 -0.920 1.0 - 0.987 -0.046-0.168 0.006 HB 0.864 0.977 0.945 0.139 0.372 0.271 0.120 0.890 0.975 0.919 0.913 0.797 0.795 0.962 0.523 1.0 0.994 1.0 -0.864 0.987 0.987 - -0.072-0.181-0.011 ES 0.070 -0.150-0.186-0.543-0.439 -0.504 0.510 0.136 -0.091-0.119-0.158-0.272-0.121-0.147-0.089 -0.071-0.061-0.072-0.070-0.046-0.046-0.072 - 0.365 0.445 GA -0.101-0.226-0.251-0.381-0.304 -0.345 0.375 -0.053-0.194-0.175-0.235-0.279-0.201-0.226-0.132 -0.180-0.172-0.181 0.101 -0.168-0.168-0.181 0.365 - 0.403 RND 0.077 -0.074-0.133-0.434-0.311 -0.397 0.534 0.120 -0.050-0.036-0.072-0.207-0.095-0.082 0.035 -0.012-0.003-0.011-0.077 0.006 0.006 -0.011 0.445 0.403 - Table 6.6: The correlation coefficients among all the measures analyzed in the benchmark ¬100%CP HD MC LOCE N DD DLOCE BCE LOC SLOC TNDj TNCj TNE TNI TND CpD HL HV HVL HLV HE HT HB ES GA RND HD - 0.698 0.359 -0.062 0.023 0.014 0.051 0.664 0.648 0.653 0.651 0.557 0.569 0.463 0.441 0.764 0.576 0.747 -1.0 0.872 0.872 0.747 0.069 0.067 0.079 MC 0.698 - 0.571 0.257 0.432 0.351 -0.142 0.472 0.667 0.936 0.937 0.803 0.827 0.718 0.671 0.782 0.762 0.786 -0.698 0.803 0.803 0.786 -0.177-0.168-0.173 LOCE 0.359 0.571 - 0.692 0.590 0.833 -0.461 0.414 0.717 0.435 0.432 0.479 0.485 0.814 0.086 0.564 0.503 0.560 -0.359 0.524 0.524 0.560 -0.461-0.452-0.476 N -0.062 0.257 0.692 - 0.708 0.870 -0.575 -0.160 0.190 0.163 0.161 0.229 0.220 0.502 -0.031 0.020 0.009 0.019 0.062 -0.007-0.007 0.019 -0.563-0.554-0.589 DD 0.023 0.432 0.590 0.708 - 0.774 -0.426 -0.178 0.280 0.306 0.304 0.385 0.372 0.723 0.026 0.089 0.056 0.087 -0.023 0.070 0.070 0.087 -0.476-0.473-0.497 DLOCE 0.014 0.351 0.833 0.870 0.774 - -0.556 -0.113 0.284 0.247 0.243 0.308 0.291 0.593 0.013 0.096 0.076 0.095 -0.014 0.073 0.073 0.095 -0.577-0.564-0.602 BCE 0.051 -0.142 -0.461-0.575-0.426 -0.556 - 0.075 -0.143-0.078-0.079-0.200-0.138-0.318 0.080 -0.021-0.006-0.020-0.051 0.001 0.001 -0.020 0.714 0.698 0.732 LOC 0.664 0.472 0.414 -0.160-0.178 -0.113 0.075 - 0.857 0.398 0.397 0.386 0.406 0.494 0.144 0.906 0.821 0.901 -0.664 0.874 0.874 0.901 0.102 0.099 0.116 SLOC 0.648 0.667 0.717 0.190 0.280 0.284 -0.143 0.857 - 0.533 0.532 0.549 0.572 0.834 0.152 0.916 0.813 0.910 -0.648 0.875 0.875 0.910 -0.137-0.137-0.137 TNDj 0.653 0.936 0.435 0.163 0.306 0.247 -0.078 0.398 0.533 - 0.849 0.753 0.781 0.555 0.747 0.702 0.697 0.707 -0.653 0.731 0.731 0.707 -0.110-0.101-0.102 TNCj 0.651 0.937 0.432 0.161 0.304 0.243 -0.079 0.397 0.532 0.849 - 0.753 0.771 0.551 0.746 0.702 0.697 0.707 -0.651 0.731 0.731 0.707 -0.116-0.107-0.111 TNE 0.557 0.803 0.479 0.229 0.385 0.308 -0.200 0.386 0.549 0.753 0.753 - 0.623 0.600 0.544 0.633 0.619 0.636 -0.557 0.646 0.646 0.636 -0.278-0.270-0.270 TNI 0.569 0.827 0.485 0.220 0.372 0.291 -0.138 0.406 0.572 0.781 0.771 0.623 - 0.619 0.559 0.658 0.645 0.662 -0.569 0.671 0.671 0.662 -0.207-0.198-0.204 TND 0.463 0.718 0.814 0.502 0.723 0.593 -0.318 0.494 0.834 0.555 0.551 0.600 0.619 - 0.132 0.688 0.605 0.683 -0.463 0.648 0.648 0.683 -0.338-0.336-0.348 CpD 0.441 0.671 0.086 -0.031 0.026 0.013 0.080 0.144 0.152 0.747 0.746 0.544 0.559 0.132 - 0.394 0.436 0.402 -0.441 0.437 0.437 0.402 0.026 0.026 0.031 HL 0.764 0.782 0.564 0.020 0.089 0.096 -0.021 0.906 0.916 0.702 0.702 0.633 0.658 0.688 0.394 - 0.932 0.999 -0.764 0.980 0.980 0.999 -0.021-0.018-0.010 HV 0.576 0.762 0.503 0.009 0.056 0.076 -0.006 0.821 0.813 0.697 0.697 0.619 0.645 0.605 0.436 0.932 - 0.946 -0.576 0.874 0.874 0.946 -0.040-0.030-0.022 HVL 0.747 0.786 0.560 0.019 0.087 0.095 -0.020 0.901 0.910 0.707 0.707 0.636 0.662 0.683 0.402 0.999 0.946 - -0.747 0.974 0.974 1.0 -0.023-0.020-0.011 HLV -1.0 -0.698-0.359 0.062 -0.023 -0.014 -0.051 -0.664-0.648-0.653-0.651-0.557-0.569-0.463-0.441 -0.764-0.576-0.747 - -0.872-0.872-0.747 -0.069-0.067-0.079 HE 0.872 0.803 0.524 -0.007 0.070 0.073 0.001 0.874 0.875 0.731 0.731 0.646 0.671 0.648 0.437 0.980 0.874 0.974 -0.872 - 1.0 0.974 0.004 0.005 0.016 HT 0.872 0.803 0.524 -0.007 0.070 0.073 0.001 0.874 0.875 0.731 0.731 0.646 0.671 0.648 0.437 0.980 0.874 0.974 -0.872 1.0 - 0.974 0.004 0.005 0.016 HB 0.747 0.786 0.560 0.019 0.087 0.095 -0.020 0.901 0.910 0.707 0.707 0.636 0.662 0.683 0.402 0.999 0.946 1.0 -0.747 0.974 0.974 1.0 -0.023-0.020-0.011 ES 0.069 -0.177-0.461-0.563-0.476 -0.577 0.714 0.102 -0.137-0.110-0.116-0.278-0.207-0.338 0.026 -0.021-0.040-0.023-0.069 0.004 0.004 -0.023 - 0.954 0.940 GA 0.067 -0.168-0.452-0.554-0.473 -0.564 0.698 0.099 -0.137-0.101-0.107-0.270-0.198-0.336 0.026 -0.018-0.030-0.020-0.067 0.005 0.005 -0.020 0.954 - 0.950 RND 0.079 -0.173-0.476-0.589-0.497 -0.602 0.732 0.116 -0.137-0.102-0.111-0.270-0.204-0.348 0.031 -0.010-0.022-0.011-0.079 0.016 0.016 -0.011 0.940 0.950 -
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 89 Table 6.7: Correlation coefficient of the most interesting static measures in the 100%CP benchmark. We highlight the highest value per row. 100%CP MC HD LOCE N DD DLOCE BCE MC •0.796 0.965 0.266 0.519 0.408 0.025 HD 0.796 •0.786 −0.108 0.052 −0.035 0.284 LOCE 0.965 0.786 •0.344 0.515 0.474 -0.038 N 0.266 −0.108 0.344 •0.765 0.877 -0.540 DD 0.519 0.052 0.515 0.765 •0.912 -0.377 DLOCE 0.408 −0.035 0.474 0.877 0.912 •-0.485 BCE 0.025 0.284 −0.038 −0.540 −0.377 −0.485 • Table 6.8: Correlation coefficient of the most interesting static measures in the ¬100%CP benchmark. We highlight the highest value per row. ¬100%CP MC H LOCE N DD DLOCE BCE MC •0.698 0.571 0.257 0.432 0.351 -0.142 HD 0.698 •0.359 0.062 0.023 0.014 0.051 LOCE 0.571 0.359 •0.692 0.590 0.833 -0.461 N 0.257 0.062 0.692 •0.708 0.870 -0.575 DD 0.432 0.023 0.590 0.708 •0.774 -0.426 DLOCE 0.351 0.014 0.833 0.870 0.774 • −0.556 BCE −0.142 0.051 −0.461 −0.575 −0.426 −0.556 • measures that are more correlated with these complexity measures (remember that all correlation coefficients can be seen in Tables 6.5 and 6.6. McCabe’s complexity is highly correlated with the number of conjunctions, disjunctions, equalities and inequalities (0.934, 0.925, 0.829 and 0.811 in 100%CP and 0.937, 0.936, 0.803 and 0.827 in ¬100%CP, respectively). These high coefficients were expected because McCabe’s complexity depends on the CFG of the program. Halstead Difficulty is highly correlated with the other Halstead measures. In addition, it is highly correlated with McCabe’s complexity (0.796 in 100%CP and 0.698 in ¬100%CP). LOCE is highly correlated with the total number of decisions and SLOC (0.976 and 0.974) in 100%CP and in ¬100%CP (0.814 and 0.717). These results were expected because SLOC and LOCE are very similar measures and the total number of decisions gives us an idea of the length of the code. The Halstead Length is highly correlated with LOC and SLOC, with a minimum value of correlation of 0.906. Moreover, the other Halstead measures are highly correlated too, except Halstead Difficulty and Level. This indicates that several Halstead measures are similar to a simple count of lines of code. In this subsection we have provided an overview of static measures that are part of our study. Now, we know the measures that are similar and those that are different. In the next section we show the measures that are more correlated with the branch coverage, which is the way we measure the difficulty of testing a program. 6.6.2 Correlation Between Coverage and Static Measures In the previous section we showed the basic relationship among the static measures, in this section we include the branch coverage in the study. The existing correlations between the branch coverage and the static measures studied give us an idea of which static measures are useful to determine
90 6.6. EMPIRICAL RESULTS a priori the complexity of the automatic test data generation task. In this study we have applied three different test data generators, two based on evolutionary techniques (ES, GA) and one based on random testing (RND). Table 6.9: Relationship between the most important static measures and the average branch coverage for all the algorithms. We highlight the highest value of correlation for each algorithm and benchmark. 100%CP ¬100%CP ES GA RND ES GA RND MC -0.150 -0.226 -0.074 -0.177 -0.168 -0.173 HD 0.070 -0.101 0.077 0.069 0.067 0.079 LOCE -0.186 -0.251 -0.133 -0.461 -0.452 -0.476 N -0.543 -0.381 -0.434 -0.563 -0.554 -0.589 DD -0.439 -0.304 -0.311 -0.476 -0.473 -0.497 DLOCE -0.504 -0.345 -0.397 -0.577 -0.564 -0.602 BCE 0.510 0.375 0.534 0.714 0.698 0.732 The first question we should answer is if there exists a link between the coverage and the traditional measures of code complexity: McCabe’s, Halstead’s, and LOCE. In Table 6.9 we show the correlation coefficients for the most important static measures and the branch coverage obtained with three automatic test data generators. The correlations between Halstead’s Difficulty and the coverage are very low, so the answer is no in this case. The correlation coefficients of McCabe’s complexity are higher than Halstead Difficulty but too low. This result was expected because, as we showed in the previous section, Halstead Difficulty is highly correlated with McCabe’s complexity. Finally, the correlation coefficients of LOCE indicate that it is more correlated with the branch coverage because this measure takes into account the nested statements. After analyzing these results, we realise that the traditional complexity measures (MC, HD, and LOCE) are not useful to measure the difficulty of testing a program. In the second group of measures, there exist higher correlations with branch coverage. The nesting degree is the static measure with the highest correlation coefficient with branch coverage in the 100%CP benchmark for the evolutionary test case generators. On the other hand, DLOCE is more correlated than the nesting degree in the ¬100%CP benchmark. Despite that the total number of decisions is not correlated with coverage, as can be seen in Tables 6.5 and 6.6 in the Appendix, the density of decisions correlates with the obtained coverage, as we show in Table 6.9. Moreover, the density of decisions is also more correlated than the traditional complexity measures. In Figure 6.6 the trend indicates that the programs with a high density of decisions are more difficult to test because a lower coverage is obtained. After analyzing the LOCE measure, we supposed that if the influence of the LOC were removed by dividing LOCE by LOC, it could be obtained a measure with a high influence of the nested level (DLOCE) (recall that that the LOCE measure weighs those nested statements). As the nesting degree is highly correlated with the branch coverage, the DLOCE would have high correlation too. After doing the correlation test, our expectations were true, as one can see in Table 6.9. These results are similar to the results obtained with the nesting degree. In the case of the benchmark ¬100%CP, DLOCE has more influence than nesting (N) in general. In Figure 6.7, we can see that the coverage clearly increases as the DLOCE decreases with the exception of the programs with DLOCE between 7 and 8.
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 91 Figure 6.6: Boxplots showing the branch coverage against the Density of Decisions for GA in ¬100%CP. Figure 6.7: Boxplots showing the branch coverage against the DLOCE for GA in ¬100%CP.
92 6.6. EMPIRICAL RESULTS Let us analyze the nesting degree. In Table 6.10, we summarize the obtained coverage in programs with different nesting degree in the two benchmarks of programs. If the nesting degree is increased, the branch coverage decreases and vice versa. It is clear that there is an inverse correlation between these variables. These correlation values are the highest ones obtained in the study of the different static measures, so we can say that the nesting degree is the feature with the highest influence on the coverage that evolutionary and random testing techniques can achieve. Nested branches pose a great challenge for the search. The high correlation value of the nesting degree supports that claim. Table 6.10: Relationship between the nesting degree and the average coverage for all the algorithms. The standard deviation is shown in subscript. We highlight the highest values of branch coverage for each algorithm and benchmark. 100%CP ¬100%CP Nesting degree ES GA RND ES GA RND 1 96.30 4.83 96.67 5.78 86.13 10.81 82.32 8.16 82.51 7.89 81.36 7.97 2 92.28 7.66 95.33 7.11 79.87 13.06 73.43 11.70 73.92 11.58 71.86 11.66 3 83.92 12.06 92.68 10.28 73.46 13.99 69.85 15.35 70.33 15.46 68.20 15.23 4 81.44 14.32 85.41 13.96 68.67 16.03 62.55 17.93 62.37 18.07 59.83 17.82 5 - - - 53.81 21.09 54.48 21.57 51.83 20.80 6 - - - 50.32 21.14 50.78 21.90 46.33 20.93 7 - - - 44.31 20.57 45.33 20.77 42.77 19.68 ρ-0.543 -0.381 -0.434 -0.563 -0.554 -0.589 Finally, we analyze the BCE measure, the new measure proposed to estimate the difficulty to generate an adequate test suite. In the 100%CP benchmark the correlation between this new measure and the coverage was 0.510 for ES, 0.375 for GA and 0.534 for RND, as we can see in Table 6.9. The obtained correlation coefficients when an RND generator is used are higher because the Markov model is inspired on it. In addition, in the ¬100%CP the correlations are even higher: 0.714 for ES, 0.698 for GA and 0.732 for RND. This promising measure is more correlated with the coverage (especially in the RND generator) than the nesting degree and the other static measures. This suggests that it is the best static complexity measure for measuring the difficulty of testing a program by an automatic test data generator. In Figure 6.8 we show the obtained average branch coverage with the random test data generator against the BCE measure. The trend is clear: the lower the value of Branch Coverage Expectation, the lower the coverage. We have opened a way to estimate the difficulty to test a program that is better than using the existing complexity measures or other known static measures like the nesting degree. 6.6.3 Another use of the Branch Coverage Expectation As we detailed in Section 6.3 for each branch (BBi, BBj) the expected number of test cases required to traverse it is 1/E[BBi, BBj]. Then, given a number of test cases x, we can compute the number of branches that would be theoretically traversed if the tester execute xrandom test cases, according to this equation:
CHAPTER 6. ESTIMATING SOFTWARE TESTING COMPLEXITY 93 Figure 6.8: Average Branch Coverage of RND against the BCE measure. f(x) = (i, j) 1 E[BBi, BBj]< x.(6.19) Thanks to this estimation, we propose a theoretical prediction about the behavior of an automatic test data generator based on random testing. In Figure 6.9 we show a plot for a particular program with the expected theoretical behavior together with the experimental data obtained using the average branch coverage of the 30 independent executions of an RND generator for that program. The features of this test program are shown in Table 6.11. The resulting curves show that our theoretical prediction and the experimental data are very similar. The theoretical prediction is more optimistic because it does not take into account data dependencies. At the first steps of the algorithm, the experimental behavior is better than the theoretical prediction, but in the region of high coverage (close to 90%), the behavior of the RND test data generator is worse than expected. One explanation for this behavior could be the presence of data dependencies in the program, which is not considered in the theoretical approach in order to keep it simple. This new proposal is useful to decide which is the best way of generating a test suite for a piece of code. It could be useful to decide the parameters of an evolutionary test data generator prior to its execution, for example, the stopping condition. It is also a way to simulate the Multi-objective approach, so you know the expected branch coverage using a particular number of test cases, for any number of them.
100 7.2. EXPERIMENTAL METHODOLOGY Figure 7.1: The general scheme of the two proposed approaches. •RQ3: How good is the mM approach performance in optimizing the coverage and the test suite size? •RQ4: Which approach is the best? In order to completely answer the questions we should use all the possible automatic test data generators both in multi and mono-objective or, at least, a large number of them. We can also focus on some test data generators and answer the previous questions on them, taking into account that in this case the results will be valid for the test data generators considered. This is what we do in this thesis. In particular, we study the MOTDGP with two objectives, maximizing the branch coverage and minimizing the oracle cost. Among our contributions, we generate the test data and we also minimize the number of tests needed to achieve different values of coverage of the program. The solutions are provided as Pareto fronts. For the MM approach, we use five test data generators: four of them based on evolutionary testing and an additional one based on random search. In the mM approach we use three mono-objective test data generators with a second phase of multi-objective test data selection. 7.2 Experimental Methodology This section is aimed at presenting the two approaches proposed to solve the MOTDGP that we have already defined formally in Section 2.2.2. It outlines the indicators used to measure the quality of the obtained results and the benchmark programs we have used. In this section we also describe how the solutions of the problem have been encoded and the genetic operators employed, the configuration of the algorithms, and the methodology we have followed. 7.2.1 The MM Approach The MM approach considers the conflicting objectives during all the test data generation process, thus a priori, it focuses on both objectives during all the process. In this approach a solution to the problem is a test suite, that is, a set of test data. These test suites are evaluated according to both objectives. The evaluation of the first objective (coverage) requires, in general, the execution of the test suite over the SUT. The evaluation of the second objective is a simple count of the number of test data in the set.
CHAPTER 7. MULTI-OBJECTIVE TEST DATA GENERATION 101 Details of the Multi-objective algorithms Here we detail the configuration of the operators and the encoding of the solutions used in the multi-objective algorithms. In the multi-objective approach, each individual is encoded as a set of test data. Table 7.1 shows the parameters of the multi-objective EAs used in the experimental section (all of them were previously described in Section 4.2). As genetic operators, we have used 2-tournament (binary tournament) as the selection scheme. This operator works by randomly choosing two individuals from the population and the one dominating the other is selected; if both solutions are non-dominated one of them is randomly selected. Table 7.1: Parameters of the multi-objective EAs used in the experimental section. NSGA-II MOCell SPEA2 PAES Population 20 indivs. 20 indivs. 20 indivs. 20 indivs. Selection BT, 2 indivs. BT, 2 indivs. BT, 2 indivs. BT, 2 indivs. Mutation Adaptive Mutation Adaptive Mutation Adaptive Mutation Adaptive Mutation Crossover Union Crossover Union Crossover Union Crossover - Replacement Elitist Elitist Elitist Elitist Total Evals. 150000 evals. 150000 evals. 150000 evals. 150000 evals. The best results were obtained with the union crossover that takes two solutions, C1and C2, and creates a new one Cthat is the union of both, that is: C=C1∪C2. If the resulting solution Chas more coverage than C1and C2then Cis the new offspring. Otherwise, the solution with more coverage (C1or C2) is the new child. Finally, the mutation operator adds new test data to the solution with probability 0.6, deletes one test datum with probability 0.2 and keeps the individual unchanged with probability 0.2. In the case of adding test data, the number of new test data is 30% of the test data present in the solution. If the resulting individual has the same coverage and more test data, at the end of the iteration, the algorithm deletes it from the population because this solution is dominated. All the multi-objective algorithms have been implemented using jMetal [66], a Java framework aimed at the development, experimentation, and study of metaheuristics for solving multi-objective optimization problems. 7.2.2 The mM Approach In this section we present the second approach. In this approach we use a mono-objective test data generator to obtain a set of test data with the highest coverage. The mono-objective test data generator deals with only one branch of the program at the same time. This is a beneficial feature to obtain high coverage because the search can focus on covering the most complex branches of the program. However, the resulting test suite is usually large, redundant and inefficient because these algorithms do not try to minimize the test suite size. One way to reduce the number of test cases in a test suite, and still test the same functionality, is by solving a Multi Objective Test Case Selection Problem (MOTCSP) on the given test suite. This problem was recently formalized by Yoo and Harman in [226] as follows: Given a test suite Tand several objective functions Fi, we must find a subset T′⊆Tsuch that T′is a Pareto optimal set with respect to the objective functions. The resulting subset of the test suite, T′, is composed of the non-dominated solutions considering the objectives as equally important. In order to solve the MOTCSP we always use in these experiments the multi-objective algorithm NSGA-II. Our implementation is able to generate a Pareto front from thousands of test cases
102 7.2. EXPERIMENTAL METHODOLOGY previously generated by the mono-objective algorithms. But first, we delete repeated test cases from the obtained test suite in order to reduce from thousands of test cases to hundreds of them. Two test cases are repeated when both of them traverse the same branches. We have compared the results obtained with and without this reduction phase, and the results are better when this reduction is applied. Finally, for the mono-objective algorithm involved in the first phase of test data generation, we use three different algorithms: a genetic algorithm, an evolutionary strategy and a random search, described in Section 4.1. Details of the Mono-objective algorithms In this work, each solution is encoded as an integer/real vector of length n(the number of arguments). As we said when we explained the test data generator (Section 5.2) the generator breaks down the global objective (to cover all the branches) into several partial objectives consisting of dealing with only one branch of the program. Thus, two stopping conditions exist: one for partial objectives and the other one for the whole test data generation process. The search for one partial objective stops when 1,000 evaluations are performed while the test data generation process ends after 150,000 evaluations. In our GA we use as recombination operator the uniform crossover (UX), in which each component of the new solution is randomly selected from the two parents. The formal definition is the same as equation (4.1) with bias = 0.5. The mutation operator adds a random value to the components of the vector. That is, xi=xi+U(−500,500) (7.1) where the probability distribution of these random values is a uniform distribution in the range [−500,500]. However, not all the components of the individual are perturbed, only half of them are. In our ES, we use a discrete crossover operator and a Gaussian mutation. We show in Table 7.2 a summary of the parameters used by the two EAs in the experimental section. Table 7.2: Parameters of the two mono-objective EAs used in the experimental section. ES GA Population 25 indivs. 25 indivs. Selection Random, 5 indivs. Random, 5 indivs. Mutation Gaussian Add U(−500,500) Crossover discrete (bias = 0.6) Uniform + arith. + arith. Replacement Elitist Elitist Stopping cond. 1,000 evals. 1,000 evals. Total Evals. 150,000 evals. 150,000 evals. After the execution of the test data generator, we obtain a huge table of coverage where the test data that satisfy a concrete branch during the execution are saved. Then, a test data selection is performed over this set using a standard NSGA-II.
CHAPTER 7. MULTI-OBJECTIVE TEST DATA GENERATION 103 7.2.3 Benchmark of Test Programs In the experimental section we use two benchmarks. The first one is composed of 800 synthetic programs and the second one is composed of 13 real-world programs1. Synthetic Programs Our program generator (Section 6.5.2) can create programs having the same value for the static measures, as well as programs having different values for the measures. In addition, the generated programs are characterized by having a 100% coverage, thus all possible branches are reachable. Our program generator takes into account the desired values of some static measures. The static measures selected are: the number of atomic conditions, the nesting degree, the number of sentences and the number of variables. The main features of the generated programs are: they deal with integer input parameters, their conditions are joined by whichever logical operator, they are randomly generated and all their branches are reachable. The methodology applied for the program generation was the following. First, we analyzed a set of Java source files from the JDK 1.6 (java.util.*, java.io.*, java.sql.*, etc.) and we computed the static measures on these files. Next, we used the ranges of the most interesting values, obtained in this previous analysis as a guide to generate Java source files having values in the same range for the static measures. This way, we generated programs with the values in these ranges, e.g., nesting degree in 1-4 (25% for each value), atomic conditions per condition in 1-4 (68.43% with 4 conditions per decision), and statements in 25, 50, 75 or 100 (25% for each value). The percentage of control flow statements is 32.23% (in this work we use IF statements), this means that the test case generator should cover around 64 different branches (32 true and 32 false) in programs with 100 statements. The previous values are realistic with respect to the static measures, making our study meaningful. Besides, we generated 50 programs for each size and nesting degree (50 x 4 sizes x 4 nesting degrees = 800), which is a total of 800 Java programs. Real Programs In order to improve the interest of our work we propose an additional benchmark of real programs. It is composed of the ten real programs used in the previous chapter (Table 6.4) and three additional programs extracted from the literature. The main features of the new programs are listed below. Table 7.3: Characteristics of the real programs. Name ND LOC Branches Arguments Description complex 3 74 24 6 Integer Calculate complex arithmetic functions remainder 6 49 18 2 Integer Calculate the remainder of an integer division tmyers 6 54 12 3 Integer Classify triangles in 4 types: Myers 7.3 Experimental Analysis In this section we present the results of the two proposed approaches. In the first subsection we analyze the MM approach and we compare the performance of the multi-objective algorithms. In the second subsection we study the mM approach and we compare the performance of the monoobjective algorithms used as the base for the approach. Then, in a third subsection we compare 1They are available at http://neo.lcc.uma.es/staff/javi/resources.html
104 7.3. EXPERIMENTAL ANALYSIS the two proposed approaches for the academic benchmark, and finally, in the last subsection, we compare both approaches with a benchmark of real programs. The benchmarks used were described in Section 7.2.3. We performed 30 independent runs of each algorithm and program, in order to obtain a very stable average of the measures. All test data generators used in this work proceed by generating test data until a maximum of 150,000 test data are generated. We also perform a multiple comparison statistical test for each program on the obtained results to compare the algorithms among them. We set a confidence level of 95% (p-value under 0.05) for the whole comparison (all the algorithms acting on a program) and we used the Bonferroni correction for each particular comparison. 7.3.1 Evaluation of the MM approach In this section, we analyze the behavior of the multi-objective algorithms with the aim of be able to answer RQ1. We have analyzed 800 programs, so we cannot represent all HV values for all the programs. For this reason, we summarize in Table 7.4 the times one algorithm has better median HV than the others. We have classified the results according to the nesting degree and the size of the SUT. For this indicator, the higher the value, the better the quality of the obtained results. Thus, by looking at the tables, we can see that MOCell was usually the algorithm computing clearly the best results regarding HV. However, when the programs are small (25-50 statements) and complex (nesting degree four), the NSGA-II algorithm has a better behavior. We must highlight the big difference between MOCell (443), NSGA-II (198) and the others altogether (43). Then, we compare the HV values of all the programs and independent executions with the Kruskal-Wallis test. In each cell of a table of statistics we have a pair (number, triangle). The number indicates how many programs are significantly different, and the triangle indicates that the program in the row is significantly better (N) or worse (▽) than the program in the column. The results are summarized in Table 7.5. Although the previous values set a clear tendency, the absence of significant differences between MOCell, NSGA-II and SPEA2, does not allow us to say that MOCell is better than the other two. However, we can mention that RNDMulti is the worst algorithm in all the programs (800) and PAES is worse than MOCell in 18 programs, NSGA-II in 9 programs, and SPEA2 in only 2 programs. With the aim of showing an example of the computed fronts for the instances, we selected one program for each nesting degree, which can represent the typical behavior of the different algorithms in this kind of instance. In Figure 7.2 are depicted the 50%-attainment surfaces of these selected programs. In the instance with low nesting degree, MOCell dominates the others and has a good performance because it reaches almost the same or better coverage with the same test data. NSGA-II has a similar behavior except in the right extreme of the figure where it is not able to reach the same maximum coverage as MOCell. On the other hand, in the program with nesting degree 4, NSGA-II is the algorithm that is able to reach the best coverage and dominates all the other fronts. The other two multi-objective algorithms (SPEA2 and PAES) have problems finding the solutions with high coverage, in the upper-right bound of the figure, and are worse than MOCell and NSGA-II. RNDMulti is always the worst. MOCell has been able to find nondominated solutions in the right area where SPEA2, PAES and RNDMulti have not found any of them (solutions in the extremes of the front). This is related to a better exploration of the search space by MOCell. Specifically, this is one of the properties of the cellular GA model, on which MOCell is based. This fact has been reported in many studies on single-objective optimization (see [6]). There is only one exception, when a program has nesting degree 4 and it is more difficult to obtain high coverage, NSGA-II has the best performance.
CHAPTER 7. MULTI-OBJECTIVE TEST DATA GENERATION 105 Table 7.4: Programs in which the median hypervolume of one algorithm is better than the others. Nesting degree Statements MOCell NSGA-II SPEA2 PAES RNDMulti 1 25 10 1 0 0 0 50 24 9 0 2 2 75 34 6 1 1 0 100 38 4 0 1 0 Total 106 20 1 4 2 2 25 13 5 1 2 3 50 35 13 0 0 0 75 37 12 0 0 0 100 40 10 0 0 0 Total 125 40 1 2 3 3 25 18 11 3 1 2 50 33 15 0 0 0 75 32 16 1 0 0 100 30 19 0 0 0 Total 116 61 4 1 2 4 25 17 20 3 2 2 50 23 25 2 1 0 75 27 19 2 0 1 100 29 13 10 0 0 Total 96 77 17 3 3 Total 443 198 23 10 10 Table 7.5: Number of programs where there exists significant difference among the HV obtained. RNDMulti PAES SPEA2 NSGA-II MOCell MOCell 800N18N0 0 − NSGA-II 800N9N0−0 SPEA2 798N2N−0 0 PAES 750N−2▽9▽18▽ RNDMulti −750▽798▽800▽800▽ We have also analyzed the reduction obtained in the number of test cases, since one of our goals is to minimize the number of test cases. We analyze the reduction experienced using our approaches compared with the use of all the generated test cases. It is very difficult to analyze this reduction because not all the algorithms achieve a 100% coverage in all the programs. For this reason, we cannot simply average the number of test cases, but we must take into account the maximum obtained coverage in order to give the real reduction made by the multi-objective algorithm. The total reduction is from thousands of test cases generated to around ten, but this reduction could also be easily computed based in the table of coverage of the algorithms by choosing one test case per branch. The drawback of the latter approach is that the minimization of the test suite would be far from optimal. For this reason, we establish a theoretical upper bound of
106 7.3. EXPERIMENTAL ANALYSIS 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 Branch Coverage Number of Test Cases Nesting 1 MOCell NSGA-II SPEA2 PAES RNDMulti (a) Program with nesting degree 1 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 Branch Coverage Number of Test Cases Nesting 2 MOCell NSGA-II SPEA2 PAES RNDMulti (b) Program with nesting degree 2 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 Branch Coverage Number of Test Cases Nesting 3 MOCell NSGA-II SPEA2 PAES RNDMulti (c) Program with nesting degree 3 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 Branch Coverage Number of Test Cases Nesting 4 MOCell NSGA-II SPEA2 PAES RNDMulti (d) Program with nesting degree 4 Figure 7.2: 50%-attainment surfaces: coverage against the number of test cases. the required number of test cases needed. This upper bound is the number of branches that were achieved by the algorithm. We compute the real oracle cost of the test suites generated by any algorithm according to the next expression: upper bound(P, A) = BP∗MaxCov(P, A) oracle cost(P, A) = tc(P,A) upper bound(P,A) (7.2) where Pis a program, Ais an algorithm, BPis the number of branches of the program P, MaxCov(P, A) is the maximum coverage obtained by the algorithm Ain the program P, and tc(P, A) is the number of test cases needed by the algorithm Ato obtain the maximum coverage in program P. We can state that the oracle cost of the test suite generated by all the multi-objectives algorithms can be reduced by our approach, only 15.12% of the test cases are needed in comparison with the computed upper bound. This reduction is computed in the case of the maximum coverage, and hence the largest number of computed test cases. But we must bear in mind that our solution is a complete Pareto front offered to the expert to make a decision about the test suite that best fits his/her needs, therefore a similar percentage of reduction is carried out for each couple coverage-number of test cases that appears in the Pareto front.
CHAPTER 7. MULTI-OBJECTIVE TEST DATA GENERATION 107 In the TDGP, it is particularly hard to achieve a 100% branch coverage, especially if one uses a multi-objective algorithm because its execution is not entirely guided to obtain a total coverage. The multi-objective approach deals with all the branches at the same time, this provokes a lack of information. In addition, the search does not spend most of its effort to cover the most complex branches. In Table 7.6 we show the average of maximum coverage (among the solutions in the front) obtained with the solutions for all the programs with different nesting degree in order to answer RQ2. We highlight the maximum values in the table for each nesting degree. As we expected, MOCell’s performance is the best on nesting degree 1, 2 and 3. On the other hand, NSGA-II obtains the best coverage with nesting degree 4. Since the differences are low, we compared the coverage values of all the programs and independent executions with the Kruskal-Wallis test. The results are summarized in Table 7.7. As we expected, MOCell obtains significant differences in more programs with respect to PAES and RNDMulti, than NSGA-II and SPEA2. Table 7.6: Relationship between the nesting degree and the average maximum coverage for the multi-objective algorithms. The standard deviation is shown in subscript. Nesting degree MOCell NSGA-II SPEAII PAES RNDMulti 1 98.102.08 97.902.22 97.532.34 93.085.30 81.3612.74 2 94.773.44 94.423.49 93.563.75 87.596.31 75.0414.00 3 90.665.83 90.415.46 89.295.65 81.557.68 69.7713.87 4 85.509.45 85.778.18 84.618.12 75.879.22 63.8715.95 Total 92.267.54 92.126.99 91.247.24 84.529.72 72.5115.57 Table 7.7: Number of programs where there exists a significant difference among the coverage values obtained. RNDMulti PAES SPEA2 NSGA-II MOCell MOCell 800N800N2N0− NSGA-II 800N799N0−0 SPEA2 800N782N−0 2▽ PAES 711N−782▽799▽800▽ RNDMulti −711▽800▽800▽800▽ If we consider the HV obtained (Table 7.4), the significant HV differences (Table 7.5), the attainment surfaces and the average maximum coverage achieved showed in Table 7.6, it is clear that the ranking of the performance of the algorithms is: MOCell is the best, second NSGA-II, third SPEA2, fourth PAES, and finally RNDMulti, the worst one, as expected. 7.3.2 Evaluation of the mM approach In this section we analyze the mM approach and try to answer RQ3. First of all, we study the values of HV. We show in Table 7.8 the programs in which one algorithm has a better value of HV. It is noteworthy that when the nesting degree is the smallest (1) the ES obtains better results and when the nesting degree is large (3 and 4) the GA is better than the others. In other words, when the program is more complex, the GA is clearly the best. The ES is better in large programs (100 statements) except when the program has nesting degree four. Then, we compared the HV
108 7.3. EXPERIMENTAL ANALYSIS Table 7.8: Programs in which the median hypervolume of one algorithm is better than the others. Nesting degree Statements GA ES RNDMono 1 25 3 3 0 50 7 18 1 75 7 26 3 100 9 33 3 Total 26 80 7 2 25 13 8 1 50 23 17 0 75 23 22 1 100 18 29 1 Total 77 76 3 3 25 23 6 0 50 31 16 0 75 30 16 0 100 21 29 0 Total 105 67 0 4 25 37 3 0 50 41 6 0 75 39 11 0 100 34 14 0 Total 151 34 0 Total 359 257 10 values of all the programs and independent executions with the Kruskal-Wallis test. The results indicate that there is no significant difference between GA and ES (Table 7.9). As we expected, the results of RNDMono are worse than ES in 786 programs and GA in 765 programs. Table 7.9: Programs where a significant difference exists among the HV obtained. RNDMono ES GA GA 765N0− ES 786N−0 RNDMono −786▽765▽ Second, we show the 50%-attainment surfaces of four representative programs with different nesting degree in Figure 7.3. In the instance with nesting degree 1, the attainment surfaces are very similar between GA and ES. RNDMono is far from the behavior of the others. In the instance with nesting degree 2, the three algorithms obtain similar results. The instances with nesting degree 3 and 4, represent the general behavior of the algorithms in most of the programs. The RNDMono is far from the others, the ES obtains similar values of coverage to the GA with the same number of test cases, but GA can achieve the best value of coverage. The GA is the best algorithm in maximum obtained coverage. This is related to a better exploitation of the search space by GA.
CHAPTER 7. MULTI-OBJECTIVE TEST DATA GENERATION 109 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 14 16 18 Branch Coverage Number of Test Cases Nesting 1 GA ES RNDMono (a) Program with nesting degree 1 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 14 16 18 Branch Coverage Number of Test Cases Nesting 2 GA ES RNDMono (b) Program with nesting degree 2 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 14 16 18 Branch Coverage Number of Test Cases Nesting 3 GA ES RNDMono (c) Program with nesting degree 3 30 40 50 60 70 80 90 100 0 2 4 6 8 10 12 14 16 18 Branch Coverage Number of Test Cases Nesting 4 GA ES RNDMono (d) Program with nesting degree 4 Figure 7.3: 50%-attainment surfaces: coverage against the number of test cases. In order to highlight the reduction of the test cases needed to achieve the maximum coverage, we have applied Equation (7.2). We can state that the oracle cost of the test suite generated by the three studied mono-objective algorithms can be reduced by our approach, only 19.32% of the test cases are needed in comparison with the computed upper bound. This percentage of test cases needed to achieve a concrete coverage is larger than the one obtained with the MM approach (15.12%). Now, let us analyze the best value of coverage obtained with the three algorithms. In Table 7.10 we show the average of maximum coverage of the three algorithms. As is known, achieving a total coverage is a great challenge for the search, for this reason, we consider that an algorithm must focus on obtaining a high value of coverage. In this sense, the GA and ES obtain very good values of coverage, both above 90% in all the cases. However, the average coverage obtained by the GA is always the best. This advantage of the GA increases in programs with higher nesting degree where high values of coverage are very difficult to obtain. We performed a statistical test (Table 7.11), but, although the GA obtains the best results, significant differences only exist in 23 programs between GA and ES. Thus, it seems that GA is the best in obtaining a high value of coverage, specifically in more complex programs.
116 7.4. CONCLUSIONS 0 20 40 60 80 100 0 2 4 6 8 10 12 14 16 18 Branch Coverage Number of Test Cases GA ES MOCell NSGA-II Figure 7.5: 50%-attainment surfaces: coverage against the number of test cases for the program line. been ignored in most of the previous studies. For this reason, in this work we have dealt with the coverage and the oracle cost as equally important targets. Our study has been performed on 800 synthetic programs. We used our program generator able to produce programs ensuring a 100% of branch coverage. This kind of programs is very useful because all the branches are reachable and we can compare the algorithms in a fair way using coverage. In addition, we have also analyzed the two proposed approaches with a benchmark of 13 real and popular programs in the literature. We have evaluated four state-of-the-art multi-objective optimization algorithms: MOCell, NSGA-II, SPEA2, and PAES, two mono-objective algorithms GA, ES, and two random algorithms as merely a ‘sanity check’. This comparison has been done on the basis of three quality indicators: the hypervolume, the 50%-empirical attainment surface, and the average maximum coverage obtained by those algorithms. We can see a final ranking of algorithms in Table B.1. In terms of convergence towards the optimal Pareto front, GA and MOCell have been the best solvers in our comparison. On the one hand, MOCell has obtained the best fronts in programs with nesting degree 1 and 2, values commonly found in practice. On the other hand, GA is the best algorithm for facing programs with high nesting degree and it is the algorithm which is significantly better in most of the programs, attending to the HV indicator and to the average maximum coverage. This fact indicates that GA is the best alternative if the tested program has a high nesting degree or we need a high coverage. But, if we have time restrictions, we highly recommend the use of MOCell as a search engine for an automatic test data generator. Although the multi-objective approach is working very well in most of the programs, we realized that dealing with only one branch at the same time (mono-objective approach) can be more effective when the program under test has high nesting degree. In addition, we must highlight that both approaches (MM and mM ) are quite good at reducing the number of test cases needed to obtain a given
CHAPTER 7. MULTI-OBJECTIVE TEST DATA GENERATION 117 Table 7.19: Ranking of algorithms according to maximum coverage and hypervolume grouped by nesting degree. Coverage Rank ND 1 ND 2 ND 3 ND 4 All 1 GA GA GA GA GA 2 ES ES ES ES ES 3 MOCell MOCell MOCell NSGA-II MOCell 4 NSGA-II NSGA-II NSGA-II MOCell NSGA-II 5 SPEA2 SPEA2 SPEA2 SPEA2 SPEA2 6 PAES PAES PAES PAES PAES 7 RNDMono RNDMono RNDMono RNDMono RNDMono 8 RNDMulti RNDMulti RNDMulti RNDMulti RNDMulti Hypervolume Rank ND 1 ND 2 ND 3 ND 4 All 1 MOCell MOCell GA GA GA 2 NSGA-II GA MOCell MOCell MOCell 3 ES NSGA-II NSGA-II ES ES 4 GA ES ES NSGA-II NSGA-II 5 PAES SPEA2 SPEA2 SPEA2 SPEA2 6 SPEA2 PAES PAES PAES PAES 7 RNDMono RNDMono RNDMono RNDMono RNDMono 8 RNDMulti RNDMulti RNDMulti RNDMulti RNDMulti coverage. The oracle cost can be greatly reduced because the mM approach only needs 19.32% of the upper bound of test cases needed for obtaining the maximum value of coverage, and the MM approach is even better, only needing a 15.12% of the test cases. This improvement justifies the use of our approaches to deal with the MOTDGP.
118 7.4. CONCLUSIONS
Part III Functional Testing 119
Chapter 8 Combinatorial Interaction Testing using Classification Tree Method 8.1 Introduction Software product specifications provide fundamental information of the software, meanwhile structural information is omitted. Software product specifications can be used as a guide for designing functional tests for the software product. However, there is no standard representation of the SUT. The Classification Tree Method [91] is a particular representation of the SUT, which is based on the category partition method [167]. It decomposes a test domain into disjoint classes representing important aspects of the test object. Frequently, the systems under test tend to be large and exhaustive testing is generally impractical. Therefore, we should use an adequacy criterion less exhaustive but with certain level of confidence, one widely used technique is Combinatorial Interaction Testing. CIT is a black box sampling technique derived from the statistical field of design of experiments. It is used to determine the smallest possible subset of tests that covers all combinations of values specified by a coverage criterion with at least one test case. A coverage criterion is defined by its strength tthat determines the degree of parameter interaction and assumes that all parameters are considered. The most common coverage criterion is 2-wise (or pairwise, t= 2) testing, that is fulfilled if all possible pairs of values are covered by at least one test case in the result test set. Hence, this criterion is the chosen one in this thesis dissertation. In addition, when the resources are limited in time or cost, important test cases should be executed earlier, then the prioritization of test cases is a must. The prioritization of test cases may reveal faults in early stages of the testing phase. Prioritization can be computed in two ways: (1) reorder an existing test suite based on a prioritization criteria; and (2) generate an ordered test suite, taking into account the importance of combinations. Consequently, we study here the Prioritized Pairwise Test Data Generation Problem (PPTDP) previously defined in Section 2.4.1. We evaluate the performance of metaheuristic techniques and compare the two different prioritization approaches. In order to achieve this objective we perform a comparison among five algorithms on a set of benchmarks found in the literature. Although combinatorial testing has been widely studied, we still find two main issues that have not been addressed by the traditional generation of test suites: the dependencies between individual test cases and the state of the SUT. Sometimes software is required to be in a particular 121
122 8.2. PRIORITIZED PAIRWISE TEST DATA GENERATION USING CTM state to test a given functionality. This is the case of most software artifacts. Actually, in very large software systems, the cost incurred to place the system in a certain state can be an issue. For example, testing the anti-lock braking system (ABS) of a car requires that the car reaches a certain speed before the system can be tested. So it makes sense to consider the generation of test sequences that allow us to test a particular functionality (acceleration of the car) while we change the state of the SUT (considering the dependency rules in the test cases) to test the next functionality (ABS). The implicit cost savings of using this technique is the reason why the generation of test sequences is relevant and deserves more research effort. In this sense, we have extended the CTM (ECTM) in Section 2.4.2 to be able to automatically generate test sequences, since it cannot be done automatically by means of the CTE XL professional tool1. We study the Test Sequence Generation Problem (TSGP), previously formulated in Section 2.4.2. We have compared the behavior of two metaheuristic techniques with an existing greedy algorithm [126]. The first proposed approach is a GA called Genetic Test Sequence Generator (GTSG). We have improved a GTSG with the addition of a Memory Operator (MemO), which is based on the operator proposed by Alba et al. [4]. It is used to reduce the amount of resources needed to compute a solution. The other proposed algorithm is based on the ACO, described in Section 4.1.3. Specifically, we propose a new technique based on ACO that is able to deal with large construction graphs. It is able to find near-optimal solutions in separated areas of the search space for the Test Sequence Generation Problem (TSGP). It is called ACO for test sequence generation (ACOts). Both proposed metaheuristics are used to generate test sequences to obtain full class and transition coverage of 12 different programs extracted from the literature. Overall, we can raise the following research questions and try to answer them in an extensive experimental study. •RQ1: Is our evolutionary approach effective when dealing with prioritization? •RQ2: Do the test sequences generated by evolutionary approaches save resources? The Classification Tree Editor (CTE) [132] is a commercial tool supporting the CTM (Figure 8.1). This tool is able to automatically generate test data, therefore we have followed its specification to integrate our proposals in this tool. 8.2 Prioritized Pairwise Test Data Generation using CTM Software testers are faced with situations in which there is not enough time for testing, since the software under test must be finished on time for the release date not to be delayed. Hence, software testers have to deal with limited resources, unfinished systems, and not much time to test the software. Although a tester aims at executing as many test cases as possible, often a test case selection has to be done. The prioritization of test cases is a re-ordering of tests to find faults in early stages. But, if the time run-out, this technique also allows the tester to specify the desired level of coverage and failure-detection. The result of the prioritization is then a schedule of test cases so that those with the highest priority, according to some criterion, are executed earlier. In this study, priorities are assigned to the classification tree elements (see Section 2.4.1) in order to indicate the importance of the element. These weights can be used to guide the test case generation in order to cover first the most important values. There exist different prioritization techniques. Elbaum et al. provide good overviews of existing approaches [67,68]. The following three models were selected to provide a basis for prioritization: 1This is a commercial tool developed by Berner & Mattner company. It was recently renamed as TESTONA
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 123 Figure 8.1: CTE XL professional tool. •Prioritization based on a usage model [211] tries to reflect usage distribution of all classes in terms of usage scenarios. Classes with a high occurrence have higher weights than classes with a low occurrence. •Prioritization based on an error model [67] aims to reflect distribution of error probabilities of all classes. Classes with a high probability of revealing an error have higher weights than classes with a low probability. •Prioritization based on a risk model [13] is similar to prioritization based on an error model but also takes error costs into account. Classes with a high risk have higher weights than classes with a low risk. Since we are facing here the Prioritized Pairwise Test Data Generation problem, we need to define weights for each pair of classes. This is done by multiplying the weight of each class involved in the pair. Following the Video Game example (Figure 2.2) the pair weight for (Startup (Playing), running) is 0.63 * 0.52 = 0.3276 . 8.2.1 Solution Approaches This study aimed to evaluate the performance of metaheuristic techniques for dealing with the PPTDGP. In order to achieve this objective we perform a comparison among five algorithms on a set of benchmarks found in the literature. We first introduce the details of our evolutionary approach, a genetic algorithm. To the best of our knowledge the author of this thesis was the first to apply an evolutionary approach to the target problem [75]. Then, we briefly describe two deterministic algorithms that we have implemented for comparison purposes, the Prioritized
124 8.2. PRIORITIZED PAIRWISE TEST DATA GENERATION USING CTM Pairwise Combination algorithm (PPC) and the Plain Pairwise Sorting (PPS). We finally present the Deterministic Density Algorithm (DDA) developed in [37] and an algorithm based on Binary Decision Diagrams (BDD) introduced by Lee [131]. Prioritized Genetic Solver The Prioritized Genetic Solver (GS) is an evolutionary approach that constructs an entire test suite taking into account priorities in the generation. It is a constructive algorithm that adds one new test datum to the partial solution in each iteration until all pairwise combinations are covered. In each iteration the algorithm tries to find the test datum that adds more coverage to the partial solution. Overall, our algorithm aims at generating an entire test suite (to cover all pairwise combinations) by generating the best test datum at a time until all pairwise combinations are covered. The best test datum is the one that most reduce the weighted value of the set of remaining pairs to cover. In this particular implementation we have used a single point crossover with probability 1 of recombining the two selected individuals. This operator is able to put together good solution components that are scattered in the small population used of 4 individuals. Regarding the mutation operator, it iterates over all the components in the solution vector changing its value by a random one of the same classification with probability 0.05. The maximum number of evaluations used as stopping criterion in the internal loop is 5,000 while the stopping condition of the external loop is to achieve full pairwise coverage. The computation of the fitness value for each solution is done through the following process: The algorithm computes the combined class pairs of the partial solution (the next test datum). After that, it removes these pairs from the set of remaining pairs. Finally, the fitness value of a solution is computed as the sum of the weights of the remaining pairs. That is, the objective value of a proposed test datum is the sum of the weights of the class pairs that are not covered yet after adding the test datum to the suite. This objective function must be minimized in order to take first the test datum covering the class pairs with higher weights. As the search progresses the computational cost of computing the fitness function is reduced, since less class pairs remain uncovered. Prioritized Pairwise Combination In this algorithm, the class pair with the highest weight from the set of uncovered class pairs is chosen for the new test datum. We determine all candidate test data containing this class pair and calculate the index values for these candidates. This index value includes the weights and the number of newly covered class pairs. PPC then selects the test datum with the highest assigned index value. This way, we can guarantee that the nfirst test data cover the nmore important class pairs. The generation process using PPC is deterministic: the same test suite is generated for identical classification trees. Plain Pairwise Sorting This algorithm first applies a plain pairwise algorithm (the one integrated in CTE XL professional tool), which computes a set of test data covering all the class pairs. Then it sorts the test data taking into account their absolute weight at first. Then, it applies as many discriminatory reorderings as test data. Note that this approach does not guarantee coverage of any nmost important class pairs by the nfirst test data. However, the generated test suite will have exactly the same size
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 125 as the plain pairwise combination, as the suite does not grow by sorting. The generation process using sorting is deterministic, however its results differ from the PPC results. Deterministic Density Algorithm In the Deterministic Density Algorithm [37] one test datum is constructed at a time and new test data are generated until all t-tuples are covered. Each classification is assigned a class value oneat-a-time. A classification that has been assigned a class value is referred to as fixed; one that has not, as free. For each classification, the class value that covers the largest density is selected. Then, a density formula calculates the likelihood of covering future tuples. To modify DDA to account for prioritization, the density formula is modified. Instead of computing the ratio of uncovered pairs to be covered, the amount of weight to be covered is computed. Binary Decision Diagrams Algorithm Binary Decision Diagrams [131] are acyclic directed graphs used to represent propositional logical formulas. In [186] the authors introduced an approach based on the modeling of the combinatorial interaction test problem as a single propositional logic formula. They constructed the formula such that the set of satisfying interpretations of the formula corresponds to the set of valid test cases and such that a one-to-one relation between a satisfying interpretation of the formula and a valid test case of the CIT problem exists. The formula is the conjunction of a subformula representing the set of all test cases and a subformula representing the set of constraints. They have used this formula in a greedy algorithm, in the following BDD, to select test cases until the desired coverage criterion is fulfilled. 8.2.2 Experimental Benchmark The experimental benchmark used for the comparison among algorithms was proposed in [37]. The scenarios S1−S8 are given in Table 8.12. The number of classes of each scenario are given in a shorthand notation, where for example S5 with 82726224consists of 2 classifications with 8 classes, 2 classifications with 7 classes, 2 classifications with 6 classes, and 4 classifications with 2 classes. Table 8.1: Scenarios and number of factors. Scenarios #Classes S1 34 S2 1020 S3 3100 S4 1019181716151413121 S5 82726224 S6 1511055141 S7 350250 S8 2021023100 The given benchmark uses four different weight distributions applied to the eight scenarios. The distributions are: 2They are available at http://neo.lcc.uma.es/staff/javi/resources.html
132 8.3. TEST SEQUENCE GENERATION USING ECTM 8.3.1 Algorithms Details In this section we describe three different approaches used to solve the TSGP. We first introduce an evolutionary approach, a Genetic Algorithm. Second, we describe our algorithmic proposal based on ACO. Finally, we briefly describe a state of the art technique from the literature for comparison purposes. We would like to highlight that the size of the test cases that compose a test sequence can vary from one to another. This fact is due to the hierarchical structure of the model. One class could be refined in several sub-classes, then the length of the test cases would be different. Consequently, we have to deal with the dynamic size of test cases in the ECTM. Genetic Test Sequence Generator The Genetic Test Sequence Generator (GTSG) constructs an entire test suite taking into account the dependencies between test data in the generation of the sequence. GTSG is an algorithm that evolves a population of solutions in each iteration until a given coverage criterion is fulfilled. The algorithm tries to find the tests that maximize the coverage, then it sequentially adds them to the solution (test sequence). In this particular algorithm the representation of a solution sol (test sequence) is a vector of integers of length l. We determine the length of the chromosome as a parameter of the memory operator (see next subsection). sol = [I1, I2, I3, ..., Il]. The outgoing transitions from a class of the current test case can be enumerated, thus each number (Ii) can be seen as the next transition chosen from the actual class to the next one. The evaluation of a solution is done by sequentially taking every single transition (class to class) of the solution and generating a sequence of test data with a particular coverage. The evaluation function selects one leaf class (from left to right) and one gene in the solution is consumed to select the next transition ti. Then, tiis added to the set of selected transitions, T′. In order to transit from one test case to another, the evaluation function consumes, at most, as many genes as the number of leaf classes present in the source test case. We may need to consume a variable number of integer numbers of the solution to transit to the next test case. It depends on the source test case. We use the following expression to select the next transition: ti=Iimod |Transitions(c)|.(8.1) where Iiis the i−th component of the Solution and T ransitions(c) is the list of possible outgoing transitions from class c. For example, if the evaluation function is considering class ciand that class has 4 outgoing transitions, we consume the next gene (integer), e.g. 6, in the solution to determine the next transition. In this example, we take the second possible transition (ti= 6 mod 4 = 2). The fitness value of a solution is the class or transition coverage, Equations (2.12) and (2.13) in Section 2.4.2, obtained by the solution when all genes have been consumed in the evaluation. In this algorithm we wish to maximize the fitness function given by Equation (2.12) for Class Coverage and Equation (2.13) for Transition Coverage. The recombination operator is not used because the exchange of genes between two individuals could generate sequences of meaningless transitions. Since we interpret each gene in the chromosome as the transition to take from among all those possible, the interpretation of each number depends on the previously consumed numbers. Let us explain this issue in detail.
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 133 Let us say we obtain, after using the single point crossover and from the initial individuals I1={1,1,1,2,1,1}and I2={1,2,1,2,1,2}, two mixed individuals I1′={1,1,1,2,1,2}and I2′={1,2,1,2,1,1}. Since the interpretation of each number depends on the state where they are consumed, the number indicates which transition must be taken from the source state. When we evaluate I1′, the first part of the individual is properly optimized. However, when the second part of the individual is being consumed, the actual test case (source state) is not the same as in the I2individual, because we have taken other transitions regarding to the first part of the individual. If we focus on the position 2 of the vector, in the I2individual it indicates to take the second transition, but in I1individual it indicates to take the first one. Consequently, now the rest of the transitions of the second part of the individual I1′are not properly optimized so as to cover all states and transitions, because the source class of the next transition is different. Regarding the mutation operator, it iterates over all the components in the solution vector uniformly changing their value by ±1. It linearly increases the probability to mutate a component in order to give a low probability to the first components of the chromosome, and a larger probability to the genes at the end of the chromosome. We aim to maintain the first part of the individual with fewer changes because a change in a gene could affect the rest of the sequence. We increase the probability from pm1to pm2. So here, pm1= 0.05 and pm2= 0.25. In this particular implementation, the best individuals of the population are kept for the next generation using a memory operator. As the population evolves, the first transitions in the individual tend to stabilize, but the algorithm still has to evaluate them at each generation. We propose saving the resulting stable first transitions in a memory slot to use them as the starting point for following optimization steps. We use the memory operator (MemO) to allow the algorithm to search in stages. This operator was first proposed by Alba et al. [4] in the context of software verification. The algorithm can optimize the whole sequence of numbers (transitions) in stages, step by step, at the same time saving the memory required to evaluate complete individuals. Instead, we only have to evaluate a shorter sequence in each individual evaluation. This operator is based on the so-called missionary technique used in [3] for reaching deep graph regions in an ACO. We use the memory operator as follows: the GTSG is executed using a relatively small chromosome length (in this approach we use a chromosome length of 20 integers). After a predetermined number of evaluations (100,000), the memory operator selects the best individual and stores its transitions to use them as the starting points for the next optimization steps. The MemO could store more than one individual as the starting point for the next generation, but in accordance with previous experimentation performed in the early stages of this study and the small population we used, the best choice is to select only the best individual. All the other transitions are removed from the memory. The internal loop of the algorithm is executed until a maximum number of evaluations is reached. Then, the best individual (partial sequence) found is added to the test suite list and the Coverage set is updated by removing the classes or transitions which are going to be covered by the new best partial sequence. Then, the memory operator stores the last test case of the best sequence to be the initial test case for the next generation. Finally, the external loop starts again with a new population until there is no class or transition left in the Coverage set or the algorithm reach a predefined number of evaluations. The advantages of using the memory operator are obvious: less memory and time are required to evaluate an individual, and thus the path can maintain a constant growth without requiring more time and memory. There are, of course, disadvantages. In particular, part of the search space is discarded and that part might in fact contain a good solution, but this is common in any non-exhaustive search algorithm.
134 8.3. TEST SEQUENCE GENERATION USING ECTM ACO Test Sequence Our ACO Test Sequence (ACOts) algorithm is an adaptation of the ACOhg algorithm proposed by Alba and Chicano [3] that can deal with the construction of huge graphs of unknown size. This new model was proposed for applying an ACO-like algorithm to the problem of searching for counterexamples of safety properties in very large concurrent models. We have adapted the algorithm with the intention of solving the TSGP. In short, two main differences between ACOts and the original ACO [65] model are as follows. First, the traditional ACO searches for the shortest path from an initial set of nodes to the objective ones. Since our objective in TSGP is to cover all classes or transitions, so we are also interested in visiting all classes and using all possible transitions between the first test case and the final test case. Second, ACOts cannot define final classes or test cases, the algorithm adds new test cases until the coverage criterion is fulfilled. In this particular implementation, the heuristic function ηdepends on each arc of the construction graph and is defined in the context of ACO algorithms. It is a non-negative function used by ACO algorithms for guiding the search. The higher the value of ηij , the higher the probability of selecting arc (i, j) during the construction phase of the ants. We use the same heuristic rate algorithm based on coverage of the greedy deterministic algorithm (Section 8.3.1) that will be presented in the following section. Another particularity of our ACO-based approach is that the algorithm applies a compact function in order to minimize the steps of the best solution (abest), resulting in the minimum number of different test cases. The compaction is as follows: since we only apply single transitions between classes, we can apply several transitions at the same time provided that the source class of the transitions is not the same or it is not an ascendant or descendant of the source class of any already selected transition. Then, we compact some of the single transitions in a complete transition that save some test cases in the resulting test suite. Continuing with the Video Game example shown in Figure 2.2, if the actual test case is Q1={controlling, running}, the following selected transitions are controlling →gameOver and running →paused. Then, we can compact the two transitions into a complete transition to obtain directly Q2={gameOver, paused}in only one test step. Greedy Deterministic Approach This approach was first introduced in [126], it will be used here for validation of our results. This algorithm uses a multi-agent system with two kinds of agents to traverse the classification tree: the walker agent and the coverage agent. Both agents will cooperatively traverse the ECTM. Travelling is done in such a way that only valid paths are taken and that all traversed paths together result in the desired coverage. A full description of the algorithm has been given in [126], so we will only outline it here. For any classification in the classification tree, a walker agent is introduced at the initial class. The initial test case is interpreted as a test step and taken into account for coverage calculation (e.g. class coverage, transition coverage). All walker agents are then moved one after another. The path of movement is calculated by coverage agents. When all agents have been considered once, the actual position of all agents is again interpreted as a test step, and is taken into account for coverage calculation, then added to the resulting test sequence. This is repeated until the desired coverage level has been reached. When there are no more valid paths to take, walker agents are stuck. In this case, the whole ECTM is reset to its initial state and a new, additional sequence, is created. When the algorithm has finished a test suite with all test steps is returned.
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 135 Algorithm 8 Pseudocode of the Heuristic Rate algorithm. 1: proc Input:candidate (Class or Transition) 2: if classcoverage && selfTransition then 3: return 0 4: end if 5: weight=1.0 ; rating=0 6: queue ←φ 7: queue += (candidate, weight) 8: while !queue.empty() do 9: (item, weight)= queue.poll() 10: if (item==candidate && rating>0) then 11: rating+=100 ; continue 12: end if 13: if (ratedItems contains item) then 14: continue 15: end if 16: ratedItems+=item 17: if (targetNodes contains item) then 18: rating+=10*weight 19: end if 20: if (item has (outgoing transitions kchildnodes kclassifications)) then 21: weight= weight*0.95; 22: end if 23: for all (item has (outgoing transitions && childnodes && classifications) of item) do 24: queue+=(item, weight) 25: end for 26: end while 27: return rating 28: end proc The Heuristic Rate algorithm is run by the aforementioned coverage agent. This agent guides the main algorithm to achieve full class and/or transition coverage. The Heuristic Rate algorithm is outlined in Algorithm 8. Its main goal is to rate the candidate transitions or classes in order to decide which is going to add more coverage to the current solution. The heuristic algorithm gets a candidate class or transition as input. For class coverage, self transitions are ignored and then zero is returned. A self-transition does not increase class coverage because the origin and the end of the transition is the same class. Otherwise, it then adds this candidate to a queue together with a weight factor, with an initial weight factor of one. A weight factor is needed to give more weight to the closest uncovered classes than those farthest away. The initial rating is set to zero. The candidate is added to the list of rated items. Then, while the queue is not empty the algorithm polls (FIFO) the next class and weight factor from the queue. If the polled node is the original candidate and if the rating is larger than zero, the algorithm has found a loop path with new items. This loop path is weighed by adding the value of 100 to the rating because we found a promising candidate. In this case or when the current item is on the list of rated items, the while loop passes to its next cycle. Otherwise this node is added to the list of rated items. If the node is on the list of target classes (it has not been used in any test step before), the algorithm adds 10 times the weight factor to the result rating. Then, if there are outgoing transitions, child nodes or classifications, the weight factor is multiplied with a punishment value. Target classes of outgoing transitions and child classes are then added to the queue together with the new weight factor. When the queue is empty the rating is returned. 8.3.2 Experimental Setup ACOts and GTSG are non-deterministic algorithms, so we performed 30 independent runs per program/coverage criterion for a meaningful statistical analysis. All the executions were run in a
136 8.3. TEST SEQUENCE GENERATION USING ECTM cluster of 16 machines with Intel Core2 Quad processors Q9400 (4 cores per processor) at 2.66 GHz and 4 GB memory running Ubuntu 12.04.1 LTS and managed by the HT Condor 7.8.4 cluster manager. In order to check whether the differences between the algorithms are statistically significant or just a matter of chance, we applied the Wilcoxon rank-sum [189] test and highlight in the tables, the differences that are statistically significant. We set a confidence level of 99.9% (p-value under 0.001) for the entire comparison (both metaheuristics acting on a program/coverage). We have marked a result in dark grey when it is the best and in light grey when it is the second best in performance. When the result of one algorithm is significantly better than the result of another algorithm (typically the one whose results is farthest), we have added an asterisk. Two asterisks are added if the algorithm is significantly better than the other two algorithms. In addition, with the aim of properly interpreting the results of statistical tests, it is always advisable to report effect size measures. For that purpose, we have also used the non-parametric effect size measure ˆ A12 statistic proposed by Vargha and Delaney [208]. Effect size provides information about the magnitude of an effect, which can be useful in determining whether it is of practical significance or not. For the experiments we use a benchmark with 12 different models of programs/artifacts listed in Table 8.73. We use a Keyboard instance [156], a Microwave [137], an Autoradio [101], and Harel’s Citizen watch [94] which is relevant in the literature. From the IBM Rhapsody instances, we took the Coffee Machine, the Communication example, the Elevator, and the Tetris game [108]. In Matlab Simulink Stateflow, we found Mealy Moore, Fuel Control, Transmission, and Aircraft [143]. In this table the second and third columns list some statistics of the resulting artifacts. Both the number of classes and number of transitions are given. The fourth and fifth column list the results for conventional test case generation computed by the CTE tool with the greedy algorithm for minimal and complete combination. Numbers indicate the size of the generated test suite. Even though the details of the case studies are given in Table 8.7, we highlight here that most instances are hierarchical and concurrent. This means that we are going to deal with test cases of different lengths. In other words, there are test cases of different lengths in the same sequence. Let us explain the notation used in the Tables 8.9 and 8.11. A single number nindicates the size of the unique test sequence: it is the number of generated test steps nneeded for 100% coverage. In the case of the metaheuristic algorithms, we provide the mean over the 30 executions. A number nfollowed by a percentage value (p%) indicates the number of generated test steps ntogether with a coverage level p% below 100%. When the number nis followed by another number (m), the first number nindicates the total number of test steps while the second number min parentheses indicates the number of sequences needed. We have implemented a re-boot mechanism in all the algorithms in case they reach a class with no exit transition. Parameter Settings A possible threat to internal validity is that we have experimented with only one set of algorithms’ parameters. Nevertheless, we have performed a previous experiment in order to select the best parameters for the GTSG and ACOts algorithms. We have tried all combinations of values shown in Table 8.8. Note that the parameters used in the final experimentation are the ones highlighted in bold. 3They are available at http://neo.lcc.uma.es/staff/javi/resources.html
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 137 Table 8.7: General characteristics of the benchmark of programs. Name Classes Transitions Minimal Complete Keyboard [156] 5 8 2 4 Microwave [137] 19 23 7 56 Autoradio [101] 20 35 11 66 Citizen [94] 62 74 31 3121 Coffee Machine 21 28 9 81 Communication 10 12 7 7 Elevator 13 18 5 80 Tetris 11 18 10 10 Mealy Moore 5 11 5 5 Fuel Control 5 27 5 600 Transmission 7 12 4 12 Aircraft 24 20 5 625 Table 8.8: Parameters setting for our proposals. The parameter’s values used in the experimentation are highlighted in bold. Algorithm Parameter Value GTSG Population Size 4, 8, 10 Crossover No, Yes (1.0 , 0.9, 0.8) Mutation Prob. 0.05, 0.1, 0.2, Dynamic (0.05-0.25) Memory Operator No , Yes Memory Slots 1, 2, 5 Chromosome length 10, 20, 50, 100 ACOts α1, 2, 5 β1, 2, 5 ρ0.1, 0.5, 0.9 maxsteps 10, 20, 50, 100 colSize 2, 5, 10 λant 400 8.3.3 Test Sequences’ Quality In this section, we analyze the behavior of the proposed approaches with the aim of analyzing the computed best solutions and highlighting the algorithm that behaves the best. The main results of the executions of the algorithms for class coverage and transition coverage can be seen in Table 8.9 and Table 8.11, respectively. For class coverage, 100% coverage was reached for 11 out of 12 programs. Achieving full coverage is the main objective for test case generation. The Aircraft program was the only one resulting in below 100%, having an 86.2% coverage, as there are unreachable or orphaned classes in the model. In all 12 programs, the highest possible class coverage was reached in a single test sequence, which is a desirable result. Regarding class coverage, differences appear in four programs (Microwave, Autoradio, Citizen, and Tetris). The greedy approach obtains better results
138 8.3. TEST SEQUENCE GENERATION USING ECTM Table 8.9: Results for test sequence generation for class coverage. Name GTSG ACOts Greedy Keyboard [156] 2 2 2 Microwave [137] 8* 8* 9 Autoradio [101] 13.30* 14 13* Citizen [94] 39.47* 36** 47 Coffee Machine 9 9 9 Communication 7 7 7 Elevator 6 6 6 Tetris 12* 12* 15 Mealy Moore 5 5 5 Fuel Control 5 5 5 Transmission 4 4 4 Aircraft 4 (86.2%) 4(86.2%) 4(86.2%) in the Autoradio program, where the difference with GTSG is not significant. For the other three programs the metaheuristic algorithms achieve total coverage using fewer test steps. For instance, both metaheuristic algorithms reduced the test suite size by more than 20% for the Tetris program. Let us analyze the Citizen program for class coverage. The analysis of this program is especially interesting because this is the most complex program. Furthermore, the differences between the algorithms are the largest. ACOts obtains the best results in this program. ACOts reduces the test suite size by more than 23% with respect to the Greedy algorithm, moreover it is 9% better than GTSG. In addition, GTSG is 15% better than the Greedy algorithm. The ACOts approach is more effective and accurate for the largest model used in this study. Regarding RQ1, it is true that the evolutionary algorithms save costs because they generate shorter test sequences than the greedy algorithm. Table 8.10: Vargha and Delaney’s statistical test results ( ˆ A12) for class coverage. Arepresents algorithms in rows and Brepresents algorithms in columns. GTSG ACOts Greedy GTSG - 0.5139 0.3889 ACOts 0.4861 - 0.4167 Greedy 0.6111 0.5833 - In light of these results and with the intention of determining whether the results are of practical significance or not, we analyze the ˆ A12 statistic. In Table 8.10 we summarize the average of the ˆ A12 statistic values for class coverage and all programs. The differences between algorithms are not very large due to we have selected small, medium, and large programs. Consequently, it is very difficult to obtain large differences in small and medium models. Numerically, the results of the ACOts are going to be better than the ones provided by GTSG and Greedy in 51.39% and 58.33% times, respectively. In addition, the results of GTSG are going to be better than the Greedy ones in 61.11% times, which is a big difference. For transition coverage (Table 8.11), only ACOts is able to obtain 100% coverage in all the programs. The other two algorithms fail to obtain total coverage in the one program (Citizen). In 11 of the 12 programs, the result only consisted of one test sequence, while in the Aircraft program two sequences were generated. The differences appear in five programs (Autoradio, Citizen, Coffee,
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 139 Table 8.11: Results for test sequence generation for transition coverage Name GTSG ACOts Greedy Keyboard [156] 5 5 5 Microwave [137] 17 17 17 Autoradio [101] 36.30 36 36 Citizen [94] 75.27* (99.9%) 64.17** 51 (92.7%) Coffee Machine 19 19 18** Communication 16* 16* 17 Elevator 9 9 9 Tetris 31 31 31 Mealy Moore 24 24 24 Fuel Control 11* 11* 12 Transmission 9 9 9 Aircraft 7 (2) 7 (2) 7 (2) Communication, and Fuel Control). In this case the Greedy algorithm is only better than the others in the Coffee Machine program, the Greedy algorithm reduces the test suite size, in this program, in one test case compared to the metaheuristic approaches. The existing differences are low in most cases except in the Citizen program where ACOts is clearly the best. It is the only algorithm that always achieves 100% transition coverage for all the programs. In the Citizen program the Greedy algorithm does not achieve full transition coverage while GTSG obtains total coverage in most executions. ACOts is better than GTSG in coverage and test suite size. ACOts is able to reduce the test suite size by 14.7% (with respect to GTSG). Table 8.12: Vargha and Delaney’s statistical test results ( ˆ A12) for transition coverage. Arepresents algorithms in rows and Brepresents algorithms in columns. GTSG ACOts Greedy GTSG - 0.5125 0.4670 ACOts 0.4875 - 0.4545 Greedy 0.5329 0.5455 - Table 8.12 shows the ˆ A12 statistical results for measuring the effect size for transition coverage. We have considered all programs, with the exception of the Citizen program where the results are not comparable. This fact is because neither GTSG nor the Greedy algorithm are able to reach full transition coverage, so the test suite is shorter but it is quite worse in quality (coverage). Although we have not included the Citizen results, where the ACOts algorithm is clearly superior, ACOts is still better than GTSG and Greedy by 51.25% and 54.55%, respectively. Furthermore, GTSG obtains smaller test suites than Greedy by 53.29%. Regarding the solution quality (coverage level), the metaheuristic approaches (ACOts and GTSG) seem to be competitive. They are both capable of generating test sequences with maximum levels of coverage, and obtain better results than the Greedy algorithm with a high probability. 8.3.4 Test Suite Coverage versus Test Suite Size Another aspect that we must take into account is the increase in the test suite size with the coverage in order to obtain total coverage. This behavior requires a further analysis to evaluate the tradeoff
140 8.3. TEST SEQUENCE GENERATION USING ECTM between coverage and test suite size because this is a key aspect when you are generating test suites [159]. We illustrate this tradeoff for the Citizen program in Figure 8.2 and 8.3 for class and transition coverage. In the figures, we show the deterministic solution of the Greedy algorithm and the median and interquartile range of the 30 executions of the metaheuristic algorithms in order to capture the average behavior of the approaches. We would like to stress that this analysis is performed on the solutions, already computed. 0 20 40 60 80 100 0 5 10 15 20 25 30 35 40 45 50 Class Coverage Number of Test Cases Greedy GTSG ACOts Figure 8.2: Median solutions and interquartile range of ACOts, GTSG and Greedy algorithms for the Citizen example for Class Coverage. Coverage versus number of test cases in the solution. Let us start with the analysis of the solution where we want to cover all the classes (class coverage) of the Citizen program. In Figure 8.2 we show that the obtained coverage is similar for the first test steps. The Greedy algorithm is slightly better with up to 54% coverage. Then, both metaheuristic algorithms continue adding coverage with the same ratio in contrast with the Greedy algorithm, which is worse in the middle stage of the sequence. GTSG obtains its maximum advantage when it achieves 80% coverage, while ACOts only achieves 72% with the same test steps (24). When only a few classes remain unvisited, ACOts is able to visit them in fewer test steps. Thus, it achieves full class coverage in only 36 test cases, three test cases less than GTSG and 11 test cases less than the Greedy algorithm. ACOts obtains total coverage with only 64 test cases in median, meanwhile GTSG has achieved 94.12% and the Greedy algorithm has achieved only 89.04% coverage with the same number of test cases. In certain regions of the graph (Figure 8.2) we observe that the same coverage is repeated in consecutive test steps. The reason is that not every class can be reached from any other class, but requires additional traversal of other covered classes and, therefore, additional test steps. We see this behavior, in particular, in the solution of the Greedy algorithm for the class coverage. This implies that we are not adding any coverage in these traversal test steps, so our algorithm should minimize them. In Figure 8.3 we show the median transition coverage and the interquartile range of the proposed
CHAPTER 8. COMBINATORIAL INTERACTION TESTING USING CTM 141 0 20 40 60 80 100 0 10 20 30 40 50 60 70 80 Transition Coverage Number of Test Cases Greedy GTSG ACOts Figure 8.3: Median solutions and interquartile range of ACOts, GTSG and Greedy algorithms for the Citizen example for Transition Coverage. Coverage versus number of test cases in the solution. algorithms achieved with each test case of all test sequences (average of 30 executions of nondeterministic algorithms). In this case, GTSG is better at the beginning because it first explores an area with a higher density of transitions (i.e. the algorithm does not have to visit an already visited node to reach a non-visited node). Besides, the Greedy algorithm obtains better coverage using the same number of test cases from 12 test cases onwards, but it is not able to achieve more than 92.7% coverage. Although the Greedy algorithm has achieved 11.59% more coverage than GTSG and 10.14% more than ACOts with 51 test cases, both metaheuristic algorithms are able to reach full coverage. In this case, ACOts is better because it achieves full transition coverage in fewer test cases and it adds coverage in each test case, progressively. This great effort in reducing traversal test steps makes the algorithm reasonably predictable. This behavior is desirable because the obtained coverage is proportional to the test cases needed to reach certain levels of coverage. For the goal of test suite minimization we have tried to optimize the test suite sizes while still achieving high levels of coverage. We have used GTSG and ACOts to search for the optimal solution but we need to evaluate the minimal test suite size using an exact approach, allowing us to know if we have reach the optimal one. Regarding computation times, we can say that the generation times for GTSG is less than 10 minutes in average, for ACOts is less than a minute in average, while the deterministic algorithm takes around 10 seconds in average. If we take into account the performance and the quality of the obtained results, it seems that ACOts is the best option, at least for the largest instances. 8.4 Conclusions In this chapter we have studied the prioritized pairwise test data generation problem with the aim of analyzing the performance of several approaches. We have compared five different approaches, three