I am use Extent Reports 3.1.5 and my reports keep getting overwritten on each test run. I have implemented to the bests of my ability the solution found on stack-overflow and various sites and no progress. I have spent 24 hours troubleshooting this issue and need help.
I even went and examined the following sites http://extentreports.com/docs/versions/3/java/#htmlreporter-features
http://extentreports.com/docs/versions/3/java/#htmlreporter-features
and check my code and still could not find the issue. If there is something i am overlooking please help me.
Again my test runs however it only writes the last test ran in my testng.xml file
This is my Base Test Class:
package test;
public class BaseTest {
//-------Page Objects----------
login_Page objBELogin;
poll_Page objCreatePoll;
survey_Page objCreateSurvey;
task_Page objCreateTaskGroup;
discussion_Page objCreateDiscussion;
userprofile_Page objUserProfile;
event_Page objectEvent;
workgroup_Page objectWorkgroup;
workroom_Page objectWorkroom;
//-----------------------------
static WebDriver driver;
static String homePage = "https://automation-ozzie.boardeffect.com/login";
ExtentReports report;
ExtentTest test;//--parent test
#BeforeClass
public void setUp() throws InterruptedException{
//--------Extent Report--------
report = ExtentFactory.getInstance();
//-----------------------------
System.setProperty("webdriver.chrome.driver","C:\\GRID\\chromedriver.exe");
ChromeOptions option = new ChromeOptions();
option.addArguments("disable-infobars");
driver = new ChromeDriver(option);
driver.manage().window().maximize();
driver.get(homePage);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#BeforeMethod
public void register(Method method) {
String testName = method.getName();
test = report.createTest(testName);
}
#AfterMethod
public void catureStatus(ITestResult result) {
if (result.getStatus()==ITestResult.SUCCESS) {
test.log(Status.PASS,"Test Method named as : "+ result.getName()+" is passed");
}else if(result.getStatus()==ITestResult.FAILURE) {
test.log(Status.PASS,"Test Method named as : "+ result.getName()+" is FAILED");
test.log(Status.FAIL,"Test failure : "+ result.getThrowable());
}
else if(result.getStatus()==ITestResult.SKIP) {
test.log(Status.PASS,"Test Method named as : "+ result.getName()+" is skipped");
}
}
#AfterClass
public void tearDown() throws InterruptedException {
report.flush();
driver.quit();
}
}
public class ExtentFactory {
public static ExtentReports getInstance() {
ExtentHtmlReporter html = new ExtentHtmlReporter("surefire-reports//Extent.html");
html.setAppendExisting(true);
ExtentReports extent = new ExtentReports();
extent.attachReporter(html);
return extent;
}
}
You have to consider adding a unique name to report file for each run.
import java.text.SimpleDateFormat;
import java.util.Date;
public class ExtentFactory {
public static ExtentReports getInstance() {
String out = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss'.html'").format(new Date());
ExtentHtmlReporter html = new ExtentHtmlReporter("surefire-reports//"+out);
ExtentReports extent = new ExtentReports();
extent.attachReporter(html);
return extent;
}
}
You will also need to move the report instance creation to #beforesuite, so that it runs only once for the entire test suite.
#BeforeSuite
public void OneTimesetUp() throws InterruptedException{
//--------Extent Report--------
report = ExtentFactory.getInstance();
//-----------------------------
}
Related
I'm using spring-kafka 2.3.8 and I'm trying to log the recovered records and commit the offsets using RetryingBatchErrorHandler. How would you commit the offset in the recoverer?
public class Customizer implements ContainerCustomizer{
private static ConsumerRecordRecoverer createConsumerRecordRecoverer() {
return (consumerRecord, e) -> {
log.info("Number of attempts exhausted. parition: " consumerRecord.partition() + ", offset: " + consumerRecord.offset());
# need to commit the offset
};
}
#Override
public void configure(AbstractMessageListenerContainer container) {
container.setBatchErrorHandler(new RetryingBatchErrorHandler(new FixedBackOff(5000L, 3L), createConsumerRecordRecoverer()));
}
The container will automatically commit the offsets if the error handler "handles" the exception, unless you set the ackAfterHandle property to false (it is true by default).
EDIT
This works as expected for me:
#SpringBootApplication
public class So69534923Application {
private static final Logger log = LoggerFactory.getLogger(So69534923Application.class);
public static void main(String[] args) {
SpringApplication.run(So69534923Application.class, args);
}
#KafkaListener(id = "so69534923", topics = "so69534923")
void listen(List<String> in) {
System.out.println(in);
throw new RuntimeException("test");
}
#Bean
RetryingBatchErrorHandler eh() {
return new RetryingBatchErrorHandler(new FixedBackOff(1000L, 2), (rec, ex) -> {
this.log.info("Retries exchausted for " + ListenerUtils.recordToString(rec, true));
});
}
#Bean
ApplicationRunner runner(ConcurrentKafkaListenerContainerFactory<?, ?> factory,
KafkaTemplate<String, String> template) {
factory.getContainerProperties().setCommitLogLevel(Level.INFO);
return args -> {
template.send("so69534923", "foo");
template.send("so69534923", "bar");
};
}
}
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.listener.type=batch
so69534923: partitions assigned: [so69534923-0]
[foo, bar]
[foo, bar]
[foo, bar]
Retries exchausted for so69534923-0#2
Retries exchausted for so69534923-0#3
Committing: {so69534923-0=OffsetAndMetadata{offset=4, leaderEpoch=null, metadata=''}}
The log was from the second run.
EDIT2
It does not work with 2.3.x; you should upgrade to a supported version.
https://spring.io/projects/spring-kafka#learn
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
I have to generate Extent Report from all executed test scripts. I am running scripts in parallel. When I use TestNG or Selenium Grid for parallel execution, in those implementation, Extent Reports are getting generated perfectly covering each executed test scripts. But when I run scripts in parallel using Cucable Plugin, Extent report gets generated but would have only 1 test case report if 2 test cases were there in execution.
I am using Cucumber (Selenium), Junit Suite Runner, Cucable Plugin
I verified Extent Report code is thread safe. So not sure, why only in case of Cucable Plugin, Extent report gets only 1 test case. Someone told me, In case of testNG, testNG itself provides additional thread safe mechanism which helps internally to have all executed test cases in report.
ExtentTestManager.java
package com.jacksparrow.automation.extent.listeners;
import java.io.IOException;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.MediaEntityBuilder;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.Markup;
import com.aventstack.extentreports.markuputils.MarkupHelper;
public class ExtentTestManager {
public static ThreadLocal<ExtentTest> testReport = new ThreadLocal<ExtentTest>();
static ExtentReports extent = ExtentManager.getReporter();
public static synchronized ExtentTest getTest() {
return testReport.get();
}
public static synchronized void setTest(ExtentTest tst)
{
testReport.set(tst);
}
public static synchronized void logInfo(String message) {
testReport.get().info(message);
}
public static synchronized void logPass(String message) {
testReport.get().pass(message);
}
public static synchronized void scenarioPass() {
String passLogg = "SCENARIO PASSED";
Markup m = MarkupHelper.createLabel(passLogg, ExtentColor.GREEN);
testReport.get().log(Status.PASS, m);
}
public static synchronized void logFail(String message) {
testReport.get().fail(message);
}
public static synchronized boolean addScreenShotsOnFailure() {
ExtentManager.captureScreenshot();
try {
testReport.get().fail("<b>" + "<font color=" + "red>" + "Screenshot of failure" + "</font>" + "</b>",
MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName).build());
} catch (IOException e) {
}
String failureLogg = "SCENARIO FAILED";
Markup m = MarkupHelper.createLabel(failureLogg, ExtentColor.RED);
testReport.get().log(Status.FAIL, m);
return true;
}
public static synchronized boolean addScreenShots() {
ExtentManager.captureScreenshot();
try {
testReport.get().info(("<b>" + "<font color=" + "green>" + "Screenshot" + "</font>" + "</b>"),
MediaEntityBuilder.createScreenCaptureFromPath(ExtentManager.screenshotName).build());
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public static synchronized ExtentTest startTest(String testName) {
return startTest(testName, "");
}
public static synchronized ExtentTest startTest(String testName, String desc) {
ExtentTest test = extent.createTest(testName, desc);
testReport.set(test);
return test;
}
}
ExtentManager.java
package com.jacksparrow.automation.extent.listeners;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import com.jacksparrow.automation.utilities.DriverManager;
import com.aventstack.extentreports.AnalysisStrategy;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.ChartLocation;
import com.aventstack.extentreports.reporter.configuration.Theme;
public class ExtentManager {
static ExtentReports extent;
static Date d = new Date();
static String fileName = "Extent_" + d.toString().replace(":", "_").replace(" ", "_") + ".html";
public synchronized static ExtentReports getReporter() {
if (extent == null) {
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/target/extent-report/"+fileName);
htmlReporter.loadXMLConfig(".\\src\\test\\resources\\extent-config.xml");
htmlReporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
htmlReporter.config().setChartVisibilityOnOpen(true);
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setDocumentTitle(fileName);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName(fileName);
//htmlReporter.setAppendExisting(true);
extent = new ExtentReports();
extent.setAnalysisStrategy(AnalysisStrategy.TEST);
extent.attachReporter(htmlReporter);
extent.setSystemInfo("Automation Analyst", "Robin Tyagi");
extent.setSystemInfo("Organization", "Way2Automation");
extent.setSystemInfo("Build no", "W2A-1234");
}
return extent;
}
public static String screenshotPath;
public static String screenshotName;
static int i=0;
public static void captureScreenshot() {
i = i + 1;
File scrFile = ((TakesScreenshot) DriverManager.getDriver()).getScreenshotAs(OutputType.FILE);
Date d = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("E dd MMM HH:mm:ss z yyyy");
String strDate = formatter.format(d);
screenshotName = strDate.replace(":", "_").replace(" ", "_") + "_"+i+".jpg";
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/extent-report/" + screenshotName));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createExtentReportDirectory() {
File file = new File(System.getProperty("user.dir") + "/target/extent-report/");
if (!file.exists()) {
if (file.mkdir()) {
} else {
}
}
}
}
Please help me to understand what could be the correct thought in order to generate Extent Report having summary of all executed test scripts when Cucable Plugin is used for achieving parallel execution in Cucumber (Selenium)
After migrating to cucumber 4.0, I am able to generate single consolidated extent report. Thank you.
I am a newbie to Windows Application Driver and my project demands automating the desktop application, so I decided to use winappdriver as it is similar to selenium, on which I am pretty confident about using.
speaking of the issue,
Just wondering if there is a way to achieve explicit wait and implicit wait using winappdriver. Following is the code i used as part of my test cases, the test fails with an exception (NoSuchElementException), however, if I put a static wait in place instead of explicit wait, it works as expected.
//Driver Setup
public class OscBase {
public static WindowsDriver<WebElement> applicaitonSession, driver = null;
public static WindowsDriver<RemoteWebElement> desktopSession = null;
public static DesiredCapabilities capabilities, cap1, cap2;
public static ProcessBuilder pBuilder;
public static Process p;
public void startDriver() {
try {
pBuilder = new ProcessBuilder("C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe");
pBuilder.inheritIO();
p = pBuilder.start();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void stopDriver() {
p.destroy();
}
public void createDesktopSession() throws MalformedURLException {
cap1 = new DesiredCapabilities();
cap1.setCapability("app", "Root");
desktopSession = new WindowsDriver<RemoteWebElement>(new URL("http://localhost:4723"), cap1);
}
public void openApplication() throws InterruptedException, MalformedURLException {
if (driver == null) {
try {
capabilities = new DesiredCapabilities();
capabilities.setCapability("app",
"Appnamewithlocation");
applicaitonSession = new WindowsDriver<WebElement>(new URL("http://localhost:4723"),
capabilities);
} catch (Exception e) {
System.out.println("Application opened!!!");
} finally {
createDesktopSession();
}
Thread.sleep(8000L);
String handle = desktopSession.findElementByAccessibilityId("InstallerView5")
.getAttribute("NativeWindowHandle");
System.out.println(handle);
int inthandle = Integer.parseInt(handle);
String hexHandle = Integer.toHexString(inthandle);
//System.out.println(hexHandle);
cap2 = new DesiredCapabilities();
cap2.setCapability("appTopLevelWindow", hexHandle);
driver = new WindowsDriver<WebElement>(new URL("http://localhost:4723"), cap2);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
public boolean isDisplayed_SafeLoginNoBtn() {
wait = new WebDriverWait(driver, 40);
return wait.until(ExpectedConditions.visibilityOf(safeLoginNoBtn())).isDisplayed();
}
#Test
public void osc_Get_Data() throws InterruptedException, IOException {
//Thread.sleep(20000);
// Boolean value=oscLogin.safeLoginNoBtn().isDisplayed();
try {
Boolean value = oscLogin.isDisplayed_SafeLoginNoBtn();
System.out.println("IS displayed========>"+value);
if (value) {
oscLogin.click_safeLogin();
}
} catch (Exception e) {
System.out.println("Safe Login!!!!");
}
Of course yes, the WebDriverWait class will work. Here's an example
WebDriverWait waitForMe = new WebDriverWait();
WebDriverWait waitForMe = new WebDriverWait(session, new TimeSpan.Fromseconds(10));
var txtLocation = session.FindElementByName("Enter a location");
waitForMe.Until(pred => txtLocation.Displayed);
I've created a detailed course about UI Automation using WinAppDriver and C# .Net. I'll be publishing it in a few days. Do let me know if you're interested :)
The Mapper didn't manage to read a file from multiple directories. Could anyone help?
I need to read one file in each mapper. I've added multiple input paths and implemented the custom WholeFileInputFormat, WholeFileRecordReader. In the map method, I don't need the input key. I make sure that each map can read a whole file.
Command line: hadoop jar AutoProduce.jar Autoproduce /input_a /input_b /output
I specified two input path----1.input_a; 2.input_b;
Run method snippets:
Job job = new Job(getConf());
job.setInputFormatClass(WholeFileInputFormat.class);
FileInputFormat.setInputPaths(job, new Path(args[0]), new Path(args[1]));
FileOutputFormat.setOutputPath(job, new Path(args[2]));
map method snippets:
public void map(NullWritable key, BytesWritable value, Context context){
FileSplit fileSplit = (FileSplit) context.getInputSplit();
System.out.println("Directory :" + fileSplit.getPath().toString());
......
}
Custom WholeFileInputFormat:
class WholeFileInputFormat extends FileInputFormat<NullWritable, BytesWritable> {
#Override
protected boolean isSplitable(JobContext context, Path file) {
return false;
}
#Override
public RecordReader<NullWritable, BytesWritable> createRecordReader(
InputSplit split, TaskAttemptContext context) throws IOException,
InterruptedException {
WholeFileRecordReader reader = new WholeFileRecordReader();
reader.initialize(split, context);
return reader;
}
}
Custom WholeFileRecordReader:
class WholeFileRecordReader extends RecordReader<NullWritable, BytesWritable> {
private FileSplit fileSplit;
private Configuration conf;
private BytesWritable value = new BytesWritable();
private boolean processed = false;
#Override
public void initialize(InputSplit split, TaskAttemptContext context)
throws IOException, InterruptedException {
this.fileSplit = (FileSplit) split;
this.conf = context.getConfiguration();
}
#Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (!processed) {
byte[] contents = new byte[(int) fileSplit.getLength()];
Path file = fileSplit.getPath();
FileSystem fs = file.getFileSystem(conf);
FSDataInputStream in = null;
try {
in = fs.open(file);
IOUtils.readFully(in, contents, 0, contents.length);
value.set(contents, 0, contents.length);
} finally {
IOUtils.closeStream(in);
}
processed = true;
return true;
}
return false;
}
#Override
public NullWritable getCurrentKey() throws IOException,InterruptedException {
return NullWritable.get();
}
#Override
public BytesWritable getCurrentValue() throws IOException,InterruptedException {
return value;
}
#Override
public float getProgress() throws IOException {
return processed ? 1.0f : 0.0f;
}
#Override
public void close() throws IOException {
// do nothing
}
}
PROBLEM:
After setting two input paths, all map tasks read files from only one directory..
Thanks in advance.
You'll have to use MultipleInputs instead of FileInputFormat in the driver. So your code should be as:
MultipleInputs.addInputPath(job, new Path(args[0]), <Input_Format_Class_1>);
MultipleInputs.addInputPath(job, new Path(args[1]), <Input_Format_Class_2>);
.
.
.
MultipleInputs.addInputPath(job, new Path(args[N-1]), <Input_Format_Class_N>);
So if you want to use WholeFileInputFormat for the first input path and TextInputFormat for the second input path, you'll have to use it the following way:
MultipleInputs.addInputPath(job, new Path(args[0]), WholeFileInputFormat.class);
MultipleInputs.addInputPath(job, new Path(args[1]), TextInputFormat.class);
Hope this works for you!