Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Test Parametrization | Pytest Framework
Python Advanced Concepts
course content

Contenido del Curso

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework

bookTest Parametrization

Parameterized testing is crucial for enhancing test coverage without writing numerous test functions for scenarios that only differ by their inputs and expected outputs. This approach not only saves time but also increases the clarity and maintainability of test suites by:

  • Reducing code duplication and the potential for errors in test code;
  • Enabling easy addition of new test cases by simply adding parameters;
  • Facilitating comprehensive testing across a wide range of inputs.

Let's consider a simple function that calculates the average of two numbers. There can be a logical error if to forget to put braces. We'll use @pytest.mark.parametrize to test this function with several pairs of numbers.

This example demonstrates how to run test_calculate_average with three different sets of numbers, checking if the function correctly computes their average.

Syntax with id

The id parameter is used to assign an identifier to each set of inputs, which helps to identify tests more easily in the test output:

Using pytest.param allows for more granular control over each test case, including setting individual IDs directly.

Syntax with ids

You can also provide a unique ID for each test case using ids, which makes test reports more readable:

In this code, each set of parameters has an associated ID that describes the test case, which will appear in the test output.

Here's what the output might look like:

1. Consider a function that multiplies two numbers. Complete the test case by filling in the missing parts:
2. What is the primary benefit of specifying identifiers using `id` or `ids` in `@pytest.mark.parametrize`?
Consider a function that multiplies two numbers. Complete the test case by filling in the missing parts:

Consider a function that multiplies two numbers. Complete the test case by filling in the missing parts:

Selecciona la respuesta correcta

What is the primary benefit of specifying identifiers using `id` or `ids` in `@pytest.mark.parametrize`?

What is the primary benefit of specifying identifiers using id or ids in @pytest.mark.parametrize?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
We're sorry to hear that something went wrong. What happened?
some-alt