Page
1
Python Unit Test Automation Automate, Organize, and Execute Unit Tests in Python — Second Edition — Ashwin Pajankar
Page
2
Python Unit Test Automation Automate, Organize, and Execute Unit Tests in Python Second Edition Ashwin Pajankar
Page
3
Python Unit Test Automation: Automate, Organize, and Execute Unit Tests in Python ISBN-13 (pbk): 978-1-4842-7853-6 ISBN-13 (electronic): 978-1-4842-7854-3 https://doi.org/10.1007/978-1-4842-7854-3 Copyright © 2022 by Ashwin Pajankar This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Development Editor: James Markham Coordinating Editor: Mark Powers Copyeditor: Kezia Endsley Cover designed by eStudioCalamar Cover image by Jason Leung on Unsplash (www.unsplash.com) Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004, U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit http://www.apress.com/ source- code. Printed on acid-free paper Ashwin Pajankar Nashik, Maharashtra, India
Page
4
I dedicate this book to Alan Mathison Turing, an English mathematician, computer scientist, logician, cryptanalyst, and philosopher who was influential in the development of theoretical computer science.
Page
5
(This page has no text content)
Page
6
(This page has no text content)
Page
7
(This page has no text content)
Page
8
(This page has no text content)
Page
9
(This page has no text content)
Page
10
(This page has no text content)
Page
11
xi About the Author Ashwin Pajankar is a programmer, a maker, an author, a YouTuber, and a science popularizer. He graduated from IIIT Hyderabad with an MTech in Computer Science and Engineering. He has a keen interest in promoting science, technology, engineering, and mathematics (STEM) education. He has written many books with Packt, Leanpub, BPB, and Apress, and has also reviewed many books for Packt and Apress. He’s also working on many more books with Apress. His YouTube channel has more than 10,000 subscribers and he also teaches more than 75,000 students on Udemy. His personal website is www.AshwinPajankar.com. His LinkedIn profile is https://in.linkedin.com/in/ashwinpajankar
Page
12
xiii About the Technical Reviewers Shraddha Joshi is currently working as an engineer at PwC with experience in testing with Python and Java in major production environments. She has worked with various global clients across multiple domains and helped them build products and solutions with full-fledged testing frameworks. She has expertise in all phases of the development process and leads the design, development, execution, and automation stages of test plans for a diverse set of system components. Previously, she was a Senior Quality Engineer at Incture Technologies, where she was involved in designing functional integration and regression test plans, building and executing manual and automated tests, and performing highly complex analysis for multiple products. She also helped set cross- functional product testing standards involving the application of advanced technical/business skills in the area of specialization. Shraddha’s great knack for simplifying concepts and explaining them in an easy- to- understand manner makes her stand apart. She is passionate about guiding and mentoring people in their technology journey. She is also actively involved in conducting workshops, webinars, and sessions. She lives in Bangalore with her family. Sujay Raghavendra is a distinguished IT professional with a master’s degree in Information Technology. His research interests include computer vision, NLP, machine learning, deep learning, and artificial intelligence. He has served as an advisor for various universities and startups. He has been active in the research community. He has also authored a book with Apress Media. He has published research papers at various international journals and conferences and is a leading industry expert and mentor for professionals.
Page
13
xv Acknowledgments I am grateful to the student and teacher community which, with their continual bombardment of queries, impelled me to learn more, simplify my findings, and organize them into a book. This book is for them. I wish to thank my friends and colleagues—the practitioners from the field—for their good counsel and for filling me in on the latest in the field of test automation. A special thanks to the technical reviewers—Shraddha and Sujay—for their vigilant review and for providing their expert opinions. I consider myself very fortunate for the editorial assistance provided by Apress; the collaboration with them has been fabulous. I am thankful to Celestin Suresh John, Senior Manager, Editorial Acquisitions, Apress and Springer Science and Business Media Company, for giving me this and many other opportunities to collaborate with Apress. I wish to acknowledge and appreciate James Markham, Mark Powers, and the team of associates from Apress who adeptly guided me through the entire process of preparation and publication.
Page
14
xvii Introduction Why This Book? I have been using Python for more than ten years on a wide variety of projects. Initially, I used it for GUI applications. Then I quickly moved to scientific usage, as my academic projects demanded it. When I entered professional life, I used it for automation first and then for implementation of alert mechanisms. I have been using Python for the last six years in the fields of scientific computing, Internet of Things (IoT), and single board computers. I have written plenty of Python code over these years. I always prefer it to bash scripting, which offers limited capabilities to users like me. At different points over the last ten years, I’ve worked as a developer, an R&D engineer, a maker, an author, and a QA specialist. I used Python in every single role. Whenever I write code, I unit test it thoroughly. I used to unit test all my Python modules in the good old manual way. I used to run all the scripts once and compare the outcome with what was expected. However, I learned that when your codebase grows larger, it’s pretty difficult to test the scripts manually. Also, all the scripts have to be tested, re-tested, and tested for regression whenever a small part of the codebase changes. I was looking for a way to run all the tests automatically, which led me to reading about test automation. It immediately piqued my curiosity and, after a couple of days, I was running my own automated Python tests. After acquainting myself with the philosophy of test automation, I applied my newfound knowledge to automate unit and integration testing to web, mobile, GUI, API, and a variety of other types of applications using programming languages like C++, Python, Java, and PHP.
Page
15
xviii I wrote this book to share my knowledge and experiences while automating unit tests in Python 3. I explore different frameworks and plugins in this book. I learned about the tools and techniques explained in this book by spending numerous hours learning, coding, discussing, and actively participating in diverse Internet forums. I have condensed the knowledge to the basics of the unit test automation frameworks. I hope you will enjoy reading and following the book as much as I enjoyed writing it. This book includes the following: • An introduction to Python and various IDEs • Various test automation frameworks for Python 3, including doctest, unittest, nose, nose2, and pytest • Logging frameworks and web driver automation • Coding standards for Python 3 test automation and implementation of test-driven development with pytest in Python 3 Who This Book Is For The main audience of this book is Python 3 programmers who want to automate their unit tests. This includes a large and diverse set of people, including developers, test automators, students, researchers, and novice learners. The book is for those who have some knowledge of the Python programming language. The test automation engineers who have already worked with other programming frameworks, such as Java and C++, will find this book immensely useful to learn how test automation is done in Python 3. If you are just beginning with Python 3 programming and want to quickly get into automating the unit tests of your modules and packages, you will find this book helpful. InTroduCTIon
Page
16
xix This book is not a book for learning Python 3 programming and syntax from scratch. It is also not a DIY cookbook for development projects. If your understanding of coding is limited, you will find it difficult to follow this book. How This Book Is Organized This book has eight chapters. Here is a sneak peek into the topics covered in each chapter: • Chapter 1: This chapter introduces you to the history and philosophy of Python. It teaches you how to install Python and how to set up the environment for Python 3 programming. It also briefly explores the new features of Python 3 and introduces you to a few popular Python 3 IDEs. • Chapter 2: The aim of this chapter is to quickly get you started with unit test automation in Python 3. The chapter revises the understanding of testing concepts and quickly moves into implementing those concepts with docstring and doctest. • Chapter 3: This chapter serves to introduce xUnit and its philosophy to you. Then it proceeds to teach you how to implement concepts of xUnit with unittest, a xUnit port for Python. • Chapter 4: This chapter explores the inadequacies of unittest. Then it explores a better unit-testing framework, called nose. It explains the installation of plugins for nose to generate reports. It also discusses nose2, which is nose's next-generation version that’s under active development. InTroduCTIon
Page
17
xx • Chapter 5: This chapter introduces you to a modular, easy-to-use, unit test framework for Python, called pytest. It discusses the drawbacks of nose and compares nose, unittest, and pytest. • Chapter 6: This chapter introduces you to a web driver automation framework known as selenium. You will learn how to use the Selenium IDE and Selenium Python library. • Chapter 7: This chapter introduces you to various logging frameworks in Python. First, you will explore the built-in framework, logging. Then you will explore a third-party logging library, called loguru. • Chapter 8: This chapter helps you understand the coding and filenaming conventions for facilitating easier test discovery across various unit test frameworks in Python. The chapter concludes the book by implementing a test-driven development in Python 3 using pytest. How to Get the Most Out of This Book To get the most out of this book, it’s best to abide by the following: • Read the chapters thoroughly. Use the chapters hands- on by following the step-by-step instructions stated in the code examples. Do not skip any of the code examples. • If need be, repeat them a second time or until the concept is firmly etched in your mind. • Join a Python community or discussion forum. InTroduCTIon
Page
18
xxi • Explore and practice with various Python IDEs • Read the online documentation available for various test automation frameworks for Python 3. • Read the blogs related to test automation, Python 3, migration to Python 3 from Python 2, logging, and test- driven development. Where Next? I have endeavored to unleash the power of the unit test automation libraries for Python 3 as an aid to the community of professional developers and testers. I recommend you read the book from cover to cover, without skipping any of the chapters, text, or code examples. I wish you well in exploring Python! A Quick Word About the Instructors’ Fraternity Attention has been paid to the sequence of chapters and to the flow of topics in each chapter. This is done particularly with an objective to assist my fellow instructors and academicians in carving out a syllabus from the Table of Contents (ToC) of the book. The complete ToC complements the syllabus of “Introduction to Software Testing,” if students were introduced to programming during their freshman year with the help of Python. I have ensured that each concept discussed in this book includes adequate hands-on content to enable you to teach better and to provide ample hands-on practice to your students. Happy learning and exploring! —Ashwin Pajankar InTroduCTIon
Page
19
1© Ashwin Pajankar 2022 A. Pajankar, Python Unit Test Automation, https://doi.org/10.1007/978-1-4842-7854-3_1 CHAPTER 1 Introduction to Python I hope you have glanced through the introduction section. If you have not, then I recommend reading it, as it will help you with the context and the philosophy of this book. Let’s begin this adventurous journey by learning the history and background of Python. I personally find Python amazing and have been enchanted by it. Python is a simple yet powerful programming language. When using Python, it’s easy to focus on the implementation of the solution to a given problem, as programmers do not have to worry about the syntax of the programming language. The History of Python Python was conceived in the late 1980s. Guido van Rossum began its implementation in late 1989 at the Centrum Wiskunde & Informatica (National Research Institute for Mathematics and Computer Science) in the Netherlands. Python is a successor to the ABC programming language, which itself was inspired by SETL. In February 1991, Van Rossum published Python code to the alt.sources newsgroup. The name Python was inspired by the television show “Monty Python’s Flying Circus,” as Van Rossum is a big fan of Monty Python.
Page
20
2 Van Rossum is the principal author of Python. He played a central role in guiding the development and evolution of Python. He held the title of Benevolent Dictator for Life for Python. In 2018, he stepped down from that role. As of the writing of this edition, he works for Microsoft. The central philosophy of Python, called the Zen of Python, is explained in PEP-20, which can be found at https://www.python.org/ dev/peps/pep- 0020. It is a collection of 20 software principles, as follows: • Beautiful is better than ugly. • Explicit is better than implicit. • Simple is better than complex. • Complex is better than complicated. • Flat is better than nested. • Sparse is better than dense. • Readability counts. • Special cases aren’t special enough to break the rules. • Practicality beats purity. • Errors should never pass silently. • Unless explicitly silenced. • In the face of ambiguity, refuse the temptation to guess. • There should be one—and preferably only one— obvious way to do it. • Although that way may not be obvious at first unless you’re Dutch. • Now is better than never. Chapter 1 IntroduCtIon to python