Test-Driven Python Development
eBook - ePub

Test-Driven Python Development

Siddharta Govindaraj

Condividi libro
  1. 264 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Test-Driven Python Development

Siddharta Govindaraj

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul 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.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Test-Driven Python Development è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Test-Driven Python Development di Siddharta Govindaraj in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatik e Programmierung in Python. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
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...

Indice dei contenuti