Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

测试

Postman 模拟产品数据断言阅读 | Elysia Tools

用明确输入与可独立核对的结果,完成三个范围有限的 Postman 练习。

案例

这个案例集合中的条目

代码json简单

Postman 基础 Collection 设置

完整的 Postman collection 设置,包括环境变量、身份验证和基础 API 测试模式

难度

3/10

预计时间

25 min

标签

postman, api testing, collections, automation

前置条件

REST API concepts, HTTP methods, JSON format

json
{
  "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": "{\n  \"email\": \"{{admin_email}}\",\n  \"password\": \"{{admin_password}}\"\n}"
            },
            "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": "{\n  \"username\": \"{{$randomUserName}}\",\n  \"email\": \"{{$randomEmail}}\",\n  \"password\": \"{{$randomPassword}}\",\n  \"firstName\": \"{{$randomFirstName}}\",\n  \"lastName\": \"{{$randomLastName}}\"\n}"
            },
            "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": "{\n  \"name\": \"Test Product {{$randomInt}}\",\n  \"description\": \"This is a test product created via API\",\n  \"price\": {{$randomPrice}},\n  \"category\": \"electronics\",\n  \"stock\": {{$randomStock}}\n}"
            },
            "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": "{\n  \"items\": [\n    {\n      \"productId\": \"{{product_id}}\",\n      \"quantity\": 2,\n      \"price\": 29.99\n    }\n  ],\n  \"shippingAddress\": {\n    \"street\": \"123 Test Street\",\n    \"city\": \"Test City\",\n    \"state\": \"TS\",\n    \"zipCode\": \"12345\",\n    \"country\": \"US\"\n  }\n}"
            },
            "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}}"
    }
  ]
}
代码json复杂

Postman 高级自动化和测试

高级 Postman 功能,包括数据驱动测试、mock 服务器、监控器和 CI/CD 集成

难度

8/10

预计时间

50 min

标签

postman, automation, performance, security, data-driven

前置条件

Postman basics, JavaScript, API testing concepts, CI/CD concepts

json
{
  "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": "{\n  \"username\": \"{{current_username}}\",\n  \"email\": \"{{current_email}}\",\n  \"password\": \"{{current_password}}\",\n  \"firstName\": \"Test\",\n  \"lastName\": \"User\"\n}"
            },
            "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": "{\n  \"email\": \"'; DROP TABLE users; --\",\n  \"password\": \"password123\"\n}"
            },
            "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": "{\n  \"name\": \"Test Product <script>alert('XSS')</script>\",\n  \"description\": \"<img src=\\\"x\\\" onerror=\\\"alert('XSS')\\\">\",\n  \"price\": 29.99\n}"
            },
            "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
*/

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

工具使用指南

帮助搜索与理解工作流的案例说明

概览

以下练习使用「Postman 基础 Collection 设置」,只追踪指定代码块;其他卡片涉及不同语言功能和依赖。

选择最小示例

只检查虚构对象与耗时上的三个断言谓词。不导入或发送 collection;其他脚本会认证、修改变量并创建数据。

使用方式

  1. 1阅读指定卡片,追踪声明的值。样本页面展示代码,不会替你执行这种语言。

常见失败与 edge cases

  • 结果范围

    下面是从源码推导的预期结果,不是编译器或运行时实测输出。交互输入、时钟、文件、线程、外部服务和框架配置不在这些练习范围内。

示例

1. 追踪 Products have required fields

如何使用

在「Postman 基础 Collection 设置」找到 Products have required fields,使用 synthetic [{id:1,name:"Demo",price:2,description:"Toy"}]; [],只依次追踪指定操作,不改变顺序。

结果

预期:four properties present; empty array skips per-item checks。属性存在不等于类型正确;空数组会跳过逐产品循环。

2. 追踪 Product details: price assertions

如何使用

在「Postman 基础 Collection 设置」找到 Product details: price assertions,使用 synthetic price=-1;0;2,只依次追踪指定操作,不改变顺序。

结果

预期:false;false;true。两个断言要求类型为数字且严格大于零,零不通过。

3. 追踪 Response time assertion

如何使用

在「Postman 基础 Collection 设置」找到 Response time assertion,使用 synthetic responseTime=2999;3000,只依次追踪指定操作,不改变顺序。

结果

预期:below(3000)=true;false。below 是严格比较,等于 3000 不满足断言;耗时均为虚构数据。

专题

API 契约定义、Schema 校验与变更测试

定义 API 契约,校验 Schema 和已捕获载荷,识别兼容性风险,并记录测试验收结果。

专题

OpenAPI 实用工作流

从 OpenAPI 生成类型与文档,审查破坏性变更,校验响应,并用压力与变异测试加固契约。

专题

JSON Schema 与 API 契约校验工具

在一个专题中比较 JSON Schema 校验、OpenAPI 响应检查、变异测试、压力测试和破坏性变更检测工具,适合 API 契约审查流程。

专题

cURL 请求转换与 HTTP 测试工作流

将 cURL 请求转换为代码片段或 HAR,安全测试请求,并结合响应上下文解释 HTTP 状态码,同时保留请求头、请求体和认证注意事项。

首页
工具3216
案例593
可视化473
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web194

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

API Mock Server / 请求模拟器

根据接口描述生成可运行的临时 Mock Server,使用 Redis 存储 1 小时并支持动态响应

Format Conversion

XLSX API 写入 Sheet

将 REST/GraphQL 返回的 JSON 自动分页并映射写入 Excel Sheet

Development

API 延迟预算规划器

规划并可视化 API 延迟预算。输入 P99 目标(如 ≤ 300ms)和各阶段分配(DNS、TCP、TLS、TTFB、Processing、Network),查看实时瀑布图、预算占用和超标告警。可选粘贴 OpenTelemetry 或 Datadog trace,反推基于真实测量的分配建议。

Development

API 请求代码片段生成器

根据请求链接、方法、请求头、Query 参数和请求体生成 cURL 及常见开发语言的代码片段

Development

API 响应契约校验器

将真实 API 响应 JSON 与 OpenAPI 3.x 中声明的 response schema 对照校验

Development

API 响应差异与语义分析器

对比两个 API 响应 JSON,标出字段级差异,并区分真正的功能变更与无害的运行时漂移

Development

OpenAPI 转 Postman Collection

把 OpenAPI 3.x 或 Swagger 2.0 规范(JSON/YAML)转成可直接导入的 Postman Collection v2.1.0,含文件夹、变量、认证与示例响应。

Development

JSON 差异可视化

比较两个 JSON 并生成带颜色、路径和统计信息的可视化差异报告

DevOps

ELK Stack 日志分析示例

全面的 ELK Stack(Elasticsearch、Logstash、Kibana)示例,用于分布式系统中的日志聚合、处理和可视化

开发

Terraform Plan JSON 样本

用于依赖可视化和变更审查的 Terraform plan JSON 文件样本,贴近 terraform show -json 输出结构

可观测性

分布式追踪示例

使用 Jaeger、OpenTelemetry 和其他现代可观测性工具的综合分布式追踪示例,适用于微服务架构

云服务

AWS EventBridge 示例

AWS EventBridge 示例,包括事件总线、规则、目标、模式注册表、自定义事件和跨账户事件路由,适用于无服务器事件驱动架构

安全

JWT 示例

从基础令牌结构到高级安全实现的全面JWT示例

文档文件

PDF示例

2026-02-01 到 2026-02-10 工具生成的PDF示例