Тестване на REST клиент с помощта на Restito Tool: Какво е Rest Client?
Какво е REST?
ПОЧИВКА означава „REpresentational State Transfer“, което е нов начин за комуникация между две системи в даден момент от време. Една от системите се нарича „REST клиент“, а другата се нарича „REST сървър“.
Преди да научим за Restito Framework за REST клиентско тестване, нека първо научим няколко основи.
Какво е REST клиент?
REST клиентът е метод или инструмент за извикване на REST сервизен API, който е достъпен за комуникация от всяка система или доставчик на услуги. Например: ако API е достъпен за получаване на информация за трафика в реално време за маршрут от Google, софтуерът/инструментът, който извиква Google API за трафик се нарича REST клиент.
Какво е REST сървър?
Това е метод или API, който е достъпен за комуникация от всяка система или доставчик на услуги. Например, Google предоставя API за получаване на информация за трафика в реално време по даден маршрут.
Тук, Google Сървърът трябва да е стартиран и работещ, за да може да приема заявки към открития API от различни клиенти.
Пример:
Време е да създадете пълен сценарий от край до край от горните дефиниции.
Нека разгледаме приложения за резервация на такси като Uber, тъй като една компания се нуждае от информация в реално време за пътната обстановка около маршрутите, в които се намира дадено превозно средство.
Клиент за почивка:
Тук клиентът е мобилното приложение на Uber, в което шофьорът е влязъл. Това приложение изпраща заявка към REST API, предоставено от Google карти за получаване на данни в реално време. Например, HTTP GET заявка.
Сървър за почивка:
В този пример, Google е доставчикът на услуги и Google API на картите отговаря с необходимите данни на заявката на приложението Uber.
И клиентът, и сървърът са еднакво важни в REST комуникацията.
Тук сме внедрили примери за автоматизирано тестване само на REST клиента. За тестване на REST сървър вижте https://www.guru99.com/api-testing-tool.html.
Какво е Restito?
Restito е рамка, разработена от Mkotsur. Това е леко приложение, което ви помага да изпълните всякакъв вид HTTP заявка. Можете да използвате Restito, за да тествате вашите REST API и да търсите проблеми във вашето приложение или вашата мрежа.
Как да тествам REST клиент с помощта на Restito?
Нека разделим упражнението на следните 4 стъпки:
- Създайте HTTP клиент и метод за изпращане на HTTP GET заявка до всяка крайна точка на сървъра. Засега смятайте, че крайната точка е
http://localhost:9092/getevents.
- Стартирайте Restito сървър, за да слушате и улавяте заявките, изпратени до крайната точка 'getevents' в localhost
http://localhost:9092/getevents.
- Създайте тестов клас, за да тествате горния клиент. Извикайте метода на HTTP клиента 'sendGETRequest', за да инициирате GET заявка към API 'getevents'.
- Валидирайте HTTP GET повикването с помощта на рамка Restito.
Нека се потопим дълбоко във всяка от горните стъпки.
Стъпка 1) Създайте HTTP клиент и метод за изпращане на HTTP GET заявка до всяка крайна точка на сървъра.
========== JAVA КОД Стартира ============
package com.chamlabs.restfulservices.client;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONObject;
/**
* This class creates a HTTP Client and has a method to send HTTP GET request:
* sendGETRequest(..)
*/
public class RestClient {
/**
* Constructor for the class RestClient
*/
public RestClient() {
System.out.println("Creating RestClient constructor");
}
/**
* Method to Send GET request to http://localhost:<<port>>/getevents
* @param port
* @return true if GET request is successfully sent. False, otherwise.
*/
public static boolean sendGETRequest(int port) {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet getRequest = new HttpGet("http://localhost:" + port + "/getevents");
//HttpResponse response = client.execute(request);
client.execute(getRequest);
System.out.println("HTTP request is sent successfully."
+ "Returning True");
return true;
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Some exception has occurred during the HTTP Client creation."
+ "Returning false");
return false;
}
}
========== JAVA КОД Приключва ============
Стъпка 2) Стартирайте Restito сървър, за да слушате и улавяте заявките, изпратени до крайната точка 'getevents' в localhost http://localhost:9092/getevents.
========== JAVA КОД Стартира ============
package com.chamlabs.restfultesting.util;
import static com.xebialabs.restito.builder.stub.StubHttp.whenHttp;
import static com.xebialabs.restito.semantics.Action.status;
import static com.xebialabs.restito.semantics.Condition.get;
import static com.xebialabs.restito.semantics.Condition.post;
import java.util.List;
import org.glassfish.grizzly.http.util.HttpStatus;
import com.xebialabs.restito.semantics.Call;
import com.xebialabs.restito.server.StubServer;
/**
* This utility class contains several utility methods like :
* restartRestitoServerForGETRequests(..)
* restartRestitoServerForPOSTRequests(..)
* waitAndGetCallList(..)
*
* @author cham6
* @email: paperplanes.chandra@gmail.com
* @fork: https://github.com/cham6/restfultesting.git
*
*/
public class TestUtil {
/**
* Utility method to start restito stub server to accept GET requests
* @param server
* @param port
* @param status
*/
public static void restartRestitoServerForGETRequests (StubServer server, int port, HttpStatus status)
{
// Kill the restito server
if (server != null) {
server.stop();
}
// Initialize and configure a newer instance of the stub server
server = new StubServer(port).run();
whenHttp(server).match(get("/getevents")).then(status(status));
}
/**
* Utility method to start restito stub server to accept POST requests
* @param server
* @param port
* @param status
*/
public static void restartRestitoServerForPOSTRequests (StubServer server, int port, HttpStatus status)
{
// Kill the restito server
if (server != null) {
server.stop();
}
// Initialize and configure a newer instance of the stub server
server = new StubServer(port).run();
whenHttp(server).match(post("/postevents")).then(status(status));
}
/**
* For a given restito stub server, loop for the given amount of seconds and
* break and return the call list from server.
*
* @param server
* @param waitTimeInSeconds
* @return
* @throws InterruptedException
*/
public static List<Call> waitAndGetCallList (StubServer server, int waitTimeInSeconds)
throws InterruptedException
{
int timeoutCount = 0;
List<Call> callList = server.getCalls();
while (callList.isEmpty()) {
Thread.sleep(1000);
timeoutCount++;
if (timeoutCount >= waitTimeInSeconds) {
break;
}
callList = server.getCalls();
}
// Wait for 2 seconds to get all the calls into callList to Eliminate any falkyness.
Thread.sleep(2000);
return server.getCalls();
}
}
========== JAVA КОД Приключва ============
Стъпка 3) Създайте тестов клас, за да тествате горния клиент. Извикайте HTTP клиентския метод sendGETRequest, за да инициирате GET заявка към API 'getevents'.
========== JAVA КОД Стартира ============
import junit.framework.TestCase;
import com.chamlabs.restfulservices.client.RestClient;
import com.chamlabs.restfultesting.util.TestUtil;
import com.xebialabs.restito.semantics.Call;
import com.xebialabs.restito.server.StubServer;
import static org.glassfish.grizzly.http.util.HttpStatus.ACCEPTED_202;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
/**
* This class contains several junit tests to validate the RestClient operations like:
* sendRequest(..)
* sendRequestWithCustomHeaders(..)
* sendPOSTRequestWithJSONBody(..)
*
*/
public class RestClientTester extends TestCase {
private static final Integer PORT = 9098;
private static final Integer PORT2 = 9099;
private static final Integer PORT3 = 9097;
public RestClientTester() {
System.out.println("Starting the test RestClientTester");
}
/**
* Junit test to validate the GET request from RestClient
* Steps:
* 1) Create a stub server using Restito framework and configure it to listen on given port
* 2) Invoke the sendGETRequest(..) method of RestClient
* 3) Restito captures the matching GET requests sent, if any.
* 4) Validate if Restito has captured any GET requests on given endpoint
* Expected Behavior:
* > Restito should have captured GET request and it should have captured only one GET request.
* Finally:
* > Stop the stub server started using restito.
*/
public void testGETRequestFromClient() {
StubServer server = null;
try {
//This will start the stub server on 'PORT' and responds with HTTP 202 'ACCEPTED_202'
TestUtil.restartRestitoServerForGETRequests(server, PORT, ACCEPTED_202);
RestClient.sendGETRequest(PORT);
List<Call> callList = TestUtil.waitAndGetCallList(server, 30);
assertTrue("GET request is not received from the RestClient. Test failed.",
(callList != null) && (callList.size() == 1));
}
catch(Exception e) {
e.printStackTrace();
fail("Test Failed due to exception : " + e);
}
finally {
if(server != null) {
server.stop();
}
}
}
========== JAVA КОД Приключва ============
Стъпка 4) Как да валидирате GET заявка с Headers и POST заявка с тялото, използвайки Restito framework.
========== JAVA КОД Стартира ============
/**
* Junit test to validate the GET request with headers from RestClient
* Steps:
* 1) Create a stub server using Restito framework and configure it to listen on given port
* 2) Invoke the sendGETRequestWithCustomHeaders(..) method of RestClient
* 3) Restito captures the matching GET requests sent, if any.
* 4) Validate if Restito has captured any GET requests on a given endpoint
* Expected Behavior:
* > Restito should have captured GET request, and it should have captured only one GET request.
* > Get the headers of the captured GET request
* and make sure the headers match to the ones configured.
* Finally:
* > Stop the stub server started using restito.
*/
public void testGETRequestWithHeadersFromClient() {
StubServer server = null;
try {
//This will start the stub server on 'PORT' and responds with HTTP 202 'ACCEPTED_202'
TestUtil.restartRestitoServerForGETRequests(server, PORT2, ACCEPTED_202);
RestClient.sendGETRequestWithCustomHeaders(PORT2);
List<Call> callList = TestUtil.waitAndGetCallList(server, 30);
assertTrue("GET request is not received from the RestClient. Test failed.",
(callList != null) && (callList.size() == 1));
//Validate the headers of the GET request from REST Client
Map<String, List<String>> headersFromRequest = callList.get(0).getHeaders();
assertTrue("GET request contains header Accept and its value ",
headersFromRequest.get("Accept").contains("text/html"));
assertTrue("GET request contains header Authorization and its value ",
headersFromRequest.get("Authorization").contains("Bearer 1234567890qwertyuiop"));
assertTrue("GET request contains header Cache-Control and its value ",
headersFromRequest.get("Cache-Control").contains("no-cache"));
assertTrue("GET request contains header Connection and its value ",
headersFromRequest.get("Connection").contains("keep-alive"));
assertTrue("GET request contains header Content-Type and its value ",
headersFromRequest.get("Content-Type").contains("application/json"));
}
catch(Exception e) {
e.printStackTrace();
fail("Test Failed due to exception : " + e);
}
finally {
if(server != null) {
server.stop();
}
}
}
/**
* Junit test to validate the POST request with body and headers from RestClient
* Steps:
* 1) Create a stub server using Restito framework and configure it to listen on given port
* 2) Invoke the sendPOSTRequestWithJSONBody(..) method of RestClient
* 3) Restito captures the matching POST requests sent, if any.
* 4) Validate if Restito has captured any POST requests on given endpoint
* Expected Behavior:
* > Restito should have captured POST request and it should have captured only one POST request.
* > Get the body of the captured POST request and validate the JSON values
* Finally:
* > Stop the stub server started using restito.
*/
public void testPOSTRequestWithJSONBody() {
StubServer server = null;
try {
//This will start the stub server on 'PORT' and responds with HTTP 202 'ACCEPTED_202'
TestUtil.restartRestitoServerForPOSTRequests(server, PORT3, ACCEPTED_202);
RestClient.sendPOSTRequestWithJSONBody(PORT3);
List<Call> callList = TestUtil.waitAndGetCallList(server, 30);
assertTrue("POST request is not received from the RestClient. Test failed.",
(callList != null) && (callList.size() == 1));
//Validate the headers of the GET request from REST Client
String requestBody = callList.get(0).getPostBody();
JSONObject postRequestJSON = new JSONObject(requestBody);
assertTrue("The timeUpdated in json is incorrect",
postRequestJSON.get("timeUpdated").toString().equalsIgnoreCase("1535703838478"));
assertTrue("The access_token in json is incorrect",
postRequestJSON.get("access_token").toString().
equalsIgnoreCase("abf8714d-73a3-42ab-9df8-d13fcb92a1d8"));
assertTrue("The refresh_token in json is incorrect",
postRequestJSON.get("refresh_token").toString().
equalsIgnoreCase("d5a5ab08-c200-421d-ad46-2e89c2f566f5"));
assertTrue("The token_type in json is incorrect",
postRequestJSON.get("token_type").toString().equalsIgnoreCase("bearer"));
assertTrue("The expires_in in json is incorrect",
postRequestJSON.get("expires_in").toString().equalsIgnoreCase("1024"));
assertTrue("The scope in json is incorrect",
postRequestJSON.get("scope").toString().equalsIgnoreCase(""));
}
catch(Exception e) {
e.printStackTrace();
fail("Test Failed due to exception : " + e);
}
finally {
if(server != null) {
server.stop();
}
}
}
}
========== JAVA КОД Приключва ============
Предимства от използването на Restito Framework за тестване на REST клиент
Ето предимствата/предимствата на Restito Framework за клиентско тестване на ReST
- Не е необходимо действителният REST сървър да бъде разработен, за да тестваме REST клиента.
- Restito предоставя силни и разнообразни помощни програми и методи за подиграване на различно поведение на сървър. Например: За да тествате как се държи REST клиентът, когато сървърът отговори с HTTP 404 грешка или HTTP 503 грешка.
- Restito сървърите могат да бъдат настроени за няколко милисекунди и могат да бъдат прекратени след приключване на тестовете.
- Restito поддържа всички видове съдържание на HTTP методи като компресирано, некомпресирано, унифицирано, приложение/текст, приложение/JSON и др.
Недостатъци на използването на Restito Framework за REST клиентско тестване
Ето минуси/недостатъци на Restito Framework за ReST клиентско тестване
- Източникът на клиента REST трябва да бъде променен, за да счита „localhost“ за сървърна машина.
- Отварянето на сървър във всеки порт може да е в конфликт, ако използваме често използван порт като „8080“ или „9443“ и т.н.
- Препоръчително е да използвате портове като 9092 или 9099, които не се използват често от други инструменти.
Oбобщение
- REST означава „REpresentational State Transfer“, което е нов стандартен начин за комуникация между две системи в даден момент от време.
- REST Client е метод или инструмент за извикване на API на REST услуга, който е изложен на комуникация от всяка система или доставчик на услуги.
- В RestServer метод или API, който е изложен за комуникация от всяка система или доставчик на услуги.
- Restito е леко приложение, което ви помага да изпълните всякакъв вид HTTP заявка
- Създайте HTTP клиент и метод за изпращане на HTTP GET заявка до всяка крайна точка на сървъра
- Стартирайте Restito сървър, за да слушате и улавяте заявките, изпратени до крайната точка „getevents“.
- Стартирайте Restito сървър, за да слушате и улавяте заявките, изпратени до крайната точка 'getevents' в localhost
- Тук сме внедрили примери за автоматизирано тестване само на REST клиента.
- Не е необходимо действителният REST сървър да бъде разработен, за да тестваме REST клиента.
- Източникът на клиента REST трябва да бъде променен, за да счита „localhost“ за сървърна машина.
