All IT Courses 50% Off
Python Tutorials

PyTest Tutorial

What is, Installation, Fixture, Assertions

In software houses when many people get together to create a single software product, they are working on small modules. All modules need to be verified weather they are working fine or not. There is a team in every department that tests every modules called software quality assurance. In Python there is a build in library called Pytest for writing tests. Let’s take a look at how this library works.

Installing Pytest

pip install pygame

To test weather pygame is installed or not use the following command

py.test -h
PyTest Tutorial

Let’s write some code.

Put the following code in a file named testfile.py

import pytest
def test_method1():
    x=2
    y=4
    assert x+1 == y,"test passeed"
    assert x == y,"test failed"
PyTest Tutorial

To run the above code use the following command.

pytest testfile.py

The following will be the output.

PyTest Tutorial

This shows that 1 test failed and one test is passed. As you can 5 is not equal to 6.

Assertions in PyTest

Pytest assertions are checks that return either True or False status. In Python Pytest, if an assertion fails in a test method, then that method execution is stopped there. The remaining python code in that test method is not executed, and Pytest assertions will continue with the next test method. 

How Pytest identify files

Pytest search for files that starts with _test or test_. We can also declare with our unique name like above then we have to explicitly mention the file name.

Running Multiple files

If we follow the namming convention then we can run multiple files using the following command.

pytest

Otherwise we need to explicitly define the file name.

pytest testfile.py

Running Pytest using Markers

We can call different methods using markers. For example there are two test methods written inside a test file. We can call them separately using command line.

Take a look at the code below to define different markers.

import pytest

@pytest.mark.one
def test_func1():
x = 2
y = 9
assert x == y

@pytest.mark.two
def test_func1():
x = "h2k"
y = "h2k"
assert x == y

Let’s run the marker two first. We need to run the following command.

pytest -m two

The following will be the output.

PyTest Tutorial
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close