avatarAngelica Lo Duca

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4728

Abstract

s">a, b</span>): <span class="hljs-keyword">return</span> a * b

<span class="hljs-keyword">def</span> <span class="hljs-title function_">divide</span>(<span class="hljs-params">a, b</span>): <span class="hljs-keyword">return</span> a / b</pre></div><p id="823f">Save the file as <code>calculator.py</code>.</p><h2 id="bfa1">Test Functions</h2><p id="e24b">In the same directory where we save the core functions, add another script for the tests named <code>test_calculator.py</code>. First, import the core functions and the Pytest library:</p><div id="b25e"><pre><span class="hljs-keyword">import</span> pytest <span class="hljs-keyword">from</span> calculator <span class="hljs-keyword">import</span> add</pre></div><p id="5880">Then, add a test for each function in the <code>calculator.py</code> file. For each function, add a separate test. For example, to test the <code>add()</code> function, write the following test:</p><div id="5210"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_addition</span>(): result = add(<span class="hljs-number">2</span>, <span class="hljs-number">4</span>) <span class="hljs-keyword">assert</span> result == <span class="hljs-number">6</span>

result = add(-<span class="hljs-number">1</span>, <span class="hljs-number">3</span>)
<span class="hljs-keyword">assert</span> result == <span class="hljs-number">2</span>

result = add(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
<span class="hljs-keyword">assert</span> result == <span class="hljs-number">0</span></pre></div><p id="4e20">Similarly, you can write tests for the other functions. You can find the complete example in <a href="https://github.com/alod83/data-science/tree/master/Tests/Calculator">this GitHub repository</a>.</p><p id="8c19">To run tests, open a terminal and run the following command from the folder where there are the two scripts:</p><div id="0a43"><pre>pytest</pre></div><p id="d8cd">You should obtain the following output:</p><div id="e9f2"><pre> % pytest

================================================== <span class="hljs-built_in">test</span> session starts =================================================== platform darwin -- Python 3.8.10, pytest-7.1.3, pluggy-1.0.0 rootdir: /Users/angelica/CNR/Git/data-science/Tests/Calculator plugins: typeguard-2.13.3, anyio-3.3.4 collected 4 items

test_calculator.py .... [100%]

=================================================== 4 passed <span class="hljs-keyword">in</span> 0.02s ====================================================</pre></div><h2 id="61e3">Using Test Fixtures</h2><p id="99f1">Let’s modify the previous example to support test fixtures. First, create a new directory and a new file named <code>calculator.py</code>. Wrap the calculation functions in a class:</p><div id="398f"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">Calculator</span>: <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">self</span>): self.result = <span class="hljs-number">0</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">self, a, b</span>):
    self.result = a + b
    <span class="hljs-keyword">return</span> self.result

<span class="hljs-keyword">def</span> <span class="hljs-title function_">subtract</span>(<span class="hljs-params">self, a, b</span>):
    self.result = a - b
    <span class="hljs-keyword">return</span> self.result
<span class="hljs-keyword">def</span> <span class="hljs-title function_">multiply</span>(<span class="hljs-params">self, a, b</span>):
    self.result = a * b
    <span class="hljs-keyword">return</span> self.result

<span class="hljs-keyword">def</span> <span class="hljs-title function_">divide</span>(<span class="hljs-params">self, a, b</span>):
    self.result = a / b
    <span class="hljs-keyword">return</span> self.result</pre></div><p id="d5b1">Then, create another script called <code>test_calculator.py</code> in the same directory. Import Pytest and the <code>Calculator</code> class at the beginning of the script:</p><div id="9e9e"><pre><span class="hljs-keyword">import</span> pytest

<span class="hljs-keyword">from</span> calculator <span class="hljs-keyword">import</span> *</pre></div><p id="62a9">Use the <code>@pytest.fixture</code> decorator to define a fixture named <code>calculator</co

Options

de>. Fixtures are functions that provide reusable resources or setup actions for tests. In this case, the <code>calculator</code> fixture creates an instance of the <code>Calculator</code> class and returns it.</p><div id="0a24"><pre><span class="hljs-meta">@pytest.fixture</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">calculator</span>(): <span class="hljs-comment"># Create an instance of the calculator</span> calc = Calculator() <span class="hljs-keyword">return</span> calc</pre></div><p id="ea03">Now we can use the test fixture <code>calculator</code> in our tests:</p><div id="57a1"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">test_multiplication</span>(<span class="hljs-params">calculator</span>): result = calculator.multiply(<span class="hljs-number">4</span>, <span class="hljs-number">3</span>) <span class="hljs-keyword">assert</span> result == <span class="hljs-number">12</span>

