23,99 €
Python's standard unittest module is based on the xUnit family of frameworks, which has its origins in Smalltalk and Java, and tends to be verbose to use and not easily extensible.The pytest framework on the other hand is very simple to get started, but powerful enough to cover complex testing integration scenarios, being considered by many the true Pythonic approach to testing in Python.
In this book, you will learn how to get started right away and get the most out of pytest in your daily work?ow, exploring powerful mechanisms and plugins to facilitate many common testing tasks. You will also see how to use pytest in existing unittest-based test suites and will learn some tricks to make the jump to a pytest-style test suite quickly and easily.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 173
Veröffentlichungsjahr: 2018
Copyright © 2018 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 or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.
Commissioning Editor:Kunal ChaudhariAcquisition Editor: Siddharth MandalContent Development Editor: Roshan KumarTechnical Editor: Jinesh TopiwalaCopy Editor: Safis EditingProject Coordinator: Hardik BhindeProofreader: Safis EditingIndexer: Priyanka DhadkeGraphics: Jason MonteiroProduction Coordinator: Deepika Naik
First published: August 2018
Production reference: 2050918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78934-756-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and, as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
pytest is one of the projects that show off the best qualities of Python; it is the easiest Python testing framework to get started and also the most powerful. The pytest developers leverage metaprogramming to help users; we can write tests as plain functions and use the assert keyword for checks, which means we can use any Python expression as a check, and we don't need to memorize the names of dozens of assertThis, assertThat methods. When there is a test failure, pytest uses sophisticated introspection to show the difference between the expected value and the value returned by the code under test. Introspection and decorators are also used to provide fixtures, parameters, grouping, skipping, and such like.
pytest is basically two parts: a library that gives you the API to write tests, and a test runner, a command-line utility that can search and execute tests across your project packages. The behavior of the pytest CLI can be configured in many ways, as described in this guide. By default, pytest is smart enough to collect tests written with the standard unittest package as well as doctest, running them and reporting all their results together. This means you can start using pytest now to run the tests you've already written with unittest and doctest.
pytest is very powerful out of the box, but it can also be enhanced by a large collection of industrial-strength plugins. A good collection of the best plugins is covered in this book.
If you are in the business of writing libraries and APIs for others to use, pytest is not only a great tool, but also a plentiful source of ideas and techniques, leveraging the best features of Python.
Anyone willing to learn pytest will be lucky to be guided by Bruno Oliveira, a long-time core developer of this most practical, powerful, and Pythonic package.
Thank you for your work on pytest, Bruno and for writing this book.
Valeu!
Luciano Ramalho Principal consultant at Thoughtworks and author of Fluent Python
Bruno Oliveira is a software developer with 18 years experience working at ESSS, developing desktop and web applications for simulation and numerical analysis for several industry sectors including oil and gas, aerospace, automotive, and chemical processes. Having taken part in the development of an internal testing framework to attend to the various needs of the applications he worked with, and having always been interested in testing and software quality, in 2012, Bruno took note of pytest and immediately fell in love with the project. He started contributing whenever he could and has been a pytest core contributor since 2014.
Igor T. Ghisi is a software developer with a BSc in computer science and an MSc in computational mechanics. He has worked for 10 years in the largest research center in Latin America, in Rio de Janeiro, building software for R&D in engineering using agile practices, with a focus on the oil and gas industry. He developed software for 3D Mesh Generation, Mesh Visualization, Reservoir Simulation, Uncertainty, and Multi-disciplinary Optimization. He switched to web development over the last four years to solve engineering problems using web and cloud technologies.
Edson Tadeu Monteiro Manoel has more than 15 years' experience working in scientific software development, mostly using a mix of C++ and Python. He has been using pytest in his everyday work since 2013.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
pytest Quick Start Guide
Packt Upsell
Why subscribe?
PacktPub.com
Foreword
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Introducing pytest
Why spend time writing tests?
A quick look at the unittest module
Why pytest?
Summary
Writing and Running Tests
Installing pytest
pip and virtualenv
Writing and running tests
Running tests
Powerful asserts
Text differences
Lists
Dictionaries and sets
How does pytest do it?
Checking exceptions: pytest.raises
Checking exception messages
Checking warnings: pytest.warns
Comparing floating point numbers: pytest.approx
Organizing files and packages
Tests that accompany your code
Tests separate from your code
Useful command-line options
Keyword expressions: -k
Stop soon: -x, --maxfail
Last failed, failed first: --lf, --ff
Output capturing: -s and --capture
Disabling capturing with -s
Capture methods with --capture
Traceback modes and locals: --tb, --showlocals
--tb=long
--tb=short
--tb=native
--tb=line
--tb=no
--showlocals (-l)
Slow tests with --durations
Extra test summary: -ra
Configuration: pytest.ini
Additional command-line: addopts
Customizing a collection
Cache directory: cache_dir
Avoid recursing into directories: norecursedirs
Pick the right place by default: testpaths
Override options with -o/--override
Summary
Markers and Parametrization
Mark basics
Creating marks
Running tests based on marks
Applying marks to classes
Applying marks to modules
Custom marks and pytest.ini
Built-in marks
@pytest.mark.skipif
pytest.skip
pytest.importorskip
@pytest.mark.xfail
pytest.xfail
Parametrization
Enter @pytest.mark.parametrize
Applying marks to value sets
Customizing test IDs
Testing multiple implementations
Summary
Fixtures
Introducing fixtures
Enter fixtures
Setup/teardown
Composability
Sharing fixtures with conftest.py files
Scopes
Scopes in action
Autouse
@pytest.mark.usefixtures
Parametrizing fixtures
Using marks from fixtures
An overview of built-in fixtures
tmpdir
tmpdir_factory
monkeypatch
How and where to patch
capsys/capfd
Binary mode
request
Tips/discussion
When to use fixtures, as opposed to simple functions
Renaming fixtures
Prefer local imports in conftest files
Fixtures as test-supporting code
Summary
Plugins
Finding and installing plugins
Finding plugins
Installing plugins
An overview of assorted plugins
pytest-xdist
pytest-cov
pytest-faulthandler
pytest-mock
pytest-django
pytest-flakes
pytest-asyncio
pytest-trio
pytest-tornado
pytest-postgresql
docker-services
pytest-selenium
pytest-html
pytest-cpp
pytest-timeout
pytest-annotate
pytest-qt
pytest-randomly
pytest-datadir
pytest-regressions
Honorable mentions
Summary
Converting unittest suites to pytest
Using pytest as a test runner
Pytest features in unittest subclasses
Converting asserts with unitest2pytest
Handling setup/teardown
Managing test hierarchies
Reusing test code with fixtures
Refactoring test utilities
Migration strategy
Summary
Wrapping Up
Overview of what we have learned
Introduction
Writing and running tests
Marks and parametrization
Fixtures
Plugins
Converting unittest suites to pytest
The pytest community
Getting involved
2016 Sprint
Next steps
Final summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Automated tests are a very important tool in a developer's tool belt. Having a set of automated tests not only increases productivity and software quality; it also works as a safety net for developers and gives confidence in relation to code refactorings. Python comes with a standard unittest module that is used to write automated tests, but there's an alternative: pytest. The pytest framework is simple to get started with, and scales from simple unit tests all the way through to complex integration testing. It is considered by many to be truly Pythonic in its approach, with simple functions, plain asserts, fixtures, plugins, and a whole plethora of features. More and more developers are adopting a full testing approach, so why not use a framework that is both simple and powerful and considered by many to be a true joy to use?
This book is for anyone who wants to start using pytest to improve their testing skills in their daily workflow. It covers everything from getting pytest installed, and its more important features, all the way through to tips and tricks to converting existing unittest-based suites to pytest. There are also several tips and discussions based on the author's many years of testing and pytest experience. We go through several code examples in this book and only an intermediate level of Python is required, although you will enjoy the book even more if you have some unittest experience.
Chapter 1, Introducing pytest, discusses why testing is important, gives a quick overview of the standard unittest module, and finally takes a look at pytest's main features.
Chapter 2, Writing and Running Tests, covers pytest installation, how pytest uses only the assert statement for checking values, testing module organization, and some very useful command-line options for increased productivity.
Chapter 3, Markers and Parametrization, explains how pytest markers work, how to skip tests based on certain conditions, and discusses the difference between expected failures and flaky tests (and how to deal with them). Finally, we will learn how to use the parametrize mark to apply different sets of inputs to the same piece of testing code, avoiding repetition and inviting us to cover more input cases.
Chapter 4, Fixtures, explores one of pytest's more loved features, fixtures. We also go over some built-in fixtures, and finally some tips and tricks to get more out of fixtures in your test suite.
Chapter 5, Plugins, shows how to install and search for useful plugins in the rich plugin ecosystem, and it also goes over a series of assorted plugins that the author finds interesting and/or must have in their daily work.
Chapter 6, Converting unittest suites to pytest, visits a bunch of techniques that will help you start using pytest, even if all your tests are written in the unittest framework. It covers everything from running test suites out of the box with no changes, all the way to converting them to make use of pytest features with time-tested techniques.
Chapter 7, Wrapping Up, goes over the possible next steps if you want to consolidate your pytest skills. We also take a look at the friendly pytest community and how you can get more involved.
Here's a short list of what you will need to get started:
A desktop computer or laptop: pytest works in Linux, Windows, and macOS-X, so pick any system you prefer.
Python 3: All examples are written in Python 3.6, but they should work with Python 3.4 or up with minor alternations, if any. Most examples can also be ported to Python 2 with a little more effort, but Python 3 is strongly recommended.
Your favorite text editor or IDE to work on the code.
Be comfortable with Python: nothing too advanced is required, but Python concepts, such as the
with
statement and decorators are important to have.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/pytest-Quick-Start-Guide. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Automated testing is considered to be an indispensable tool and methodology for producing high-quality software. Testing should be a part of every professional software developer's toolbox, yet at the same time, it is considered by many to be a boring and repetitive part of the job. But that does not have to be the case when you use pytest as your testing framework.
This book will introduce you to various key features and will teach how to use pytest effectively in your day-to-day coding tasks right from the first chapter, focusing on making you productive as quickly as possible. Writing tests should then become a joy, rather than a boring part of the job.
We will start by taking a look at the reasons why automated testing is important. I will also try to convince you that it is not something that you should have simply because it is the right thing to do. Automated testing is something that you will want to have because it will make your job much easier and more enjoyable. We will take a glimpse at Python's standard unittest module, and introduce pytest and why it carries so much more punch while also being dead simple to get started with. Then, we will cover how to write tests, how to organize them into classes and directories, and how to use pytest's command line effectively. From there, we will take a look at how to use marks to control skipping tests or expecting test failures, how to use custom marks to your advantage, and how to test multiple inputs using the same testing code parameterization to avoid copy/pasting code. This will help us to learn how to manage and reuse testing resources and environments using one of pytest's most loved features: fixtures. After that, we will take a tour of some of the more popular and useful plugins from the vast plugin ecosystem that pytest has to offer. Finally, we will approach the somewhat more advanced topic of how to gradually convert unittest based test suites into the pytest style in order to take advantage of its many benefits in existing code bases.
In this chapter, we will take a quick look at why we should be testing, the built-in unittest module, and an overview of pytest. Here is what will be covered:
Why spend time writing tests?
A quick look at the
unittest
module
Why pytest?
Let's get started by taking a step back and thinking about why writing tests is considered to be so important.
Testing programs manually is natural; writing automated tests is not.
Programmers use various techniques when learning to code or when dabbling in new technologies and libraries. It is common to write short snippets, follow a tutorial, play in the REPL, or even use Jupyter (http://jupyter.org/). Often, this involves manually verifying the results of what is being studied by using print statements or plotting graphics. This is easy, natural, and a perfectly valid way of learning new things.
This pattern, however, should not be carried over to professional software development. Professional software is not simple; on the contrary
