allure report +selenide, Attached console print log is empty - selenium-webdriver

I am using selenide, testng and allure reports.My goal is just print console logs into the allure report
I am using below code (demo)to add text printed on console to attach to my allure reports :
import com.codeborne.selenide.testng.TextReport;
import com.codeborne.selenide.testng.annotations.Report;
import io.qameta.allure.Attachment;
import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import static com.codeborne.selenide.CollectionCondition.size;
import static com.codeborne.selenide.Condition.enabled;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.*;
import java.io.IOException;
import java.util.List;
#Report
#Listeners(TextReport.class)
public class GoogleTestNGTest {
#Attachment
public String logOutput(List<String> outputList) {
String output = "";
for (String o : outputList)
output += o + " ";
return output;
}
#AfterMethod
protected void printLog(ITestResult testResult) throws IOException {
logOutput(Reporter.getOutput(testResult));
}
#BeforeMethod
public void setUp() {
TextReport.onSucceededTest = true;
TextReport.onFailedTest = true;
open("http://google.com/ncr");
}
#Test(enabled = true)
public void failingMethod() {
$(By.name("q")).shouldBe(visible, enabled);
$("#missing-button").click();
}
#Test
public void successfulMethod() {
$(By.name("q")).setValue("selenide").pressEnter();
$$("#ires .g").shouldHave(size(10));
}
}
The problem is that the printLog is empty
screenshot
how i can fix it ?

I got this working by adding this to my browser setup method:
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
And added this to my code which handles the allure report generation:
List<String> logs = Selenide.getWebDriverLogs(LogType.BROWSER);
Allure.addAttachment("Console logs: ", logs.toString());

i am using for logs..
protected static void log(String stringToLog) {
final String uuid = UUID.randomUUID().toString();
final StepResult result = new StepResult()
.withName(stringToLog);
getLifecycle().startStep(uuid, result);
try {
getLifecycle().updateStep(uuid, s -> s.withStatus(Status.PASSED));
} finally {
getLifecycle().stopStep(uuid);
}
}

Related

Why getting resource list null for webpage when automating desktop application i.e. hybrid (Desktop and Web)?

I am automating hybrid application i.e. Desktop and WebApplication. We have desktop application in which some of pages are integrated using WebPages and some one pages are in desktop application. Below is the code which I have used to open Desktop Application. And its opening the application successfully. But When I am going to print resource list size, it comes 'null' where locator for resourcelist is showing correct count in chrome browser. I can login successfully using winium driver instance. After logged in, list of resources are present which I integrated in webpage.
Let me know if I am doing wrong in given code?
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
public class VMSWiniumBaseDriver {
public WiniumDriver driver;
String applicationPath = "C:\\Users\\prashantn\\Downloads\\Publish\\ABC.exe";
#Parameters({ "windowsPlatform" })
#BeforeClass(alwaysRun = true)
public void initialize(String browser) throws IOException, InterruptedException {
if (browser.equalsIgnoreCase("desktop")) {
try {
WiniumDriverService service;
DesktopOptions option;
option = new DesktopOptions();
option.setApplicationPath(applicationPath);
File driverPath = new File(System.getProperty("user.dir") + File.separator + "driver" + File.separator
+ "Winium.Desktop.Driver.exe");
service = new WiniumDriverService.Builder().usingDriverExecutable(driverPath).usingPort(9999)
.withVerbose(true).withSilent(false).buildDesktopService();
try {
service.start();
} catch (IOException e) {
System.out.println("Exception while starting WINIUM service");
e.printStackTrace();
}
driver = new WiniumDriver(service, option);
} catch (Exception e) {
System.out.println(e);
}
}
}
#AfterClass(alwaysRun = true)
public void TeardownTest() {
if (null == driver) {
driver.close();
driver.quit();
}
}
public WiniumDriver getDriver() {
return driver;
}
}
Here is
CommonUtilities.Java
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.ThreadLocalRandom;
import org.openqa.selenium.WebDriver;
import org.sikuli.hotkey.Keys;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.sikuli.script.ScreenImage;
import dataproviders.VMSConfigFileReader;
import managers.VMSWiniumBaseDriver;
public class CommonUtilities extends VMSWiniumBaseDriver {
public WebDriver getWebDriverInstance() {
WebDriver webDriver = (WebDriver) driver;
return webDriver;
}
}
LoginPage.java
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.winium.WiniumDriver;
import utilities.CommonUtilities;
public class LoginPage{
#FindBy(id = "PART_EditableTextBox")
WebElement userName;
#FindBy(id = "TextBlock_Password")
WebElement passwordInput;
#FindBy(id = "LoginButton")
WebElement loginButton;
#FindBy(xpath = "//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']")
List<WebElement> resourcesList;
public void getResourcesList() {
CommonUtilities commonUtilities = new CommonUtilities();
// System.out.println("Page Source :: "+commonUtilities.getWebDriverInstance());
List<WebElement> list = commonUtilities.getWebDriverInstance().findElements(By.xpath(
"//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']"));
System.out.println("Resources Size :: " + list.size());
for (int i = 0; i < resourcesList.size(); i++) {
System.out.println("Resource Name :: " + resourcesList.get(i).getText());
}
}
}
Exception Log:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElements(org.openqa.selenium.By)" because the return value of "utilities.CommonUtilities.getWebDriverInstance()" is null
at pageobjects.LoginPage.getResourcesList(LoginPage.java:57)
at testcases.AppLaunchTest.selectLayOutBasic1(AppLaunchTest.java:62)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:599)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:764)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1218)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.runSuites(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1037)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