<span class="hljs-keyword">def</span> <span class="hljs-title function_">test_division</span>(<span class="hljs-params">calculator</span>): result = calculator.divide(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>) <span class="hljs-keyword">assert</span> result == <span class="hljs-number">5</span></pre></div><p id="8b02">Finally, run the test:</p><div id="2f2a"><pre>pytest</pre></div><p id="75c1">You should obtain the following output:</p><div id="eaff"><pre>pytest ================================================== <span class="hljs-built_in">test</span> session starts =================================================== platform darwin -- Python 3.8.10, pytest-7.1.3, pluggy-1.0.0 rootdir: /Users/angelica/CNR/Git/data-science/Tests/CalculatorFixture plugins: typeguard-2.13.3, anyio-3.3.4 collected 4 items

test_calculator.py .... [100%]

=================================================== 4 passed <span class="hljs-keyword">in</span> 0.01s ====================================================</pre></div><p id="1dd5">You can find the complete example in <a href="https://github.com/alod83/data-science/tree/master/Tests/CalculatorFixture">this GitHub repository</a>.</p><h1 id="5db7">Summary</h1><p id="7dee">Congratulations! You have just learned how to add tests to your Python code using Pytest! Embracing Pytest as your testing framework ensures the reliability and longevity of your Python code!</p><p id="88ee">Using Pytest is simple: you need to write intuitive test functions!</p><h1 id="6847">You may also be interested in…</h1><div id="1c25" class="link-block"> <a href="https://readmedium.com/4-docker-options-you-may-not-know-fef301a5ce03"> <div> <div> <h2>4 Docker Options You May Not Know</h2> <div><h3>How to remove an image in Docker, rebuild an image from the base image, pass some configuration files to a Docker…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*caYEXbcQD5x5KsFp)"></div> </div> </div> </a> </div><div id="8c83" class="link-block"> <a href="https://towardsdatascience.com/how-to-install-spark-nlp-5fcd36fab378"> <div> <div> <h2>How to Install Spark NLP</h2> <div><h3>A step-by-step tutorial on how to make Spark NLP work on your local computer</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*8RT0UoNWQ31EWeb_)"></div> </div> </div> </a> </div><div id="dfbb" class="link-block"> <a href="https://towardsdatascience.com/getting-started-with-data-cleaning-in-python-pandas-76d977f95b57"> <div> <div> <h2>Getting Started with Data Cleaning in Python Pandas</h2> <div><h3>A practical example of performing data cleaning using the popular Python library.</h3></div> <div><p>towardsdatascience.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*MY1E2eNLAiNodAt6)"></div> </div> </div> </a> </div></article></body>

Programming, Python

How to Test Your Python Code with Pytest

Simplify your testing process and enhance code quality with Pytest

Image by Author

Are you tired of spending hours debugging your code and fixing errors that could have easily been prevented? We know how frustrating it can be to have code that doesn’t work correctly, especially when you’re under pressure to deliver results. But fear not! There’s a solution: Pytest.

Pytest is a robust testing framework that helps ensure your code works as expected, even under different scenarios and conditions. Integrating Pytest into your code allows you to identify and fix bugs before they become problems, saving you time and effort in the long run.

In this article, we’ll show you how to start with Pytest. From setting up your environment to writing tests that cover all your code, we’ve got you covered. So why wait? Let’s start testing and ensure your code works flawlessly every time.

We’ll cover:

  • An Overview of Pytest
  • A Practical Example

Let’s start by describing an overview of Pytest.

An Overview of Pytest

Pytest is a testing framework for Python that focuses on simplicity and ease of use. To install Pytest, run the following command:

$ pip install pytest

Pytest follows a modular and extensible architecture, allowing developers to organize tests into individual test functions or classes.

