Register to get access to free programming courses with interactive exercises

Pytest framework Python: Automated testing

When there are a lot of tests and test files, new questions arise:

  • How to group the tests?
  • How to run all the tests in one directory?
  • How many tests should be there?
  • How long should the tests be?
  • Can we run the tests in parallel?

Test frameworks solve these issues. They help organize the structure of tests and give many handy things, such as convenient output. We'll get acquainted with most of these features later in the course.

The Pytest framework is popular in the Python world, and we'll focus on it in this lesson.

What is Pytest

Python is one of the few languages whose standard library already includes the latest framework — it is called unittest. It would be logical to look at it here, but it is deeply tied to classes you may not know. Therefore, we're looking at Pytest, which is still more popular than the embedded framework.

Next, we'll create a project from scratch and add tests.

The setup of Pytest

Create a directory somewhere on your computer with the name hexlet_pytest. Go into it and run the following commands:

# Installing Poetry via the link:
poetry new . # Creating the base structure
poetry install # Installing dependencies

The poetry new command creates a dummy Python package and adds a directory for future tests. Install Pytest in the dev group using the poetry add-G dev pytest command. Check that everything is working correctly:

poetry run pytest
# We see a sample output
platform darwin -- Python 3.8.2, pytest-5.4.3, py-1.10.0, pluggy-0.13.1
rootdir: /private/tmp/hexlet_pytest
collected 0 items

======= no tests ran in 0.01s =======

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.