BaseTest class doesn't initialize the Webdriver instance

I have gone through similar type Q&As, but couldn't figure out the issue in my code.
This is my BaseTest class
`
package com.supportiveTests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;
public class BaseTests {
public static WebDriver driver;
#Before
public void setUpDriver() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/Drivers/chromedriver.exe");
driver = new ChromeDriver();
}
#After
public void quitDriver() {
this.driver.quit();
System.out.println("done AfterTest");
}
}
`
This is my stepDefinition class (LoginPageSteps)
`
package com.stepDefinitions;
import com.pageObjects.LoginPage;
import com.supportiveTests.BaseTests;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.testng.annotations.Test;
#Test
public class LoginPageSteps extends BaseTests {
LoginPage obj_login;
#Given("User is on Google Home page")
public void user_is_on_google_home_page() {
BaseTests.driver.navigate().to("https://www.google.com/");
}
#Given("User is navigated to SwagLabs Login page")
public void user_is_navigated_to_swag_labs_login_page() {
BaseTests.driver.navigate().to("https://www.saucedemo.com/");
}
#When("^User enters valid (.*) and (.*)$")
public void user_enters_valid_standard_user_and_secret_sauce(String username, String password) {
obj_login = new LoginPage(driver);
obj_login.enterUserName(username);
obj_login.enterPassword(password);
}
#When("clicks on LOGIN button")
public void clicks_on_login_button() {
obj_login.clickOnLogin();
}
#Then("User is navigated to SwagLAbs Home page")
public void user_is_navigated_to_swag_l_abs_home_page() throws InterruptedException {
BaseTests.driver.getCurrentUrl().contains("https://www.saucedemo.com/inventory.html");
Thread.sleep(2000);
BaseTests.driver.quit();
}
}
`
This is my TestRunner class
`
package com.supportiveTests;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(features = "src/test/Features",
glue = {"com/stepDefinitions"},
monochrome = true,
plugin = {
"pretty", "html:target/HTMLReports/report.html",
"json:target/JSONReports/report.json",
"junit:target/JUnitReports/report.xml"
}
)
public class TestRunner {
}
`
This is my pageObject class (LoginPage)
`
package com.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
By txt_username = By.xpath("//input[#id='user-name']");
By txt_password = By.xpath("//input[#id='password']");
By btn_login = By.xpath("//input[#id='login-button']");
public void enterUserName(String username){
driver.findElement(txt_username).sendKeys(username);
}
public void enterPassword(String password){
driver.findElement(txt_password).sendKeys(password);
}
public void clickOnLogin(){
driver.findElement(btn_login).click();
}
}
When the above TestRunner class is executed, I get this error
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.navigate()" because "com.supportiveTests.BaseTests.driver" is null
at com.stepDefinitions.LoginPageSteps.user_is_on_google_home_page(LoginPageSteps.java:16)
I went through the similar Q&As, where the solutions for driver initialization were provided, but couldn't figure out the issue. I am at basic level of Selenium testing framework, so appreciate any guidance on fixing this.

Getting an error as while reading a JSON file containing 'Usernames' and 'Passwords' using TestNG DataProviders in Selenium

Getting an error as while reading a JSON file using TestNG DataProviders in Selenium.
Error:
class com.google.gson.JsonObject cannot be cast to class org.json.simple.JSONObject (com.google.gson.JsonObject and org.json.simple.JSONObject are in unnamed module of loader &apos;app&apos;)
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.google.gson.JsonParser;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataDrivenTest_json {
WebDriver driver;
#BeforeClass
void setUp() { /* to set up chromedriver */
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.MILLISECONDS);
}
#Test(dataProvider="dp") /* using dataproviders*/
void login(String data) {
String list[] = data.split(",");
driver.get("some website url");
driver.findElement(By.cssSelector("[id='Email']")).sendKeys(list[0]);//username
driver.findElement(By.cssSelector("[id='Password']")).sendKeys(list[1]);//password
driver.findElement(By.cssSelector("[type='submit']")).click();
}
#DataProvider(name="dp")
public String[] readJson() throws IOException{
#SuppressWarnings("deprecation")
JsonParser jsonparser = new JsonParser();
FileReader reader =new FileReader("C:\\Users\\dell\\eclipse-workspace-
photon\\ExcelDriven\\src\\test\\java\\Testdata.json");
#SuppressWarnings("deprecation")
Object obj = jsonparser.parse(reader); //java object
JSONObject userLoginsJsonObj = (JSONObject)obj;
JSONArray userLoginsArray =(JSONArray)userLoginsJsonObj.get("userLogins");
String array[] = new String[userLoginsArray.size()];
for(int i=0; i<userLoginsArray.size();i++) {
JSONObject users = (JSONObject)userLoginsArray.get(i);
String username = (String)users.get("username");
String password = (String)users.get("password");
array[i] = username+","+password;
}
return array;
}
#AfterClass
void tearDown() { //close driver
driver.close();
}
}
/*My MavenProject has testng included and pom.xml file has 'com.googlecode.json-simple' dependency added.Still the above error is visible in console.*/
You import class org.json.simple.JSONObject while you need to import com.google.gson.JsonObject. You cannot just cast an object to any class even if that class has the same name. The package of the class also matters.

the method get(class <ReportClass>) is undefined for the type ExtentReport

i'm making selenium extent report but i'm getting error on - static final ExtentReports extrpt=ExtentReports.get(ReportClass.class);
after mouse hover on get i'm getting below info.
the method get(class ) is undefined for the type ExtentReports
it's my simple java project please tell me where am i doing mistake.
package DemoPacakge;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
public class ReportClass {
// * ReportClass .class will become TheClassName.class
static final ExtentReports extrpt=ExtentReports.get(ReportClass.class);
public void test()
{
WebDriver driver =new FirefoxDriver();
driver.get("http://learn-automation.com/advance-selenium-reporting-with-screenshots/");
String tile=driver.getTitle();
Assert.assertTrue(tile.contains("learn"));
}
}
Please see the examples section: http://extentreports.relevantcodes.com/1x/docs.html#examples
There are a few errors such as, you are not initializing the report with a "file-path". You have not instructed Extent to start a test either. Try with the below code, it should work:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;
public class ReportClass {
static final ExtentReports extrpt = ExtentReports.get(ReportClass.class);
WebDriver driver;
#BeforeClass
public void beforeClass() {
extrpt.init("file-path.html", true);
extrpt.config().displayCallerClass(false);
}
#Test
public void test() {
extrpt.startTest("Test");
driver = new FirefoxDriver();
extrpt.log(LogStatus.INFO, "Starting FirefoxDriver..");
driver.get("http://learn-automation.com/advance-selenium-reporting-with-screenshots/");
extrpt.log(LogStatus.INFO, "Navigating to learn-automation.com..");
String title = driver.getTitle();
extrpt.log(LogStatus.INFO, "Title: " + title);
try {
Assert.assertTrue(title.contains("learn"));
extrpt.log(LogStatus.PASS, "Step Passed");
}
catch (AssertionError e) {
extrpt.log(LogStatus.FAIL, "<pre>" + e.getMessage() + "</pre>");
}
}
#AfterTest
public void afterTest() {
driver.quit();
extrpt.endTest();
}
}

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources