How to create report having classes and its corresponding tests with extent reports - extentreports

I have the following testng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="suite" verbose="8">
<parameter name="nodeURL" value=""></parameter>
<listeners>
<listener class-name="com.org.CustomExtentReporter"></listener>
</listeners>
<test name="Default test1">
<classes>
<class
name="com.org.SuiteConfiguration">
</class>
<class name="com.org.web.HomePage"> </class>
<class name="com.org.web.Dashboard"> </class>
</classes>
</test>
</suite>
In above xml i have two classes, these will create the report with 4 test node and its log in extent reports.
I want the report to be generated in the following manner:
Test Class1
Test case 1
Test case 2
Test Class2
Test case 1
Test case 2
Now when the user clicks on Test Case 1, the log/result will get displayed corresponding to test class only.
Can we do that using Extent Reporting? I am using ITestListener for testng reporting.
public class CustomExtentReporter implements ITestListener {
ExtentReports extent = ExtentManager.getInstance();
public static ExtentTest test;
public void onTestStart(ITestResult result) {
//System.out.println("onTestStart called ...");
test = extent.createTest(result.getMethod().getMethodName());
}
public void onTestSuccess(ITestResult result) {
//test = extent.createTest("passTest");
//System.out.println("onTestSuccess called ...");
test.log(Status.PASS, MarkupHelper.createLabel(result.getMethod().getMethodName() + "Test Case Status is passed", ExtentColor.GREEN));
}
public void onTestFailure(ITestResult result) {
WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");
//System.out.println("onTestFailure called ...");
//test.log(Status.FAIL, MarkupHelper.createLabel(result.getMethod().getMethodName() + " - Test Case Failed", ExtentColor.RED));
String screenShotPath = ScreenShotRecorder.captureScreenshot(driver, result.getMethod().getMethodName());
test.log(Status.FAIL, MarkupHelper.createLabel(result.getThrowable() + " - Test Case Failed", ExtentColor.RED));
try {
test.fail(result.getThrowable()).addScreenCaptureFromPath(screenShotPath);
} catch (IOException e) {
test.log(Status.FAIL, "!!!!!!!!! Exception occurred while attaching the screenshot to extent report");
}
//test.log(Status.FAIL, MarkupHelper.createLabel(result.getThrowable() + " - Test Case Failed", ExtentColor.RED));
}
public void onTestSkipped(ITestResult result) {
test.log(Status.SKIP, MarkupHelper.createLabel(result.getMethod().getMethodName() + " - Test Case Skipped", ExtentColor.ORANGE));
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
//System.out.println("onTestFailedButWithinSuccessPercentage called ...");
}
public void onStart(ITestContext context) {
//System.out.println("onStart called ...");
//System.out.println("test name ::: "+ context.getName());
//test = extent.createTest(context.getName());
}
public void onFinish(ITestContext context) {
//System.out.println("onFinish called ...");
extent.flush();
extent.removeTest(test);
}

Related

Execution Flow of Actuator

I have Actuator implemented in spring boot application and these actuator code are executed when i'm running main class from some ide like Eclipse but when i'm running .jar from terminal this code is not executed at run time. Is their any difference on running main class or running jar in spring boot actuator ?
I have tried by putting some sysout and its getting printed when running main class but not when running jar file.
#Component
public class MicroServiceInfoConfiguror implements HealthIndicator, InfoContributor {
private static final Logger logger = LoggerFactory.getLogger(MicroserviceHealthIndicator.class);
#PersistenceContext
private EntityManager em;
#Override
public void contribute(Info.Builder builder) {
int a = 10/0;
System.out.println("*****************************Info***************************************************");
}
#Override
public Health health() {
int a = 10/0;
System.out.println("Here in health indicator..........................***********************************************");
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
#Transactional(readOnly = true)
private int check() {
Integer count = null;
try {
Query query = em.createNativeQuery("select count(1) FROM system");
List results = query.getResultList();
for (Object next : results) {
count = ((BigInteger) next).intValue();
}
logger.info("Health Check:" + count);
System.out.println("Health Check:" + count);
} catch (Exception e) {
logger.error("Exception occurred in check()", e);
}
return (count != null && count.intValue() > 0) ? 0 : -1;
}
}
It should print all sysout in both the cases

Associate async task's completion/progress monitor with session

I want to be able to perform an asynchronous task in java and be able to keep a completion (and if possible progress) monitor associated to the user's session. Is this possible, and if yes what is the way to do it?
Currently the task is implemented synchronously as a stateless session bean method, which is called from a jax-rs endpoint.
I looked at https://docs.oracle.com/javaee/7/tutorial/ejb-async001.htm but AsyncResult is not serializable so I guess I cannot add it to session.
Using the Spring annotation #Async, you can make any bean/method asynchronous.
The container will create a new thread and method will be executed asynchronously. You can as well pass a session object into this method and upon completion, you can mark an attribute in the session object.
Example:- https://spring.io/guides/gs/async-method/
JSF example, works in Wildfly:
1 inside in view (xhtml) we have an upload form and progress meter
<h:form>
<div align="justify">
<p:fileUpload style="width: auto" fileUploadListener="#{fileUploadCtrl.handleFileUpload}" mode="advanced" label="Please pick XLS file" update="messages" auto="true" sizeLimit="1000000" allowTypes="/(\.|\/)(xls|xlsx)$/" />
<p:growl id="messages" showDetail="false" life="4000"/>
</div>
</h:form>
<h:form id="wholeform">
<h:outputText id="statusot" value="#{fileUploadCtrl.message}" />
<p:spacer width="10" height="10"/>
<p:poll interval="1" listener="#{fileUploadCtrl.updateStatus}" update="wholeform" />
</h:form>
2 in controller, which is a managed bean, we process file and once a second update status
#ManagedBean
#ViewScoped
public class FileUploadCtrl {
#EJB
private SomeBusinessLogicClass model;
#EJB
private ProgressTracker progress;
private Future<List<String>> asyncResult;
private int progressId = 0;
private String message;
private boolean busy = false;
public void handleFileUpload(FileUploadEvent event) {
Set<String> ids = model.populate(event.getFile().getContents());
progressId = progress.newIndex();
asyncResult = model.process(ids);
busy = true;
FacesMessage message = new FacesMessage("Loaded " + ids.size() + " objects", "");
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void updateStatus() {
if (!busy)
return;
try {
if (asyncResult.isDone()) {
List<String> r = asyncResult.get();
message = "Job done";
busy = false;
progress.delIndex(progressId);
} else {
message = progress.getIndex(progressId)+"-th element in work";
}
} catch (Exception e) {
System.out.println("updateStatus " + e.toString());
}
}
3 All business logic is in EJBs like SomeBusinessLogicClass or many others. Also we need a simple progress-manager EJB, I post it completely
#Singleton
public class ProgressTracker {
private Map<Integer,Integer> indexes = new HashMap<>();
public Map<Integer, Integer> getIndexes() {
return indexes;
}
public void setIndexes(Map<Integer, Integer> indexes) {
this.indexes = indexes;
}
public Integer newIndex() {
Integer size = indexes.size();
indexes.put(size,0);
return size;
}
public void incIndex(final Integer index) {
int old = indexes.get(index);
old++;
indexes.put(index,old);
}
public Integer getIndex(final Integer index) {
return indexes.get(index);
}
public void delIndex(Integer index) {
indexes.remove(index);
}
}
Maybe this example is not elegant, I'm almost newbie with frontends, but it is working and better, than nothing.

IOSDrive becomes null and Appium TestNG tests restarts the app in between

I am facing issues with appium test groups. I have written multiple test cases for my app and running different sets at a time.
Basically, my test flow is: Login with Google => Input Password => Logout
Then for another set same flow with Login with Facebook.
Following is the code is written in AppiumTest.java file
#Test
public class AppiumTest {
IOSDriver<MobileElement> driver = null;
public DesiredCapabilities capabilitiesForDevice(String deviceCode) {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("udid", "SOME_VALID_UDID"); // 7+
capabilities.setCapability("platformVersion", "10.3.3");
capabilities.setCapability("app", "PACKAGE_PATH");
capabilities.setCapability("noReset", false);
capabilities.setCapability("showXcodeLog", true);
capabilities.setCapability("clearSystemFiles", false);
...
return capabilities;
}
#BeforeSuite(groups = {"google"}) // Removing suite also does not make any effect
public void setup() throws MalformedURLException {
System.out.print("Setting up driver.\n");
DesiredCapabilities capabilities = capabilitiesForDevice("iPhone5s");
String url = "http://0.0.0.0:4723/wd/hub";
driver = new IOSDriver<MobileElement>(new URL(url), capabilities);
}
#AfterSuite(groups = {"facebook"})
// Removing suite also does not make any effect
// Between 2 tests execution this method is not being called
public void tearDown() {
System.out.println("AfterSuite ... QUITTING DRIVER...");
driver.quit();
}
public MobileElement getElementByName(String name) {
try {
MobileElement theElement = (MobileElement) (new WebDriverWait(driver, 30))
.until(ExpectedConditions.visibilityOfElementLocated(By.name(name)));
return theElement;
} catch (Exception e) {
// e.printStackTrace();
}
return null;
}
public MobileElement getElementByXPath(String xpath) {
try {
MobileElement theElement = (MobileElement) (new WebDriverWait(driver, 30))
.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return theElement;
} catch (Exception e) {
// e.printStackTrace();
}
return null;
}
#Test(groups = {"google"}, priority = 1)
public void loginWithGoogle() {
if (driver == null) {
printLog("Test driver is null.");
try {
setup();
} catch (MalformedURLException e) {
// e.printStackTrace();
}
}
printLog("driver = " + driver);
printLog("\nLoading is null and not logged in.." + System.currentTimeMillis());
String googleIcon = "icon google";
MobileElement gLoginElement = getElementByName(googleIcon);
gLoginElement.click();
printLog("\nGoogle clicked.." + System.currentTimeMillis());
...
// Input Credentials for Google auth or select user from the auth list
// Assert.assertEquals("Hi test found.", "Test", "Test1");
}
public void loginWithIncorrectPassword() {
String passwordEntry = "//XCUIElementTypeApplication[#name=\"eCare Vault\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeScrollView/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeSecureTextField";
MobileElement pwdEntryElement = getElementByXPath(passwordEntry);
String passwordString = "12345";
pwdEntryElement.sendKeys(passwordString);
printLog("\n{Priority=>2} Password entered..." + passwordString + " # " + System.currentTimeMillis());
...
printLog("\nSend clicked..." + System.currentTimeMillis());
// Assert for incorrect pwd.
}
#Test(groups = {"google"}, priority = 12)
public void loginWithIncorrectPasswordGoogle() {
loginWithIncorrectPassword();
}
public void loginWithCorrectPassword() {
String passwordEntry = "//XCUIElementTypeApplication[#name=\"eCare Vault\"]/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeScrollView/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeSecureTextField";
MobileElement pwdEntryElement = getElementByXPath(passwordEntry);
String passwordString = "VALID PWD";
pwdEntryElement.sendKeys(passwordString);
printLog("\n{Priority=>6} Password entered..." + passwordString + " # " + System.currentTimeMillis());
// XCUIElementTypeButton[#name="Send"]
String sendKey = "Send";
MobileElement sendKeyElement = getElementByName(sendKey);
sendKeyElement.click();
printLog("\nSend clicked..." + System.currentTimeMillis());
}
#Test(groups = {"google"}, priority = 16)
public void loginWithCorrectPasswordGoogle() {
loginWithCorrectPassword();
}
public void logoutButtonClicked() {
// This method will logout user from the app and loads the main screen from where user will be able to tap the Google/Facebook icon
System.out.println("\nLogged out from ECV..." + System.currentTimeMillis());
}
#Test(groups = {"google"}, priority = 19)
public void logoutButtonClickedGoogle() {
logoutButtonClicked();
}
#Test(groups = {"facebook"}, priority = 20)
public void loginWithFB() {
System.out.println("\nLogin with Facebook..." + System.currentTimeMillis());
if (driver == null) {
printLog("Test driver is null.");
try {
setup();
} catch (MalformedURLException e) {
// e.printStackTrace();
}
}
printLog("driver = " + driver);
System.out.println("\nLoading is null and not logged in.." + System.currentTimeMillis());
String fbIcon = "icon facebook";
MobileElement fbLoginElement = getElementByName(fbIcon);
fbLoginElement.click();
System.out.println("\nFacebook clicked.." + System.currentTimeMillis());
...
// "Log In with the Facebook App" button exists for FB app login
// "Log In with the Facebook App" -> Tap
...
continueLoginElement.click();
System.out.println("\nKalis loggedIn.." + System.currentTimeMillis());
}
System.out.println(
"\n{Priority=>1} Password screen found.." + pwdScreen.getText() + " " + System.currentTimeMillis());
// Assert.assertEquals("Hi test found.", "Test", "Test1");
}
#Test(groups = {"facebook"}, priority = 22)
public void loginWithIncorrectPasswordFB() {
loginWithIncorrectPassword();
}
#Test(groups = {"facebook"}, priority = 26)
public void loginWithCorrectPasswordFB() {
loginWithCorrectPassword();
}
#Test(groups = {"facebook"}, priority = 28)
public void homePageLoadedFB() {
homePageLoaded();
}
#Test(groups = {"facebook"}, priority = 29)
public void logoutButtonClickedFB() {
logoutButtonClicked();
}
private void printLog(String message) {
System.out.println(message);
}
}
Testng.xml example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="TestGoogle">
<groups>
<run>
<include name="google" />
</run>
</groups>
<classes>
<class name="login.googleLogin.AppiumTest" />
</classes>
</test> <!-- Test -->
<test name="TestFB">
<groups>
<run>
<include name="facebook" />
</run>
</groups>
<classes>
<class name="login.googleLogin.AppiumTest" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
When I right click on testng.xml and run the test as TestNG Suite, the app gets restarted when the first test "TestGoogle" is completed and there after a 5-10 seconds restarts, the app continues running and executes pending test cases for "TestFacebook".
When I combine Facebook and Google, test cases for Google/Facebook are not executed.
<run>
<include name="google" />
<include name="facebook" />
</run>
Please give me hint of how to solve the issue.

Spring Integration: how to read multiple RSS channels?

I wrote my app that reads RSS feed. It works super with one channel which I have in beans.xml like this:
<feed:inbound-channel-adapter id="news"
channel="inputRssFeedChannel"
url="http://feeds.feedburner.com/Techcrunch">
<int:poller fixed-rate="5000" max-messages-per-poll="100"/>
</feed:inbound-channel-adapter>
<int:service-activator input-channel="inputRssFeedChannel"
ref="rssPrintOutService"
method="printRss"
output-channel="nullChannel"/>
Every time it just calls RssHandler which deal with SyndEntry. But what should I do if I'd like to read few rss urls (2,5,20 or etc...)?
Create your own implementation of org.springframework.integration.core.MessageSource and use it in input-channel reference like the following:
<int:inbound-channel-adapter id="newsInput" ref="newsReader">
<int:poller fixed-rate="1" time-unit="SECONDS" max-messages-per-poll="1"/>
</int:inbound-channel-adapter>
<bean id="newsReader" class="blog.NewsReader">
<property name="fetcherListener">
<bean class="blog.helper.FetcherEventListenerImpl"/>
</property>
<property name="urls">
<list>
<value>http://www.gridshore.nl/feed/</value>
<value>https://spring.io/blog.atom</value>
<value>http://feeds.foxnews.com/foxnews/video?format=xml</value>
</list>
</property>
</bean>
The class NewsReader uses list mentioned in urls propriety and retrieve the feed.
Please refer to the receive method below.
public class NewsReader implements MessageSource, InitializingBean {
private static Logger logger = LoggerFactory.getLogger(NewsReader.class);
private FeedFetcherCache feedInfoCache;
private FeedFetcher feedFetcher;
private FetcherListener fetcherListener;
private List<String> urls;
#Override
public Message receive() {
List<SyndFeed> feeds = obtainFeedItems();
return MessageBuilder.withPayload(feeds)
.setHeader("feedid", "newsfeed").build();
}
private List<SyndFeed> obtainFeedItems() {
List<SyndFeed> feed = new ArrayList<>();
try {
for (String url : urls) {
feed.add(feedFetcher.retrieveFeed(new URL(url)));
}
} catch (IOException e) {
logger.error("IO Problem while retrieving feed", e);
} catch (FeedException e) {
logger.error("Feed Problem while retrieving feed", e);
} catch (FetcherException e) {
logger.error("Fetcher Problem while retrieving feed", e);
}
return feed;
}
#Override
public void afterPropertiesSet() throws Exception {
feedInfoCache = HashMapFeedInfoCache.getInstance();
feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
if (fetcherListener != null) {
feedFetcher.addFetcherEventListener(fetcherListener);
}
}
public void setFetcherListener(FetcherListener fetcherListener) {
this.fetcherListener = fetcherListener;
}
public void setUrls(List<String> urls) {
this.urls = urls;
}
In case you want to take a look of my complete code:
git clone https://github.com/BikashShaw/MultipleRSSFeedRead.git

Issue with retrieveing the Manager of a System User in a Custom workflow - CRM 2013

Issues with custom workflow activity in CRM 2013 On-prem
I'm trying to pass the Manager of the System
here is the code that I'm running, it gets to setting the MANAGER and stops
I put the ran the FetchXML seperatly and it does return a value so I know what bit works
public class CaseAccountManagerManagersLookup : CodeActivity
{
// Inputs
[Input("Enter Case")]
[ReferenceTarget("incident")]
public InArgument<EntityReference> CA { get; set; }
// Outputs
[Output("Manager Output")]
[ReferenceTarget("systemuser")]
public OutArgument<EntityReference> AMOUT { get; set; }
protected override void Execute(CodeActivityContext executionContext)
{
// Context
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//Create the tracing service
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
// get the account and renewals manager ID's
var CASE = CA.Get<EntityReference>(executionContext);
tracingService.Trace("Case ID = " + CASE.Id);
try
{
// FETCH
string fetchXml = string.Format(#"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='incident'>
<attribute name='title' />
<attribute name='incidentid' />
<order attribute='title' descending='false' />
<filter type='and'>
<condition attribute='incidentid' operator='eq' value='{0}' />
</filter>
<link-entity name='contact' from='contactid' to='customerid' alias='ak'>
<link-entity name='account' from='accountid' to='parentcustomerid' alias='al'>
<link-entity name='systemuser' from='systemuserid' to='bc_dssalesperson' alias='am'>
<attribute name='parentsystemuserid' />
</link-entity>
</link-entity>
</link-entity>
</entity>
</fetch>", CASE.Id);
EntityCollection case_results = service.RetrieveMultiple(new FetchExpression(fetchXml));
//tracingService.Trace("fetch has run");
if (case_results.Entities.Count != 0)
{
foreach (var a in case_results.Entities)
{
//if (a.Attributes.Contains("ai_parentsystemuserid"))
//{
tracingService.Trace("set manager id next");
var MANAGERID = (EntityReference)a.Attributes["parentsystemuserid"];
tracingService.Trace("manager id set");
AMOUT.Set(executionContext, MANAGERID);
throw new InvalidOperationException("Want to see trace");
//}
}
}
tracingService.Trace("end ");
}
catch (Exception e)
{
throw new InvalidPluginExecutionException("Plugin - CaseAccountManagerManagerLookup - " + e.Message);
}
finally
{
throw new InvalidOperationException("Want to see trace");
}
}
}
Try to use am.parentsystemuserid instead of just parentsystemuserid.
Are you sure that the guid that you are passing is in the correct form?
{8B8099A6-8B89-E411-883D-D89D676552A0}
this is what i get from the export but you are writing
8B8099A6-8B89-E411-883D-D89D676552A0
Also are you sure about the record that you are trying to retrieve? Is the chain complete with data?
case-> contact -> account -> parent user -> parent user ?

Resources