This pytest plugin creates test reports as JSON. This makes it easy to process test results in other applications.
It can report a summary, test details, captured output, logs, exception tracebacks and more. Additionally, you can use the available fixtures and hooks to add metadata and customize the report as you like.
Or use the pytest_json_runtest_metadatahook (in your conftest.py) to add metadata based on the current test run. The dict returned will automatically be merged with any existing metadata. E.g., this adds the start and stop time of each test's call stage:
Also, you could add metadata using pytest-metadata's --metadata switch which will add metadata to the report's environment section, but not to a specific test item. You need to make sure all your metadata is JSON-serializable.
A note on hooks
If you're using a pytest_json_* hook although the plugin is not installed or not active (not using --json-report), pytest doesn't recognize it and may fail with an internal error like this:
INTERNALERROR> pluggy.manager.PluginValidationError: unknown hook 'pytest_json_runtest_metadata' in plugin <module 'conftest' from 'conftest.py'>
You can avoid this by declaring the hook implementation optional:
You can modify the entire report before it's saved by using the pytest_json_modifyreport hook.
Just implement the hook in your conftest.py, e.g.:
def pytest_json_modifyreport(json_report):
# Add a key to the report
json_report['foo'] = 'bar'
# Delete the summary from the report
del json_report['summary']
After pytest_sessionfinish, the report object is also directly available to script via config._json_report.report. So you can access it using some built-in hook:
If you really want to change how the result of a test stage run is turned into JSON, you can use the pytest_json_runtest_stage hook. It takes a TestReport and returns a JSON-serializable dict:
The environment section is provided by pytest-metadata. All metadata given by that plugin will be added here, so you need to make sure it is JSON-serializable.
A list of log records. The fields of a log record are the logging.LogRecord attributes, with the exception that the fields exc_info and args are always empty and msg contains the formatted log message.
You can apply logging.makeLogRecord() on a log record to convert it back to a logging.LogRecord object.
When the warning was captured. ("config", "collect" or "runtest" as listed here)
Example
[
{
"code": "C1",
"path": "/path/to/tests/test_foo.py",
"nodeid": "test_foo.py::TestFoo",
"message": "cannot collect test class 'TestFoo' because it has a __init__ constructor"
}
]
Related tools
pytest-json has some great features but appears to be unmaintained. I borrowed some ideas and test cases from there.
tox has a switch to create a JSON report including a test result summary. However, it just provides the overall outcome without any per-test details.
Alternatives
Use instead of pytest-json-report: tools that do the same job, closest first.