Python Testing with Pytest. 2 Ed
Test applications, packages, and libraries large and small with pytest, Python’s most powerful testing framework. pytest helps you write tests quickly and keep them readable and maintainable. In this fully revised edition, explore pytest’s superpowers — simple asserts, fixtures, parametrization, markers, and plugins — while creating simple tests and test suites against a small database application. Using a robust yet simple fixture model, it’s just as easy to write small tests with pytest as it is to scale up to complex functional testing. This book shows you how.
Pytest is undeniably the best choice for testing Python projects. It’s a full-featured, flexible, and extensible testing framework. pytest’s fixture model allows you to share test data and setup procedures across multiple layers of tests. The pytest framework gives you powerful features such as assert rewriting, parametrization, markers, plugins, parallel test execution, and clear test failure reporting — with no boilerplate code.
With simple step-by-step instructions and sample code, this book gets you up to speed quickly on this easy-to-learn yet powerful tool. Write short, maintainable tests that elegantly express what you’re testing. Speed up test times by distributing tests across multiple processors and running tests in parallel. Use Python’s builtin assert statements instead of awkward assert helper functions to make your tests more readable. Move setup code out of tests and into fixtures to separate setup failures from test failures. Test error conditions and corner cases with expected exception testing, and use one test to run many test cases with parameterized testing. Extend pytest with plugins, connect it to continuous integration systems, and use it in tandem with tox, mock, coverage, and even existing unittest tests.
Write simple, maintainable tests quickly with pytest.
What You Need:
The examples in this book were written using Python 3.10 and pytest 7. pytest 7 supports Python 3.5 and above.
Если вам понравилась эта книга поделитесь ею с друзьями, тем самым вы помогаете нам развиваться и добавлять всё больше интересных и нужным вам книг!
Python Testing with pytest, 2nd Edition
- 2nd edition is now in print and shipping from various booksellers.
- eBook
- is available through Pragmatic
- includes pdf, epub, and mobi (for Kindle)
- paper editions
- bookshop.org
- Amazon
- Barnes & Noble
- Waterstones
- It might be at your local independent bookstore. If not, they could order it for you.
- Or request it from your library.
Why a Second Edition?#
This section is an excerpt from the Preface, which is available to read as a larger excerpt on the books Pragmatic page.
Both Python and pytest have changed since the first edition of this book was published in 2017. There have been updates to pytest that are now reflected in the book, such as:
There have also been updates to Python that are reflected in the book:
Also, since publication of the first edition, I have taught many, many people about pytest, and I think I’ve learned how to be a better teacher. The second edition not only expands on what is covered in the first edition—it grew from 7 to 17 chapters!—but also it presents the material in what I think is a more gradual, digestible manner.
So what’s in all of these new chapters?
- More on parametrization, markers, coverage, mocking, tox and continuous integration, and third-party plugins. All of these topics were covered in the first edition, but in this edition I expand that coverage. I pulled the discussion of parametrization into its own chapter and added a discussion of advanced parametrization techniques. I delve more deeply into markers and include an example of how to pass data from markers to fixtures (which is super cool). I also take you on a deeper dive into test coverage, mocking, and CI, and using and building your own plugins to extend pytest’s capabilities.
- A discussion of test strategy. Feedback from the first edition was that the book was great for the mechanics of how to use pytest, but the “What test do I write?” information was a bit lacking. The new Chapter 7: Strategy is push in the right direction of what tests to write. A complete treatment of test strategy would be a book in itself; however, this chapter will get you started.
- Information about the Python search path. A lot of readers reached out to me asking about how to get their tests to see their test code, and the first edition didn’t cover it. The project in this book, Cards, doesn’t have that problem because it’s an installed Python package. However, lots of user projects are applications or scripts or lots of other things that are not installed packages. This chapter offers a focused look at the problem and provides some solutions.
I moved coverage of command-line flags and configuration settings in general to their own chapter at the end of the book where, after you’ve learned the basics of pytest, you can check out the ton of cool options that can help you run your tests more efficiently and effectively.
Also, I consolidated the information about debugging test failures into a chapter of its own. In the last edition, this information was spread all throughout the book. It is my hope that when you are faced with a deadline and a failing test suite, bringing this information together into one chapter will help you figure an answer out quickly and ease some stress.
Finally, the example project changed. The first edition used a project called Tasks to illustrate how to use pytest. Now it’s called Cards. Here’s why:
- It’s easier to say out loud. (Try it. Say “tasks” three times, then “cards” three times. Right?)
- The new project itself is different because it uses Typer instead of Click for command-line functionality. Typer code is easier to read.
- The project also uses Rich for formatting the output. Rich didn’t exist (neither did Typer) when the first edition was written.
The code examples have also been simplified. The directory structure of the first edition code examples followed a progression of a possible test directory within a project, with most of the project removed. Seriously, I think it made sense to me at the time. In this edition, there is a project in its own directory, cards_proj , with no tests. Then each of the chapters have test code (if appropriate) that either work on the one project, or on some local code. Trust me, I think you’ll agree that it’s way easier to follow along now.
Python Testing with pytest: Simple, Rapid, Effective, and Scalable, 2nd Edition
Test applications, packages, and libraries large and small with pytest, Python’s most powerful testing framework. pytest helps you write tests quickly and keep them readable and maintainable. In this fully revised edition, explore pytest’s superpowers – simple asserts, fixtures, parametrization, markers, and plugins – while creating simple tests and test suites against a small database application. Using a robust yet simple fixture model, it’s just as easy to write small tests with pytest as it is to scale up to complex functional testing. This book shows you how.
pytest is undeniably the best choice for testing Python projects. It’s a full-featured, flexible, and extensible testing framework. pytest’s fixture model allows you to share test data and setup procedures across multiple layers of tests. The pytest framework gives you powerful features such as assert rewriting, parametrization, markers, plugins, parallel test execution, and clear test failure reporting – with no boilerplate code.
With simple step-by-step instructions and sample code, this book gets you up to speed quickly on this easy-to-learn yet powerful tool. Write short, maintainable tests that elegantly express what you’re testing. Speed up test times by distributing tests across multiple processors and running tests in parallel. Use Python’s builtin assert statements instead of awkward assert helper functions to make your tests more readable. Move setup code out of tests and into fixtures to separate setup failures from test failures. Test error conditions and corner cases with expected exception testing, and use one test to run many test cases with parameterized testing. Extend pytest with plugins, connect it to continuous integration systems, and use it in tandem with tox, mock, coverage, and even existing unittest tests.
Write simple, maintainable tests quickly with pytest.
The examples in this book were written using Python 3.10 and pytest 7. pytest 7 supports Python 3.5 and above.
Acknowledgments Preface Why pytest? Learn pytest While Testing a Sample Application How This Book Is Organized What You Need to Know Why a Second Edition? Example Code and Online Resources Part I. Primary Power 1. Getting Started with pytest Installing pytest Running pytest Review Exercises What’s Next 2. Writing Test Functions Installing the Sample Application Writing Knowledge-Building Tests Using assert Statements Failing with pytest.fail() and Exceptions Writing Assertion Helper Functions Testing for Expected Exceptions Structuring Test Functions Grouping Tests with Classes Running a Subset of Tests Review Exercises What’s Next 3. pytest Fixtures Getting Started with Fixtures Using Fixtures for Setup and Teardown Tracing Fixture Execution with –setup-show Specifying Fixture Scope Sharing Fixtures through conftest.py Finding Where Fixtures Are Defined Using Multiple Fixture Levels Using Multiple Fixtures per Test or Fixture Deciding Fixture Scope Dynamically Using autouse for Fixtures That Always Get Used Renaming Fixtures Review Exercises What’s Next 4. Builtin Fixtures Using tmp_path and tmp_path_factory Using capsys Using monkeypatch Remaining Builtin Fixtures Review Exercises What’s Next 5. Parametrization Testing Without Parametrize Parametrizing Functions Parametrizing Fixtures Parametrizing with pytest_generate_tests Using Keywords to Select Test Cases Review Exercises What’s Next 6. Markers Using Builtin Markers Skipping Tests with pytest.mark.skip Skipping Tests Conditionally with pytest.mark.skipif Expecting Tests to Fail with pytest.mark.xfail Selecting Tests with Custom Markers Marking Files, Classes, and Parameters Using “and,” “or,” “not,” and Parentheses with Markers Being Strict with Markers Combining Markers with Fixtures Listing Markers Review Exercises What’s Next Part II. Working with Projects 7. Strategy Determining Test Scope Considering Software Architecture Evaluating the Features to Test Creating Test Cases Writing a Test Strategy Review Exercises What’s Next 8. Configuration Files Understanding pytest Configuration Files Saving Settings and Flags in pytest.ini Using tox.ini, pyproject.toml, or setup.cfg in place of pytest.ini Determining a Root Directory and Config File Sharing Local Fixtures and Hook Functions with conftest.py Avoiding Test File Name Collision Review Exercises What’s Next 9. Coverage Using coverage.py with pytest-cov Generating HTML Reports Excluding Code from Coverage Running Coverage on Tests Running Coverage on a Directory Running Coverage on a Single File Review Exercises What’s Next 10. Mocking Isolating the Command-Line Interface Testing with Typer Mocking an Attribute Mocking a Class and Methods Keeping Mock and Implementation in Sync with Autospec Making Sure Functions Are Called Correctly Creating Error Conditions Testing at Multiple Layers to Avoid Mocking Using Plugins to Assist Mocking Review Exercises What’s Next 11. tox and Continuous Integration What Is Continuous Integration? Introducing tox Setting Up tox Running tox Testing Multiple Python Versions Running tox Environments in Parallel Adding a Coverage Report to tox Specifying a Minimum Coverage Level Passing pytest Parameters Through tox Running tox with GitHub Actions Review Exercises What’s Next 12. Testing Scripts and Applications Testing a Simple Python Script Testing an Importable Python Script Separating Code into src and tests Directories Defining the Python Search Path Testing requirements.txt-Based Applications Review Exercises What’s Next 13. Debugging Test Failures Adding a New Feature to the Cards Project Installing Cards in Editable Mode Debugging with pytest Flags Re-Running Failed Tests Debugging with pdb Combining pdb and tox Review Exercises What’s Next Part III. Booster Rockets 14. Third-Party Plugins Finding Plugins Installing Plugins Exploring the Diversity of pytest Plugins Running Tests in Parallel Randomizing Test Order Review Exercises What’s Next 15. Building Plugins Starting with a Cool Idea Building a Local conftest Plugin Creating an Installable Plugin Testing Plugins with pytester Testing Multiple Python and pytest Versions with tox Publishing Plugins Review Exercises What’s Next 16. Advanced Parametrization Using Complex Values Creating Custom Identifiers Parametrizing with Dynamic Values Using Multiple Parameters Using Indirect Parametrization Review Exercises What’s Next A1. Virtual Environments A2. pip