parallel-testing with SeleniumGrid and headless Chrome - selenium-grid

I try to run the same end2end test parallel (load test, JMeter with JUnitSampler).
If i run parallel tests with real chromeBrowser, its working fine. If i run the Tests with chromeOption “--headless”, no tests are running. What could be the difference between real chromeBrowser and headless chromeBrowser?
One test with headlessBrowser (not parallel) is also running well.
Step1 - JUnit Test:
public class AppTest extends TestCase{
private Logger logger;
private WebDriver driver;
private String user;
private String passwd;
#Before
#Override
public void setUp() throws MalformedURLException {
logger = LoggerFactory.getLogger(AppTest.class);
user = “user”;
passwd = “12345”;
DesiredCapabilities caps = DesiredCapabilities.chrome();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments(“--headless”);
chromeOptions.addArguments(“--incognito”);
caps.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new RemoteWebDriver(new URL(“http://127.0.0.1:4444/wd/hub”), caps);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
#Test
public void workFlow() throws InterruptedException {
driver.get("https://somesite.de");
try {
WebElement input = driver.findElement(By.id(“login-form-username”));
input.click();
input.clear();
input.sendKeys(user);
} catch (NoSuchElementException e) {
fail(“Element not found”);
}
try {
Thread.sleep(1000);
WebElement myButton = driver.findElement(By.className("my-button”));
myButton.click();
} catch (NoSuchElementException e) {
fail(“Element not found”);
}
try {
Thread.sleep(2000);
WebElement input = driver.findElement(By.id(“password-form-password”));
input.click();
input.sendKeys(passwd);
} catch (NoSuchElementException e) {
fail(“Element not found”);
}
try {
WebElement myButton = driver.findElement(By.className(“my-button”));
myButton.click();
} catch (NoSuchElementException e) {
fail(“Element not found”);
}
try {
Thread.sleep(2000);
List<WebElement> displayBoxHeaders = driver.findElements(By.className(“box-complete-header”));
assertThat(displayBoxHeaders.get(1).getText()).contains(user);
WebElement logo = displayBoxHeaders.get(0);
String svg = logo.findElement(By.tagName(“svg”)).findElement(By.tagName(“g”)).findElement(By.tagName(“path”)).getAttribute(“class”);
assertThat(svg).isNotNull().isNotEmpty();
} catch (NoSuchElementException e) {
fail();
}
try {
WebElement displayText = driver.findElement(By.id(“ui-form-text”));
String text = displayText.getText();
assertThat(text).isNotNull().isNotEmpty();
} catch (Exception e) {
fail();
}
try {
WebElement myButton = driver.findElement(By.className(my-button”));
myButton.click();
} catch (NoSuchElementException e) {
fail(“Element not found”);
}
}
#After
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
Step2 - JUnitSampler in JMeter with JUnitTestClass above.
Step3 - SeleniumGrid in Docker
git clone https://github.com/SeleniumHQ/docker-selenium.git
cd docker-selenium
docker run -d -p 4444:4444 --name selenium-hub selenium/hub:3.5.3-boron
docker run -d --link selenium-hub:hub -e NODE_MAX_INSTANCES=100 -e NODE_MAX_SESSION=100 selenium/node-chrome:3.5.3-boron
Step3 - Run single Thread in JMeter:
Test runs successfully.
Step4 - Run 5 Threads in parallel in JMeter:
First test runs successfully, other four not.
Error: is ElementNotFound in each failed test run
It is important for the test that the browser instances do not have the same session.

Related

Extent Report in Jenkins is displaying blank icon for attached screenshots

I have generated a runnable jar of my project, and running it on other machine through jenkins.
Jar file executing successfully and generating extent report also,
but there is a blank icon on the place of screenshots.
I have searched on google but did not find any relevant solution to solve my problem.
I am using Intellij IDE and opening the extent report by using the option of "Open in Browser".
When there are more than two screenshots attached(like in above case) with the extent report, it is showing blank icon and showing error when opening the image in new tab.
(When opening the extent report by going into the folder where it is actually saved in the system, it is working as expected).
My code:
#BeforeTest
public void setExtent() {
extent = new ExtentReports(System.getProperty("user.dir")+ "/test-output/Login.html", true);
System.out.println("KKKKKKK");
extentTest = extent.startTest("Start the Execution");
extent.addSystemInfo("Host Name", "Live Contract");
extent.addSystemInfo("User Name", "Shivam Goyal");
extent.addSystemInfo("Environment", "Develop");
extentTest.log(LogStatus.INFO, "Test Execution started");
}
public static String getScreenshot(WebDriver driver, String screenshotName) {
String dateName = new SimpleDateFormat("ddMMyyyyhhmmss").format(new Date());
TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir")+ "/test-output/"+ screenshotName + dateName + ".png";
File destination = new File(path);
try {
FileUtils.copyFile(src, destination);
}
catch(IOException e){
System.out.println("Capture Failed" +e.getMessage());
}
return path;
}
#Test
public void openURL() throws IOException, InterruptedException, HeadlessException, UnsupportedFlavorException {
System.out.println("test openWeb");
extentTest = extent.startTest("LC1_1.1 - Verify the Login Panel of \"Berater\".");
try {
//Accept All cookies
driver.findElement(By.className(property.getProperty("LiveContractCookies"))).click();
//Test case LC1_1.1 Open the given URL in Browser (Aufruf der entsprechenden URL im Browser)
boolean Homescreen = driver.findElement(By.name(property.getProperty("BeraterLoginPanelName1"))).isDisplayed();
Thread.sleep(3000);
Assert.assertTrue(Homescreen);
} catch (NoSuchElementException e) {
e.printStackTrace();
}
}
#Test
public void checkEntryFields() throws InterruptedException {
extentTest = extent.startTest("LC1_1.2 - Verify the Entry fields on Berater's login panel");
try {
driver.findElement(By.className(property.getProperty("LiveContractCookies"))).click();
WebElement username = driver.findElement(By.name(property.getProperty("username_fieldName")));
WebElement password = driver.findElement(By.name(property.getProperty("password_fieldName")));
username.click();
username.sendKeys("Test123");
password.click();
password.sendKeys("9876554");
Thread.sleep(1000);
System.out.println(username.getText());
String usnm = username.getAttribute("value");
String pass = password.getAttribute("value");
System.out.println("Something happening");
Assert.assertEquals("Test123", usnm);
Assert.assertEquals("98765", pass);
}
catch(Exception e){
e.printStackTrace();
}
}
#AfterMethod
public void tearDown(ITestResult result) {
if(result.getStatus() == ITestResult.FAILURE){
extentTest.log(LogStatus.FAIL, "Test Case Failed is" +result.getName());
extentTest.log(LogStatus.FAIL, "Test Case Failed is" +result.getThrowable());
String screenshotPath = Login.getScreenshot(driver, result.getName());
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));
}
else if(result.getStatus() == ITestResult.SKIP){
extentTest.log(LogStatus.SKIP, "Test Case Skipped is "+result.getName());
}
else if(result.getStatus() == ITestResult.SUCCESS){
extentTest.log(LogStatus.PASS, "Test Case Passed is "+result.getName());
}
extent.endTest(extentTest);
//extent.flush();
driver.quit();
//tempDriver.quit();
//tempDriver.quit();
}
#AfterTest
public void endReport() {
try{
extent.flush();
}
catch(Exception e){
e.getMessage();
}
//extent.close();
}

java.lang.NullPointerException while invoking driver.quit() within #AfterClass annotated method through Selenium WebDriver and JUnit

I created a test using JUnit and in class #AfterClass I put the driver.quit () command to shut down the browser when the tests are finished but the eclipse displays the java.lang.NullPointerException message.
The test class populates several fields and then makes a query in the base, displays the result in the Eclipse console and should close the browser but displays the java.lang.NullPointerException message.
Below is the log and test script.
public class validarStatus {
private static WebDriver driver;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver.exe");
}
#Test
public void validarStatusOs() throws InterruptedException {
WebDriver driver = new ChromeDriver();
driver.get("http://10.5.9.45/BKOMais_S86825EstrategiaBackOfficeClaroFixo");
driver.manage().window().maximize();
// Logar BkoMais
driver.findElement(By.id("matricula_I")).sendKeys("844502");
driver.findElement(By.id("senha_I")).sendKeys("Pw34Jdt#*");
driver.findElement(By.id("bt_entrar")).click();
// Logar na Estratégia
driver.findElement(By.id("mn_backoffice")).click();
driver.findElement(By.id("mn_bkoffice_prod_203")).click();// Produto
driver.findElement(By.id("mn_bkoffice_est_57")).click();// Estratégia
// Selecionado a atividade
Select atividade = new Select(driver.findElement(By.id("cboAtividade")));
atividade.selectByIndex(3);
// Registro >> Novo
Thread.sleep(500);
driver.findElement(By.id("mn_registro")).click();
driver.findElement(By.id("mn_novo_caso")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Cod Os Estratégia VREL
String CodOs = driver.findElement(By.xpath("//*[#id=\"content\"]/div[1]/fieldset[1]/div[2]/div[3]/span"))
.getText();
// Campo Análise de Contrato
Select analiseContrato = new Select(driver.findElement(By.id("cboMotivo")));
analiseContrato.selectByIndex(5);
try {
// Campo Ação
Select acao = new Select(driver.findElement(By.id("cboSubMotivo")));
acao.selectByIndex(3);
// Status
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement ele = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("cboStatus")));
String valorStatus = ele.getText();
// driver.findElement(By.id("cboStatus")).getText();
Assert.assertEquals(" R", valorStatus);
// Chamado
driver.findElement(By.id("txtChamado")).sendKeys("Teste");
// Observação
driver.findElement(By.id("txtObservacao")).sendKeys("Teste 07/06/2018");
// Botão Salvar
driver.findElement(By.id("btnSalvar")).click();
} catch (StaleElementReferenceException e) {
// Campo Ação
Select acao = new Select(driver.findElement(By.id("cboSubMotivo")));
acao.selectByIndex(3);
// Status
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement ele = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("cboStatus")));
String valorStatus = ele.getText();
// String valorStatus = driver.findElement(By.id("cboStatus")).getText();
Assert.assertEquals(" R", valorStatus);
// Chamado
driver.findElement(By.id("txtChamado")).sendKeys("Teste");
// Observação
driver.findElement(By.id("txtObservacao")).sendKeys("Teste 07/06/2018");
// Botão Salvar
driver.findElement(By.id("btnSalvar")).click();
} catch (Exception e) {
// Campo Ação
Select acao = new Select(driver.findElement(By.id("cboSubMotivo")));
acao.selectByIndex(3);
// Status
String valorStatus = driver.findElement(By.id("cboStatus")).getText();
Assert.assertEquals(" R", valorStatus);
// Chamado
driver.findElement(By.id("txtChamado")).sendKeys("Teste");
// Observação
driver.findElement(By.id("txtObservacao")).sendKeys("Teste 07/06/2018");
// Botão Salvar
driver.findElement(By.id("btnSalvar")).click();
}
// Select na base para validar o status da NU_OS
ValidarEstrategiaPage p = new ValidarEstrategiaPage();
p.returnNuOs(CodOs);
// Saindo do Bko+
Thread.sleep(1000);
driver.findElement(By.linkText("Sair")).click();
}
#AfterClass
public static void closeBrowser() {
driver.quit();
}}
You clearly defined your WebDriver object as local variable inside the method:
#Test
public void validarStatusOs() throws InterruptedException {
WebDriver driver = new ChromeDriver();
In order for both the 'After' and 'Test' methods to interact with the global variable, change to:
#Test
public void validarStatusOs() throws InterruptedException {
driver = new ChromeDriver();
And BTW, change your class name from 'validarStatus' to 'ValidarStatus'. Starting a class name in upper case letter is a major best practice in Java.
As per your code block you have defined a global instance of WebDriver as:
private static WebDriver driver;
Within validarStatusOs() method you have initialized another local instance of WebDriver as:
WebDriver driver = new ChromeDriver();
When the control of your program comes out of validarStatusOs() method, the local instance of WebDriver is no more accessible.
So, when the control of your program enters within closeBrowser() method it tries to use the global instance of WebDriver and throws java.lang.NullPointerException.
Solution
As you have declared a global instance of WebDriver, use the same instance throughout your program. So you need to change the line:
WebDriver driver = new ChromeDriver();
To:
driver = new ChromeDriver();

Unable to find the element on emulator screen of Android app

The element appears within the appium view but unfortunately the element does not seems visible while automating it.
private AndroidDriver driver;
String idOfCNIC = "com.tez.androidapp:id/imageViewNICDetails";
this.driver.findElement(By.id(idOfCNIC))`
Following is the driver initialization code :
private static AndroidDriver driver;
public static AndroidDriver getDriver() {
if (driver == null) {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("deviceName", "920121cb3c7fc34a");
caps.setCapability("platformName", "Android");
caps.setCapability(CapabilityType.VERSION, "6.0.1");
caps.setCapability(CapabilityType.BROWSER_NAME, "Android");
caps.setCapability("app", "path_of_app");
(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
try {
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), caps);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return driver;
}
Hi could you please use following versions of Appium java client and Selenium:
Appium Java-Client : 6.0.0-BETA5
Selenium-server : 3.9.1 Appium
Desktop as Appium Inspector : 1.6.1
Also please try with the following code for driver initialization :
private static AndroidDriver<?> driver;
public static AndroidDriver getDriver() {
if (driver == null) {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(MobileCapabilityType.DEVICE_NAME, "920121cb3c7fc34a");
caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
caps.setCapability(MobileCapabilityType.AUTOMATION_NAME,"Appium ");
caps.setCapability(MobileCapabilityType.VERSION, "6.0.1");
caps.setCapability(MobileCapabilityType.APP, "path_of_app");
caps.setCapability("appWaitActivity", "*");
try {
driver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), caps);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return driver;
}
I hope this solves your problem. Thanks!

How to select elements from autosuggest box using selenium webdriver

I m sending the firepath screenshot
I want to select first element and display in element text box
Can someone please help in this
You can update your code as below:
public class SelectAutoSugggestedValue {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("automation tutorial");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List allOptions = driver.findElements(By.xpath("//td/span[text()='automationtutorial']"));
for (int i = 0; i < allOptions.size(); i++) {
String option = allOptions.get(i).getText();
System.out.println(option);
}
}
}

Selenium logs out automatically

I am working on VCM and have created some test script using Selenium and TestNG (not using webdriver).
The problem is that as soon as it logins it automatically logs-out showing the error that the link was not found. If individual run the scripts run perfectly but when running the Suite it always fails showing above mentioned error.
Here's my code for reference:
#BeforeTest
public void setup()
{
selenium = new DefaultSelenium("localhost",4444,"*firefox","http://BaseURL/");
selenium.start();
selenium.windowMaximize();
}
#AfterTest
public void teardown()
{
this.selenium.close();
}
#Test public void testTC_07() throws Exception {
selenium.open("http://BaseWebsite");
selenium.type("name=j_username", "UserId");
selenium.type("name=j_password", "PassWord");
selenium.click("id=login-button");
selenium.waitForPageToLoad("60000");
selenium.click("id=href_Menus");
selenium.waitForPageToLoad("60000");
selenium.click("link=TestContents");
selenium.waitForPageToLoad("60000");
selenium.click("link=Test");
selenium.waitForPageToLoad("60000");
selenium.click("link=Test_title");
selenium.waitForPopUp("Pop Up Window", "60000");
selenium.selectWindow("null");
verifyEquals(selenium.getTitle(), "Test_Title Properties Window");
verifyTrue(selenium.isTextPresent("Title"));
selenium.type("id=textbox", "");
Thread.sleep(10000);
selenium.click("id=doOK");
String title= selenium.getTitle();
if(title!="Window Title"){
selenium.close();
selenium.selectWindow("null");
selenium.click("link=Logout");
selenium.waitForPageToLoad("60000");
}
else{
TC_07.fail(null);
this.selenium.close();
}
}