import subprocess
import json
# Paths to collection and environment files
collection_file = 'postman_collection.json'
environment_file = 'postman_environment.json'
# Run Newman command with JSON reporter
command = [
'newman', 'run', collection_file,
'-e', environment_file,
'--reporters', 'cli,json',
'--reporter-json-export', 'newman_report.json'
]
result = subprocess.run(command, capture_output=True, text=True)
# Check exit code
assert result.returncode == 0, f"Newman run failed with exit code {result.returncode}"
# Load JSON report
with open('newman_report.json') as f:
report = json.load(f)
# Check all tests passed
assert report['run']['stats']['failed'] == 0, "Some tests failed in Newman run"
print("Newman run successful: all tests passed.")This script runs the Newman CLI command using Python's subprocess module. It specifies the collection and environment files, and requests both CLI and JSON reports.
After running, it checks the exit code to confirm the run was successful.
Then it loads the JSON report file and asserts that zero tests failed.
This ensures the CI/CD pipeline can detect failures and pass/fail accordingly.