Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
pytest Quick Start Guide
pytest Quick Start Guide

pytest Quick Start Guide: Write better Python code with simple and maintainable tests

eBook
€8.99 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

pytest Quick Start Guide

Writing and Running Tests

In the previous chapter, we discussed why testing is so important and looked at a brief overview of the unittest module. We also took a cursory look at pytest's features, but barely got a taste of them.

In this chapter, we will start our journey with pytest. We will be pragmatic, so this means that we will not take an exhaustive look at all of the things it's possible to do with pytest, but instead provide you with a quick overview of the basics to make you productive quickly. We will take a look at how to write tests, how to organize them into files and directories, and how to use pytest's command line effectively.

Here's what is covered in this chapter:

  • Installing pytest
  • Writing and running tests
  • Organizing files and packages
  • Useful command-line options
  • Configuration: pytest.ini file
In the chapter, there are a lot of examples...

Installing pytest

Installing pytest is really simple, but first, let's take a moment to review good practices for Python development.

All of the examples are for Python 3. They should be easy to adapt to Python 2 if necessary.

pip and virtualenv

The recommended practice for installing dependencies is to create a virtualenv. A virtualenv (https://packaging.python.org/guides/installing-using-pip-and-virtualenv/) acts like a complete separate Python installation from the one that comes with your operating system, making it safe to install the packages required by your application without risk of breaking your system Python or tools.

Now we will learn how to create a virtual environment and install pytest using pip. If...

Writing and running tests

Using pytest, all you need to do to start writing tests is to create a new file named test_*.py and write test functions that start with test:

    # contents of test_player_mechanics.py
def test_player_hit():
player = create_player()
assert player.health == 100
undead = create_undead()
undead.hit(player)
assert player.health == 80

To execute this test, simply execute pytest, passing the name of the file:

λ pytest test_player_mechanics.py

If you don't pass anything, pytest will look for all of the test files from the current directory recursively and execute them automatically.

You might encounter examples on the internet that use py.test in the command line instead of pytest. The reason for that is historical: pytest used to be part of the py package, which provided several general purpose utilities, including...

Organizing files and packages

Pytest needs to import your code and test modules, and it is up to you how to organize them. Pytest supports two common test layouts, which we will discuss next.

Tests that accompany your code

You can place your test modules together with the code they are testing by creating a tests folder next to the modules themselves:

setup.py
mylib/
tests/
__init__.py
test_core.py
test_utils.py
__init__.py
core.py
utils.py

By putting the tests near the code they test, you gain the following advantages:

  • It is easier to add new tests and test modules in this hierarchy and keep them in sync
  • Your tests are now part of your package, so they can be deployed and run in other...

Useful command-line options

Now we will take a look at command-line options that will make you more productive in your daily work. As stated at the beginning of the chapter, this is not a complete list of all of the command-line features; just the ones that you will use (and love) the most.

Keyword expressions: -k

Often, you don't exactly remember the full path or name of a test that you want to execute. At other times, many tests in your suite follow a similar pattern and you want to execute all of them because you just refactored a sensitive area of the code.

By using the -k <EXPRESSION> flag (from keyword expression), you can run tests whose item id loosely matches the given expression:

λ pytest -k &quot...

Configuration: pytest.ini

Users can customize some pytest behavior using a configuration file called pytest.ini. This file is usually placed at the root of the repository and contains a number of configuration values that are applied to all test runs for that project. It is meant to be kept under version control and committed with the rest of the code.

The format follows a simple ini-style format with all pytest-related options under a [pytest] section. For more details, go to:https://docs.python.org/3/library/configparser.html.

[pytest]

The location of this file also defines what pytest calls the root directory (rootdir): if present, the directory that contains the configuration file is considered the root directory.

The root directory is used for the following:

  • To create the tests node IDs
  • As a stable location to store information about the project (by pytest plugins and features...

Summary

In this chapter, we covered how to use virtualenv and pip to install pytest. After that, we jumped into how to write tests, and the different ways to run them so that we can execute just the tests we are interested in. We had an overview of how pytest can provide rich output information for failing tests for different built-in data types. We learned how to use pytest.raises and pytest.warns to check exceptions and warnings, and pytest.approx to avoid common pitfalls when comparing floating point numbers. Then, we briefly discussed how to organize test files and modules in your projects. We also took a look at some of the more useful command-line options so that we can get productive right away. Finally, we covered how pytest.ini files are used for persistent command-line options and other configuration.

In the next chapter, we will learn how to use marks to help us skip...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Become proficient with pytest from day one by solving real-world testing problems
  • Use pytest to write tests more efficiently
  • Scale from simple to complex and functional testing

Description

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.

Who is this book for?

This book is for Python programmers that want to learn more about testing. This book is also for QA testers, and those who already benefit from programming with tests daily but want to improve their existing testing tools.

What you will learn

  • Write and run simple and complex tests
  • Organize tests in files and directories
  • Find out how to be more productive on the command line
  • Markers and how to skip, xfail and parametrize tests
  • Explore fxtures and techniques to use them effectively, such as tmpdir, pytestconfg, and monkeypatch
  • Convert unittest suites to pytest using little-known techniques
  • Use third-party plugins

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 29, 2018
Length: 160 pages
Edition : 1st
Language : English
ISBN-13 : 9781789343823
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 29, 2018
Length: 160 pages
Edition : 1st
Language : English
ISBN-13 : 9781789343823
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
pytest Quick Start Guide
€24.99
Clean Code in Python
€36.99
Modern Python Standard Library Cookbook
€41.99
Total 103.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Introducing pytest Chevron down icon Chevron up icon
Writing and Running Tests Chevron down icon Chevron up icon
Markers and Parametrization Chevron down icon Chevron up icon
Fixtures Chevron down icon Chevron up icon
Plugins Chevron down icon Chevron up icon
Converting unittest suites to pytest Chevron down icon Chevron up icon
Wrapping Up Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9
(7 Ratings)
5 star 57.1%
4 star 14.3%
3 star 0%
2 star 14.3%
1 star 14.3%
Filter icon Filter
Top Reviews

Filter reviews by




Denivy Braiam Ruck Nov 21, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very rounded book with lots of tips and tricks both for python development and a healthy testing environment. It offers real examples and solutions for problems you may face in production.The book itself has a very near-the-user language and is very enjoyable to read! No issues found in the Kindle version.
Amazon Verified review Amazon
William Jamir Jun 17, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a well-written book, and it's pretty easy to get going. The highlight for me is the way the book not only explains how to use pytest but also why its features are useful, with practical examples and tips.I'm sure that even readers that have been using pytest for a few years will benefit and gain some insights.
Amazon Verified review Amazon
Winston Churchill-Joell Apr 20, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As advertised, this book is a quick start guide to get you familiar with the core capabilities of the pytest framework and best practices for using it in production. Collaboration and version control are always kept in mind; the idea of why you're testing feels like it's always present, so the topics and tips have context with what you're likely going to encounter, rather than simply covered in isolation. Throughout the book, I felt like I'm getting an insider's perspective and not only an overview, but recommendations on the best way to proceed. In a relatively brief span of pages the author delivers a solid foundation for the reader in a humorous and conversational tone that makes the content an easy read. I highly recommend.
Amazon Verified review Amazon
Anderson Ferreira Dec 19, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
O livro é excelente, com detalhes e ótimas dicas de uso, não é muito aprofundado no pytest mas é pra quem quer e precisa usar rápido.
Amazon Verified review Amazon
D. Bhaduri Oct 30, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Self taught Python programmer, so, testing and test driven development are new to me. I'm careful about introducing too many packages that overlap with the standard library, but, I wanted to learn more about pytest as an alternative to unittest. Written by a contributor to the project, this book was an excellent and succinct introduction to (what i assume) is the 20% of pytest that is used 80% of the time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.