Search code examples
jsonpython-3.xselenium-webdriverpytestpytest-html

generate html and json reports for selenium python automation test using pytest


I have a selenium python automation test, it works fine, now I want to generate Html and JSON reports and have screenshots in the report using pytest. I am new to automation and python so I am not much aware of how its done.

following is my code

test_screenshot.py

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytest_html
from selenium.common.exceptions import InvalidSessionIdException

def test_Openurl(setup):
    driver = setup["driver"]
    url = setup["url"]
    try:
        driver.get(url)
    except Exception as e:
        print(e.message)

    assert driver.current_url == URL
    driver.save_screenshot("ss.png")
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.save_screenshot("ss1.png")
    driver.close()

conftest.py

import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

def pytest_addoption(parser):
    parser.addoption("--url", action="store", default="https://google.com/")

@pytest.fixture()
def setup(pytestconfig):
    s = Service("C:/Users/Yash/Downloads/chromedriver_win32/chromedriver.exe") 
    driver = webdriver.Chrome(service=s)
    driver.maximize_window()
    yield {"driver":driver, "url": pytestconfig.getoption("url")}

I ran this using

pytest test_screenshot.py --url "https://www.netflix.com/in/"

Test case is passed. How do I generate HTML and JSON report? I tried this

pytest -v -s --json-report --json-report-indent=4 --json-report-file=report/report.json --html=report/report.html test_screenshot.py

but got this error

ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --json-report --json-report-indent=4 --json-report-file=report/report.json inifile: None


Solution

  • You need to install these two libraries : https://pypi.org/project/pytest-json-report/ & https://pypi.org/project/pytest-html/