When you build your test using Pytest, you must follow the steps described below:

  1. Create a new script test_<mytest>.py for your tests. Import Pytest into the script.
  2. Define Your Test Functions: A test function is a Python function that verifies a specific aspect of your code’s behavior. Each test function should be self-contained, focusing on a single test case. Pytest automatically discovers and executes these test functions.
  3. Test Naming Convention: Each test function must start with test_ to make Pytest recognize it correctly.
  4. Test Assertions: Use test assertions to define the function's behavior. Pytest provides a wide range of powerful assertion functions.
  5. Test Fixtures: Fixtures are functions that provide reusable and preconfigured resources or test data to your test functions.

A List of Some Assets Functions

Here are some of the main assertions provided by Pytest:

  1. assert: Make simple assertions by checking if a given condition is true
  2. assertEqual: Compare two values for equality. It checks if the expected value is equal to the actual value
  3. assertTrue and assertFalse: Verify if a given condition is true or false.
  4. assertRaises: Check if a specific exception is raised when executing a code.
  5. assertIn and assertNotIn: Verify if a value is present or absent in a given collection or sequence
  6. assertAlmostEqual: Compare floating-point values to a specified degree of precision.
  7. assertDictEqual: Check if two dictionaries have the same set of key-value pairs.
  8. assertRaisesRegex: Verify if a specific exception is raised and the exception message matches a regular expression pattern.

Now that you have seen the basic concepts behind Pytest let’s move on to a practical example.

A Practical Example

Let’s imagine we want to build a calculator and test if we have implemented it correctly. First, we define the core functions, and then we write tests.

Core Functions

The core functions implement the calculator's operations. For example, we can write the following simple code to implement the primary operations:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    return a / b

Save the file as calculator.py.

Test Functions

In the same directory where we save the core functions, add another script for the tests named test_calculator.py. First, import the core functions and the Pytest library:

import pytest
from calculator import add

Then, add a test for each function in the calculator.py file. For each function, add a separate test. For example, to test the add() function, write the following test:

def test_addition():
    result = add(2, 4)
    assert result == 6

    result = add(-1, 3)
    assert result == 2

    result = add(0, 0)
    assert result == 0

Similarly, you can write tests for the other functions. You can find the complete example in this GitHub repository.

To run tests, open a terminal and run the following command from the folder where there are the two scripts:

pytest

You should obtain the following output:

 % pytest
================================================== test session starts ===================================================
platform darwin -- Python 3.8.10, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/angelica/CNR/Git/data-science/Tests/Calculator
plugins: typeguard-2.13.3, anyio-3.3.4
collected 4 items                                                                                                        

test_calculator.py ....                                                                                            [100%]

=================================================== 4 passed in 0.02s ====================================================

Using Test Fixtures

Let’s modify the previous example to support test fixtures. First, create a new directory and a new file named calculator.py. Wrap the calculation functions in a class:

class Calculator:
    def __init__(self):
        self.result = 0

    def add(self, a, b):
        self.result = a + b
        return self.result

    def subtract(self, a, b):
        self.result = a - b
        return self.result
    def multiply(self, a, b):
        self.result = a * b
        return self.result

    def divide(self, a, b):
        self.result = a / b
        return self.result

Then, create another script called test_calculator.py in the same directory. Import Pytest and the Calculator class at the beginning of the script:

import pytest
from calculator import *

Use the @pytest.fixture decorator to define a fixture named calculator. Fixtures are functions that provide reusable resources or setup actions for tests. In this case, the calculator fixture creates an instance of the Calculator class and returns it.

@pytest.fixture
def calculator():
    # Create an instance of the calculator
    calc = Calculator()
    return calc

Now we can use the test fixture calculator in our tests:

def test_multiplication(calculator):
    result = calculator.multiply(4, 3)
    assert result == 12

def test_division(calculator):
    result = calculator.divide(10, 2)
    assert result == 5

Finally, run the test:

pytest

You should obtain the following output:

pytest
================================================== test session starts ===================================================
platform darwin -- Python 3.8.10, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/angelica/CNR/Git/data-science/Tests/CalculatorFixture
plugins: typeguard-2.13.3, anyio-3.3.4
collected 4 items                                                                                                        

test_calculator.py ....                                                                                            [100%]

=================================================== 4 passed in 0.01s ====================================================

You can find the complete example in this GitHub repository.

Summary

Congratulations! You have just learned how to add tests to your Python code using Pytest! Embracing Pytest as your testing framework ensures the reliability and longevity of your Python code!

Using Pytest is simple: you need to write intuitive test functions!

You may also be interested in…

Python
Programming
Testing
Pytest
Coding
Recommended from ReadMedium