Best Carina code snippet using com.qaprosoft.carina.core.foundation.report.email.EmailReportItemCollector
Source:AbstractTest.java  
...62import com.qaprosoft.carina.core.foundation.report.TestResultItem;63import com.qaprosoft.carina.core.foundation.report.TestResultType;64import com.qaprosoft.carina.core.foundation.report.email.EmailManager;65import com.qaprosoft.carina.core.foundation.report.email.EmailReportGenerator;66import com.qaprosoft.carina.core.foundation.report.email.EmailReportItemCollector;67import com.qaprosoft.carina.core.foundation.report.spira.Spira;68import com.qaprosoft.carina.core.foundation.report.testrail.TestRail;69import com.qaprosoft.carina.core.foundation.utils.Configuration;70import com.qaprosoft.carina.core.foundation.utils.Configuration.DriverMode;71import com.qaprosoft.carina.core.foundation.utils.Configuration.Parameter;72import com.qaprosoft.carina.core.foundation.utils.DateUtils;73import com.qaprosoft.carina.core.foundation.utils.JsonUtils;74import com.qaprosoft.carina.core.foundation.utils.Messager;75import com.qaprosoft.carina.core.foundation.utils.R;76import com.qaprosoft.carina.core.foundation.utils.SpecialKeywords;77import com.qaprosoft.carina.core.foundation.utils.metadata.MetadataCollector;78import com.qaprosoft.carina.core.foundation.utils.metadata.model.ElementsInfo;79import com.qaprosoft.carina.core.foundation.utils.naming.TestNamingUtil;80import com.qaprosoft.carina.core.foundation.utils.resources.I18N;81import com.qaprosoft.carina.core.foundation.utils.resources.L10N;82import com.qaprosoft.carina.core.foundation.utils.resources.L10Nparser;83import com.qaprosoft.carina.core.foundation.webdriver.DriverPool;84import com.qaprosoft.carina.core.foundation.webdriver.device.DevicePool;85/*86 * AbstractTest - base test for UI and API tests.87 * 88 * @author Alex Khursevich89 */90@Listeners({AbstractTestListener.class})91public abstract class AbstractTest // extends DriverHelper92{93    protected static final Logger LOGGER = Logger.getLogger(AbstractTest.class);94    protected APIMethodBuilder apiMethodBuilder;95    protected static final long IMPLICIT_TIMEOUT = Configuration.getLong(Parameter.IMPLICIT_TIMEOUT);96    protected static final long EXPLICIT_TIMEOUT = Configuration.getLong(Parameter.EXPLICIT_TIMEOUT);97    protected static final String SUITE_TITLE = "%s%s%s - %s (%s%s)";98    protected static final String XML_SUITE_NAME = " (%s)";99    protected static ThreadLocal<String> suiteNameAppender = new ThreadLocal<String>();100    101    // 3rd party integrations102    protected String browserVersion = "";103    protected long startDate;104    @BeforeSuite(alwaysRun = true)105    public void executeBeforeTestSuite(ITestContext context) throws Throwable {106    	107    	DevicePool.addDevices();108        // Add shutdown hook109        Runtime.getRuntime().addShutdownHook(new ShutdownHook());110        // Set log4j properties111        PropertyConfigurator.configure(ClassLoader.getSystemResource("log4j.properties"));112        // Set SoapUI log4j properties113        System.setProperty("soapui.log4j.config", "./src/main/resources/soapui-log4j.xml");114        try {115            Logger root = Logger.getRootLogger();116            Enumeration<?> allLoggers = root.getLoggerRepository().getCurrentCategories();117            while (allLoggers.hasMoreElements()) {118                Category tmpLogger = (Category) allLoggers.nextElement();119                if (tmpLogger.getName().equals("com.qaprosoft.carina.core")) {120                    tmpLogger.setLevel(Level.toLevel(Configuration.get(Parameter.CORE_LOG_LEVEL)));121                }122            }123        } catch (NoSuchMethodError e) {124            LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!");125        }126        startDate = new Date().getTime();127        LOGGER.info(Configuration.asString());128        // Configuration.validateConfiguration();129        LOGGER.debug("Default thread_count=" + context.getCurrentXmlTest().getSuite().getThreadCount());130        context.getCurrentXmlTest().getSuite().setThreadCount(Configuration.getInt(Parameter.THREAD_COUNT));131        LOGGER.debug("Updated thread_count=" + context.getCurrentXmlTest().getSuite().getThreadCount());132        // update DataProviderThreadCount if any property is provided otherwise sync with value from suite xml file133        int count = Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT);134        if (count > 0) {135            LOGGER.debug("Updated 'data_provider_thread_count' from "136                    + context.getCurrentXmlTest().getSuite().getDataProviderThreadCount() + " to " + count);137            context.getCurrentXmlTest().getSuite().setDataProviderThreadCount(count);138        } else {139            LOGGER.debug("Synching data_provider_thread_count with values from suite xml file...");140            R.CONFIG.put(Parameter.DATA_PROVIDER_THREAD_COUNT.getKey(), String.valueOf(context.getCurrentXmlTest().getSuite().getDataProviderThreadCount()));141            LOGGER.debug("Updated 'data_provider_thread_count': " + Configuration.getInt(Parameter.DATA_PROVIDER_THREAD_COUNT));142        }143        LOGGER.debug("Default data_provider_thread_count="144                + context.getCurrentXmlTest().getSuite().getDataProviderThreadCount());145        LOGGER.debug("Updated data_provider_thread_count="146                + context.getCurrentXmlTest().getSuite().getDataProviderThreadCount());147        if (!Configuration.isNull(Parameter.URL)) {148            if (!Configuration.get(Parameter.URL).isEmpty()) {149                RestAssured.baseURI = Configuration.get(Parameter.URL);150            }151        }152        try {153            L10N.init();154        } catch (Exception e) {155            LOGGER.error("L10N bundle is not initialized successfully!", e);156        }157        try {158            I18N.init();159        } catch (Exception e) {160            LOGGER.error("I18N bundle is not initialized successfully!", e);161        }162        try {163            L10Nparser.init();164        } catch (Exception e) {165            LOGGER.error("L10Nparser bundle is not initialized successfully!", e);166        }167        try {168        	TestRail.updateBeforeSuite(context, this.getClass().getName(), getTitle(context));169        } catch (Exception e) {170        	LOGGER.error("TestRail is not initialized successfully!", e);171        }172		try {173			if (!Configuration.get(Parameter.ACCESS_KEY_ID).isEmpty()) {174				LOGGER.info("Initializing AWS S3 client...");175				AmazonS3Manager.getInstance().initS3client(Configuration.get(Parameter.ACCESS_KEY_ID),176						Configuration.get(Parameter.SECRET_KEY));177				updateS3AppPath();178			}179		} catch (Exception e) {180            LOGGER.error("AWS S3 client is not initialized successfully!", e);181		}182        183        // moved from UITest->executeBeforeTestSuite184        String customCapabilities = Configuration.get(Parameter.CUSTOM_CAPABILITIES);185        if (!customCapabilities.isEmpty()) {186            //redefine core properties using custom capabilities file187        	Map<String, String> properties = Configuration.loadCoreProperties(customCapabilities);188            //reregister device if mobile core properties are redefined 189            DevicePool.addDevice(properties);190        }191    }192    193    @BeforeClass(alwaysRun = true)194    public void executeBeforeTestClass(ITestContext context) throws Throwable {195        // do nothing for now196    }197    @AfterClass(alwaysRun = true)198    public void executeAfterTestClass(ITestContext context) throws Throwable {199        if (Configuration.getDriverMode() == DriverMode.CLASS_MODE) {200            LOGGER.debug("Deinitialize driver(s) in UITest->AfterClass.");201            quitDrivers();202        }203    }204    @BeforeMethod(alwaysRun = true)205    public void executeBeforeTestMethod(XmlTest xmlTest, Method testMethod,206                                        ITestContext context) throws Throwable {207        // do nothing for now208        Spira.registerStepsFromAnnotation(testMethod);209        210        apiMethodBuilder = new APIMethodBuilder();211    }212    213    214    @AfterMethod(alwaysRun = true)215    public void executeAfterTestMethod(ITestResult result) {216        try {217            DriverMode driverMode = Configuration.getDriverMode();218            if (driverMode == DriverMode.METHOD_MODE) {219                LOGGER.debug("Deinitialize driver(s) in @AfterMethod.");220                quitDrivers();221            }222            // TODO: improve later removing duplicates with AbstractTestListener223            //handle Zafira already passed exception for re-run and do nothing. maybe return should be enough224            if (result.getThrowable() != null && result.getThrowable().getMessage() != null225                    && result.getThrowable().getMessage().startsWith(SpecialKeywords.ALREADY_PASSED)) {226                // [VD] it is prohibited to release TestInfoByThread in this place.!227                return;228            }229            //handle AbstractTest->SkipExecution230            if (result.getThrowable() != null && result.getThrowable().getMessage() != null231                    && result.getThrowable().getMessage().startsWith(SpecialKeywords.SKIP_EXECUTION)) {232                // [VD] it is prohibited to release TestInfoByThread in this place.!233                return;234            }235            String test = TestNamingUtil.getCanonicalTestName(result);236            List<String> tickets = Jira.getTickets(result);237            result.setAttribute(SpecialKeywords.JIRA_TICKET, tickets);238            Jira.updateAfterTest(result);239            // Populate Spira Steps240            Spira.updateAfterTest(result, (String) result.getTestContext().getAttribute(SpecialKeywords.TEST_FAILURE_MESSAGE), tickets);241            Spira.clear();242            // Populate TestRail Cases243            if (!R.ZAFIRA.getBoolean("zafira_enabled")){244                result.setAttribute(SpecialKeywords.TESTRAIL_CASES_ID, TestRail.getCases(result));245                TestRail.updateAfterTest(result, (String) result.getTestContext().getAttribute(SpecialKeywords.TEST_FAILURE_MESSAGE));246                TestRail.clearCases();247            }248            //we shouldn't deregister info here as all retries will not work249            //TestNamingUtil.releaseZafiraTest();250            // clear jira tickets to be sure that next test is not affected.251            Jira.clearTickets();252            Artifacts.clearArtifacts();253            try {254                ThreadLogAppender tla = (ThreadLogAppender) Logger.getRootLogger().getAppender("ThreadLogAppender");255                if (tla != null) {256                    tla.closeResource(test);257                }258            } catch (NoSuchMethodError e) {259                LOGGER.error("Unable to redefine logger level due to the conflicts between log4j and slf4j!");260            }261        } catch (Exception e) {262            LOGGER.error("Exception in AbstractTest->executeAfterTestMethod: " + e.getMessage());263            e.printStackTrace();264        }265    }266    @AfterSuite(alwaysRun = true)267    public void executeAfterTestSuite(ITestContext context) {268        try {269            if (Configuration.getDriverMode() == DriverMode.SUITE_MODE) {270                LOGGER.debug("Deinitialize driver(s) in UITest->AfterSuite.");271                quitDrivers();                272            }273            ReportContext.removeTempDir(); //clean temp artifacts directory274            HtmlReportGenerator.generate(ReportContext.getBaseDir().getAbsolutePath());275            String browser = getBrowser();276            String deviceName = getDeviceName();277            String suiteName = getSuiteName(context);278            String title = getTitle(context);279            TestResultType testResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults());280            String status = testResult.getName();281            title = status + ": " + title;282            String env = "";283            if (!Configuration.isNull(Parameter.ENV)) {284                env = Configuration.get(Parameter.ENV);285            }286            if (!Configuration.get(Parameter.URL).isEmpty()) {287                env += " - <a href='" + Configuration.get(Parameter.URL) + "'>" + Configuration.get(Parameter.URL) + "</a>";288            }289            ReportContext.getTempDir().delete();290            // Update JIRA291            Jira.updateAfterSuite(context, EmailReportItemCollector.getTestResults());292            // Update Spira293            Spira.updateAfterSuite(this.getClass().getName(), testResult, title + "; " + getCIJobReference(), suiteName, startDate);294            //generate and send email report by Zafira to test group of people295            String emailList = Configuration.get(Parameter.EMAIL_LIST);296            String failureEmailList = Configuration.get(Parameter.FAILURE_EMAIL_LIST);297            String senderEmail = Configuration.get(Parameter.SENDER_EMAIL);298            String senderPassword = Configuration.get(Parameter.SENDER_PASSWORD);299            // Generate and send email report using regular method300            EmailReportGenerator report = new EmailReportGenerator(title, env,301                    Configuration.get(Parameter.APP_VERSION), deviceName,302                    browser, DateUtils.now(), DateUtils.timeDiff(startDate), getCIJobReference(),303                    EmailReportItemCollector.getTestResults(),304                    EmailReportItemCollector.getCreatedItems());305            String emailContent = report.getEmailBody();306			 307            if (!R.ZAFIRA.getBoolean("zafira_enabled")) {308            	//Do not send email if run is running with enabled Zafira309	            EmailManager.send(title, emailContent,310	                    emailList,311	                    senderEmail,312	                    senderPassword);313	314	            if (testResult.equals(TestResultType.FAIL) && !failureEmailList.isEmpty()) {315	                EmailManager.send(title, emailContent,316	                        failureEmailList,317	                        senderEmail,318	                        senderPassword);319	            }320            }321            // Store emailable report under emailable-report.html322            ReportContext.generateHtmlReport(emailContent);323            printExecutionSummary(EmailReportItemCollector.getTestResults());324            TestResultType suiteResult = EmailReportGenerator.getSuiteResult(EmailReportItemCollector.getTestResults());325            switch (suiteResult) {326                case SKIP_ALL:327                    Assert.fail("All tests were skipped! Analyze logs to determine possible configuration issues.");328                    break;329                case SKIP_ALL_ALREADY_PASSED:330                    LOGGER.info("Nothing was executed in rerun mode because all tests already passed and registered in Zafira Repoting Service!");331                    break;332                default:333                    //do nothing334            }335            336        } catch (Exception e) {337            LOGGER.error("Exception in AbstractTest->executeAfterSuite: " + e.getMessage());338            e.printStackTrace();...Source:EmailTest.java  
...15 *******************************************************************************/16package com.qaprosoft.carina.core.foundation.reporting;17import com.qaprosoft.carina.core.foundation.report.TestResultItem;18import com.qaprosoft.carina.core.foundation.report.TestResultType;19import com.qaprosoft.carina.core.foundation.report.email.EmailReportItemCollector;20import com.qaprosoft.carina.core.foundation.report.email.EmailReportItemComparator;21import com.qaprosoft.carina.core.foundation.report.email.EmailValidator;22import org.testng.Assert;23import org.testng.annotations.Test;24public class EmailTest {25    private static final String EMAIL = "test123@gmail.com";26    private static final TestResultItem TEST_RESULT_ITEM1 = new TestResultItem("carina-reporting", "Test api 1", "", TestResultType.PASS,27            "", "", "");28    private static final TestResultItem TEST_RESULT_ITEM1_1 = new TestResultItem("carina-reporting", "Test api 1", "", TestResultType.PASS,29            "", "", "");30    private static final TestResultItem TEST_RESULT_ITEM2 = new TestResultItem("carina-reporting", "Test api 2", "", TestResultType.PASS,31            "", "", "");32    private static final TestResultItem TEST_RESULT_ITEM3 = new TestResultItem("carina-reporting", "Test api 3", "", TestResultType.PASS,33            "", "", "");34    private static final String CREATED_ITEM1 = "item 1";35    private static final String CREATED_ITEM2 = "item 2";36    @Test37    public void testEmailValidator() {38        EmailValidator emailValidator = new EmailValidator();39        Assert.assertTrue(emailValidator.validate(EMAIL), EMAIL + " is not validated email");40    }41    @Test42    public void testEmailReportCollector() {43        EmailReportItemCollector.push(TEST_RESULT_ITEM1);44        EmailReportItemCollector.push(TEST_RESULT_ITEM2);45        EmailReportItemCollector.push(TEST_RESULT_ITEM3);46        Assert.assertTrue(EmailReportItemCollector.getTestResults().contains(TEST_RESULT_ITEM1),47                TEST_RESULT_ITEM1.getTest() + " wasn't added to email report results map");48        Assert.assertTrue(EmailReportItemCollector.getTestResults().contains(TEST_RESULT_ITEM2),49                TEST_RESULT_ITEM2.getTest() + " wasn't added to email report results map");50        Assert.assertTrue(EmailReportItemCollector.getTestResults().contains(TEST_RESULT_ITEM3),51                TEST_RESULT_ITEM3.getTest() + " wasn't added to email report results map");52    }53    @Test54    public void testPushStringEmailReportCollector() {55        EmailReportItemCollector.push(CREATED_ITEM1);56        EmailReportItemCollector.push(CREATED_ITEM2);57        Assert.assertTrue(EmailReportItemCollector.getCreatedItems().contains(CREATED_ITEM1),58                CREATED_ITEM1 + " wasn't added to email created items list");59        Assert.assertTrue(EmailReportItemCollector.getCreatedItems().contains(CREATED_ITEM1),60                CREATED_ITEM2 + " wasn't added to email created items list");61    }62    @Test63    public void testEmailReportComparatorTheDifferentTestResultItems() {64        Assert.assertFalse(isEqual(TEST_RESULT_ITEM1, TEST_RESULT_ITEM2),65                TEST_RESULT_ITEM1.getTest() + " is the same as " + TEST_RESULT_ITEM2.getTest());66    }67    @Test68    public void testEmailReportComparatorTheSameTestResultItems() {69        Assert.assertTrue(isEqual(TEST_RESULT_ITEM1, TEST_RESULT_ITEM1_1),70                TEST_RESULT_ITEM1.getTest() + " is different than " + TEST_RESULT_ITEM1_1.getTest());71    }72    private boolean isEqual(TestResultItem testResultItem1, TestResultItem testResultItem2) {73        EmailReportItemComparator comparator = new EmailReportItemComparator();...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
