How to Generate HTML Report for Pytest Execution

Generate Pytest HTML Report for Pytest Execution, The primary advantage of the report feature is that the output gets generated in a simpler & readable format, mostly in the form of HTML or XML files. Since these file formats are widely used, it makes the task of decoding the output easier.

pytest-html is a plugin for pytest that generates a HTML report for the test results.

Requirements

You will need the following prerequisites in order to use pytest-html:

  • Python 3.6+ or PyPy3

Pytest HTML Report

Lets, Generate a Pytest HTML report to view the python automation results. before writing the code, Install pytest-html.

Installation

  • To install pytest-html:
$ pip install pytest-html
  • Then run your tests with:
$ pytest --html=report.html

Coding the test file

Let’s create a sample.py file as follows:

import json


class StudentData:
    def __init__(self):
        self.__data = None

    def connect(self, data_file):
        with open(data_file) as json_file:
            self.__data = json.load(json_file)

    def get_data(self, name):
        for stu in self.__data['students']:
            if stu['name'] == name:
                return stu

    def close(self):
        pass
  • Similarly, let’s create a test_sample.py file accordingly:
from sample import StudentData
import pytest

@pytest.fixture(scope='module')
def db():
    print('*****SETUP*****')
    db = StudentData()
    db.connect('data.json')
    yield db
    print('******TEARDOWN******')
    db.close()


def test_scott_data(db):
    scott_data = db.get_data('Joseph')
    assert scott_data['id'] == 1
    assert scott_data['name'] == 'Joseph'
    assert scott_data['result'] == 'pass'


def test_mark_data(db):
    mark_data = db.get_data('Jaden')
    assert mark_data['id'] == 2
    assert mark_data['name'] == 'Jaden'
    assert mark_data['result'] == 'fail'
  • You can see, we have used a .json file, since here we testing files along with databases. So, the data.json file is as follows:
{
    "students": [
        {
            "id": 1,
            "name": "Joseph",
            "result": "pass"
        },
        {
            "id": 2,
            "name": "Jaden",
            "result": "fail"
        }
    ]
}

Your testing file should be as follows:

  • Now, let’s execute the following command in our terminal:
py.test --html=report.html -s

  • We can now see an extra file named  report.html in our IDE, which is created by default. On running the html file we will get like this:

  • Now, change an assert result for which test case will fail and see how report.html changes: