From 56e3d487a5c940ad0806a38178289f2e46e88e5e Mon Sep 17 00:00:00 2001 From: Anh Tester Date: Tue, 27 Feb 2024 22:14:54 +0700 Subject: [PATCH] =?UTF-8?q?B=C3=A0i=2015=2016=20TestListener=20and=20Log4j?= =?UTF-8?q?2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + pom.xml | 20 +++++- .../com/anhtester/globals/ConfigsGlobal.java | 3 + .../java/com/anhtester/utils/LogUtils.java | 54 +++++++++++++++ src/main/resources/log4j2.properties | 25 +++++++ src/main/resources/log4j2_OFF.xml | 21 ++++++ .../CategoryTest_Listener.java | 68 ++++++++++++++++++ .../Bai16_Log4j2/CategoryTest_Log4j2.java | 69 +++++++++++++++++++ .../java/com/anhtester/common/BaseTest.java | 13 +--- .../com/anhtester/listeners/TestListener.java | 62 +++++++++++++++++ .../resources/testdata/CreateCategory.json | 2 +- suites/SuiteDemoListener.xml | 15 ++++ 12 files changed, 339 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/anhtester/utils/LogUtils.java create mode 100644 src/main/resources/log4j2.properties create mode 100644 src/main/resources/log4j2_OFF.xml create mode 100644 src/test/java/com/anhtester/Bai15_TestListener/CategoryTest_Listener.java create mode 100644 src/test/java/com/anhtester/Bai16_Log4j2/CategoryTest_Log4j2.java create mode 100644 src/test/java/com/anhtester/listeners/TestListener.java create mode 100644 suites/SuiteDemoListener.xml diff --git a/.gitignore b/.gitignore index 2fc9d21..9111725 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ logs/ *.log *.avi *.mp4 +test-output/ diff --git a/pom.xml b/pom.xml index aee6341..9677169 100644 --- a/pom.xml +++ b/pom.xml @@ -40,13 +40,13 @@ org.slf4j slf4j-api - 2.1.0-alpha1 + 2.0.11 org.slf4j slf4j-simple - 2.1.0-alpha1 + 2.0.11 @@ -68,7 +68,21 @@ net.datafaker datafaker - 2.0.2 + 2.1.0 + + + + + org.apache.logging.log4j + log4j-core + 2.23.0 + + + + + org.apache.logging.log4j + log4j-api + 2.23.0 diff --git a/src/main/java/com/anhtester/globals/ConfigsGlobal.java b/src/main/java/com/anhtester/globals/ConfigsGlobal.java index 52c1d46..849dceb 100644 --- a/src/main/java/com/anhtester/globals/ConfigsGlobal.java +++ b/src/main/java/com/anhtester/globals/ConfigsGlobal.java @@ -6,4 +6,7 @@ public class ConfigsGlobal { public static String URI = PropertiesHelper.getValue("URI"); public static String USERNAME = PropertiesHelper.getValue("USERNAME"); public static String PASSWORD = PropertiesHelper.getValue("PASSWORD"); + public static int TCS_TOTAL; + public static int PASSED_TOTAL; + public static int FAILED_TOTAL; } diff --git a/src/main/java/com/anhtester/utils/LogUtils.java b/src/main/java/com/anhtester/utils/LogUtils.java new file mode 100644 index 0000000..36cf7bf --- /dev/null +++ b/src/main/java/com/anhtester/utils/LogUtils.java @@ -0,0 +1,54 @@ +package com.anhtester.utils; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class LogUtils { + //Initialize Log4j instance + private static final Logger Log = LogManager.getLogger(LogUtils.class); + + //Info Level Logs + public static void info(String message) { + Log.info(message); + } + + public static void info(Object object) { + Log.info(object); + } + + //Warn Level Logs + public static void warn(String message) { + Log.warn(message); + } + + public static void warn(Object object) { + Log.warn(object); + } + + //Error Level Logs + public static void error(String message) { + Log.error(message); + } + + public static void error(Object object) { + Log.error(object); + } + + //Fatal Level Logs + public static void fatal(String message) { + Log.fatal(message); + } + + public static void fatal(Object message) { + Log.fatal(message); + } + + //Debug Level Logs + public static void debug(String message) { + Log.debug(message); + } + + public static void debug(Object object) { + Log.debug(object); + } +} \ No newline at end of file diff --git a/src/main/resources/log4j2.properties b/src/main/resources/log4j2.properties new file mode 100644 index 0000000..70bee00 --- /dev/null +++ b/src/main/resources/log4j2.properties @@ -0,0 +1,25 @@ +name=PropertiesConfigLog4j2 +property.filename=logs/applog.log +appenders=console, file + +appender.console.type=Console +appender.console.name=STDOUT +appender.console.layout.type=PatternLayout +appender.console.layout.pattern=[%level] %d{dd-MM-yyyy HH:mm:ss} [%t] %c{1} - %msg%n + +appender.file.type=File +appender.file.name=LOGFILE +appender.file.fileName=${filename} +appender.file.layout.type=PatternLayout +appender.file.layout.pattern=[%level] %d{dd-MM-yyyy HH:mm:ss} [%t] %c{1} - %msg%n + +loggers=file +logger.file.name=LOGFILE +logger.file.level=info +logger.file.appenderRefs=file +logger.file.appenderRef.file.ref=LOGFILE + +rootLogger.level=info +rootLogger.appenderRefs=stdout, file +rootLogger.appenderRef.stdout.ref=STDOUT +rootLogger.appenderRef.file.ref=LOGFILE \ No newline at end of file diff --git a/src/main/resources/log4j2_OFF.xml b/src/main/resources/log4j2_OFF.xml new file mode 100644 index 0000000..7df731c --- /dev/null +++ b/src/main/resources/log4j2_OFF.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/java/com/anhtester/Bai15_TestListener/CategoryTest_Listener.java b/src/test/java/com/anhtester/Bai15_TestListener/CategoryTest_Listener.java new file mode 100644 index 0000000..312b682 --- /dev/null +++ b/src/test/java/com/anhtester/Bai15_TestListener/CategoryTest_Listener.java @@ -0,0 +1,68 @@ +package com.anhtester.Bai15_TestListener; + +import com.anhtester.common.BaseTest; +import com.anhtester.globals.TokenGlobal; +import com.anhtester.listeners.TestListener; +import io.restassured.http.ContentType; +import io.restassured.path.json.JsonPath; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.testng.Assert; +import org.testng.TestListenerAdapter; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; +import org.testng.reporters.TestHTMLReporter; + +import java.io.File; + +import static io.restassured.RestAssured.given; + +//@Listeners(TestListener.class) +//@Listeners(value = {TestListener.class, TestListenerAdapter.class, TestHTMLReporter.class}) +public class CategoryTest_Listener extends BaseTest { + + int CATEGORY_ID; + + @Test(priority = 1) + public void testAddNewCategory() { + System.out.println("Create Category"); + String dataFile = "src/test/resources/testdata/CreateCategory.json"; + + RequestSpecification request = given(); + request.baseUri("https://api.anhtester.com/api") + .accept(ContentType.JSON) + .contentType(ContentType.JSON) + .header("Authorization", "Bearer " + TokenGlobal.TOKEN) + .body(new File(dataFile)); + + Response response = request.post("/category"); + + response.prettyPrint(); + response.then().statusCode(200); + + CATEGORY_ID = Integer.parseInt(response.path("response.id").toString()); + System.out.println(CATEGORY_ID); + + } + + @Test(priority = 2) + public void getCategoryById() { + System.out.println("Get Category By Id"); + + RequestSpecification request = given(); + request.baseUri("https://api.anhtester.com/api") + .accept(ContentType.JSON) + .contentType(ContentType.JSON) + .header("Authorization", "Bearer " + TokenGlobal.TOKEN); + + System.out.println("CATEGORY_ID: " + CATEGORY_ID); + Response response = request.get("/category/" + CATEGORY_ID); + + response.prettyPrint(); + response.then().statusCode(200); + + JsonPath jsonPath = response.jsonPath(); + Assert.assertEquals(jsonPath.get("response.name"), "Auto API A5", "The Category Name not match."); + + } +} \ No newline at end of file diff --git a/src/test/java/com/anhtester/Bai16_Log4j2/CategoryTest_Log4j2.java b/src/test/java/com/anhtester/Bai16_Log4j2/CategoryTest_Log4j2.java new file mode 100644 index 0000000..68c06d4 --- /dev/null +++ b/src/test/java/com/anhtester/Bai16_Log4j2/CategoryTest_Log4j2.java @@ -0,0 +1,69 @@ +package com.anhtester.Bai16_Log4j2; + +import com.anhtester.common.BaseTest; +import com.anhtester.globals.TokenGlobal; +import com.anhtester.listeners.TestListener; +import com.anhtester.utils.LogUtils; +import io.restassured.http.ContentType; +import io.restassured.path.json.JsonPath; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.testng.Assert; +import org.testng.TestListenerAdapter; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; +import org.testng.reporters.TestHTMLReporter; + +import java.io.File; + +import static io.restassured.RestAssured.given; + +//@Listeners(TestListener.class) +@Listeners(value = {TestListener.class, TestListenerAdapter.class, TestHTMLReporter.class}) +public class CategoryTest_Log4j2 extends BaseTest { + + int CATEGORY_ID; + + @Test(priority = 1) + public void testAddNewCategory() { + LogUtils.info("Create Category"); + String dataFile = "src/test/resources/testdata/CreateCategory.json"; + + RequestSpecification request = given(); + request.baseUri("https://api.anhtester.com/api") + .accept(ContentType.JSON) + .contentType(ContentType.JSON) + .header("Authorization", "Bearer " + TokenGlobal.TOKEN) + .body(new File(dataFile)); + + Response response = request.post("/category"); + LogUtils.info(response.prettyPrint()); + response.prettyPrint(); + response.then().statusCode(200); + + CATEGORY_ID = Integer.parseInt(response.path("response.id").toString()); + LogUtils.info(CATEGORY_ID); + + } + + @Test(priority = 2) + public void getCategoryById() { + LogUtils.info("Get Category By Id"); + + RequestSpecification request = given(); + request.baseUri("https://api.anhtester.com/api") + .accept(ContentType.JSON) + .contentType(ContentType.JSON) + .header("Authorization", "Bearer " + TokenGlobal.TOKEN); + + LogUtils.info("CATEGORY_ID: " + CATEGORY_ID); + Response response = request.get("/category/" + CATEGORY_ID); + LogUtils.info(response.prettyPrint()); + response.prettyPrint(); + response.then().statusCode(200); + + JsonPath jsonPath = response.jsonPath(); + Assert.assertEquals(jsonPath.get("response.name"), "Auto API A5", "The Category Name not match."); + + } +} \ No newline at end of file diff --git a/src/test/java/com/anhtester/common/BaseTest.java b/src/test/java/com/anhtester/common/BaseTest.java index fca6abd..3b3fcfa 100644 --- a/src/test/java/com/anhtester/common/BaseTest.java +++ b/src/test/java/com/anhtester/common/BaseTest.java @@ -3,25 +3,19 @@ import com.anhtester.globals.ConfigsGlobal; import com.anhtester.globals.TokenGlobal; import com.anhtester.helpers.PropertiesHelper; +import com.anhtester.listeners.TestListener; import com.anhtester.model.LoginPOJO; import com.anhtester.model.data.LoginPOJO_Builder; import com.google.gson.Gson; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.BeforeTest; +import org.testng.annotations.*; import static io.restassured.RestAssured.given; +@Listeners(TestListener.class) public class BaseTest { - @BeforeClass - public void beforeClass(){ - System.out.println("This is before class CHA"); - } - @BeforeSuite public void setupSuite() { PropertiesHelper.loadAllFiles(); @@ -29,7 +23,6 @@ public void setupSuite() { @BeforeTest public void loginUser() { - //LoginPOJO loginPOJO = new LoginPOJO(ConfigsGlobal.USERNAME, ConfigsGlobal.PASSWORD); LoginPOJO loginPOJO = LoginPOJO_Builder.getDataLogin(); Gson gson = new Gson(); diff --git a/src/test/java/com/anhtester/listeners/TestListener.java b/src/test/java/com/anhtester/listeners/TestListener.java new file mode 100644 index 0000000..c60d85d --- /dev/null +++ b/src/test/java/com/anhtester/listeners/TestListener.java @@ -0,0 +1,62 @@ +package com.anhtester.listeners; + +import com.anhtester.globals.ConfigsGlobal; +import com.anhtester.utils.LogUtils; +import org.testng.ITestContext; +import org.testng.ITestListener; +import org.testng.ITestResult; + +public class TestListener implements ITestListener { + @Override + public void onStart(ITestContext result) { + LogUtils.info("\n **********************************"); + //Read Properties - loadAllFiles() + //Select Database - lưu trữ vào biến toàn cục + //Connect tới bên thứ 3 cho thuê reports chẳng hạn + } + + @Override + public void onFinish(ITestContext result) { + //Tổng kết lại tình hình chạy test + //In ra logs cho biết là đã kết thức và chạy được bao nhiêu cái pass/fail + //Gửi mail đến mail chung để nắm bắt tình hình - Lấy ra các biến toàn cục hoặc file logs, report + LogUtils.info("Đã gửi mail đến admin@anhtester.com"); + LogUtils.info("Tổng số test cases: " + ConfigsGlobal.TCS_TOTAL); + LogUtils.info("Số test cases passed: " + ConfigsGlobal.PASSED_TOTAL); + LogUtils.info("Số test cases failed: " + ConfigsGlobal.FAILED_TOTAL); + } + + @Override + public void onTestStart(ITestResult result) { + LogUtils.info("Đang chạy test case: " + result.getName()); + //Mình sẽ bắt cái tên TCs để ghi logs và ghi vào report (Allure report) + ConfigsGlobal.TCS_TOTAL++; + } + + @Override + public void onTestSuccess(ITestResult result) { + //Cộng 1 đơn vị vào 1 biến toàn cục để nắm bắt số lượng tcs pass + LogUtils.info("Test case passed: " + result.getName()); + ConfigsGlobal.PASSED_TOTAL++; + } + + @Override + public void onTestFailure(ITestResult result) { + //Cộng 1 đơn vị vào 1 biến toàn cục để nắm bắt số lượng tcs fail + LogUtils.error("Test case failed: " + result.getName()); + LogUtils.error(result.getThrowable()); + ConfigsGlobal.FAILED_TOTAL++; + } + + @Override + public void onTestFailedButWithinSuccessPercentage(ITestResult result) { + // TODO Auto-generated method stub + + } + + @Override + public void onTestSkipped(ITestResult result) { + // TODO Auto-generated method stub + + } +} diff --git a/src/test/resources/testdata/CreateCategory.json b/src/test/resources/testdata/CreateCategory.json index e5e64db..0bdc52e 100644 --- a/src/test/resources/testdata/CreateCategory.json +++ b/src/test/resources/testdata/CreateCategory.json @@ -1 +1 @@ -{"name":"Internal Hospitality Designer"} \ No newline at end of file +{"name":"Auto API A12"} \ No newline at end of file diff --git a/suites/SuiteDemoListener.xml b/suites/SuiteDemoListener.xml new file mode 100644 index 0000000..f327696 --- /dev/null +++ b/suites/SuiteDemoListener.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file