Run Postman collection using Newman in CI/CD pipeline
Preconditions (3)
✅ Expected Result: Newman runs the Postman collection successfully, all tests pass, and the pipeline logs show a summary of the test results
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.
Now add data-driven testing by running the same Postman collection with three different environment files in the CI/CD pipeline.
newman run mycollection.json --reporters cli,json --reporter-json-export result.json
newman run collection.json --reporters cli --reporter-json-export report.json
Pass the test and this pattern moves unknown