cookies) {
137 | requestSpecBuilder.addCookies(cookies);
138 | return this;
139 | }
140 |
141 | /**
142 | * Defines Cookies to Request Specification
143 | *
144 | * @param cookies
145 | * @return this
146 | */
147 | public RestUtil cookies(Cookies cookies) {
148 | requestSpecBuilder.addCookies(cookies);
149 | return this;
150 | }
151 |
152 | /**
153 | * Defines Cookie to Request Specification
154 | *
155 | * @param cookie
156 | * @return this
157 | */
158 | public RestUtil cookie(Cookie cookie) {
159 | requestSpecBuilder.addCookie(cookie);
160 | return this;
161 | }
162 |
163 | /**
164 | * Defines Body to Request Specification
165 | *
166 | * @param body
167 | * @return this
168 | */
169 | public RestUtil body(Object body) {
170 | requestSpecBuilder.setBody(body);
171 | return this;
172 | }
173 |
174 | /**
175 | * Defines the Expected Status Code following successful api execution for validation
176 | *
177 | * @param expectedStatusCode
178 | * @return this
179 | */
180 | public RestUtil expectedStatusCode(HttpStatus expectedStatusCode) {
181 | this.expectedStatusCode = expectedStatusCode;
182 | return this;
183 | }
184 |
185 | /**
186 | * Defines the Expected Response Content Type following successful api execution for validation
187 | *
188 | * @param contentType
189 | * @return this
190 | */
191 | public RestUtil expectedResponseContentType(ContentType contentType) {
192 | this.expectedResponseContentType = contentType.toString();
193 | return this;
194 | }
195 |
196 | /**
197 | * Defines the Expected Response Content Type following successful api execution for validation
198 | *
199 | * @param contentType
200 | * @return this
201 | */
202 | public RestUtil expectedResponseContentType(String contentType) {
203 | this.expectedResponseContentType = contentType;
204 | return this;
205 | }
206 |
207 | /**
208 | * Hits the Pre-Defined Request Specification as PUT Request
209 | *
210 | * On successful response, method validates:
211 | * - Status Code against the Status Code provided in Request Specification
212 | * - Content Type against the Content Type provided in Request Specification
213 | *
214 | * @return this
215 | */
216 | public RestUtil put() {
217 | requestSpecification = requestSpecBuilder.build();
218 | apiResponse =
219 | given()
220 | .log().all()
221 | .filter(new APIResponseFilter())
222 | .spec(requestSpecification)
223 | .when()
224 | .put()
225 | .then()
226 | .assertThat()
227 | .statusCode(expectedStatusCode.getCode())
228 | .contentType(expectedResponseContentType)
229 | .and()
230 | .extract()
231 | .response();
232 |
233 | return this;
234 | }
235 |
236 | /**
237 | * Hits the Pre-Defined Request Specification as DELETE Request
238 | *
239 | * On successful response, method validates:
240 | * - Status Code against the Status Code provided in Request Specification
241 | * - Content Type against the Content Type provided in Request Specification
242 | *
243 | * @return this
244 | */
245 | public RestUtil delete() {
246 | requestSpecification = requestSpecBuilder.build();
247 | apiResponse =
248 | given()
249 | .log().all()
250 | .filter(new APIResponseFilter())
251 | .spec(requestSpecification)
252 | .when()
253 | .delete()
254 | .then()
255 | .assertThat()
256 | .statusCode(expectedStatusCode.getCode())
257 | .contentType(expectedResponseContentType)
258 | .and()
259 | .extract()
260 | .response();
261 |
262 | return this;
263 | }
264 |
265 | /**
266 | * Hits the Pre-Defined Request Specification as POST Request
267 | *
268 | * On successful response, method validates:
269 | * - Status Code against the Status Code provided in Request Specification
270 | * - Content Type against the Content Type provided in Request Specification
271 | *
272 | * @return this
273 | */
274 | public RestUtil post() {
275 | requestSpecification = requestSpecBuilder.build();
276 | apiResponse =
277 | given()
278 | .log().all()
279 | .filter(new APIResponseFilter())
280 | .spec(requestSpecification)
281 | .when()
282 | .post()
283 | .then()
284 | .assertThat()
285 | .statusCode(expectedStatusCode.getCode())
286 | .contentType(expectedResponseContentType)
287 | .and()
288 | .extract()
289 | .response();
290 |
291 | return this;
292 | }
293 |
294 | /**
295 | * Hits the Pre-Defined Request Specification as GET Request
296 | *
297 | * On successful response, method validates:
298 | * - Status Code against the Status Code provided in Request Specification
299 | * - Content Type against the Content Type provided in Request Specification
300 | *
301 | * @return this
302 | */
303 | public RestUtil get() {
304 | requestSpecification = requestSpecBuilder.build();
305 | apiResponse =
306 | given()
307 | .log().all()
308 | .filter(new APIResponseFilter())
309 | .spec(requestSpecification)
310 | .when()
311 | .get()
312 | .then()
313 | .assertThat()
314 | .statusCode(expectedStatusCode.getCode())
315 | .contentType(expectedResponseContentType)
316 | .and()
317 | .extract()
318 | .response();
319 |
320 | return this;
321 | }
322 |
323 | /**
324 | * Returns the apiResponse Object
325 | *
326 | * @return apiResponse
327 | */
328 | public Response response() {
329 | return apiResponse;
330 | }
331 |
332 | /**
333 | * Returns the apiResponse Object as String
334 | *
335 | * @return apiResponse
336 | */
337 | public String getApiResponseAsString() {
338 | return apiResponse.asString();
339 | }
340 |
341 | /**
342 | * Converts the Response Object into the provided Class Type
343 | *
344 | * @param type
345 | * @param
346 | * @return
347 | * @throws AutomationException
348 | */
349 | public T responseToPojo(Class type) throws AutomationException {
350 | try {
351 | return new ObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY).readValue(getApiResponseAsString(), type);
352 | } catch (IOException ioex) {
353 | throw new AutomationException("Response Received did not match the expected Response Format POJO: " + type.getName() + ioex);
354 | }
355 | }
356 |
357 | /**
358 | * Converts the Response Object into the provided Class Type
359 | *
360 | * @param type
361 | * @param
362 | * @return
363 | * @throws AutomationException
364 | */
365 | public T responseToPojo(TypeReference type) throws AutomationException {
366 | try {
367 | return (T) new ObjectMapper().enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY).readValue(getApiResponseAsString(), type);
368 | } catch (IOException ioex) {
369 | throw new AutomationException(ioex);
370 | }
371 | }
372 |
373 | }
374 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/exceptions/AutomationException.java:
--------------------------------------------------------------------------------
1 | package framework.utils.exceptions;
2 |
3 | /* -----------------------------------------------------------------------
4 | - ** Rest API Testing Framework using RestAssured **
5 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
6 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
7 | ----------------------------------------------------------------------- */
8 | public class AutomationException extends Exception {
9 |
10 | public AutomationException(String message) {
11 | super(message);
12 | }
13 |
14 | public AutomationException(Exception ex) {
15 | super(ex);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/globalConstants/APIEndPoint.java:
--------------------------------------------------------------------------------
1 | package framework.utils.globalConstants;
2 |
3 | /* -----------------------------------------------------------------------
4 | - ** Rest API Testing Framework using RestAssured **
5 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
6 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
7 | ----------------------------------------------------------------------- */
8 | public class APIEndPoint {
9 |
10 | public static final String USER_PROFILES = "/user-service/api/";
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/globalConstants/HttpStatus.java:
--------------------------------------------------------------------------------
1 | package framework.utils.globalConstants;
2 |
3 | /* -----------------------------------------------------------------------
4 | - ** Rest API Testing Framework using RestAssured **
5 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
6 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
7 | ----------------------------------------------------------------------- */
8 | public enum HttpStatus {
9 |
10 | CONTINUE(100, "Continue"),
11 | SWITCHING_PROTOCOL(101, "Switching Protocols"),
12 | PROCESSING(102, "Processing"),
13 |
14 | OK(200, "OK"),
15 | CREATED(201, "Created"),
16 | ACCEPTED(202, "Accepted"),
17 | NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
18 | NO_CONTENT(204, "No Content"),
19 | RESET_CONTENT(205, "Reset Content"),
20 | PARTIAL_CONTENT(206, "Partial Content"),
21 | MULTI_STATUS(207, "Multi-Status (WebDAV; RFC 4918"),
22 | ALREADY_REPORTED(208, "Already Reported (WebDAV; RFC 5842)" ),
23 | IM_USED(226, "IM Used (RFC 3229)"),
24 |
25 | MULTIPLE_CHOICES(300, "Multiple Choices"),
26 | MOVED_PERMANENTLY(301, "Moved Permanently"),
27 | FOUND(302, "Found"),
28 | SEE_OTHER(303, "See Other (since HTTP/1.1)"),
29 | NOT_MODIFIED(304, "Not Modified"),
30 | USE_PROXY(305, "Use Proxy (since HTTP/1.1)"),
31 | SWITCH_PROXY(306, "Switch Proxy"),
32 | TEMPORARY_REDIRECT(307, "Temporary Redirect (since HTTP/1.1)"),
33 | PERMANENT_REDIRECT(308, "Permanent Redirect (approved as experimental RFC)[12]"),
34 |
35 | BAD_REQUEST(400, "Bad Request"),
36 | UNAUTHORIZED(401, "Unauthorized"),
37 | PAYMENT_REQUIRED(402, "Payment Required"),
38 | FORBIDDEN(403, "Forbidden"),
39 | NOT_FOUND(404, "Not Found"),
40 | METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
41 | NOT_ACCEPTABLE(406, "Not Acceptable"),
42 | PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
43 | REQUEST_TIMEOUT(408, "Request Timeout"),
44 | CONFLICT(409, "Conflict"),
45 | GONE(410, "Gone"),
46 | LENGTH_REQUIRED(411, "Length Required"),
47 | PRECONDITION_FAILED(412, "Precondition Failed"),
48 | REQUEST_ENTITY_TOO_LARGE(413, "Request Entity Too Large"),
49 | REQUEST_URI_TOO_LONG(414, "Request-URI Too Long"),
50 | UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
51 | REQUESTED_RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"),
52 | EXPECTATION_FAILED(417, "Expectation Failed"),
53 |
54 | INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
55 | NOT_IMPLEMENTED(501, "Not Implemented"),
56 | BAD_GATEWAY(502, "Bad Gateway"),
57 | SERVICE_UNAVAILABLE(503, "Service Unavailable"),
58 | GATEWAY_TIMEOUT(504, "Gateway Timeout"),
59 | HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
60 | VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates (RFC 2295)"),
61 | INSUFFICIENT_STORAGE(507, "Insufficient Storage (WebDAV; RFC 4918)"),
62 | LOOP_DETECTED(508, "Loop Detected (WebDAV; RFC 5842)"),
63 | BANDWIDTH_LIMIT_EXCEEDED(509, "Bandwidth Limit Exceeded (Apache bw/limited extension)"),
64 | NOT_EXTEND(510, "Not Extended (RFC 2774)"),
65 | NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required (RFC 6585)"),
66 | CONNECTION_TIMED_OUT(522, "Connection timed out"),
67 | PROXY_DECLINED_REQUEST(523, "Proxy Declined Request"),
68 | TIMEOUT_OCCURRED(524, "A timeout occurred")
69 | ;
70 |
71 | private int code;
72 | private String desc;
73 | private String text;
74 |
75 | HttpStatus(int code, String desc) {
76 | this.code = code;
77 | this.desc = desc;
78 | this.text = Integer.toString(code);
79 | }
80 |
81 | /**
82 | * Gets the HTTP status code
83 | * @return the status code number
84 | */
85 | public int getCode() {
86 | return code;
87 | }
88 |
89 | /**
90 | * Gets the HTTP status code as a text string
91 | * @return the status code as a text string
92 | */
93 | public String asText() {
94 | return text;
95 | }
96 |
97 | /**
98 | * Get the description
99 | * @return the description of the status code
100 | */
101 | public String getDesc() {
102 | return desc;
103 | }
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/globalConstants/PathConfig.java:
--------------------------------------------------------------------------------
1 | package framework.utils.globalConstants;
2 |
3 | /* -----------------------------------------------------------------------
4 | - ** Rest API Testing Framework using RestAssured **
5 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
6 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
7 | ----------------------------------------------------------------------- */
8 | public class PathConfig {
9 |
10 | private final static String PROPERTIES_TEST = "./src/main/resources/test.properties";
11 | private final static String PROPERTIES_LOG4J = "./src/test/resources/log4j2.xml";
12 |
13 | private static String OUTPUT_DIR_NAME = "";
14 | private static String OUTPUT_DIR = "";
15 | private static String REPORTS_PATH = "";
16 | private static String APPLOGS_PATH = "";
17 |
18 | public static String getLog4JPropertiesPath() {
19 | return PROPERTIES_LOG4J;
20 | }
21 |
22 | public static String getOutputDirName() {
23 | return OUTPUT_DIR_NAME;
24 | }
25 |
26 | public static void setOutputDirName(String outputDirName) {
27 | OUTPUT_DIR_NAME = outputDirName;
28 | }
29 |
30 | public static String getOutputDir() {
31 | return OUTPUT_DIR;
32 | }
33 |
34 | public static void setOutputDir(String outputDir) {
35 | OUTPUT_DIR = outputDir;
36 | }
37 |
38 | public static String getReportsPath() {
39 | return REPORTS_PATH;
40 | }
41 |
42 | public static void setReportsPath(String reportsPath) {
43 | REPORTS_PATH = reportsPath;
44 | }
45 |
46 | public static String getApplogsPath() {
47 | return APPLOGS_PATH;
48 | }
49 |
50 | public static void setApplogsPath(String applogsPath) {
51 | APPLOGS_PATH = applogsPath;
52 | }
53 |
54 | public static String getPropertiesTest() {
55 | return PROPERTIES_TEST;
56 | }
57 |
58 | public static String getPropertiesLog4j() {
59 | return PROPERTIES_LOG4J;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/initializers/TestInit.java:
--------------------------------------------------------------------------------
1 | package framework.utils.initializers;
2 |
3 | import com.aventstack.extentreports.Status;
4 | import framework.utils.globalConstants.PathConfig;
5 | import framework.utils.reportManagement.OutputUtil;
6 | import framework.utils.reportManagement.extent.ExtentTestManager;
7 | import org.apache.logging.log4j.LogManager;
8 | import org.apache.logging.log4j.Logger;
9 | import org.testng.ITestContext;
10 | import org.testng.ITestResult;
11 | import org.testng.annotations.*;
12 |
13 | import java.time.LocalDateTime;
14 | import java.time.format.DateTimeFormatter;
15 |
16 | /* -----------------------------------------------------------------------
17 | - ** Rest API Testing Framework using RestAssured **
18 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
19 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
20 | ----------------------------------------------------------------------- */
21 | public class TestInit {
22 |
23 | private final Logger _logger = LogManager.getLogger(TestInit.class);
24 |
25 | @BeforeSuite(alwaysRun = true)
26 | public void initializeTestSuite(ITestContext context) {
27 | DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy_HH-mm-ss");
28 | System.setProperty("current.date", LocalDateTime.now().format(format));
29 | OutputUtil.createOutputDirectory();
30 |
31 | System.setProperty("applogs.path", PathConfig.getApplogsPath() + "ExecutionLog.log");
32 | org.apache.logging.log4j.core.LoggerContext ctx =
33 | (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
34 | ctx.reconfigure();
35 |
36 | _logger.info("*** Test Suite " + context.getName() + " started ***");
37 | }
38 |
39 | @BeforeClass(alwaysRun = true)
40 | public void initializeTestClass(ITestContext context) {
41 |
42 | }
43 |
44 | @BeforeMethod(alwaysRun = true)
45 | public void config(ITestResult result) {
46 | }
47 |
48 | @AfterMethod(alwaysRun = true)
49 | public void tearDown(ITestResult iTestResult) {
50 |
51 | if (iTestResult.getStatus() == ITestResult.SUCCESS) {
52 |
53 | } else if (iTestResult.getStatus() == ITestResult.FAILURE) {
54 | ExtentTestManager.log(_logger, Status.FAIL, iTestResult.getThrowable());
55 | } else if (iTestResult.getStatus() == ITestResult.SKIP) {
56 | ExtentTestManager.log(_logger, Status.SKIP, iTestResult.getThrowable());
57 | }
58 |
59 | ExtentTestManager.endTest();
60 | }
61 |
62 | @AfterSuite(alwaysRun = true)
63 | public void completeSuite(ITestContext context) {
64 | _logger.info("*** Test Suite " + context.getName() + " ending ***");
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/logManagement/APIResponseFilter.java:
--------------------------------------------------------------------------------
1 | package framework.utils.logManagement;
2 |
3 | import com.aventstack.extentreports.Status;
4 | import com.aventstack.extentreports.markuputils.Markup;
5 | import com.aventstack.extentreports.markuputils.MarkupHelper;
6 | import framework.utils.reportManagement.extent.ExtentTestManager;
7 | import io.restassured.filter.Filter;
8 | import io.restassured.filter.FilterContext;
9 | import io.restassured.filter.log.LogDetail;
10 | import io.restassured.internal.print.RequestPrinter;
11 | import io.restassured.internal.print.ResponsePrinter;
12 | import io.restassured.response.Response;
13 | import io.restassured.specification.FilterableRequestSpecification;
14 | import io.restassured.specification.FilterableResponseSpecification;
15 | import org.apache.commons.io.output.WriterOutputStream;
16 |
17 | import java.io.PrintStream;
18 | import java.io.StringWriter;
19 | import java.util.HashSet;
20 |
21 | /* -----------------------------------------------------------------------
22 | - ** Rest API Testing Framework using RestAssured **
23 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
24 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
25 | ----------------------------------------------------------------------- */
26 | public class APIResponseFilter implements Filter {
27 |
28 | @Override
29 | public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
30 | Response response = ctx.next(requestSpec, responseSpec);
31 | String responseStr = ResponsePrinter.print(response,
32 | response,
33 | new PrintStream(new WriterOutputStream(new StringWriter())),
34 | LogDetail.ALL,
35 | true,
36 | new HashSet<>());
37 |
38 | String requestStr = RequestPrinter.print(requestSpec,
39 | requestSpec.getMethod(),
40 | requestSpec.getURI(),
41 | LogDetail.ALL,
42 | new HashSet<>(),
43 | new PrintStream(new WriterOutputStream(new StringWriter())),
44 | true);
45 |
46 | Markup m = MarkupHelper.createCodeBlock(requestStr, responseStr);
47 | ExtentTestManager.getTest().log(Status.INFO, m);
48 | return response;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/propertiesManagement/TestProperties.java:
--------------------------------------------------------------------------------
1 | package framework.utils.propertiesManagement;
2 |
3 | import framework.utils.exceptions.AutomationException;
4 | import framework.utils.globalConstants.PathConfig;
5 |
6 | import java.io.FileInputStream;
7 | import java.io.FileNotFoundException;
8 | import java.io.IOException;
9 | import java.text.MessageFormat;
10 | import java.util.Properties;
11 |
12 | /* -----------------------------------------------------------------------
13 | - ** Rest API Testing Framework using RestAssured **
14 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
15 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
16 | ----------------------------------------------------------------------- */
17 | public final class TestProperties {
18 |
19 | private static final TestProperties TEST_PROPERTIES = new TestProperties();
20 | private static Properties properties;
21 |
22 | public static final TestProperties init() {
23 | TestProperties testProp = TEST_PROPERTIES;
24 | testProp.getInstance();
25 | return testProp;
26 | }
27 |
28 | private void getInstance() {
29 | if (properties == null) {
30 | properties = new Properties();
31 | System.out.println("Loading Properties");
32 | try {
33 | FileInputStream inputStream = new FileInputStream(PathConfig.getPropertiesTest());
34 | properties.load(inputStream);
35 | } catch (FileNotFoundException ex) {
36 |
37 | } catch (IOException e) {
38 | e.printStackTrace();
39 | }
40 | }
41 | }
42 |
43 | public String getProperty(String propertyName) throws AutomationException {
44 |
45 | Object value = properties.get(propertyName);
46 | if (value != null) {
47 | return properties.get(propertyName).toString();
48 | } else {
49 | String errorLog = MessageFormat.format("Error occurred while getting {0} Property from MlsTestProperties. This could be due to no such property available in MlsTestProperties.properties file.", propertyName);
50 | throw new AutomationException(errorLog);
51 | }
52 | }
53 |
54 | public boolean getBooleanProperty(String propertyName) {
55 | return Boolean.parseBoolean(properties.getProperty(propertyName));
56 | }
57 |
58 | public Integer getIntegerProperty(String propertyName) {
59 | return Integer.parseInt(properties.getProperty(propertyName));
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/reportManagement/OutputUtil.java:
--------------------------------------------------------------------------------
1 | package framework.utils.reportManagement;
2 |
3 | import framework.utils.globalConstants.PathConfig;
4 |
5 | import java.io.File;
6 |
7 | /* -----------------------------------------------------------------------
8 | - ** Rest API Testing Framework using RestAssured **
9 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
10 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
11 | ----------------------------------------------------------------------- */
12 | public class OutputUtil {
13 |
14 | public static void createOutputDirectory() {
15 | String timestamp = System.getProperty("current.date");
16 | String outputDirName = "Output_" + timestamp;
17 |
18 | /** Output Directory Structure Definition **/
19 | PathConfig.setOutputDirName(outputDirName);
20 | PathConfig.setOutputDir("./Output/" + outputDirName);
21 | PathConfig.setReportsPath(PathConfig.getOutputDir() + File.separator + "Reports" + File.separator);
22 | PathConfig.setApplogsPath(PathConfig.getOutputDir() + File.separator + "Applogs" + File.separator);
23 |
24 | new File(PathConfig.getOutputDir()).mkdir();
25 | new File(PathConfig.getApplogsPath()).mkdir();
26 | new File(PathConfig.getReportsPath()).mkdir();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/reportManagement/extent/ExtentManager.java:
--------------------------------------------------------------------------------
1 | package framework.utils.reportManagement.extent;
2 |
3 | import com.aventstack.extentreports.AnalysisStrategy;
4 | import com.aventstack.extentreports.ExtentReports;
5 | import com.aventstack.extentreports.reporter.ExtentSparkReporter;
6 | import com.aventstack.extentreports.reporter.configuration.Theme;
7 | import framework.utils.globalConstants.PathConfig;
8 |
9 | import java.io.File;
10 |
11 | /* -----------------------------------------------------------------------
12 | - ** Rest API Testing Framework using RestAssured **
13 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
14 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
15 | ----------------------------------------------------------------------- */
16 | public class ExtentManager {
17 |
18 | private static ExtentReports extent;
19 | private static String reportFileName = "ExecutionReport_" + System.getProperty("current.date") + ".html";
20 | private static String fileSeperator = System.getProperty("file.separator");
21 | private static String reportFilepath = PathConfig.getReportsPath();
22 | private static String reportFileLocation = reportFilepath + fileSeperator + reportFileName;
23 |
24 |
25 | public static ExtentReports getInstance() {
26 | if (extent == null)
27 | createInstance();
28 | return extent;
29 | }
30 |
31 | public static ExtentReports createInstance() {
32 |
33 | extent = new ExtentReports();
34 | extent.setAnalysisStrategy(AnalysisStrategy.CLASS);
35 |
36 | String fileName = getReportPath(reportFilepath);
37 |
38 | ExtentSparkReporter htmlReporter = new ExtentSparkReporter(fileName);
39 | htmlReporter.config().setTheme(Theme.STANDARD);
40 | htmlReporter.config().setDocumentTitle(reportFileName);
41 | htmlReporter.config().setEncoding("utf-8");
42 | htmlReporter.config().setReportName(reportFileName);
43 | htmlReporter.config().setTimeStampFormat("EEEE, MMMM dd, yyyy, hh:mm a '('zzz')'");
44 |
45 | extent.attachReporter(htmlReporter);
46 |
47 | return extent;
48 | }
49 |
50 | private static String getReportPath(String path) {
51 | File testDirectory = new File(path);
52 | if (!testDirectory.exists()) {
53 | if (testDirectory.mkdir()) {
54 | return reportFileLocation;
55 | } else {
56 | return System.getProperty("user.dir");
57 | }
58 | } else {
59 | //System.out.println("Directory already exists: " + path);
60 | }
61 | return reportFileLocation;
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/reportManagement/extent/ExtentModuleManager.java:
--------------------------------------------------------------------------------
1 | package framework.utils.reportManagement.extent;
2 |
3 | import com.aventstack.extentreports.ExtentReports;
4 | import com.aventstack.extentreports.ExtentTest;
5 |
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | /* -----------------------------------------------------------------------
10 | - ** Rest API Testing Framework using RestAssured **
11 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
12 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
13 | ----------------------------------------------------------------------- */
14 | public class ExtentModuleManager {
15 |
16 | static Map extentModulesMap = new HashMap();
17 | static ExtentReports extent = ExtentManager.getInstance();
18 |
19 | public static synchronized ExtentTest getModule(String module) {
20 |
21 | ExtentTest currentThread = extentModulesMap.get(module);
22 |
23 | if (currentThread == null) {
24 | return createModule(module);
25 | } else {
26 | return currentThread;
27 | }
28 |
29 | }
30 |
31 | private static synchronized ExtentTest createModule(String module) {
32 | ExtentTest test = extent.createTest(module);
33 | extentModulesMap.put(module, test);
34 | return test;
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/reportManagement/extent/ExtentReporter.java:
--------------------------------------------------------------------------------
1 | package framework.utils.reportManagement.extent;
2 |
3 | import com.aventstack.extentreports.ExtentTest;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /* -----------------------------------------------------------------------
9 | - ** Rest API Testing Framework using RestAssured **
10 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
11 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
12 | ----------------------------------------------------------------------- */
13 | public class ExtentReporter {
14 |
15 | private static Map reporterMap = new HashMap();
16 |
17 | public static ExtentTest get(Integer integer) {
18 | return reporterMap.get(integer);
19 | }
20 |
21 | public static void set(Integer integer, ExtentTest test) {
22 | reporterMap.put(integer, test);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/framework/utils/reportManagement/extent/ExtentTestManager.java:
--------------------------------------------------------------------------------
1 | package framework.utils.reportManagement.extent;
2 |
3 | import com.aventstack.extentreports.ExtentReports;
4 | import com.aventstack.extentreports.ExtentTest;
5 | import com.aventstack.extentreports.Status;
6 | import com.aventstack.extentreports.markuputils.ExtentColor;
7 | import com.aventstack.extentreports.markuputils.MarkupHelper;
8 | import com.aventstack.extentreports.model.Media;
9 | import org.apache.logging.log4j.Logger;
10 |
11 | import java.text.MessageFormat;
12 |
13 | /* -----------------------------------------------------------------------
14 | - ** Rest API Testing Framework using RestAssured **
15 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
16 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
17 | ----------------------------------------------------------------------- */
18 | public class ExtentTestManager {
19 |
20 | static ExtentReports extent = ExtentManager.getInstance();
21 |
22 | public static synchronized ExtentTest getTest() {
23 | return ExtentReporter
24 | .get((int) (Thread.currentThread().getId()));
25 | }
26 |
27 | public static synchronized ExtentTest startTest(String module, String testCase, String... params) {
28 | ExtentTest extentModule = ExtentModuleManager.getModule(module);
29 | String testCaseDescription = MessageFormat.format(testCase, params);
30 | ExtentTest test = extentModule.createNode(testCaseDescription);
31 | ExtentReporter.set((int) (Thread.currentThread().getId()), test);
32 |
33 | return test;
34 | }
35 |
36 | public static synchronized void endTest() {
37 | extent.flush();
38 | }
39 |
40 | public static synchronized void log(Logger logger, Status status, Object logObject) {
41 | ExtentTest test = getTest();
42 |
43 | if (logObject instanceof String) {
44 | test.log(status, (String) logObject);
45 | logger.info((String) logObject);
46 | } else if (logObject instanceof Throwable) {
47 | test.log(status, MarkupHelper.createCodeBlock(((Throwable) logObject).getMessage()));
48 | logger.info(((Throwable) logObject).getStackTrace().toString());
49 | } else if (logObject instanceof Media) {
50 | test.log(status, (Media) logObject);
51 | }
52 |
53 | }
54 |
55 | public static synchronized void step(Logger logger, String log) {
56 | ExtentTest test = getTest();
57 | test.log(Status.INFO, MarkupHelper.createLabel("Performing -> " + log, ExtentColor.INDIGO));
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/resources/log4j2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | [%highlight{%-5level}] %d{DEFAULT} %logger{36} - %msg%n%throwable{short.lineNumber}
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/main/resources/test.properties:
--------------------------------------------------------------------------------
1 | # APPLICATION DETAILS #
2 | app.url = http://198.71.61.246:9000/
3 |
4 | # APP SERVER DETAILS #
5 | app.server.ip = 198.71.61.246
6 | app.server.username = username
7 | app.server.password = password
8 |
9 | app.server.application.log = path-to-application-log-file
10 |
11 | # G E N E R A T E S E R V E R L O G S
12 | save.application.server.logs = No
13 | application.server.logs.lines = 1000
--------------------------------------------------------------------------------
/src/test/java/TC_AddUserAPI.java:
--------------------------------------------------------------------------------
1 | import framework.model.User;
2 | import framework.service.UserProfileService;
3 | import framework.utils.common.Randomizer;
4 | import framework.utils.exceptions.AutomationException;
5 | import framework.utils.globalConstants.HttpStatus;
6 | import framework.utils.initializers.TestInit;
7 | import framework.utils.reportManagement.extent.ExtentTestManager;
8 | import org.testng.annotations.Test;
9 |
10 | import static org.assertj.core.api.Assertions.assertThat;
11 |
12 | /* -----------------------------------------------------------------------
13 | - ** Rest API Testing Framework using RestAssured **
14 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
15 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
16 | ----------------------------------------------------------------------- */
17 | public class TC_AddUserAPI extends TestInit {
18 |
19 | /**
20 | * Test Case: TC02_AddUserProfile
21 | * Test Type: Positive
22 | * Description: To verify that user is able to add new user in system through API
23 | *
24 | * @throws AutomationException
25 | */
26 | @Test
27 | public void TC02_AddUserProfile() throws AutomationException {
28 |
29 | ExtentTestManager.startTest("Add User Profile", "To verify that user is able to add new users in system through API");
30 |
31 | User userToCreate = new User(Randomizer.randomNumberWithoutZero(5));
32 | User createdUser = (User) UserProfileService
33 | .init()
34 | .addUserProfiles(userToCreate)
35 | .getResponse();
36 |
37 | assertThat(createdUser).usingRecursiveComparison().ignoringFields("id").isEqualTo(userToCreate);
38 |
39 | }
40 |
41 | /**
42 | * Test Case: TC03_AddUserProfileExistingUserId
43 | * Test Type: Negative
44 | * Description: To verify that user is not able to add new user in system through API if provided userID already exists in system
45 | *
46 | * @throws AutomationException
47 | */
48 | @Test
49 | public void TC03_AddUserProfileExistingUserId() throws AutomationException {
50 |
51 | ExtentTestManager.startTest("Add User Profile", "To verify that user is not able to add new user in system through API if provided userID already exists in system");
52 |
53 | User userToCreate = new User(Randomizer.randomNumberWithoutZero(5));
54 | userToCreate.setUserid("KRISHAN001");
55 |
56 | UserProfileService
57 | .init()
58 | .isNegativeTest(HttpStatus.INTERNAL_SERVER_ERROR)
59 | .addUserProfiles(userToCreate);
60 |
61 | }
62 |
63 | /**
64 | * Test Case: TC04_AddUserProfileAlphabeticStatus
65 | * Test Type: Negative
66 | * Description: To verify that user is not able to add new user in system through API if provided status is not numeric
67 | *
68 | * @throws AutomationException
69 | */
70 | @Test
71 | public void TC04_AddUserProfileAlphabeticStatus() throws AutomationException {
72 |
73 | ExtentTestManager.startTest("Add User Profile", "To verify that user is not able to add new user in system through API if provided status is not numeric");
74 |
75 | User userToCreate = new User(Randomizer.randomNumberWithoutZero(5));
76 | userToCreate.setStatus("STATUS");
77 |
78 | UserProfileService
79 | .init()
80 | .isNegativeTest(HttpStatus.BAD_REQUEST)
81 | .addUserProfiles(userToCreate);
82 |
83 | }
84 |
85 | }
86 |
--------------------------------------------------------------------------------
/src/test/java/TC_DeleteUserAPI.java:
--------------------------------------------------------------------------------
1 | import framework.model.User;
2 | import framework.service.UserProfileService;
3 | import framework.utils.common.Randomizer;
4 | import framework.utils.exceptions.AutomationException;
5 | import framework.utils.globalConstants.HttpStatus;
6 | import framework.utils.initializers.TestInit;
7 | import framework.utils.reportManagement.extent.ExtentTestManager;
8 | import org.testng.annotations.Test;
9 |
10 | import java.util.List;
11 |
12 | import static org.assertj.core.api.Assertions.assertThat;
13 |
14 | /* -----------------------------------------------------------------------
15 | - ** Rest API Testing Framework using RestAssured **
16 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
17 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
18 | ----------------------------------------------------------------------- */
19 | public class TC_DeleteUserAPI extends TestInit {
20 |
21 | /**
22 | * Test Case: TC09_DeleteUserProfile
23 | * Test Type: Positive
24 | * Description: To verify that user is able to delete existing user in system through API
25 | *
26 | * @throws AutomationException
27 | */
28 | @Test
29 | public void TC09_DeleteUserProfile() throws AutomationException {
30 |
31 | ExtentTestManager.startTest("Delete User Profile", "To verify that user is able to delete existing user in system through API");
32 |
33 | User createdUser = (User) UserProfileService
34 | .init()
35 | .addUserProfiles(new User(Randomizer.randomNumberWithoutZero(5)))
36 | .getResponse();
37 |
38 | UserProfileService
39 | .init()
40 | .deleteUserProfiles(createdUser.getUserid());
41 |
42 | }
43 |
44 | /**
45 | * Test Case: TC10_DeleteUserProfile
46 | * Test Type: Negative
47 | * Description: To verify that user is able to delete user in system if userid provided does not exist through API
48 | *
49 | * @throws AutomationException
50 | */
51 | @Test
52 | public void TC10_DeleteUserProfile() throws AutomationException {
53 |
54 | ExtentTestManager.startTest("Delete User Profile", "To verify that user is able to delete user in system if userid provided does not exist through API");
55 |
56 | List userList = (List) UserProfileService
57 | .init()
58 | .getUserProfiles()
59 | .getResponse();
60 |
61 | User userToDelete = userList.get(1);
62 | userToDelete.setUserid("SampleInvalidUserID");
63 |
64 | UserProfileService
65 | .init()
66 | .isNegativeTest(HttpStatus.INTERNAL_SERVER_ERROR)
67 | .modifyUserProfiles(userToDelete);
68 |
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/src/test/java/TC_GetAllUsersAPI.java:
--------------------------------------------------------------------------------
1 | import framework.service.UserProfileService;
2 | import framework.utils.exceptions.AutomationException;
3 | import framework.utils.initializers.TestInit;
4 | import framework.utils.reportManagement.extent.ExtentTestManager;
5 | import org.testng.annotations.Test;
6 |
7 | /* -----------------------------------------------------------------------
8 | - ** Rest API Testing Framework using RestAssured **
9 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
10 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
11 | ----------------------------------------------------------------------- */
12 | public class TC_GetAllUsersAPI extends TestInit {
13 |
14 | /**
15 | * Test Case: TC01_GetAllUsers
16 | * Description: To verify that user is able to get all users in system through API
17 | *
18 | * @throws AutomationException
19 | */
20 | @Test
21 | public void TC01_GetAllUsers() throws AutomationException {
22 |
23 | ExtentTestManager.startTest("Get All Users", "To verify that user is able to get all users in system through API");
24 |
25 | UserProfileService
26 | .init()
27 | .getUserProfiles();
28 |
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/java/TC_GetUserByID.java:
--------------------------------------------------------------------------------
1 | import framework.service.UserProfileService;
2 | import framework.utils.exceptions.AutomationException;
3 | import framework.utils.globalConstants.HttpStatus;
4 | import framework.utils.initializers.TestInit;
5 | import framework.utils.reportManagement.extent.ExtentTestManager;
6 | import org.testng.annotations.Test;
7 |
8 | /* -----------------------------------------------------------------------
9 | - ** Rest API Testing Framework using RestAssured **
10 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
11 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
12 | ----------------------------------------------------------------------- */
13 | public class TC_GetUserByID extends TestInit {
14 |
15 | /**
16 | * Test Case: TC05_GetUserByID
17 | * Description: To verify that user is able to get user details through API
18 | *
19 | * @throws AutomationException
20 | */
21 | @Test
22 | public void TC05_GetUserByID() throws AutomationException {
23 |
24 | ExtentTestManager.startTest("Get User By ID", "To verify that user is able to get user details through API if userid is provided");
25 |
26 | UserProfileService
27 | .init()
28 | .getUserProfileByID("KRISHAN001");
29 |
30 | }
31 |
32 | /**
33 | * Test Case: TC06_GetUserByIDInvalidUserID
34 | * Test Type: Negative
35 | * Description: To verify that user is not able to get user details through API if userid provided does not exist
36 | *
37 | * @throws AutomationException
38 | */
39 | @Test
40 | public void TC06_GetUserByIDInvalidUserID() throws AutomationException {
41 |
42 | ExtentTestManager.startTest("Get User By ID", "To verify that user is not able to get user details through API if userid provided does not exist");
43 |
44 | UserProfileService
45 | .init()
46 | .isNegativeTest(HttpStatus.INTERNAL_SERVER_ERROR)
47 | .getUserProfileByID("INVALIDTESTID");
48 |
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/src/test/java/TC_ModifyUserAPI.java:
--------------------------------------------------------------------------------
1 | import framework.model.User;
2 | import framework.service.UserProfileService;
3 | import framework.utils.common.Randomizer;
4 | import framework.utils.exceptions.AutomationException;
5 | import framework.utils.globalConstants.HttpStatus;
6 | import framework.utils.initializers.TestInit;
7 | import framework.utils.reportManagement.extent.ExtentTestManager;
8 | import org.testng.annotations.Test;
9 |
10 | import java.util.List;
11 |
12 | import static org.assertj.core.api.Assertions.assertThat;
13 |
14 | /* -----------------------------------------------------------------------
15 | - ** Rest API Testing Framework using RestAssured **
16 | - Author: Krishan Chawla (krishanchawla1467@gmail.com)
17 | - Git Repo: https://github.com/krishanchawla/api-testing-rest-assured-java-framework
18 | ----------------------------------------------------------------------- */
19 | public class TC_ModifyUserAPI extends TestInit {
20 |
21 | /**
22 | * Test Case: TC07_ModifyUserProfile
23 | * Test Type: Positive
24 | * Description: To verify that user is able to modify existing user in system through API
25 | *
26 | * @throws AutomationException
27 | */
28 | @Test
29 | public void TC07_ModifyUserProfile() throws AutomationException {
30 |
31 | ExtentTestManager.startTest("Modify User Profile", "To verify that user is able to modify existing user in system through API");
32 |
33 | List userList = (List) UserProfileService
34 | .init()
35 | .getUserProfiles()
36 | .getResponse();
37 |
38 | User userToModify = userList.get(1);
39 | userToModify.setFirstname("ModifiedFirstName" + Randomizer.randomNumeric(5));
40 |
41 | User createdUser = (User) UserProfileService
42 | .init()
43 | .modifyUserProfiles(userToModify)
44 | .getResponse();
45 |
46 | assertThat(createdUser).usingRecursiveComparison().isEqualTo(userToModify);
47 |
48 | }
49 |
50 | /**
51 | * Test Case: TC08_ModifyUserProfile
52 | * Test Type: Negative
53 | * Description: To verify that user is able to modify user in system if userid provided does not exist through API
54 | *
55 | * @throws AutomationException
56 | */
57 | @Test
58 | public void TC08_ModifyUserProfile() throws AutomationException {
59 |
60 | ExtentTestManager.startTest("Modify User Profile", "To verify that user is able to modify user in system if userid provided does not exist through API");
61 |
62 | List userList = (List) UserProfileService
63 | .init()
64 | .getUserProfiles()
65 | .getResponse();
66 |
67 | User userToModify = userList.get(1);
68 | userToModify.setUserid("SampleInvalidUserID");
69 |
70 | UserProfileService
71 | .init()
72 | .isNegativeTest(HttpStatus.INTERNAL_SERVER_ERROR)
73 | .modifyUserProfiles(userToModify);
74 |
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/testng.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------