Test-Driven Python Development
eBook - ePub

Test-Driven Python Development

Siddharta Govindaraj

Compartir libro
  1. 264 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Test-Driven Python Development

Siddharta Govindaraj

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

About This Book

  • Write robust and easily maintainable code using the principles of test driven development
  • Get solutions to real-world problems faced by Python developers
  • Go from a unit testing beginner to a master through a series of step-by-step tutorials that are easy to follow

Who This Book Is For

This book is intended for Python developers who want to use the principles of test-driven development (TDD) to create efficient and robust applications. In order to get the best out of this book, you should have development experience with Python.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Test-Driven Python Development un PDF/ePUB en línea?
Sí, puedes acceder a Test-Driven Python Development de Siddharta Govindaraj en formato PDF o ePUB, así como a otros libros populares de Informatik y Programmierung in Python. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2015
ISBN
9781783987931

Test-Driven Python Development


Table of Contents

Test-Driven Python Development
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Getting Started with Test-Driven Development
Prerequisites
Understanding test-driven development
TDD versus unit testing versus integration testing
Using TDD to build a stock alert application
Writing our first test
Analyzing the test output
Test errors versus test failures
Making the test pass
Reorganizing the test code
Running the tests after the reorganization
Summary
2. Red-Green-Refactor – The TDD Cycle
Tests are executable requirements
Arrange-Act-Assert
Documenting our tests
Testing for exceptions
Exploring assert methods
Specific asserts versus generic asserts
Setup and teardown
Brittle tests
Refactoring the design
Refactoring tests
Exploring the Rule classes
Exercise
Summary
3. Code Smells and Refactoring
A dual crossover moving average
Implementing the dual crossover moving average
Identifying code smells
Refactoring
The Rename Variable and Rename Method refactorings
Commenting Styles
Replace Magic Literals with Constants
The Extract Method refactoring
Replace Calculation with Temporary Variable
Extract Conditional to Method
The DRY principle
Single Responsibility Principle
Extract Class
Move Method to Class
The importance of tests
Exercise
Wrapping up
Summary
4. Using Mock Objects to Test Interactions
Hand writing a simple mock
Using the Python mocking framework
Mocking objects
Mocking return values
Mocking side effects
How much mocking is too much?
Mocks versus stubs versus fakes versus spies
Patching methods
An important gotcha when patching
Tying it all together
Summary
5. Working with Legacy Code
What is legacy code?
Understanding the code
What are characterization tests?
Using the Python interactive shell to understand the code
Writing a characterization test
Using pdb to understand the code
Some common pdb commands
Walking through a pdb session
Techniques to break dependencies
The Rope refactoring library
Separate initialization from execution
Use default values for parameters
Extract the method and test
Inject dependencies
Inherit and test
Stubbing local methods
Extract the method and stub
The cycle continues
Time to refactor
Long-term refactoring
Summary
6. Maintaining Your Test Suite
Goals of test maintenance
Organizing tests
Filesystem layout
Naming conventions
Test suite grouping
Making tests readable
Using docstrings
Using fixtures
Fixtures and patching
Using a custom test case class hierarchy
Writing tests closer to the domain
Writing helper methods
Writing better asserts
Using custom equality checkers
Using matchers
Summary
7. Executable Documentation with doctest
Our first doctest
Running the doctest
Test failures
Testing for exceptions
Package-level doctests
Maintaining doctests
Running a suite of doctests
Setup and teardown
Limitations of doctest
Doctest directives
How do doctests fit into the TDD process?
Summary
8. Extending unittest with nose2
Getting started with nose2
Writing tests for nose2
Setup and teardown
Parameterized tests
Generated tests
Layers
nose2 plugins
Doctest support
Writing test results to an XML file
Measuring test coverage
Debugging test failures
nose2 configuration
Summary
9. Unit Testing Patterns
Pattern – fast tests
Pattern – running a subset of tests
Test loaders
Using the load_tests protocol
Skipping tests
Pattern – using attributes
Attributes with vanilla unittests
Pattern – expected failures
Pattern – data-driven tests
Pattern – integration and system tests
Pattern – spies
Pattern – asserting a sequence of calls
Pattern – patching the open function
Pattern – mocking with mutable args
Summary
10. Tools to Improve Test-Driven Development
TDD tools
py.test
py.test versus nose2
Trial
Sure
PyHamcrest
Integrating with build tools
Paver
Integrating with packaging tools
Setuptools
Distutils
Integrating with continuous integration tools
Jenkins
Travis CI
Other tools
tox
Sphinx
IDE integration
Summary
A. Answers to Exercises
Red-Green-Refactor – The TDD Cycle
Code Smells and Refactoring
B. Working with Older Python Versions
Writing code that is compatible across versions
Running tests from the command line
Running the examples in this book
Index

Test-Driven Python Development

Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2015
Production reference: 1210415
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-792-4
www.packtpub.com
Cover image by Jayanand Govindaraj ()

Credits

Author
Siddharta Govindaraj
Reviewers
Sharad Bagri
Kevin Davenport
Vivek Vidyasagaran
Devesh Chanchlani
Dorai Thodla
Kiran Gangadharan
Cees de Groot
David Simick
Fernando Ramos
Christopher Humphries
Commissioning Editor
Julian Ursell
Acquisition Editor
Nikhil Karkal
Content Development Editor
Sumeet Sawant
Technical Editor
Ruchi Desai
Copy Editors
Vikrant Phadke
Sameen Siddiqui
Alpha Singh
Project Coordinator
Danuta Jones
Proofreaders
Simran Bhogal
Stephen Copestake
Safis Editing
Paul Hindle
Indexer
Mariammal Chettiyar
Graphics
Jason Monteiro
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta

About the Author

Siddharta Govindaraj first encountered Python in 2002, and it has remained his favorite programming language ever since. He was an early participant in BangPypers, India's first Python community, and a speaker at InPycon. He is the founder of Silver Stripe Software, an Indian product start-up that develops products based on Python. A vocal proponent of the language, Siddharta extols the virtues of Python to anyone who will listen—and also to those who won't. His blog is at http://www.siddharta.me.
2323__perlego__chap...

Índice