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
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,
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
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
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
passed asserting test
#pytest #python #testing #developer