How to Generate HTML Report for Pytest Execution

Generate 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 file. 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.


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

  • Python 3.6+ or PyPy3


  • 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 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):
  • Similarly, let’s create a file accordingly:
from sample import StudentData
import pytest

def db():
    db = StudentData()
    yield db

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 tsting files along with databases. So, 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: