Руководство пользователя Postman: Как использовать инструмент для тестирования API

Руководство пользователя Postman: Как использовать инструмент для тестирования API

Руководство пользователя Postman: Как использовать инструмент для тестирования API

Код машин 7 нояб. 2021 г.

Что такое Postman? (дословный перевод "почтальон")

Postman - это масштабируемый инструмент тестирования API, который быстро интегрируется в конвейер CI/CD.
Он был создан индийским программистом Abhinav Asthana (сейчас живет и работает в Силиконовой долине) в 2012 году как побочный проект для упрощения рабочего процесса при разработке и тестировании API.

В разработке ПО, CI (continuous integration)/CD (continuous delivery или continuous deployment) или CICD — это комбинация непрерывной интеграции и непрерывного развертывания программного обеспечения в процессе разработки.
CI/CD объединяет разработку, тестирование и развёртывание приложения.
В настоящий момент DevOps-программисты стремятся применять CI/CD практически для всех задач.

В этом руководстве вы узнаете:

  • Зачем использовать Postman?
  • Как использовать Postman для выполнения запросов к API
  • Работа с GET запросами
  • Работа с POST запросами
  • Как параметризовать запросы
  • Как создавать тесты
  • Как создавать коллекции
  • Как запускать коллекции с помощью программы запуска коллекций
  • Как запускать коллекции с помощью Newman

Зачем использовать Postman?

Более чем 4 миллиона программистов в настоящее время используют программное обеспечение Postman по следующим причинам:

  • Доступность – Чтобы использовать инструмент Postman, нужно просто войти в свою учетную запись, что облегчает доступ к файлам в любое время и в любом месте.
  • Использование коллекций – Postman позволяет пользователям создавать коллекции для своих вызовов API Postman. Каждая коллекция может создавать вложенные папки и несколько запросов. Это помогает в организации ваших наборов тестов.
  • Совместная работа – Коллекции и среды могут быть импортированы или экспортированы, что упрощает обмен файлами. Прямая ссылка также может быть использована для обмена коллекциями.
  • Создание сред – Наличие нескольких сред способствует меньшему повторению тестов, так как можно использовать одну и ту же коллекцию, но для другой среды. Именно здесь будет происходить параметризация, которую мы обсудим в дальнейшем.
  • Создание тестов – Контрольные точки тестирования, такие как проверка статуса успешного ответа HTTP, могут быть добавлены к каждому вызову API Postman, что помогает обеспечить тестирование.
  • Автоматизированное тестирование – С помощью программы сбора данных или Newman тесты можно выполнять в несколько итераций, экономя время на повторяющиеся тесты.
  • Отладка – Консоль Postman помогает проверить, какие данные были получены, что упрощает отладку тестов.
  • Непрерывная интеграция – Благодаря своей способности поддерживать непрерывную интеграцию поддерживаются методы разработки.

Как скачать и установить POSTMAN

Будучи инструментом с открытым исходным кодом, Postman можно легко скачать. (Также возможно работать в онлайн версии системы, но по опыту в ней возможны зависания и проблемы с ответами сервера).
Вот шаги по установке:

Шаг 1) Перейдите на https://www.postman.com/downloads/ и выберите желаемую платформу Mac, Windows или Linux. Нажмите кнопку Загрузить.

Шаг 2) Индикатор загрузки будет отображаться на странице Apps. Когда Postman будет загружен, нажмите Установить.

Шаг 3) Начнется установка

Шаг 4) В следующем окне, Signup или войдите в аккаунт Postman

ПРИМЕЧАНИЕ: Есть два способа зарегистрировать учетную запись Postman. Один из них - создать собственную учетную запись Postman, а другой - использовать учетную запись Google. Хотя Postman позволяет пользователям использовать инструмент без входа в систему, регистрация гарантирует, что ваша коллекция сохранена и доступна для последующего использования.

Шаг 5) Выберите необходимые инструменты рабочей области и нажмите Save My Preferences

Шаг 6) Вы увидите экран запуска

Как использовать Postman для выполнения запросов к API

Ниже представлено рабочее пространство Postman. Давайте рассмотрим пошаговый процесс использования Postman и различные функции инструментов Postman!

  1. New – Здесь вы создадите новый запрос, коллекцию или среду.
  2. Import – Это используется для импорта коллекции или среды. Существуют такие опции, как импорт из файла, папки, ссылка или вставка необработанного текста.
  3. Runner – Тесты автоматизации могут быть выполнены с помощью программы сбора данных. Это будет обсуждаться далее в следующем блоке.
  4. Open New – Откройте новую вкладку, Окно Postman или Окно Runner, нажав эту кнопку.
  5. My Workspace – Вы можете создать новое рабочее пространство индивидуально или в команде
  6. Invite – Сотрудничайте в рабочей области, приглашая членов команды.
  7. History – Прошлые запросы, которые вы отправляли, будут отображаться в истории. Это позволяет легко отслеживать выполненные вами действия.
  8. Collections – Организуйте свой набор тестов, создавая коллекции. Каждая коллекция может содержать вложенные папки и несколько запросов. Запрос или папка также могут быть продублированы.
  9. Request tab – Здесь отображается заголовок запроса, над которым вы работаете. По умолчанию “Untitled Request” будет отображаться для запросов без названий.
  10. HTTP Request – При нажатии на эту кнопку отобразится раскрывающийся список различных запросов, таких как GET, POST, COPY, DELETE, etc. В Postman API тестировании, наиболее часто используемые запросы - GET и POST.
  11. Request URL – Также известный как конечная точка, это место, где вы определите ссылку, с которой будет взаимодействовать API.
  12. Save –Если в запросе есть изменения, необходимо нажать кнопку Сохранить, чтобы новые изменения не были потеряны или перезаписаны.
  13. Params – Здесь вы напишете параметры, необходимые для запроса, такие как значения ключей.
  14. Authorization – Для доступа к API-интерфейсам необходима авторизация. Это может быть в виде имени пользователя и пароля, токена на предъявителя (bearer token) и т.д.
  15. Headers – Вы можете задать заголовки, такие как тип контента JSON, в зависимости от запроса.
  16. Body – Именно здесь можно настроить детали в запросе, обычно используемом в запросе POST.
  17. Pre-request Script – Это сценарии, которые будут выполняться перед запросом. Обычно сценарии предварительного запроса для среды настройки используются для обеспечения того, чтобы тесты выполнялись в правильной среде.
  18. Tests – Это сценарии, выполняемые во время запроса. Важно иметь тесты, поскольку он устанавливает контрольные точки, чтобы проверить, в порядке ли статус ответа, получены ли ожидаемые данные и другие тесты.

Working with GET Requests

Get requests are used to retrieve information from the given URL. There will be no changes done to the endpoint.

We will use the following URL for all examples in this Postman tutorial

https://jsonplaceholder.typicode.com/users

In the workspace

  1. Set your HTTP request to GET.
  2. In the request URL field, input link
  3. Click Send
  4. You will see 200 OK Message
  5. There should be 10 user results in the body which indicates that your test has run successfully.

*Note: There may be cases that Get Postman request may be unsuccessful. It can be due to an invalid request URL or authentication is needed.

Working with POST Requests

Post requests are different from Get request as there is data manipulation with the user adding data to the endpoint. Using the same data from the previous tutorial in Get request, let’s now add our own user.

Step 1) Click a new tab to create a new request.

Step 2) In the new tab

  1. Set your HTTP request to POST.
  2. Input the same link in request url: https://jsonplaceholder.typicode.com/users
  3. switch to the Body tab

Step 3) In Body,

  1. Click raw
  2. Select JSON

Step 4) Copy and paste just one user result from the previous get request like below. Ensure that the code has been copied correctly with paired curly braces and brackets. Change id to 11 and name to any desired name. You can also change other details like the address.

[ { "id": 11, "name": "Krishna Rungta", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } } ]

*Note: Online Post request should have the correct format to ensure that requested data will be created. It is a good practice to use Get first to check the JSON format of the request. You can use tools like https://jsonformatter.curiousconcept.com/

Step 5) Next,

  1. Click Send.
  2. Status: 201 Created should be displayed
  3. Posted data are showing up in the body.

How to Parameterize Requests

Data Parameterization is one of the most useful features of Postman. Instead of creating the same requests with different data, you can use variables with parameters. These data can be from a data file or an environment variable. Parameterization helps to avoid repetition of the same tests and iterations can be used for automation testing.

Parameters are created through the use of double curly brackets: {{sample}}. Let’s take a look at an example of using parameters in our previous request:

Now let’s create a parameterize get request.

Step 1)

  1. Set your HTTP request to GET
  2. Input this link: https://jsonplaceholder.typicode.com/users. Replace the first part of the link with a parameter such as {{url}}. Request url should now be {{url}}/users.
  3. Click send.

There should be no response since we have not set the source of our parameter.

Step 2) To use the parameter you need to set the environment

  1. Click the eye icon
  2. Click edit to set the variable to a global environment which can be used in all collections.

Step 3) In variable,

  1. set the name to the url which is https://jsonplaceholder.typicode.com
  2. click Save.

Step 4) Click close if you see the next screen

Step 5) Go back to your Get request then click send. There should now be results for your request.

*Note: Always ensure that your parameters have a source such as an environment variable or data file to avoid errors.

How to Create Postman Tests

Postman Tests are JavaScript codes added to requests that help you verify results such as successful or failed status, comparison of expected results, etc. It usually starts with pm.test. It can be compared to asserts, verify commands available in other tools.

Let’s do some basic API testing using Postman for our parameterize requests from the previous lesson.

Step 1) Go to your GET user request from the previous tutorial.

  1. Switch to the tests tab. On the right side are snippet codes.
  2. From the snippets section, click on “Status code: Code is 200”.

The pane is auto-populated

Step 2) Now click Send. The test result should now be displayed.

Step 3) Go back to the test tab and let’s add another test. This time we will compare the expected result to the actual result.

From the snippets section, click on “Response body:JSON value check”. We will be checking if Leanne Graham has the userid 1.

Step 4)

  1. Replace “Your Test Name” from the code with “Check if user with id1 is Leanne Graham” so that the test name specifies exactly what we want to test.
  2. Replace jsonData.value with jsonData[0].name. To get the path, check the body in Get result earlier. Since Leanne Graham is userid 1, jsonData is in the first result which should start with 0. If you want to get the second result, use jsonData[1] and so on for succeeding results.
  3. In to eql, input “Leanne Graham”

pm.test("Check if user with id1 is Leanne Graham", function () { var jsonData = pm.response.json(); pm.expect(jsonData[0].name).to.eql("Leanne Graham"); });

Step 5) Click send. There should now be two passed test results for your request.

*Note: There are different kind of tests that can be created in Postman. Try to explore the tool and see what tests will fit your needs.

How to Create Collections

Collections play an important role in organizing test suites. It can be imported and exported making it easy to share collections amongst the team. In this tutorial, we will learn how to create and execute a collection.

Let’s start in creating a collection:

Step 1) Click on the New button at the top left corner of the page.

Step 2) Select Collection. Create collection window should pop up.

Step 3) Input the desired collection name and description then click create. A collection should now be created.

Step 4) Go back to the previous Get request. Click Save

Step 5)

  1. Select Postman Test Collection.
  2. Click Save to Postman Test Collection

Step 6) Postman test collection should now contain one request.

Step 7) Repeat steps 4-5 for the previous Post request so that collection will now have two requests.

How to Run Collections using Collection Runner

There are two ways to run a collection which is the Collection Runner and Newman. Let’s begin by executing the collection in Collection Runner.

Step 1) Click on the Runner button found at the top of the page next to the Import button.

Step 2) Collection Runner page should appear such as below. Following is the description of various fields

Step 3) Run your Postman Test Collection by setting up the following:

  • Choose Postman test collection- Set iterations as 3
  • Set delay as 2500 ms
  • Click on Run Postman Test… button

Step 4) Run Results page should be displayed after clicking the Run button. Depending on the delay, you should see the tests as they execute.

  1. Once tests have finished, you can see the test status if it is Passed or Failed and the results per iteration.
  2. You see Pass status for the Get Requests
  3. Since we did not have any tests for Post, there should be a message that the request did not have any tests.

You can see how important it is that there are tests in your requests so that you can verify HTTP request status if successful and the data is created or retrieved.

How to Run Collections using Newman

Another way to run a collection is via Newman. The main differences between Newman and Collection Runner are the following:

  1. Newman is an add-on for Postman. You will need to install it separately from the Native App.
  2. Newman uses the command line while Collection Runner has a GUI.
  3. Newman can be used for continuous integration.

To install Newman and run our collection from it, do the following:

Step 1) Install nodejs using this link: http://nodejs.org/download/

Step 2) Open the command line and enter

npm install -g newman

Newman should now be installed on your computer.

Step 3) Once Newman has been installed, let’s go back to our Postman workspace.In the Collections box, click on the three dots. Options should now appear. Select Export.

Step 4) Choose Export Collection as Collection v2.1 (Recommended) then click Export.

Step 5) Select your desired location then click Save. It is advisable to create a specific folder for your Postman tests. A collection should now be exported to your chosen local directory.

Step 6) We will also need to export our environment. Click on the eye icon beside the environment dropdown in Global, select Download as JSON. Select your desired location then click Save. It is advisable that the environment should be in the same folder as your collection.

Step 7) Environment should now be exported to the same local directory as Collection.

Step 8) Now go back to command line and change the directory to where you have saved the collection and environment.

cd C:\Users\Asus\Desktop\Postman Tutorial

Step 9) Run your collection using this command:

newman run PostmanTestCollection.postman_collection.json -e Testing.postman_globals.json

Run results should now appear such as below.

For guide is a reference to some basic Newman codes for execution:

  1. Run a collection only. This can be used if there is no environment or test data file dependency.newman run <collection name>
  2. Run a collection and environment. The -e indicator is for environment.newman run <collection name> -e <environment name>
  3. Run a collection with desired no. of iterations.newman run <collection name> -n <no.of iterations>
  4. Run with data file.newman run <collection name> --data <file name>  -n <no.of iterations> -e <environment name>
  5. Set delay time. This is important as tests may fail if it is run without delay due to requests being started without the previous request completing processing on the endpoint server.

newman run <collection name> -d <delay time>

Summary

  • API Testing using Postman: Postman is an application for testing APIs. Postman is one of the most popular tools used in API testing by sending requests to the webserver and getting the response back
  • Accessibility, Use of Collections, Collaboration, Continuous Integration, are some of the Key features to learn in Postman
  • It’s recommended you create an account in Postman, so your collections are available online
  • You can parameterize request in Postman
  • You can create Tests to verify a postman request
  • Collections can be run using Newman or Collection Runner

Подписывайтесь на новости Цифровой фабрики в Telegram:
Журнал Цифровая фабрика — всё об использовании новых технологий в жизни, культуре и продажах

Обложка: Midjourney

Теги

Все представленные на сайте материалы предназначены исключительно для образовательных целей и не предназначены для медицинских консультаций, диагностики или лечения. Администрация сайта, редакторы и авторы статей не несут ответственности за любые последствия и убытки, которые могут возникнуть при использовании материалов сайта.