in Python programming

Brief introduction to pytest: python best testing tool

Introduction to pytest: python best testing tool

What is pytest? if you check on their website they say:

pytest: helps you write better programs

basically pytest is a full-featured python testing tool:

  • multi-platform support (Windows, Linux, OS X, etc.)
  • free and open-source (distributed under the MIT license)
  • well tested
  • with a clear and full documentation

How to install pytest testing tool

Installing pytest is pretty easy, you just need a python package installer like pip or easy_install.

below are the commands needed to install the tool either in the case you want to use pip or easy_install, so open a terminal window (or command-line if you are on Windows) and type in:

pip install -U pytest # if you have pip
easy_install -U pytest # if you have easy_install

Once you have completed the installation you can check the installed version by typing:

$ py.test --version
This is pytest version 2.9.2, imported from ...

If you get an error check the known installation issues otherwise if you can correctly see the version installed then go straight to the next paragraph to run your first test.

Running the first pytest test (I know it sounds orrible)

Create a file with your editor (I use Sublime Text) and name it test_example.py

# content of test_example.py
def crazy_sum(x, y):
	return x + y + 78

def test_answer():
	assert crazy_sum(1, 1) == 2

Now all you have to do is to execute the test function by typing in the terminal:

$ py.test
====================== test session starts ======================
platform darwin -- Python 2.7.11, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /Users/ares/Devel/test_pytest, inifile: 
plugins: cov-2.2.1, flakes-1.0.1, nodev-0.9.8, pep8-1.0.6, timeout-1.0.0
collected 1 items 

test_example.py F

======================= FAILURES ========================
______________________ test_answer ______________________

    def test_answer():
>   	assert crazy_sum(1, 1) == 2
E    assert 80 == 2
E     +  where 80 = crazy_sum(1, 1)

test_sample.py:6: AssertionError
================= 1 failed in 0.01 seconds =================

Obviously we obtain an error because our crazy sum function returns 80 instead of 2.

Running multiple tests

what happends when I lauch py.test command?

pytest will look for all the files in the current directory and its subdirectories matching test_*.py and *_test.py. Inside each of the files it searches for test_ prefixed test functions or methods. If you are curious about how pytest discoveries test functions take a look at this link.