- Валидация статус-кода
- Валидация времени ответа
- Валидация тела ответа
- Валидация JSON-ответа
- Валидация заголовка
- Чейнинг тестов
- Валидация динамических данных
- Данные в переменной окружения
- Валидация Schema-ответа
- Валидация динамического ответа
- Валидация версии API
- Валидация передачи файла
- Аутентификация и авторизация
- Извлечение и обработка данных
- Сессии
- Пагинация
- Нагрузочное
- Валидация БД
В Postman скрипты пишутся на JavaScript во вкладке «Тесты» после отправки API-запроса. Каждый скрипт ниже — связан с определенным API-запросом и выполняется автоматически после отправки этого запроса. Скрипт имеет доступ к данным ответа и запроса и различным функциям Postman.
Базовая структура скрипта выглядит следующим образом:
// Test script pm.test("Test Description", function () { // Assertion logic goes here });
Валидация статус-кода
// Test if the response status code is 200 (OK) pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
Валидация времени ответа
// Test if the response time is less than 500ms pm.test("Response time is within acceptable range", function () { pm.expect(pm.response.responseTime).to.be.below(500); });
Валидация тела ответа
// Test if the response body contains a specific value pm.test("Response body contains expected data", function () { pm.expect(pm.response.text()).to.include("expected_value"); });
Валидация JSON-ответа
// Test if the response is a valid JSON pm.test("Response is valid JSON", function () { pm.expect(pm.response.json()).to.be.an("object"); });
Валидация заголовка
// Test if a specific header is present in the response pm.test("Header is present in the response", function () { pm.response.to.have.header("header_name"); });
Чейнинг тестов
// Chaining multiple test assertions pm.test("Chaining multiple assertions", function () { pm.expect(pm.response.json().property1).to.eql("value1"); pm.expect(pm.response.json().property2).to.eql("value2"); });
Валидация динамических данных
// Test if a specific value in the response matches the environment variable pm.test("Dynamic data validation", function () { pm.expect(pm.response.json().user_id).to.eql(pm.environment.get("user_id")); });
Данные в переменной окружения
var jsonData = pm.response.json(); pm.environment.set("companyIdToDelete", jsonData.data._id);
Валидация Schema-ответа
// Test if the response adheres to a specific JSON schema pm.test("Response schema validation", function () { const schema = { "type": "object", "properties": { "property1": { "type": "string" }, "property2": { "type": "number" } } }; pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true; });
Валидация динамического ответа
// Validate dynamic data in the response by extracting values from the response and using them in assertions. // Extract a value from the response and use it in an assertion pm.test("Dynamic response validation", function () { var responseBody = pm.response.json(); var dynamicValue = responseBody.dynamic_property; pm.expect(dynamicValue).to.equal(pm.variables.get("expected_dynamic_value")); });
Валидация версии API
// Test different API versions var apiVersion = "v2"; pm.test("API versioning validation", function () { pm.request.headers.add({ key: "Accept-Version", value: apiVersion }); pm.sendRequest(function (response) { pm.expect(response.status).to.equal(200); pm.expect(response.json().version).to.equal(apiVersion); }); });
Валидация передачи файла
// Test file upload pm.test("File upload validation", function () { var formData = { file: { value: pm.globals.get("fileData"), options: { filename: "sample.txt", contentType: "text/plain" } } }; pm.sendRequest({ url: "https://api.example.com/upload", method: "POST", body: formData }, function (response) { pm.expect(response.status).to.equal(200); pm.expect(response.json().success).to.be.true; }); });
Аутентификация и авторизация
// Test authentication and authorization pm.test("Authentication and authorization", function () { var authToken = pm.environment.get("authToken"); pm.request.headers.add({ key: "Authorization", value: "Bearer " + authToken }); pm.sendRequest(function (response) { pm.expect(response.status).to.equal(200); pm.expect(response.json().authorized).to.be.true; }); });
Извлечение и обработка данных
// Extract and transform data from the response pm.test("Data extraction and transformation", function () { var responseArray = pm.response.json().data; var transformedData = responseArray.map(function (item) { return { id: item.id, name: item.first_name + " " + item.last_name" }; }); // Use transformed data for assertions or environment variables pm.expect(transformedData[0].name).to.include("John"); pm.environment.set("transformedData", JSON.stringify(transformedData)); });
Управление сессиями
//Simulate session management by saving and reusing session tokens. // Session management using session tokens var sessionToken; pm.test("Login and session management", function () { // Perform login and extract session token from the response sessionToken = pm.response.json().session_token; pm.environment.set("sessionToken", sessionToken); }); pm.test("Authenticated request using session token", function () { // Use the saved session token for authenticated requests pm.request.headers.add({ key: "Authorization", value: "Bearer " + sessionToken }); pm.sendRequest(function (response) { pm.expect(response.status).to.equal(200); }); });
Пагинация
// Test APIs that return paginated results and validate pagination logic. // Pagination testing pm.test("Pagination testing", function () { var response = pm.response.json(); var currentPage = response.page; var totalPages = response.total_pages; // Validate pagination logic pm.expect(currentPage).to.be.at.least(1); pm.expect(currentPage).to.be.at.most(totalPages); });
Нагрузочное
//Perform load testing by sending multiple concurrent requests. // Load testing with concurrent requests var concurrentRequests = 10; pm.test("Load testing", function () { var requests = []; for (var i = 0; i < concurrentRequests; i++) { requests.push(pm.sendRequest); } Promise.all(requests).then(function (responses) { responses.forEach(function (response) { pm.expect(response.status).to.equal(200); }); }); });
Валидация БД
// Validate API responses by comparing them with data from a database. // Database validation using a mock database var mockDatabase = [ { id: 1, name: "Item 1" }, { id: 2, name: "Item 2" } ]; pm.test("Database validation", function () { var response = pm.response.json(); mockDatabase.forEach(function (item) { var matchingItem = response.find(function (responseItem) { return responseItem.id === item.id; }); pm.expect(matchingItem.name).to.equal(item.name); }); });
Хинт: тест-кейсы можно генерировать в ИИ-ассистенте Postbot в правом верхнем углу окна тест-кейсов. Более сложные тест-кейсы, с assertions и условиями — придется внимательно изучать документацию.