🎯 Exemplos recomendados
Balanced sample collections from various categories for you to explore
Coleções Postman - Testes de API
Exemplos abrangentes de coleções Postman incluindo testes de API, scripts de automação, variáveis de ambiente, servidores mock e padrões avançados de teste para REST APIs
💻 Configuração Básica de Coleção Postman json
🟢 simple
⭐⭐
Configuração completa de coleção Postman com variáveis de ambiente, autenticação e padrões básicos de teste de API
⏱️ 25 min
🏷️ postman, api testing, collections, automation
Prerequisites:
REST API concepts, HTTP methods, JSON format
{
"info": {
"name": "E-Commerce API",
"description": "A comprehensive collection for testing e-commerce REST API endpoints",
"version": "1.0.0",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Authentication",
"item": [
{
"name": "User Login",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Test response status and structure",
"pm.test('Status code is 200', function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test('Response has token', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('token');",
" pm.expect(jsonData).to.have.property('user');",
"});",
"",
"// Set environment variables for authentication",
"if (pm.response.code === 200) {",
" const jsonData = pm.response.json();",
" pm.environment.set('auth_token', jsonData.token);",
" pm.environment.set('user_id', jsonData.user.id);",
" pm.environment.set('user_email', jsonData.user.email);",
" ",
" // Set token expiration (assuming 24 hours)",
" const expiresAt = Date.now() + (24 * 60 * 60 * 1000);",
" pm.environment.set('token_expires_at', expiresAt.toString());",
"}",
"",
"// Log successful authentication",
"console.log('User authenticated successfully:', pm.environment.get('user_email'));"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{
"email": "{{admin_email}}",
"password": "{{admin_password}}"
}"
},
"url": {
"raw": "{{base_url}}/api/auth/login",
"host": ["{{base_url}}"],
"path": ["api", "auth", "login"]
}
}
},
{
"name": "User Registration",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 201', function () {",
" pm.response.to.have.status(201);",
"});",
"",
"pm.test('Response has user data', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('user');",
" pm.expect(jsonData.user).to.have.property('id');",
" pm.expect(jsonData.user).to.have.property('email');",
" pm.expect(jsonData.user.email).to.eql(pm.request.body.raw);",
"});",
"",
"pm.test('Password is not returned in response', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.user).to.not.have.property('password');",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{
"username": "{{$randomUserName}}",
"email": "{{$randomEmail}}",
"password": "{{$randomPassword}}",
"firstName": "{{$randomFirstName}}",
"lastName": "{{$randomLastName}}"
}"
},
"url": {
"raw": "{{base_url}}/api/auth/register",
"host": ["{{base_url}}"],
"path": ["api", "auth", "register"]
}
}
},
{
"name": "Refresh Token",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"// Check if token is expired",
"const expiresAt = pm.environment.get('token_expires_at');",
"if (expiresAt && Date.now() > parseInt(expiresAt)) {",
" console.log('Token expired, skipping refresh request');",
" // Skip this request if token is expired",
" postman.setNextRequest(null);",
"} else {",
" console.log('Token valid, proceeding with refresh');",
"}"
],
"type": "text/javascript"
}
},
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 200', function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test('New token received', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('token');",
" ",
" // Update environment with new token",
" if (jsonData.token) {",
" pm.environment.set('auth_token', jsonData.token);",
" const expiresAt = Date.now() + (24 * 60 * 60 * 1000);",
" pm.environment.set('token_expires_at', expiresAt.toString());",
" }",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Authorization",
"value": "Bearer {{auth_token}}"
}
],
"url": {
"raw": "{{base_url}}/api/auth/refresh",
"host": ["{{base_url}}"],
"path": ["api", "auth", "refresh"]
}
}
}
]
},
{
"name": "Products",
"item": [
{
"name": "Get All Products",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 200', function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test('Response is an array', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.be.an('array');",
"});",
"",
"pm.test('Products have required fields', function () {",
" const jsonData = pm.response.json();",
" if (jsonData.length > 0) {",
" jsonData.forEach(product => {",
" pm.expect(product).to.have.property('id');",
" pm.expect(product).to.have.property('name');",
" pm.expect(product).to.have.property('price');",
" pm.expect(product).to.have.property('description');",
" });",
" }",
"});",
"",
"// Store first product ID for later use",
"if (pm.response.code === 200) {",
" const jsonData = pm.response.json();",
" if (jsonData.length > 0) {",
" pm.environment.set('product_id', jsonData[0].id);",
" }",
"}"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"url": {
"raw": "{{base_url}}/api/products?page={{page}}&limit={{limit}}&category={{category}}",
"host": ["{{base_url}}"],
"path": ["api", "products"],
"query": [
{
"key": "page",
"value": "{{page}}",
"description": "Page number for pagination"
},
{
"key": "limit",
"value": "{{limit}}",
"description": "Number of items per page"
},
{
"key": "category",
"value": "{{category}}",
"description": "Filter by category",
"disabled": true
}
]
}
}
},
{
"name": "Get Product by ID",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 200', function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test('Product has required fields', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.expect(jsonData).to.have.property('name');",
" pm.expect(jsonData).to.have.property('price');",
" pm.expect(jsonData).to.have.property('description');",
" pm.expect(jsonData).to.have.property('category');",
" pm.expect(jsonData).to.have.property('stock');",
"});",
"",
"pm.test('Price is a positive number', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.price).to.be.a('number');",
" pm.expect(jsonData.price).to.be.above(0);",
"});",
"",
"pm.test('Stock is a non-negative integer', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.stock).to.be.a('number');",
" pm.expect(jsonData.stock).to.be.at.least(0);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"url": {
"raw": "{{base_url}}/api/products/{{product_id}}",
"host": ["{{base_url}}"],
"path": ["api", "products", "{{product_id}}"]
}
}
},
{
"name": "Create Product",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 201', function () {",
" pm.response.to.have.status(201);",
"});",
"",
"pm.test('Product created successfully', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.expect(jsonData).to.have.property('name');",
" pm.expect(jsonData.name).to.eql(JSON.parse(pm.request.body.raw).name);",
"});",
"",
"// Store new product ID",
"if (pm.response.code === 201) {",
" const jsonData = pm.response.json();",
" pm.environment.set('new_product_id', jsonData.id);",
"}"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "Authorization",
"value": "Bearer {{auth_token}}"
}
],
"body": {
"mode": "raw",
"raw": "{
"name": "Test Product {{$randomInt}}",
"description": "This is a test product created via API",
"price": {{$randomPrice}},
"category": "electronics",
"stock": {{$randomStock}}
}"
},
"url": {
"raw": "{{base_url}}/api/products",
"host": ["{{base_url}}"],
"path": ["api", "products"]
}
}
}
]
},
{
"name": "Orders",
"item": [
{
"name": "Create Order",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 201', function () {",
" pm.response.to.have.status(201);",
"});",
"",
"pm.test('Order created with required fields', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('id');",
" pm.expect(jsonData).to.have.property('userId');",
" pm.expect(jsonData).to.have.property('items');",
" pm.expect(jsonData).to.have.property('totalAmount');",
" pm.expect(jsonData).to.have.property('status');",
"});",
"",
"pm.test('Order status is pending', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.status).to.eql('pending');",
"});",
"",
"// Store order ID for later use",
"if (pm.response.code === 201) {",
" const jsonData = pm.response.json();",
" pm.environment.set('order_id', jsonData.id);",
"}"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
},
{
"key": "Authorization",
"value": "Bearer {{auth_token}}"
}
],
"body": {
"mode": "raw",
"raw": "{
"items": [
{
"productId": "{{product_id}}",
"quantity": 2,
"price": 29.99
}
],
"shippingAddress": {
"street": "123 Test Street",
"city": "Test City",
"state": "TS",
"zipCode": "12345",
"country": "US"
}
}"
},
"url": {
"raw": "{{base_url}}/api/orders",
"host": ["{{base_url}}"],
"path": ["api", "orders"]
}
}
},
{
"name": "Get Order by ID",
"event": [
{
"listen": "test",
"script": {
"exec": [
"pm.test('Status code is 200', function () {",
" pm.response.to.have.status(200);",
"});",
"",
"pm.test('Order belongs to authenticated user', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.userId).to.eql(pm.environment.get('user_id'));",
"});",
"",
"pm.test('Order has items array', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData.items).to.be.an('array');",
" pm.expect(jsonData.items.length).to.be.above(0);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "Authorization",
"value": "Bearer {{auth_token}}"
}
],
"url": {
"raw": "{{base_url}}/api/orders/{{order_id}}",
"host": ["{{base_url}}"],
"path": ["api", "orders", "{{order_id}}"]
}
}
}
]
}
],
"event": [
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"// Global pre-request script",
"// Check if authentication token is valid",
"const token = pm.environment.get('auth_token');",
"const expiresAt = pm.environment.get('token_expires_at');",
"",
"// Auto-refresh token if needed",
"if (token && expiresAt && Date.now() > parseInt(expiresAt)) {",
" console.log('Token expired, attempting refresh');",
" // This would trigger the refresh token request",
"}",
"",
"// Set random values for dynamic data",
"pm.environment.set('randomInt', Math.floor(Math.random() * 1000));",
"pm.environment.set('randomPrice', (Math.random() * 100 + 10).toFixed(2));",
"pm.environment.set('randomStock', Math.floor(Math.random() * 100) + 1);"
]
}
},
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"// Global test script",
"// Log response details for debugging",
"console.log('Response Status:', pm.response.code);",
"console.log('Response Time:', pm.response.responseTime);",
"",
"// Check if response time is acceptable",
"pm.test('Response time is less than 3000ms', function () {",
" pm.expect(pm.response.responseTime).to.be.below(3000);",
"});",
"",
"// Check content-type header",
"pm.test('Response has Content-Type header', function () {",
" pm.expect(pm.response.headers.get('Content-Type')).to.include('application/json');",
"});"
]
}
}
],
"variable": [
{
"key": "randomUserName",
"value": "{{$randomUserName}}"
},
{
"key": "randomEmail",
"value": "{{$randomEmail}}"
},
{
"key": "randomPassword",
"value": "{{$randomPassword}}"
},
{
"key": "randomFirstName",
"value": "{{$randomFirstName}}"
},
{
"key": "randomLastName",
"value": "{{$randomLastName}}"
}
]
}
💻 Automação Avançada e Testes Postman json
🔴 complex
⭐⭐⭐⭐
Recursos avançados do Postman incluindo testes orientados a dados, servidores mock, monitores e integração CI/CD
⏱️ 50 min
🏷️ postman, automation, performance, security, data-driven
Prerequisites:
Postman basics, JavaScript, API testing concepts, CI/CD concepts
{
"info": {
"name": "Advanced API Testing Suite",
"description": "Advanced collection with data-driven testing, performance monitoring, and automation features",
"version": "2.0.0",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Data-Driven Tests",
"item": [
{
"name": "User Registration Data-Driven",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"// Load test data from CSV or environment",
"const testData = pm.collectionVariables.get('test_data') || [",
" {username: 'testuser1', email: '[email protected]', password: 'password123', expectedStatus: 201},",
" {username: 'testuser2', email: '[email protected]', password: 'password456', expectedStatus: 201},",
" {username: '', email: '[email protected]', password: 'password789', expectedStatus: 400},",
" {username: 'testuser3', email: 'invalid-email', password: 'password012', expectedStatus: 400}",
"];",
"",
"// Get current iteration data",
"const currentIndex = parseInt(pm.environment.get('data_iteration') || '0');",
"const currentData = testData[currentIndex % testData.length];",
"",
"// Set request body with current data",
"pm.environment.set('current_username', currentData.username);",
"pm.environment.set('current_email', currentData.email);",
"pm.environment.set('current_password', currentData.password);",
"pm.environment.set('expected_status', currentData.expectedStatus);",
"",
"// Increment iteration for next run",
"pm.environment.set('data_iteration', (currentIndex + 1).toString());"
],
"type": "text/javascript"
}
},
{
"listen": "test",
"script": {
"exec": [
"const expectedStatus = parseInt(pm.environment.get('expected_status'));",
"",
"pm.test('Status code is ' + expectedStatus, function () {",
" pm.response.to.have.status(expectedStatus);",
"});",
"",
"// Additional tests based on expected status",
"if (expectedStatus === 201) {",
" pm.test('User created successfully', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('user');",
" pm.expect(jsonData.user.email).to.eql(pm.environment.get('current_email'));",
" });",
"} else if (expectedStatus === 400) {",
" pm.test('Validation error returned', function () {",
" const jsonData = pm.response.json();",
" pm.expect(jsonData).to.have.property('error');",
" });",
"}"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{
"username": "{{current_username}}",
"email": "{{current_email}}",
"password": "{{current_password}}",
"firstName": "Test",
"lastName": "User"
}"
},
"url": {
"raw": "{{base_url}}/api/auth/register",
"host": ["{{base_url}}"],
"path": ["api", "auth", "register"]
}
}
}
]
},
{
"name": "Performance Tests",
"item": [
{
"name": "Load Test - Product Search",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Performance assertions",
"pm.test('Response time is under 1000ms', function () {",
" pm.expect(pm.response.responseTime).to.be.below(1000);",
"});",
"",
"pm.test('Response size is reasonable', function () {",
" const responseSize = pm.response.responseSize;",
" pm.expect(responseSize).to.be.below(1024 * 1024); // Less than 1MB",
"});",
"",
"// Log performance metrics",
"console.log('Performance Metrics:');",
"console.log('- Response Time:', pm.response.responseTime + 'ms');",
"console.log('- Response Size:', pm.response.responseSize + ' bytes');",
"console.log('- Headers Size:', pm.response.headers.length + ' headers');",
"",
"// Store performance data for analysis",
"const performanceData = {",
" timestamp: new Date().toISOString(),",
" responseTime: pm.response.responseTime,",
" responseSize: pm.response.responseSize,",
" statusCode: pm.response.code,",
" endpoint: '/api/products/search'",
" userAgent: pm.request.headers.get('User-Agent')",
"};",
"",
"// Send to monitoring service (pseudo-code)",
"// pm.sendRequest({",
"// url: 'https://monitoring.example.com/api/metrics',",
"// method: 'POST',",
"// header: {",
"// 'Content-Type': 'application/json'",
"// },",
"// body: JSON.stringify(performanceData)",
"// });"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/api/products/search?q={{search_term}}&limit={{search_limit}}",
"host": ["{{base_url}}"],
"path": ["api", "products", "search"],
"query": [
{
"key": "q",
"value": "{{search_term}}",
"description": "Search query"
},
{
"key": "limit",
"value": "{{search_limit}}",
"description": "Number of results"
}
]
}
}
},
{
"name": "Stress Test - Concurrent Requests",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"// Simulate concurrent requests",
"const concurrentRequests = parseInt(pm.environment.get('concurrent_requests') || '5');",
"const requestDelay = Math.random() * 100; // Random delay up to 100ms",
"",
"console.log('Simulating concurrent request #' + (parseInt(pm.environment.get('request_count') || '0') + 1));",
"",
"// Add artificial delay to simulate real-world conditions",
"setTimeout(function() {",
" pm.environment.set('request_count', (parseInt(pm.environment.get('request_count') || '0') + 1).toString());",
"}, requestDelay);"
],
"type": "text/javascript"
}
},
{
"listen": "test",
"script": {
"exec": [
"// Stress test assertions",
"pm.test('Server responds under load', function () {",
" // Allow 500 status under load",
" pm.expect([200, 500]).to.include(pm.response.code);",
"});",
"",
"pm.test('Response time is acceptable under load', function () {",
" // More lenient timeout under load",
" pm.expect(pm.response.responseTime).to.be.below(5000);",
"});",
"",
"// Track request counts",
"const totalRequests = parseInt(pm.environment.get('total_requests') || '0') + 1;",
"pm.environment.set('total_requests', totalRequests.toString());",
"",
"const successCount = parseInt(pm.environment.get('success_count') || '0');",
"if (pm.response.code === 200) {",
" pm.environment.set('success_count', (successCount + 1).toString());",
"}",
"",
"console.log('Total requests:', totalRequests);",
"console.log('Success rate:', (successCount / totalRequests * 100).toFixed(2) + '%');"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"url": {
"raw": "{{base_url}}/api/health",
"host": ["{{base_url}}"],
"path": ["api", "health"]
}
}
}
]
},
{
"name": "Security Tests",
"item": [
{
"name": "SQL Injection Test",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Security test for SQL injection",
"const maliciousPayloads = [",
" "'; DROP TABLE users; --",",
" "' OR '1'='1",",
" "'; INSERT INTO users (email) VALUES ('[email protected]'); --"",
"];",
"",
"pm.test('Server rejects SQL injection attempts', function () {",
" // Should not return 200 for malicious payloads",
" pm.expect(pm.response.code).to.not.eql(200);",
"});",
"",
"pm.test('No database error messages exposed', function () {",
" const responseText = pm.response.text();",
" const errorPatterns = [/SQL/i, /mysql/i, /database/i, /syntax error/i];",
" ",
" errorPatterns.forEach(pattern => {",
" pm.expect(responseText).to.not.match(pattern);",
" });",
"});",
"",
"pm.test('Response time is consistent', function () {",
" // SQL injection should be rejected quickly",
" pm.expect(pm.response.responseTime).to.be.below(1000);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{
"email": "'; DROP TABLE users; --",
"password": "password123"
}"
},
"url": {
"raw": "{{base_url}}/api/auth/login",
"host": ["{{base_url}}"],
"path": ["api", "auth", "login"]
}
}
},
{
"name": "XSS Protection Test",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// XSS protection test",
"const xssPayloads = [",
" '<script>alert("XSS")</script>',",
" 'javascript:alert("XSS")',",
" '<img src="x" onerror="alert(\"XSS\")">',",
" '"><script>alert("XSS")</script>'",
"];",
"",
"pm.test('Server sanitizes XSS attempts', function () {",
" const responseText = pm.response.text();",
" ",
" // Check that script tags are removed or escaped",
" pm.expect(responseText).to.not.include('<script>');",
" pm.expect(responseText).to.not.include('javascript:');",
" pm.expect(responseText).to.not.include('onerror=');",
"});",
"",
"pm.test('Response is safe for display', function () {",
" const responseText = pm.response.text();",
" ",
" // No unescaped HTML or JavaScript",
" const dangerousPatterns = [",
" /<script/i,",
" /javascript:/i,",
" /on\w+=/i",
" ];",
" ",
" dangerousPatterns.forEach(pattern => {",
" pm.expect(responseText).to.not.match(pattern);",
" });",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{
"name": "Test Product <script>alert('XSS')</script>",
"description": "<img src=\"x\" onerror=\"alert('XSS')\">",
"price": 29.99
}"
},
"url": {
"raw": "{{base_url}}/api/products",
"host": ["{{base_url}}"],
"path": ["api", "products"]
}
}
}
]
},
{
"name": "API Documentation Tests",
"item": [
{
"name": "OpenAPI Schema Validation",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate response against OpenAPI schema",
"const validateAgainstSchema = function(response, schemaName) {",
" try {",
" const responseJson = response.json();",
" // This would integrate with OpenAPI validation library",
" // For now, we'll do basic structural validation",
" ",
" const schemas = {",
" 'User': ['id', 'username', 'email'],",
" 'Product': ['id', 'name', 'price', 'description'],",
" 'Order': ['id', 'userId', 'items', 'totalAmount', 'status']",
" };",
" ",
" const requiredFields = schemas[schemaName] || [];",
" ",
" requiredFields.forEach(field => {",
" pm.expect(responseJson).to.have.property(field);",
" });",
" ",
" return true;",
" } catch (error) {",
" console.log('Schema validation error:', error.message);",
" return false;",
" }",
"};",
"",
"pm.test('Response matches OpenAPI schema', function () {",
" const endpoint = pm.info.requestName;",
" let schemaName = 'Unknown';",
" ",
" if (endpoint.includes('User')) schemaName = 'User';",
" else if (endpoint.includes('Product')) schemaName = 'Product';",
" else if (endpoint.includes('Order')) schemaName = 'Order';",
" ",
" const isValid = validateAgainstSchema(pm.response, schemaName);",
" pm.expect(isValid).to.be.true;",
"});",
"",
"// Test response headers for API compliance",
"pm.test('API compliance headers present', function () {",
" pm.expect(pm.response.headers.get('X-API-Version')).to.exist;",
" pm.expect(pm.response.headers.get('X-Rate-Limit-Remaining')).to.exist;",
" pm.expect(pm.response.headers.get('Cache-Control')).to.exist;",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [
{
"key": "Accept",
"value": "application/json"
}
],
"url": {
"raw": "{{base_url}}/api/products/{{product_id}}",
"host": ["{{base_url}}"],
"path": ["api", "products", "{{product_id}}"]
}
}
}
]
}
],
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"// Global advanced pre-request script",
"// Load environment-specific configurations",
"const environment = pm.environment.get('env_type') || 'development';",
"const configs = {",
" development: {",
" timeout: 5000,",
" retries: 1,",
" strict_ssl: false",
" },",
" staging: {",
" timeout: 3000,",
" retries: 2,",
" strict_ssl: true",
" },",
" production: {",
" timeout: 2000,",
" retries: 3,",
" strict_ssl: true",
" }",
"};",
"",
"const config = configs[environment];",
"pm.environment.set('request_timeout', config.timeout.toString());",
"pm.environment.set('max_retries', config.retries.toString());",
"",
"// Advanced error tracking",
"pm.environment.set('request_start_time', Date.now().toString());",
"pm.environment.set('request_uuid', pm.variables.replaceIn('{{$randomUUID}}'));"
],
"type": "text/javascript"
}
},
{
"listen": "test",
"script": {
"exec": [
"// Global advanced test script",
"// Comprehensive logging and monitoring",
"const requestStartTime = parseInt(pm.environment.get('request_start_time') || Date.now());",
"const requestUuid = pm.environment.get('request_uuid');",
"const responseTime = Date.now() - requestStartTime;",
"",
"// Advanced logging with correlation ID",
"console.log('=== Request Details ===');",
"console.log('Request ID:', requestUuid);",
"console.log('Method:', pm.info.requestMethod);",
"console.log('URL:', pm.info.requestName);",
"console.log('Status Code:', pm.response.code);",
"console.log('Response Time:', responseTime + 'ms');",
"console.log('Response Size:', pm.response.responseSize + ' bytes');",
"console.log('Environment:', pm.environment.get('env_type'));",
"console.log('========================');",
"",
"// Performance thresholds based on environment",
"const envType = pm.environment.get('env_type') || 'development';",
"const thresholds = {",
" development: 5000,",
" staging: 3000,",
" production: 2000",
"};",
"",
"const threshold = thresholds[envType];",
"",
"pm.test('Response time meets SLA (' + threshold + 'ms)', function () {",
" pm.expect(responseTime).to.be.below(threshold);",
"});",
"",
"// Advanced response validation",
"pm.test('Response structure is valid JSON', function () {",
" try {",
" const responseJson = pm.response.json();",
" pm.expect(responseJson).to.be.an('object');",
" } catch (e) {",
" // If response is not JSON, that's okay for some endpoints",
" if (pm.response.headers.get('Content-Type')?.includes('application/json')) {",
" throw e;",
" }",
" }",
"});",
"",
"// Error handling and alerting",
"if (pm.response.code >= 500) {",
" console.error('SERVER ERROR DETECTED!');",
" console.error('Request ID:', requestUuid);",
" console.error('Response:', pm.response.text());",
" ",
" // Send alert to monitoring system (pseudo-code)",
" // sendAlert({",
" // level: 'error',",
" // message: 'Server error in API call',",
" // requestId: requestUuid,",
" // endpoint: pm.info.requestName,",
" // statusCode: pm.response.code",
" // });",
"}",
"",
"// Track test execution metrics",
"const testMetrics = {",
" timestamp: new Date().toISOString(),",
" requestId: requestUuid,",
" endpoint: pm.info.requestName,",
" method: pm.info.requestMethod,",
" statusCode: pm.response.code,",
" responseTime: responseTime,",
" responseSize: pm.response.responseSize,",
" environment: envType",
"};",
"",
"// Store metrics for analysis",
"const metricsArray = JSON.parse(pm.environment.get('test_metrics') || '[]');",
"metricsArray.push(testMetrics);",
"",
"// Keep only last 100 metrics to avoid memory issues",
"if (metricsArray.length > 100) {",
" metricsArray.splice(0, metricsArray.length - 100);",
"}",
"",
"pm.environment.set('test_metrics', JSON.stringify(metricsArray));"
],
"type": "text/javascript"
}
}
],
"variable": [
{
"key": "data_iteration",
"value": "0"
},
{
"key": "concurrent_requests",
"value": "5"
},
{
"key": "request_count",
"value": "0"
},
{
"key": "total_requests",
"value": "0"
},
{
"key": "success_count",
"value": "0"
},
{
"key": "test_metrics",
"value": "[]"
}
]
}
// Environment Configuration Examples:
// Development Environment:
/*
{
"name": "Development",
"values": [
{
"key": "base_url",
"value": "http://localhost:3000",
"enabled": true
},
{
"key": "admin_email",
"value": "[email protected]",
"enabled": true
},
{
"key": "admin_password",
"value": "password123",
"enabled": true
},
{
"key": "page",
"value": "1",
"enabled": true
},
{
"key": "limit",
"value": "10",
"enabled": true
},
{
"key": "search_term",
"value": "laptop",
"enabled": true
},
{
"key": "search_limit",
"value": "20",
"enabled": true
},
{
"key": "env_type",
"value": "development",
"enabled": true
}
]
}
*/
// Newman Command Line Usage:
/*
// Run collection with environment
newman run collection.json -e environment.json
// Run with data file for data-driven testing
newman run collection.json -d test_data.csv
// Generate reports
newman run collection.json -r html,cli,json
// Run specific folders
newman run collection.json --folder "Authentication"
// Run with iteration count
newman run collection.json -n 5
// Run with timeout
newman run collection.json --timeout-request 10000
// Ignore redirects
newman run collection.json --ignore-redirects
// Run with global variables
newman run collection.json --global-var "base_url=https://api.example.com"
*/
// CSV Example for Data-Driven Testing:
/*
username,email,password,expectedStatus
testuser1,[email protected],password123,201
testuser2,[email protected],password456,201
invalid,[email protected],password789,400
,[email protected],password012,400
*/