Python is a dynamically-typed language used in software development and other areas such as data analysis, research science etc which has been on the increase over the past years and the need to properly, effectively and efficiently put the software’s used in these fields to the test is prominent to ensure they produce the correct expected results. Here comes “pytest”

What is pytest:

Pytest is a framework that makes building simple and scalable tests easy.

Why pytest

  • No boiler code required
  • Complex test are made simple to write
  • Tests are easy to read
  • You can get started in seconds
  • You use assert to fail a test unlike Unittest which uses things such as self.assertEqual etc
  • It can be use to run tests written for Unittest

Pytest Installation

Run the following command on your command line

pip install pytest

Conditions For Carrying out Test In pytest

In order to carry out test in pytest, the following conditions are to be made,

  • The file has to start with test_ or end with _test
  • Tests classes should be name Test

Getting started with Pytest

let’s create a simple test function in a file called**_ test_medium.py_**

def func(x):
    return x + 1

def test_correct():
    assert func(4) == 5
def test_false_answer():
    assert func (3) == 8

Next:

we run

pytest test_sample.py in our current working directory

Image for post

our output

Interpretation of pytest Output

From the above output, we can see 1 test was failed and the other passed.Here is the beauty of pytest when compared to other testing frameworks i.e the test is very easy to read and understand

Assertions About Expected Exceptions

In order to write assertions about raised exceptions, you can use pytest.raises as a context manager. For example,

import pytest 

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0

output

Image for post

passed asserting test

#pytest #python #testing #developer

Pytest Tutorial for Absolute Beginners
3.70 GEEK