Introducing Automated Unit Testing in a Legacy PHP System

Total Page:16

File Type:pdf, Size:1020Kb

Introducing Automated Unit Testing in a Legacy PHP System Introducing Automated Unit Testing in a Legacy PHP System Alexander Olsson February 22, 2010 Abstract Introducing unit testing in a previously untested system is problematic. De- velopers may lack experience from extensive unit testing, and many work hours is likely needed before the system has high test coverage. It is therefore important to early on choose a framework and a strategy for implementing tests which suits both the developers and the system. The framework is selected from a survey based on requirements specified by the company and an initial guess of important testing criteria. The survey is complemented with test implementations and interviews to capture group- specific viewpoints. A strategy for implementing tests is decided using a code analysis tool, which estimates implementation effort and testing need on a per-unit basis. A test implementation order is suggested by ranking units using a diagram-based method. This approach allows for fitting the strategy to the testing skills of the team. In this application, the most suitable framework from a selection of frame- works is PHPUnit. The framework and strategy is experimentally verified on a PHP web system with over 40k SLOC and a development team of 8 people. As the team is fairly inexperienced with unit testing, a test implementation strategy which prioritize low-effort units was chosen. Furthermore, a small li- brary of unit tests is implemented and serves as templates for system-specific tests and strategy validation. i ii Acknowledgement Iwouldliketothankthemanypeoplewhohelpedmeduringmythesis.First and foremost, Richard Kronf¨alt, my supervisor at Axis Communications who has come up with countless of ideas and suggestions. Secondly, Mathias Haage, my supervisor from Lund Institute of Technol- ogy has helped me with anything concerning my thesis and answered all my questions. Thirdly, the people at Axis Communications, and especially the ones at VHS. In particular Hans M˚ansson, who have come with many good insights of how to further improve what I’ve been doing. Also from VHS, Michael Rengbrandt helped particularly with tests needed for the thesis to be complete. iii iv Contents 1 Introduction 1 1.1 Background ............................ 1 1.2 Problem description ........................ 2 1.3 Problem approach ......................... 2 2 Theory 3 2.1 Software Testing ......................... 3 2.1.1 Unit Testing ........................ 4 2.1.2 Integration Testing .................... 7 2.1.3 System Testing ...................... 7 2.2 Frameworks ............................ 8 2.2.1 The xUnit Family of Frameworks ............ 8 2.2.2 FIT ............................ 8 3Framework 11 3.1 Selection Criteria ......................... 11 3.1.1 Quantification of Selection Criteria ........... 12 3.2 Benchmark test suite ....................... 12 3.3 Nominated frameworks ...................... 15 3.4 Framework Case Study ...................... 16 3.4.1 Overview ......................... 16 3.4.2 Survey Interpretation ................... 17 3.5 Framework evaluation ...................... 18 3.5.1 PHPUnit ......................... 18 3.5.2 SimpleTest ......................... 20 3.5.3 Testilence ......................... 22 3.5.4 SnapTest ......................... 24 3.5.5 PHPSpec ......................... 27 3.5.6 PHPT ........................... 29 3.6 Conclusion ............................. 31 v 4Integration 33 4.1 Where to start .......................... 33 4.1.1 An example ........................ 33 4.1.2 Approach ......................... 34 4.1.3 Summary ......................... 36 4.2 Making the analysis ........................ 36 4.3 Creating an analysis tool ..................... 37 4.3.1 PHPA: List of units .................... 37 4.3.2 PHPA: Cyclomatic complexity .............. 38 4.3.3 PHPA: Dependency .................... 41 4.3.4 PHPA: Frequency ..................... 42 4.3.5 Analysis Results ..................... 43 4.4 Choosing the entry point ..................... 46 4.4.1 Creating the ranked list ................. 47 4.5 Writing tests ........................... 49 4.5.1 Implementation ...................... 50 4.6 Putting it all together ...................... 53 4.7 Validation ............................. 54 5 Conclusion 57 5.1 Discussion ............................. 58 6 Summary 63 A Source Code 65 A.1 Complex .............................. 65 A.1.1 Complex class ....................... 65 A.1.2 Filehandler ........................ 70 A.1.3 Config ........................... 71 A.1.4 Complex slim ....................... 72 B Case study 75 B.1 Introduction ............................ 75 B.2 Task ................................ 76 B.2.1 Purpose .......................... 76 B.2.2 Task ............................ 77 B.3 Survey ............................... 86 Bibliography 86 vi Chapter 1 Introduction 1.1 Background Automated software unit testing may be performed in several different ways. It is often difficult to proclaim one school as superior. Coding standards, languages, requirements and personal taste will influence the choices made when introducing automated testing. Automated testing is a quick and easy way to swiftly verify the func- tionality of a given system. It can be used after implementing changes to the system to verify that parts not touched by the new implementation still works in the same manner. Creating the test cases itself is also a way to force the developer to find a solution to the problem at hand before implementing, resulting in better code[16]. Unfortunately, testing is too often cut from a project to save time and money. It may be argued that enough testing is performed by the developers as they write the source code. This is, however, prone to result in faulty code. Implementing new features may break some previously working code and without an automated test suite there is no way to verify this, aside from checking manually. Bugs will be discovered later in the project and will both delay the time and increase the costs of the project. In many cases the delay and increased cost is a substantial amount of the project’s initial values. One mean to overcome these issues is to introduce automated testing. Different approaches to accomplish this in a legacy system will be discussed and evaluated in this thesis. 1 1.2. PROBLEM DESCRIPTION CHAPTER 1. INTRODUCTION 1.2 Problem description In a system which have been existing for several years a need for systematic testing has risen. As the system have increased not only in complexity but also size it has become difficult to manually verify and validate the system. Manual testing has also proved to be time consuming and mistakes are more commonly made. 1.3 Problem approach There are mainly two tasks which will be carried out in this thesis. First, aframeworkforunittestingisneeded.Thebestone,accordingtoselected criteria, for this specific application will be chosen. Second, the framework should be integrated into the existing system. In this phase, how to imple- ment test cases and overcome difficulties when doing so will be discussed. Finding a suitable framework poses several difficulties. Some questions we need to answer before we can make a choice is; What do the current legacy system require from the framework in order • for it to be applicable to the system? What functionality would improve the quality of the resulting tests? • What do the developers need, and want? • Answering these questions is not trivial. No questions holds an objective answer, but rather depends on humans and personal taste. Different people may also have different opinions on, for example, what functionality is neces- sary. In order to get a fair understanding of the answers to these questions a case study with two developers of the system were performed and is further discussed in section 3.4.Furtherdiscussionoftheanswerstothesequestions is the criteria for selecting a framework, covered by section 3.1. Once a fitting framework has been found, a way to integrate the frame- work along with methods for implementing unit test cases and best practices is needed. As there are many test cases which needs to be implemented, the test cases for a unit will be implemented according to priority. The priority of a unit will be decided by examining the effort for bringing the unit under test and comparing it to the value the unit provides from being under test. The effort is measured in terms of cyclomatic complexity and dependencies. The value is measured in number of invocations during a certain timespan. The results are illustrated in a diagram where each of the two quantities (ef- fort and value) will be on each axis of the diagram. This is further discussed in section 4.3.5. 2 Chapter 2 Theory 2.1 Software Testing In software testing, there are usually three parts of the hierarchy: Unit test- ing, integration testing and system testing. Unit testing is performed by the developer to ensure his newly developed unit is working as intended. This is further described in section 2.1.1.Integrationtestingisperformedtoas- sure that all current units, including the newly developed ones, are working together as a whole, known as a module. This is further described in sec- tion 2.1.2.Finally,asystemtestiscarriedouttoensuretheend-to-end system is working satisfactory. This is further described in section 2.1.3. The procedure of testing is illustrated in figure 2.1.[19] Figure 2.1: Testing methodology in a typical software development situation. 3 2.1. SOFTWARE TESTING CHAPTER 2. THEORY Sometimes, integration and system
Recommended publications
  • Codeigniter-Testing-Guide-Sample.Pdf
    CodeIgniter Testing Guide Beginners’ Guide to Automated Testing in PHP. Kenji Suzuki and Mat Whitney This book is for sale at http://leanpub.com/codeigniter-testing-guide This version was published on 2016-01-23 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2015 - 2016 Kenji Suzuki and Mat Whitney Tweet This Book! Please help Kenji Suzuki and Mat Whitney by spreading the word about this book on Twitter! The suggested hashtag for this book is #CITestGuide. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: https://twitter.com/search?q=#CITestGuide Contents Preface ............................................... i The Book at a Glance ..................................... i What You Need for This Book ................................. iii Who should read This Book? ................................. iii Why PHPUnit? ........................................ iv Is This a CodeIgniter Book? .................................. iv Is Testing PHP Applications Difficult? ............................ iv Is Testing CodeIgniter Applications Difficult? .................... v Testing is Fun and Easy ................................ v Conventions Used in This Book ................................ v Errata .............................................
    [Show full text]
  • Towards a Taxonomy of Sunit Tests *
    Towards a Taxonomy of SUnit Tests ? Markus G¨alli a Michele Lanza b Oscar Nierstrasz a aSoftware Composition Group Institut f¨urInformatik und angewandte Mathematik Universit¨atBern, Switzerland bFaculty of Informatics University of Lugano, Switzerland Abstract Although unit testing has gained popularity in recent years, the style and granularity of individual unit tests may vary wildly. This can make it difficult for a developer to understand which methods are tested by which tests, to what degree they are tested, what to take into account while refactoring code and tests, and to assess the value of an existing test. We have manually categorized the test base of an existing object-oriented system in order to derive a first taxonomy of unit tests. We have then developed some simple tools to semi-automatically categorize tests according to this taxonomy, and applied these tools to two case studies. As it turns out, the vast majority of unit tests focus on a single method, which should make it easier to associate tests more tightly to the methods under test. In this paper we motivate and present our taxonomy, we describe the results of our case studies, and we present our approach to semi-automatic unit test categorization. 1 Key words: unit testing, taxonomy, reverse engineering 1 13th International European Smalltalk Conference (ESUG 2005) http://www.esug.org/conferences/thirteenthinternationalconference2005 ? We thank St´ephane Ducasse for his helpful comments and gratefully acknowledge the financial support of the Swiss National Science Foundation for the project “Tools and Techniques for Decomposing and Composing Software” (SNF Project No.
    [Show full text]
  • YOSSEF BENHAROSH RESUME 972 (0) 544-308209 | [email protected] | Kiryat Gat, Israel
    YOSSEF BENHAROSH RESUME 972 (0) 544-308209 | [email protected] | Kiryat Gat, Israel PHP & Drupal developer, June 2011 – present Freelance web developer for 4 years who works with the following technologies: PHP, MySQL, Javascript, jQuery, Drupal, HTML/HTML5, CSS/CSS3. Specializes in PHP development. Including: Object-Oriented Programming, mySQL as a data base, and Laravel as a framework. Drupal developer, specializing in developing new modules and themes, and in taming existing modules. Good working knowledge of organic SEO. Chosen works freefax.co.il – PHP site that provides fax services. I worked as a PHP and mySQL programmer, as well as on the front end with jQuery, Ajax, html and CSS. I wrote the cart and invoice modules and the user class. puzzlemedia.co.il – Bilingual Drupal website for film producers. www.yaronlivne.co.il – Drupal based app that I wrote most of its modules and developed its’ theme. ZEZBRA – A startup that I themed its Drupal site, as well as developed its PHP based cellular version. reshetech.co.il – Hebrew tutorials website based on PHP. phpenthusiast.com – English tutorials website devoted to Object Oriented PHP. Github projects myAPI – I think it is the simplest way to provide API services for small businesses that want to provide data based services to their customers. csvtax – Drupal 7 module that transforms a CSV file into hierarchical taxonomy. cornerslider – A jQuery popup that slides the content in and out when the user scrolls down and up the page. Technologies Back end programming languages: PHP, mySQL. Front end programming languages: CSS/3, HTML/5, javascript.
    [Show full text]
  • 2.5 the Unit Test Framework (UTF)
    Masaryk University Faculty of Informatics C++ Unit Testing Frameworks Diploma Thesis Brno, January 2010 Miroslav Sedlák i Statement I declare that this thesis is my original work of authorship which I developed individually. I quote properly full reference to all sources I used while developing. ...…………..……… Miroslav Sedlák Acknowledgements I am grateful to RNDr. Jan Bouda, Ph.D. for his inspiration and productive discussion. I would like to thank my family and girlfriend for the encouragement they provided. Last, but not least, I would like to thank my friends Ing.Michal Bella who was very supportive in verifying the architecture of the extension of Unit Test Framework and Mgr. Irena Zigmanová who helped me with proofreading of this thesis. ii Abstract The aim of this work is to gather, clearly present and test the use of existing UTFs (CppUnit, CppUnitLite, CppUTest, CxxTest and other) and supporting tools for software project development in the programming language C++. We will compare the advantages and disadvantages of UTFs and theirs tools. Another challenge is to design effective solutions for testing by using one of the UTFs in dependence on the result of analysis. Keywords C++, Unit Test (UT), Test Framework (TF), Unit Test Framework (UTF), Test Driven Development (TDD), Refactoring, xUnit, Standard Template Library (STL), CppUnit, CppUnitLite, CppUTest Run-Time Type Information (RTTI), Graphical User Interface (GNU). iii Contents 1 Introduction ....................................................................................................................................
    [Show full text]
  • Civil Good: a Platform for Sustainable and Inclusive Online Discussion
    Civil Good: A Platform For Sustainable and Inclusive Online Discussion An Interactive Qualifying Project submitted to the faculty of Worcester Polytechnic Institute In partial fulfillment of the requirements for the degree of Bachelor of Science by: Steven Malis (Computer Science), Tushar Narayan (Computer Science), Ian Naval (Computer Science), Thomas O'Connor (Biochemistry), Michael Perrone (Physics and Mathematics), John Pham (Computer Science), David Pounds (Computer Science and Robotics Engineering), December 19, 2013 Submitted to: Professor Craig Shue, WPI Advisor Alan Mandel, Creator of the Civil Good concept Contents 1 Executive Summary1 1.1 Overview of Recommendations......................2 2 Authorship5 3 Introduction 10 3.1 Existing Work - Similar Websites.................... 11 4 Psychology 17 4.1 Online Disinhibition........................... 17 4.2 Format of Discussions.......................... 22 4.3 Reducing Bias with Self-Affirmation................... 28 4.4 Other Psychological Influences...................... 34 5 Legal Issues 38 5.1 Personally Identifiable Information................... 38 5.2 Intellectual Property........................... 42 5.3 Defamation................................ 45 5.4 Information Requests........................... 46 5.5 Use by Minors............................... 49 5.6 General Litigation Avoidance and Defense............... 51 6 Societal Impact 52 6.1 Political Polarization........................... 52 6.2 Minority Opinion Representation.................... 55 6.3 History and Political
    [Show full text]
  • Enhancement in Nunit Testing Framework by Binding Logging with Unit Testing
    International Journal of Science and Research (IJSR), India Online ISSN: 2319-7064 Enhancement in Nunit Testing Framework by binding Logging with Unit testing Viraj Daxini1, D. A. Parikh2 1Gujarat Technological University, L. D. College of Engineering, Ahmedabad, Gujarat, India 2Associate Professor and Head, Department of Computer Engineering, L. D. College of Engineering, Ahmadabad, Gujarat, India Abstract: This paper describes the new testing library named log4nunit testing library which is enhanced version of nunit testing library as it is binded to logging functionality. NUnit is similar to xunit testing family in all that cases are built directly to the code of the project. Log4NUnit testing library provides the capability to log the results of tests along with testing classes. It also provides the capability to log the messages from within the testing methods. It supplies extension of NUnit’s Test class method in terms of logging the results. It has functionality to log the entity of test cases, based on the Logging framework, to document the test settings which is done at the time of testing, test case execution and it’s results. Attractive feature of new library is that it will redirect the log message to console at runtime if Log4net library is not present in the class path. It will make easy for those users who do not want to download Logging framework and put it in their class path. Log4NUnit also include a Log4net logger methods and implements utility of logging methods such as info, debug, warn, fatal etc. This work was prompted due to lack of published results concerning the implementation of Log4NUnit.
    [Show full text]
  • Cakephp Cookbook Documentation Release 4.X
    CakePHP Cookbook Documentation Release 4.x Cake Software Foundation Sep 25, 2021 Contents 1 CakePHP at a Glance 1 Conventions Over Configuration........................................1 The Model Layer................................................1 The View Layer.................................................2 The Controller Layer..............................................2 CakePHP Request Cycle............................................3 Just the Start...................................................4 Additional Reading...............................................4 2 Quick Start Guide 13 Content Management Tutorial......................................... 13 CMS Tutorial - Creating the Database..................................... 15 CMS Tutorial - Creating the Articles Controller................................ 19 3 4.0 Migration Guide 29 Deprecated Features Removed......................................... 29 Deprecations.................................................. 29 Breaking Changes................................................ 31 New Features.................................................. 37 4 Tutorials & Examples 41 Content Management Tutorial......................................... 41 CMS Tutorial - Creating the Database..................................... 43 CMS Tutorial - Creating the Articles Controller................................ 47 CMS Tutorial - Tags and Users......................................... 56 CMS Tutorial - Authentication......................................... 64 CMS Tutorial - Authorization.........................................
    [Show full text]
  • PHP 7 Y Laravel
    PHP 7 y Laravel © All rights reserved. www.keepcoding.io 1. Introducción Nada suele ser tan malo como lo pintan © All rights reserved. www.keepcoding.io When people tell me PHP is not a real programming language http://thecodinglove.com/post/114654680296 © All rights reserved. www.keepcoding.io Quién soy • Alicia Rodríguez • Ingeniera industrial ICAI • Backend developer • @buzkall • buzkall.com http://buzkall.com © All rights reserved. www.keepcoding.io ¿Qué vamos a ver? • Instalación y desarrollo en local • PHP 7 • Laravel • Test unitarios • Cómo utilizar una API externa © All rights reserved. www.keepcoding.io ¿Qué sabremos al terminar? • PHP mola • Crear un proyecto de cero • Depurar y hacer test a nuestro código • Un poco de análisis técnico y bolsa © All rights reserved. www.keepcoding.io Seguridad Security is not a characteristic of a language as much as it is a characteristic of a developer Essential PHP Security. Chris Shiflett. O’Reilly © All rights reserved. www.keepcoding.io Popularidad en Stackoverflow http://stackoverflow.com/research/developer-survey-2016 © All rights reserved. www.keepcoding.io Popularidad en Github http://redmonk.com/sogrady/2016/07/20/language-rankings-6-16/ © All rights reserved. www.keepcoding.io Frameworks por lenguaje https://hotframeworks.com/ © All rights reserved. www.keepcoding.io Su propia descripción • PHP is a popular general-purpose scripting language that is especially suited to web development. • Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world. https://secure.php.net/ © All rights reserved. www.keepcoding.io Historia de PHP • Creado por Rasmus Lerdorf en 1995 como el conjunto de scripts "Personal Home Page Tools", referenciado como "PHP Tools”.
    [Show full text]
  • Introduction to Unit Testing
    INTRODUCTION TO UNIT TESTING In C#, you can think of a unit as a method. You thus write a unit test by writing something that tests a method. For example, let’s say that we had the aforementioned Calculator class and that it contained an Add(int, int) method. Let’s say that you want to write some code to test that method. public class CalculatorTester { public void TestAdd() { var calculator = new Calculator(); if (calculator.Add(2, 2) == 4) Console.WriteLine("Success"); else Console.WriteLine("Failure"); } } Let’s take a look now at what some code written for an actual unit test framework (MS Test) looks like. [TestClass] public class CalculatorTests { [TestMethod] public void TestMethod1() { var calculator = new Calculator(); Assert.AreEqual(4, calculator.Add(2, 2)); } } Notice the attributes, TestClass and TestMethod. Those exist simply to tell the unit test framework to pay attention to them when executing the unit test suite. When you want to get results, you invoke the unit test runner, and it executes all methods decorated like this, compiling the results into a visually pleasing report that you can view. Let’s take a look at your top 3 unit test framework options for C#. MSTest/Visual Studio MSTest was actually the name of a command line tool for executing tests, MSTest ships with Visual Studio, so you have it right out of the box, in your IDE, without doing anything. With MSTest, getting that setup is as easy as File->New Project. Then, when you write a test, you can right click on it and execute, having your result displayed in the IDE One of the most frequent knocks on MSTest is that of performance.
    [Show full text]
  • Phpunit Manual Release Latest
    PHPUnit Manual Release latest Sebastian Bergmann Aug 18, 2021 Contents 1 Installing PHPUnit 3 1.1 Requirements...............................................3 1.2 Recommended PHP configuration....................................3 1.3 PHP Archive (PHAR)..........................................3 1.3.1 PHAR Implementation Details.................................4 1.3.2 Verifying PHPUnit PHAR Releases..............................4 1.4 Composer.................................................5 1.5 Global Installation............................................5 1.6 Webserver................................................6 2 Writing Tests for PHPUnit 7 2.1 Test Dependencies............................................8 2.2 Data Providers.............................................. 11 2.3 Testing Exceptions............................................ 17 2.4 Testing PHP Errors, Warnings, and Notices............................... 17 2.5 Testing Output.............................................. 20 2.6 Error output............................................... 21 2.6.1 Edge Cases........................................... 23 3 The Command-Line Test Runner 25 3.1 Command-Line Options......................................... 26 3.2 TestDox.................................................. 32 4 Fixtures 35 4.1 More setUp() than tearDown()...................................... 38 4.2 Variations................................................. 38 4.3 Sharing Fixture.............................................. 38 4.4 Global State..............................................
    [Show full text]
  • Secure PHP Development Handbook PHP Security Community of Practice Revision V1.0
    Queen's Secure PHP Development Handbook PHP Security Community of Practice Revision v1.0 Table of Contents • Queen's Secure PHP Development Handbook • Table of Contents • Introduction o Document Scope o How To Contribute o About The Authors . Document Contributors • PHP Configuration o Prerequisites o Development Environment . Workspace Recommendations . Source Control . Subversion Client Setup o Code Commenting . Special Considerations . php.ini o Production Environment . Special Considerations . php.ini • University Standards o Authentication o Database Connectivity . Connecting to Student Data Warehouse . Connecting to Human Resources o Online Payments • Application Design . Definition . Model . View . Controller . Implementation • Application Testing o Security Auditing and Penetration Testing o Testing for New Applications o Testing for Existing Applications / Commercial Software • Security Vulnerabilities o CSRF (Cross Site Request Forgeries) Attacks . Description . Example . Prevention o Remote Code Execution . Description . Example . Prevention o SQL Injection Vulnerabilities . Description . Example . Prevention . References o Format String Vulnerabilities . Description . Example . Prevention . References o XSS (Cross Site Scripting) Vulnerabilities . Description . Example . Prevention • Conclusion • Appendices Introduction This document provides recommendations and security best practices for PHP development at Queen's University. The primary goal of this document is to provide a snap shot of current recommendations for PHP developers
    [Show full text]
  • Phpunit Manual Version Latest
    PHPUnit Manual Version latest Sebastian Bergmann sept. 07, 2021 Table des matières 1 Installer PHPUnit 3 1.1 Pré-requis.................................................3 1.2 PHP Archive (PHAR)..........................................3 1.2.1 Windows............................................4 1.2.2 Vérification des versions PHAR de PHPUnit.........................4 1.3 Composer.................................................6 1.4 Paquets optionnels............................................6 2 Écrire des tests pour PHPUnit9 2.1 Dépendances des tests.......................................... 10 2.2 Fournisseur de données......................................... 13 2.3 Tester des exceptions........................................... 18 2.4 Tester les erreurs PHP.......................................... 19 2.5 Tester la sortie écran........................................... 21 2.6 Sortie d’erreur.............................................. 22 2.6.1 Cas limite............................................ 24 3 Lanceur de tests en ligne de commandes 27 3.1 Options de la ligne de commandes.................................... 28 3.2 TestDox.................................................. 34 4 Fixtures 35 4.1 Plus de setUp() que de tearDown().................................... 38 4.2 Variantes................................................. 38 4.3 Partager les Fixtures........................................... 38 4.4 Etat global................................................ 39 5 Organiser les tests 41 5.1 Composer une suite de tests
    [Show full text]