API Navigator Logo

Python Create API Test Report

Author: Newtum

This example shows how to generate a simple HTML test report after running a series of API tests. For more advanced reporting, consider using `pytest-html`.

Generating an HTML Report

We can collect the results of our API tests (e.g., test name, status, duration) in a list. After the tests run, we can iterate through this list to generate an HTML file with a summary table.

import datetime

# In a real test run, this data would be collected dynamically.
test_results = [
    {'name': 'Test Get All Posts', 'status': 'PASS', 'duration': 0.82},
    {'name': 'Test Get Single Post', 'status': 'PASS', 'duration': 0.31},
    {'name': 'Test Create New Post', 'status': 'FAIL', 'duration': 1.15},
    {'name': 'Test Update Post', 'status': 'PASS', 'duration': 0.76},
]

def generate_html_report(results):
    report_html = """
    <html>
    <head>
        <title>API Test Report</title>
        <style>
            body { font-family: sans-serif; }
            table { border-collapse: collapse; width: 100%; }
            th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; }
            th { background-color: #f2f2f2; }
            .pass { color: green; }
            .fail { color: red; font-weight: bold; }
        </style>
    </head>
    <body>
        <h1>API Test Report</h1>
        <p>Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        <table>
            <tr><th>Test Name</th><th>Status</th><th>Duration (s)</th></tr>
            {table_rows}
        </table>
    </body>
    </html>
    """
    
    rows_html = ""
    for result in results:
        status_class = 'pass' if result['status'] == 'PASS' else 'fail'
        rows_html += f"""
        <tr>
            <td>{result['name']}</td>
            <td class="{status_class}">{result['status']}</td>
            <td>{result['duration']}</td>
        </tr>"""

    final_report = report_html.format(
        table_rows=rows_html
    )
    return final_report

# Generate the report
html_content = generate_html_report(test_results)

# In a real script, you would save this to a file:
# with open('test_report.html', 'w') as f:
#     f.write(html_content)

print("HTML report generated (content below):")
print("-----------------------------------------")
print(html_content)