Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 23405

Real Python: Effective Python Testing With pytest

$
0
0

pytest is a popular testing framework for Python that simplifies the process of writing and executing tests. To start using pytest, install it with pip in a virtual environment. pytest offers several advantages over unittest that ships with Python, such as less boilerplate code, more readable output, and a rich plugin ecosystem.

pytest comes packed with features to boost your productivity. Its fixtures allow for explicit dependency declarations, making tests more understandable and reducing implicit dependencies. Parametrization in pytest helps prevent redundant test code by enabling multiple test cases from a single test function definition. This framework is highly customizable, so you can tailor it to your project’s needs.

By the end of this tutorial, you’ll understand that:

  • Using pytest requires installing it with pip in a virtual environment to set up the pytest command.
  • pytest allows for less code, easier readability, and more features compared to unittest.
  • Managing test dependencies and state with pytest is made efficient through the use of fixtures, which provide explicit dependency declarations.
  • Parametrization in pytest helps avoid redundant test code by allowing multiple test scenarios from a single test function.
  • Assertion introspection in pytest provides detailed information about failures in the test report.

Free Bonus:5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

Take the Quiz: Test your knowledge with our interactive “Effective Testing with Pytest” quiz. You’ll receive a score upon completion to help you track your learning progress:


Effective Python Testing With Pytest

Interactive Quiz

Effective Testing with Pytest

In this quiz, you'll test your understanding of pytest, a Python testing tool. With this knowledge, you'll be able to write more efficient and effective tests, ensuring your code behaves as expected.

How to Install pytest

To follow along with some of the examples in this tutorial, you’ll need to install pytest. As most Python packages, pytest is available on PyPI. You can install it in a virtual environment using pip:

Windows PowerShell
PS> python-mvenvvenvPS> .\venv\Scripts\activate(venv)PS> python-mpipinstallpytest
Copied!
Shell
$ python-mvenvvenv
$ sourcevenv/bin/activate
(venv)$ python-mpipinstallpytest
Copied!

The pytest command will now be available in your installation environment.

What Makes pytest So Useful?

If you’ve written unit tests for your Python code before, then you may have used Python’s built-in unittest module. unittest provides a solid base on which to build your test suite, but it has a few shortcomings.

A number of third-party testing frameworks attempt to address some of the issues with unittest, and pytest has proven to be one of the most popular. pytest is a feature-rich, plugin-based ecosystem for testing your Python code.

If you haven’t had the pleasure of using pytest yet, then you’re in for a treat! Its philosophy and features will make your testing experience more productive and enjoyable. With pytest, common tasks require less code and advanced tasks can be achieved through a variety of time-saving commands and plugins. It’ll even run your existing tests out of the box, including those written with unittest.

As with most frameworks, some development patterns that make sense when you first start using pytest can start causing pains as your test suite grows. This tutorial will help you understand some of the tools pytest provides to keep your testing efficient and effective even as it scales.

Less Boilerplate

Most functional tests follow the Arrange-Act-Assert model:

  1. Arrange, or set up, the conditions for the test
  2. Act by calling some function or method
  3. Assert that some end condition is true

Testing frameworks typically hook into your test’s assertions so that they can provide information when an assertion fails. unittest, for example, provides a number of helpful assertion utilities out of the box. However, even a small set of tests requires a fair amount of boilerplate code.

Imagine you’d like to write a test suite just to make sure that unittest is working properly in your project. You might want to write one test that always passes and one that always fails:

Pythontest_with_unittest.py
fromunittestimportTestCaseclassTryTesting(TestCase):deftest_always_passes(self):self.assertTrue(True)deftest_always_fails(self):self.assertTrue(False)
Copied!

You can then run those tests from the command line using the discover option of unittest:

Shell
(venv)$ python-munittestdiscover
F.======================================================================FAIL: test_always_fails (test_with_unittest.TryTesting)----------------------------------------------------------------------Traceback (most recent call last):  File "...\effective-python-testing-with-pytest\test_with_unittest.py",  line 10, in test_always_fails    self.assertTrue(False)AssertionError: False is not true----------------------------------------------------------------------Ran 2 tests in 0.006sFAILED (failures=1)
Copied!

As expected, one test passed and one failed. You’ve proven that unittest is working, but look at what you had to do:

Read the full article at https://realpython.com/pytest-python-testing/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]


Viewing all articles
Browse latest Browse all 23405

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>