Automation
Introduction
Postman's scripting features offer a robust toolkit for automating API testing, providing the flexibility needed for complex scenarios. In this article, we'll dive deeper into practical examples, showcasing how scripts can be used to handle dynamic data, automate assertions, and optimize your API testing workflow.
First of all, let's understand what is scripting.
What is Scripting?
Scripting in general refers to the process of writing code to automate tasks. In Postman, scripts are written in JavaScript and can be used to automate various tasks, including:
- Generating dynamic data
- Automating assertions
- Managing request headers dynamically
- Saving responses to variables
- And much more
For example, you can use scripts to generate random data, automate assertions, and manage request headers dynamically. We'll explore these techniques in detail in the following sections.
There are two types of scripts in Postman:
Pre-request Script
A pre-request script is a script that is executed before the request is sent. It can be used to generate dynamic data, automate assertions, and manage request headers dynamically.
Test Script
A test script is a script that is executed after the response is received. It can be used to automate assertions and save responses to variables.
First of all, let's learn what is variables in Postman.
Variables
Variables are used to store data that can be used in requests. For example, you can define variables for a request and use them in that request. This makes it easy to reuse data across requests. There are different types of variables in Postman, including environment variables, global variables, collection variables, and local variables. We'll explore these variables in detail in the following sections.
Environment Variables
Environment variables are used to store data that is specific to an environment. For example, you can have different environments for development, testing, and production. You can define variables for each environment and use them in your requests. This makes it easy to switch between different environments without changing the request configurations manually.
You can use this script to set and get environment variables.
// Set environment variables
pm.environment.set("username", "john_doe");
const username = pm.environment.get("username");
console.log(username); // john_doe
Global Variables
Global variables are used to store data that is common across all environments. For example, you can define a global variable for the base URL of your API. This variable can then be used in all your requests.
You can use this script to set and get global variables.
// Set global variables
pm.globals.set("baseURL", "https://api.example.com");
const baseURL = pm.globals.get("baseURL");
console.log(baseURL); // https://api.example.com
Collection Variables
Collection variables are used to store data that is specific to a collection. For example, you can define variables for a collection of requests. These variables can then be used in all the requests in that collection.
You can use this script to set and get collection variables.
// Set collection variables
pm.collectionVariables.set("username", "john_doe");
const username = pm.collectionVariables.get("username");
console.log(username); // john_doe
Local Variables
Local variables are used to store data that is specific to a request. For example, you can define variables for a request. These variables can then be used in that request.
You can use this script to set and get local variables.
// Set local variables
pm.variables.set("username", "john_doe");
const username = pm.variables.get("username");
console.log(username); // john_doe
Now, you might be wondering when to use environment variables, global variables, and collection variables. Here is a simple rule of thumb:
- Use environment variables for data that is specific to an environment.
- Use global variables for data that is common across all environments.
- Use collection variables for data that is specific to a collection.
- Use local variables for data that is specific to a request.
Generating Dynamic Data: Automating Random Data
Generating dynamic data is crucial for testing scenarios where unique inputs are required. Postman allows you to create random data using scripts, making your tests more versatile.
// Generate a random username and email address
const randomUsername = "user_" + Math.floor(Math.random() * 1000);
const randomEmail = `user${Math.floor(Math.random() * 1000)}@example.com`;
const randomPassword = "password" + Math.floor(Math.random() * 1000);
// Store the generated values in environment variables
pm.variables.set("dynamicUsername", randomUsername);
pm.variables.set("dynamicEmail", randomEmail);
// Request Body
const requestBody = {
username: randomUsername,
email: randomEmail,
password: randomPassword,
};
// Set the request body
pm.request.body.raw = JSON.stringify(requestBody);
In this script, we generate a random username, email address, and password. These values are then stored in environment variables, which can be used in subsequent requests. This ensures that each request uses unique data, preventing conflicts and ensuring the correctness of your tests.
Dynamic Request Headers: Automating Authorization Tokens
Automating authorization tokens in Postman is essential for secure API testing. You can use environment variables and scripts to manage authorization dynamically.
// Get the access token from the environment variable
const accessToken = pm.environment.get("access_token");
// If the access token is available, add it to the request headers
if (accessToken) {
pm.request.headers.add({
key: "Authorization",
value: `Bearer ${accessToken}`,
});
} else {
pm.response.to.have.status(401); // Unauthorized if no access token is available
}
In this script, the request checks if an access token is available in the environment. If present, it adds the token to the request headers. If not, the test fails with a 401 Unauthorized status, ensuring that requests without proper authorization are flagged.
Automating Complex Assertions: Validating Nested JSON Properties
API responses often include nested JSON structures. Postman's scripting capabilities allow you to navigate and validate nested properties efficiently.
Test scripts can be used to validate nested JSON properties. It is called when the response is received. The response body can be accessed using pm.response.json().
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); // Check if the response status code is 200
});
pm.test("Response should be a valid JSON", function () {
pm.response.to.be.json; // Check if the response is in JSON format
});
pm.test("Response contains valid address", function () {
// Get the response body, parse it to JSON
const responseBody = pm.response.json();
// Assertions
// Check if the response body has the address property, and it is an object
pm.expect(responseBody).to.have.property("address").that.is.an("object");
// Check if the address object has the city property, and it is a string
pm.expect(responseBody.address).to.have.property("city").that.is.a("string");
// Check if the address has city property, and it is equal to New York
pm.expect(responseBody.address.city).to.equal("New York");
// Can also use regex to validate the zip code
pm.expect(responseBody.address.zipCode).to.match(/^\d{5}$/);
});
In this script, the test validates the presence of the address object in the response and checks specific properties within it (city and zipCode). Using these assertions, you can ensure the correctness of complex, nested JSON structures.
Saving Responses to Variables: Extracting Data from Responses
Postman allows you to save responses to variables, which can be used in subsequent requests. This is useful for scenarios where you need to extract data from a response and use it in subsequent requests.
// Get the response body
const responseBody = pm.response.json();
// Save the response body to variables
pm.environment.set("userId", responseBody.id);
pm.environment.set("username", responseBody.username);
pm.environment.set("email", responseBody.email);
In this script, the response body is saved to environment variables. These variables can then be used in subsequent requests, ensuring that each request uses unique data.
However, I would recommend you to use if conditions to check if the response is valid before saving it to environment variables. For example, if the response is an error, you don't want to save it to environment variables.
// Get the response body
const responseBody = pm.response.json();
// Check if the response is valid
if (pm.response.code === 200) {
// Save the response body to environment variables
pm.environment.set("userId", responseBody.id);
pm.environment.set("username", responseBody.username);
pm.environment.set("email", responseBody.email);
}
Conclusion
These practical examples illustrate the power of Postman's scripting capabilities. By handling dynamic data, automating complex assertions, and managing request headers dynamically, you can create comprehensive and efficient API tests. As you continue exploring Postman automation, leverage these techniques to enhance your testing suite, making it more adaptable and robust. Happy scripting and testing!