Re: Need to restart selenium server after few executions

337 views
Skip to first unread message

Edwolb

unread,
Feb 14, 2013, 10:38:02 AM2/14/13
to seleniu...@googlegroups.com
I'd recommend posting the code that you're using to execute it, along with more information about your server setup.

On Monday, 11 February 2013 05:34:06 UTC-5, pcoignant wrote:
I'm with selenium 2.29

I have some tests wich works fine with selenium 2.15. After the upgrade of my firefox, i had to upgrade my selenium version so i take the 2.29

My problem is that now, sometimes, my tests failed because element are not found. It's never the same element and i have implemented implicit and explicit timeout.

Even with a big timemout, several minutes, my tests failed because element is not found but the element is here.

I have noticed that the first time i execute the test after the selenium server is started, my test is passed. The second time, sometimes my test is passed and sometimes my test is failed. And after, my test is always failed.

If i restart the selenium server, the test is OK the first time and after failed. I have also tried to run my test with chrome or internet explorer but my test is also failed. The problem is the same wit internet explorer. With chrome, i have the following error :

Driver  exception org.openqa.selenium.StaleElementReferenceException: getElementTagName execution failed;

I precise that my test is executed with jenkins.

Is there a performance problem with the selenium server ? or am i missing something in my test or the use of timeout ?

Thanks for your help

pcoignant

unread,
Feb 15, 2013, 5:33:28 AM2/15/13
to seleniu...@googlegroups.com
I have changed my code to use a fluent wait but I have the same problem. The function which is called to wait is as follow :


    public static WebElement findElementOnPage(final WebDriver testDriver, final Logger testLogger, int waitingTime, final By elementToFind) {
        FluentWait<WebDriver> wait = new FluentWait<WebDriver>(testDriver)
                .withTimeout(waitingTime, TimeUnit.SECONDS)
                .pollingEvery(500, TimeUnit.MILLISECONDS)
                .ignoring(NoSuchElementException.class);

        return wait.until(new ExpectedCondition<WebElement>() {
            public WebElement apply(WebDriver webDriver) {
                return testDriver.findElement(elementToFind);
            }
        });
    }

This function is called by this type of code :

WebElement selectDepartment = UtilsSelenium.findElementOnPage(driver, createLog, 60, By.id("COMPONENT_fields(departmentId)"));
        Select dropDownDepartment = new Select(selectDepartment);
        dropDownDepartment.selectByVisibleText(department);
       
regardless the value of the waiting time, big or small, i have the error element not find but i can see that the page is completely loaded and the element is present

Thanks

pcoignant

unread,
Feb 15, 2013, 5:39:56 AM2/15/13
to seleniu...@googlegroups.com
and my server setup :

selenium server standalone 2.29
windows 7
4GO of memory
CPU Intel Core 2 Duo 2,53 and 2,54 GHz
Firefox 18

I execute only one test.

pcoignant

unread,
Feb 21, 2013, 11:22:49 AM2/21/13
to seleniu...@googlegroups.com
Am i the only one in this case ?

ASP

unread,
Feb 21, 2013, 11:32:24 AM2/21/13
to seleniu...@googlegroups.com
when I started selenium implementation I had same issues that you are having. when I started doing more research it was because of bad code, xpath. Just looking at few lines of code its very difficult for me to answer you. 

what I did was ... when particular test failed for me. I tried to replicate same scenario manually n then look in a code. if there are ways to improve it I would improve it. I made sure I run test atleast 10 times and try to break it.

hope that helps 


ASP

pcoignant

unread,
Feb 21, 2013, 11:39:02 AM2/21/13
to seleniu...@googlegroups.com
I have new logs from my code obtained by the seleniumEventListener class and the afterFindBy method but they are stranges :

1/02/13 17:19:29.632 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Element By.id: COMPONENT_fields(profileId) found
21/02/13 17:19:29.849 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Element By.xpath: .//option[normalize-space(.) = "ProfSeleniumNoRecord"] found
21/02/13 17:19:30.193 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Click on By.xpath: .//option[normalize-space(.) = "ProfSeleniumNoRecord"]
21/02/13 17:19:32.514 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Element By.id: multswitch_CREATE_FOLD_User_img found
21/02/13 17:19:32.862 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Click on By.id: multswitch_CREATE_FOLD_User_img
21/02/13 17:19:32.994 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Element By.id: COMPONENT_fields(User_firstName) found
21/02/13 17:19:33.369 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Field By.id: COMPONENT_fields(User_firstName) is empty
21/02/13 17:19:33.521 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Element By.id: COMPONENT_fields(User_firstName) found
21/02/13 17:20:35.958 | DEBUG | [main] | [fr.kurmi.Selenium.Dev.Create.CreateUser] | Driver  exception org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"COMPONENT_fields(User_firstName)"}
Command duration or timeout: 60.13 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.29.0', revision: '58258c3', time: '2013-01-17 22:46:35'


I have an exception wich says element not found but this same element is found in the line before and the page have not changed between the two logs. See my code for this exception :

driver.findElement(By.id("multswitch_CREATE_FOLD_User_img")).click();
               
        //Saisie infos user

        //Line with no error in the log
        driver.findElement(By.id("COMPONENT_fields(User_firstName)")).clear();
      //Line in error in the log
        driver.findElement(By.id("COMPONENT_fields(User_firstName)")).sendKeys(firstName);
        driver.findElement(By.id("COMPONENT_fields(User_lastName)")).clear();

If i restart my selenium server, this step of my test will pass for one or time and will failed after

Thanks for the help

ASP

unread,
Feb 21, 2013, 11:46:39 AM2/21/13
to seleniu...@googlegroups.com
can you post your HTML for "COMPONENT_fields(User_firstName)" id ? and some more test code ? 

pcoignant

unread,
Feb 22, 2013, 4:59:33 AM2/22/13
to seleniu...@googlegroups.com
The HTML for the component :

<font class="consultValue">
<span>
<input id="COMPONENT_fields(User_firstName)" class="input" type="text" onchange="setModificationMark('ANY_CHANGE_WARNING');onFieldValueChanged('User_firstName');" onkeypress="return validFormEnterKey(event.keyCode,this);" value="" name="COMPONENT_fields(User_firstName)">
</span>
</font>

pcoignant

unread,
Feb 22, 2013, 5:04:16 AM2/22/13
to seleniu...@googlegroups.com
My test :

//@Stochastic
@Listeners(TestNGListener.class)
public class createUser extends FeedTest{
 
    private WebDriver driver;
       
    private static Logger createLog = Logger.getLogger(createUser.class);
   
   
   
    @BeforeClass
    public void beforeClass() throws Exception {
        System.setProperty("log.directory", this.getClass().getName());
        PropertyConfigurator.configure(System.getProperty("log4j.configuration"));
        driver = UtilsSelenium.createDriver(createLog);
       
    }   
   
    @BeforeMethod
    public void beforeMethod() throws Exception {
        Utils.login(driver,createLog, System.getProperty("base.URL"),"adminSelenium", "adminSelenium");
    }   
   
    @Test(dataProvider = "feeder")
    @Source("fr//Selenium/properties/Data/create/createUserUnique.csv")
    public void createUser(String department, String profil, String equipment, String firstName, String lastName, String middleName, String userId, String password, String pin, String email, Boolean deviceProfil, String phoneButtonTemplate, String product, String modele, String protocol, String securityProfil, String directoryNumber, String macAdress) throws Exception {
        createLog.info("Début du test QuikcCreateUser");
       
        String language = Utils.findLanguage(driver, createLog);
       

        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","ONGLET_create_FR"))).click();       
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","ONGLET_create_EN"))).click();       
           

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible d'effectuer le create. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible d'effectuer le create. Screenshot correspondant : " + screenshotName);
       
        }


        //Selection du contexte

        WebElement selectDepartment = UtilsSelenium.findElementOnPage(driver, createLog, 60, By.id("COMPONENT_fields(departmentId)"));
        Select dropDownDepartment = new Select(selectDepartment);
        dropDownDepartment.selectByVisibleText(department);
        WebElement selectEquipment = UtilsSelenium.findElementOnPage(driver, createLog, 60, By.id("COMPONENT_fields(create_ECOSYSTEM_SELECTOR)"));
        Select dropDownEquipment = new Select(selectEquipment);
        dropDownEquipment.selectByVisibleText(equipment);
        WebElement selectProfile = UtilsSelenium.findElementOnPage(driver, createLog, 60, By.id("COMPONENT_fields(profileId)"));
        Select dropDownProfile = new Select(selectProfile);
        dropDownProfile.selectByVisibleText(profil);
       
        driver.findElement(By.id("multswitch_create_FOLD_User_img")).click();
               
        //Saisie infos user
        driver.findElement(By.id("COMPONENT_fields(User_firstName)")).clear();

        driver.findElement(By.id("COMPONENT_fields(User_firstName)")).sendKeys(firstName);
        driver.findElement(By.id("COMPONENT_fields(User_lastName)")).clear();
        driver.findElement(By.id("COMPONENT_fields(User_lastName)")).sendKeys(lastName);
        driver.findElement(By.id("COMPONENT_fields(User_middleName)")).clear();
        driver.findElement(By.id("COMPONENT_fields(User_middleName)")).sendKeys(middleName);
       
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_create__FR"))).click();       
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_create__EN"))).click();       
           

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible d'appliquer le script . Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible d'appliquer le script . Screenshot correspondant : " + screenshotName);
       
        }
       
        userId = driver.findElement(By.id("COMPONENT_fields(User_userId)")).getAttribute("value");
        driver.findElement(By.id("COMPONENT_fields(User_password)")).clear();
        driver.findElement(By.id("COMPONENT_fields(User_password)")).sendKeys(password);
        driver.findElement(By.id("COMPONENT_fields_confirm(User_password)")).clear();
        driver.findElement(By.id("COMPONENT_fields_confirm(User_password)")).sendKeys(password);
        driver.findElement(By.id("COMPONENT_fields(User_pin)")).clear();
        driver.findElement(By.id("COMPONENT_fields(User_pin)")).sendKeys(pin);
        driver.findElement(By.id("COMPONENT_fields_confirm(User_pin)")).clear();
        driver.findElement(By.id("COMPONENT_fields_confirm(User_pin)")).sendKeys(pin);
        driver.findElement(By.id("COMPONENT_fields(User_email)")).clear();
        driver.findElement(By.id("COMPONENT_fields(User_email)")).sendKeys(email);
        //UtilsSelenium.createScreenshot(driver, createLog, "01-createUserPart_" + userId);
       
        //Saisie infos device profil
        if(deviceProfil)
        {
            driver.findElement(By.id("checkbox_COMPONENT_fields(User_deviceProfile)")).click();
            WebElement selectPhoneButtonTemplate = UtilsSelenium.findElementOnPage(driver, createLog, 60, By.id("COMPONENT_fields(User_devicePhoneButtonTemplate)"));
            Select dropDownPhoneButtonTemplate = new Select(selectPhoneButtonTemplate);
            dropDownPhoneButtonTemplate.selectByVisibleText(phoneButtonTemplate);
            WebElement selectProduct = driver.findElement(By.id("COMPONENT_fields(User_deviceProduct)"));
            Select dropDownProduct = new Select(selectProduct);
            dropDownProduct.selectByVisibleText(product);
            WebElement selectModele = driver.findElement(By.id("COMPONENT_fields(User_deviceModel)"));
            Select dropDownModele = new Select(selectModele);
            dropDownModele.selectByVisibleText(modele);
            WebElement selectProtocol = driver.findElement(By.id("COMPONENT_fields(User_deviceProtocol)"));
            Select dropDownProtocol = new Select(selectProtocol);
            dropDownProtocol.selectByVisibleText(protocol);
            //UtilsSelenium.createScreenshot(driver, createLog, "02-createDeviceProfilPart_" + userId);
        }
       
        //Saisie infos ligne
        driver.findElement(By.id("multswitch_create_FOLD_Line_img")).click();
        driver.findElement(By.xpath("/html/body/div[2]/table/tbody/tr[2]/td[2]/form[2]/table/tbody/tr[3]/td/div/div[2]/table/tbody/tr/td[2]/table/tbody/tr/td[2]/a/img")).click();
        //driver.findElement(By.id("COMPONENT_fields(Line_directoryNumber)")).clear();
        //driver.findElement(By.id("COMPONENT_fields(Line_directoryNumber)")).sendKeys(directoryNumber);
       
        directoryNumber = driver.findElement(By.id("COMPONENT_fields(Line_directoryNumber)")).getAttribute("value");
       
        //UtilsSelenium.createScreenshot(driver, createLog, "03-createLinePart_" + userId);
       
        //Saisie infos device
        driver.findElement(By.id("multswitch_create_FOLD_Device_img")).click();
        driver.findElement(By.id("COMPONENT_fields(Device_ciscoName)")).clear();
        driver.findElement(By.id("COMPONENT_fields(Device_ciscoName)")).sendKeys(macAdress);
        WebElement selectPhoneButtonTemplate = driver.findElement(By.id("COMPONENT_fields(Device_phoneButtonTemplate)"));
        Select dropDownPhoneButtonTemplate = new Select(selectPhoneButtonTemplate);
        dropDownPhoneButtonTemplate.selectByVisibleText(phoneButtonTemplate);
        WebElement selectProduct = driver.findElement(By.id("COMPONENT_fields(Device_product)"));
        Select dropDownProduct = new Select(selectProduct);
        dropDownProduct.selectByVisibleText(product);
        WebElement selectModele = driver.findElement(By.id("COMPONENT_fields(Device_model)"));
        Select dropDownModele = new Select(selectModele);
        dropDownModele.selectByVisibleText(modele);
        WebElement selectProtocol = driver.findElement(By.id("COMPONENT_fields(Device_protocol)"));
        Select dropDownProtocol = new Select(selectProtocol);
        dropDownProtocol.selectByVisibleText(protocol);
        WebElement selectSecurityProfil = driver.findElement(By.id("COMPONENT_fields(Device_securityProfile)"));
        Select dropDownSecurityProfil = new Select(selectSecurityProfil);
        dropDownSecurityProfil.selectByVisibleText(securityProfil);
        //new Select(driver.findElement(By.id("COMPONENT_fields(Device_securityProfile)"))).selectByVisibleText(securityProfil);
        //UtilsSelenium.createScreenshot(driver, createLog, "03-createDevicePart_" + userId);
       
        //Application du create
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_create_CREATE_FR"))).click();       
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_create_CREATE_EN"))).click();       
           

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible d'effectuer le create. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible d'effectuer le create. Screenshot correspondant : " + screenshotName);
       
        }
       
       
        UtilsSelenium.waitingPage(driver, createLog, 120);
       
       
        if(language.equals("FR"))
        {
            UtilsSelenium.verifyMessage(driver, createLog, "04-create_" + userId, UtilsSelenium.getTraduction("Traduction.properties","create_OK_FR"));
            UtilsSelenium.verifyErrorMessage(driver, createLog, "04-createError_" + userId);
            createLog.info("create OK");
        }
        else if(language.equals("EN"))
        {
            UtilsSelenium.verifyMessage(driver, createLog, "04-create_" + userId, UtilsSelenium.getTraduction("Traduction.properties","create_OK_EN"));
            UtilsSelenium.verifyErrorMessage(driver, createLog, "04-createError_" + userId);
            createLog.info("create OK");
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de vérifier le create. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de vérifier le create. Screenshot correspondant : " + screenshotName);
       
        }

        //Click sur le lien suite création pour consultation
        driver.findElement(By.linkText(firstName + " " + lastName + " (" + userId + ")")).click();
        createLog.info("Consultation du composant " + userId);
        //UtilsSelenium.createScreenshot(driver, createLog, "05-ConsultComponent_" + userId);

        //Click sur le bouton Audit depuis page de consultation
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_AUDIT_FR"))).click();       
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_AUDIT_EN"))).click();       
           

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de trouver le bouton audit. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de trouver le bouton audit. Screenshot correspondant : " + screenshotName);
       
        }

        //Click sur le bouton Audit depuis page accueil audit
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_AUDIT_FR"))).click();       
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_AUDIT_EN"))).click();       
           

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de trouver le bouton audit. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de trouver le bouton audit. Screenshot correspondant : " + screenshotName);
       
        }
       
        //Vérification de l'audit
        //TODO checker résultat en fonction du languague et être plus précis sur vérif
        UtilsSelenium.waitingPage(driver, createLog, 120);

        if(language.equals("FR"))
        {
            try{
                UtilsSelenium.verifyMessage(driver, createLog, "06-AuditResult_" + userId, UtilsSelenium.getTraduction("Traduction.properties","AUDIT_OK_FR"));
                UtilsSelenium.verifyErrorMessage(driver, createLog, "06-AuditResultError_" + userId);
                Assert.assertTrue(driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","AUDIT_NO_DIFFERENCE_FR")));
                String randomFileName = UtilsSelenium.createScreenshot(driver, createLog, "06-AuditResult_" + userId);
                createLog.info("Résultat de l'audit: " + driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText());
               
            }
            catch(AssertionFailedError e)
            {
                String randomFileName = UtilsSelenium.createScreenshot(driver, createLog, "06-AuditResult_" + userId);
                createLog.info("Résultat de l'audit: " + driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText());
                Assert.assertTrue("Différences trouvées lors de l'audit: " + driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText(),driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","AUDIT_NO_DIFFERENCE_FR")));
               
            }       
        }
        else if(language.equals("EN"))
        {
            try{
                UtilsSelenium.verifyMessage(driver, createLog, "04-create_" + userId, UtilsSelenium.getTraduction("Traduction.properties","AUDIT_OK_EN"));
                UtilsSelenium.verifyErrorMessage(driver, createLog, "04-createError_" + userId);
                Assert.assertTrue(driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","AUDIT_NO_DIFFERENCE_EN")));
                String randomFileName = UtilsSelenium.createScreenshot(driver, createLog, "06-AuditResult_" + userId);
                createLog.info("Résultat de l'audit: " + driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText());
               
            }
            catch(AssertionFailedError e)
            {
                String randomFileName = UtilsSelenium.createScreenshot(driver, createLog, "06-AuditResult_" + userId);
                createLog.info("Résultat de l'audit: " + driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText());
                Assert.assertTrue("Différences trouvées lors de l'audit: " + driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText(),driver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "AUDIT_RESULT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","AUDIT_NO_DIFFERENCE_EN")));
               
            }

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de vérifier le résultat de l'audit. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de vérifier le résultat de l'audit. Screenshot correspondant : " + screenshotName);
       
        }
       
       
       
        //Click sur bouton back pour retour page de consultation
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_BACK_FR"))).click();       
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_BACK_EN"))).click();       
           

        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de trouver le bouton retour. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de trouver le bouton retour. Screenshot correspondant : " + screenshotName);
       
        }
       
        //Click sur bouton Delete depuis page de consultation
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_DELETE_FR"))).click();
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_DELETE_EN"))).click();
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de trouver le bouton Delete. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de trouver le bouton Delete. Screenshot correspondant : " + screenshotName);
       
        }
       
        //Alert DeleteAlert = driver.switchTo().alert();
        //DeleteAlert.accept();
        //UtilsSelenium.createScreenshot(driver, createLog, "07-DeleteConfirm_" + userId);
       
        //Validation de la confirmation
        if(language.equals("FR"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_CONFIRM_FR"))).click();
        }
        else if(language.equals("EN"))
        {
            driver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","BUTTON_CONFIRM_EN"))).click();
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de trouver le bouton Confirmer. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de trouver le bouton Confirmer. Screenshot correspondant : " + screenshotName);
       
        }
       
        UtilsSelenium.waitingPage(driver, createLog, 120);
       
       
        if(language.equals("FR"))
        {
            UtilsSelenium.verifyMessage(driver, createLog, "04-create_" + userId, UtilsSelenium.getTraduction("Traduction.properties","DELETE_OK_FR"));
            UtilsSelenium.verifyErrorMessage(driver, createLog, "04-createError_" + userId);
            createLog.info("Delete OK");
        }
        else if(language.equals("EN"))
        {
            UtilsSelenium.verifyMessage(driver, createLog, "04-create_" + userId, UtilsSelenium.getTraduction("Traduction.properties","DELETE_OK_EN"));
            UtilsSelenium.verifyErrorMessage(driver, createLog, "04-createError_" + userId);
            createLog.info("Delete OK");
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(driver, createLog, "LanguageUnknown");
            createLog.info("Language inconnu. Impossible de vérifier le Delete. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de vérifier le Delete. Screenshot correspondant : " + screenshotName);
       
        }

    }
   
    @AfterMethod
    public void afterMethod() throws Exception {

        Utils.logout(driver,createLog);

    }
   
   
    @AfterClass
    public void afterClass() {

    System.setProperty("log.directory", this.getClass().getName());
    PropertyConfigurator.configure(System.getProperty("log4j.configuration"));
    UtilsSelenium.closeDriver(driver, createLog);

pcoignant

unread,
Feb 22, 2013, 5:06:05 AM2/22/13
to seleniu...@googlegroups.com
One of my utils class :


package fr..Selenium.Utils;

import junit.framework.Assert;
import junit.framework.AssertionFailedError;

import fr..Selenium.Utils.UtilsSelenium;

import org.apache.log4j.*;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ById;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.TestNGException;



public class Utils {

   
    public static void login(WebDriver testDriver, Logger testLogger, String url, String login, String password) throws Exception{
        testDriver.get(url);
       
        testDriver.switchTo().frame("_iframe");
       
        if(testDriver.findElement(By.className("login_connection_msg")).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","LOGIN_MESSAGE_FR"))  || testDriver.findElement(By.className("login_connection_msg")).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","LOGIN_MESSAGE_EN")))
        {
            testDriver.findElement(By.name("login")).clear();
            testDriver.findElement(By.name("login")).sendKeys(login);
            testDriver.findElement(By.name("password")).clear();
            testDriver.findElement(By.name("password")).sendKeys(password);
            testDriver.findElement(By.className("btn_login")).click();

           
                //if(testDriver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "BUTTON_MY_ACCOUNT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_FR")) || testDriver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "BUTTON_MY_ACCOUNT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_EN")))
                //if(testDriver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_FR"))) !=null || testDriver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_EN"))) != null)
                   
                if(testDriver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "BUTTON_LOGOUT"))) != null)
                {
                    testLogger.info("Login OK avec login " + login + " et password " + password);
                }
                else{
                    throw new NoSuchElementException("Bouton Mon compte non trouvé");
                }
           
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(testDriver, testLogger, "LoginPageUnknown");
            testLogger.info("Page de login incorrecte. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Page de login incorrecte. Screenshot correspondant :" + screenshotName);
        }
    }   
   
    public static void logout(WebDriver testDriver, Logger testLogger) throws Exception{
       
        //String language = Utils.findLanguage(testDriver, testLogger);
       
        /*if(language.equals("FR"))
        {
            testDriver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","LOGOUT_BUTTON_FR"))).click();
            testLogger.info("Logout OK");
        }
        else if(language.equals("EN"))
        {
            testDriver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","LOGOUT_BUTTON_EN"))).click();
            testLogger.info("Logout OK");
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(testDriver, testLogger, "LanguageUnknown");
            testLogger.info("Language inconnu. Impossible de vérifier la déconnexion. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Impossible de vérifier la déconnexion. Screenshot correspondant : " + screenshotName);
       
        }*/
        testDriver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "BUTTON_LOGOUT")));
    }   
   
    public static String findLanguage(WebDriver testDriver, Logger testLogger) throws Exception{
       
        if(testDriver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_FR"))) != null)
        {
            return "FR";
        }
        else if(testDriver.findElement(By.linkText(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_EN"))) != null )
        {
            return "EN";
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(testDriver, testLogger, "LanguageUnknown");
            testLogger.info("Language inconnu. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Screenshot correspondant : " + screenshotName);
        }
       
    }
   
public static String findLanguageByXPath(WebDriver testDriver, Logger testLogger) throws Exception{
       
        if(testDriver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "BUTTON_MY_ACCOUNT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_FR")))
        {
            return "FR";
        }
        else if(testDriver.findElement(By.xpath(UtilsSelenium.getXpath("Xpath.properties", "BUTTON_MY_ACCOUNT"))).getText().contains(UtilsSelenium.getTraduction("Traduction.properties","LANGUAGE_EN")))
        {
            return "EN";
        }
        else
        {
            String screenshotName = UtilsSelenium.createScreenshot(testDriver, testLogger, "LanguageUnknown");
            testLogger.info("Language inconnu. Screenshot correspondant : " + screenshotName);
           
            throw new AssertionFailedError("Language inconnu. Screenshot correspondant : " + screenshotName);

pcoignant

unread,
Feb 22, 2013, 5:08:06 AM2/22/13
to seleniu...@googlegroups.com
and the other utils method :

    //private static Logger utilsSeleniumLog = Logger.getLogger(UtilsSelenium.class);
   
    public static String getTraduction(String fileName,String key)throws Exception{
       
        Properties traduction = new Properties();
        //FileInputStream trad = new FileInputStream("src/fr//Selenium/properties/Traductions/" + fileName);
        try{
        traduction.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("fr//Selenium/properties/Traductions/" + fileName));
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return traduction.getProperty(key);
    }
   
public static String getTestProperties(String directory, String fileName,String key)throws Exception{
       
        Properties testProperties = new Properties();
        //FileInputStream trad = new FileInputStream("src/fr//Selenium/properties/Traductions/" + fileName);
        try{
        testProperties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("fr//Selenium/properties/Data/" + directory + File.separator + fileName));
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return testProperties.getProperty(key);
    }
   
public static String getXpath(String fileName,String key)throws Exception{
       
        Properties Xpath = new Properties();
        //FileInputStream trad = new FileInputStream("src/fr//Selenium/properties/Traductions/" + fileName);
        try{
        Xpath.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("fr//Selenium/properties/Xpath/" + fileName));
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return Xpath.getProperty(key);
    }
   
    public static WebDriver createDriver(Logger testLogger) throws Exception{
       
       
        WebDriver driver;
       
        WebDriverEventListener eventListener = new SeleniumEventListener(testLogger);
        //FirefoxProfile profile = new ProfilesIni().getProfile("Selenium");
        //profile.
        DesiredCapabilities driverCapabilities = new DesiredCapabilities();
       
        driverCapabilities.setBrowserName(System.getProperty("driver.Type"));
        driverCapabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
        //driverCapabilities.setCapability(FirefoxDriver.PROFILE, profile);

        driver = new EventFiringWebDriver(new ScreenShotRemoteWebDriver(new URL(System.getProperty("selenium.Server")),driverCapabilities)).register(eventListener);
       
        //driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.manage().window().maximize();
       
       
        testLogger.info("Driver de type " + System.getProperty("driver.Type") + " lancé sur le server Selenium " + System.getProperty("selenium.Server"));
       
        return driver;
       
    }
   
    public static void closeDriver(WebDriver driver, Logger logger){
       
        StringBuffer verificationErrors = new StringBuffer();
       
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            Assert.fail(verificationErrorString);
        }
       
        logger.info("Driver fermé");
       
        }

   
    public static void verifyMessage(WebDriver testDriver, Logger testLogger, String filename, String message) throws Exception{
       
        try{
            Assert.assertTrue(testDriver.findElement(By.className("message")).getText().contains(message));
            String randomFileName = createScreenshot(testDriver, testLogger, filename);
            testLogger.info("Message " + testDriver.findElement(By.className("message")).getText() + " trouvé. Screenshot correspondant : " + randomFileName);
        }
        catch(AssertionFailedError e)
        {
            verifyErrorMessage(testDriver, testLogger, filename + "_Error");
            String randomFileName = createScreenshot(testDriver, testLogger, "Message");
            testLogger.info("Message " + testDriver.findElement(By.className("message")).getText() + " trouvé à la place de " + message + " Screenshot correspondant : " + randomFileName);
            Assert.assertTrue("Message " + testDriver.findElement(By.className("message")).getText() + " trouvé à la place de " + message + " Screenshot correspondant : " + randomFileName,testDriver.findElement(By.className("message")).getText().contains(message));
           
        }
       
    }
   
    public static void verifyErrorMessage(WebDriver testDriver, Logger testLogger, String filename) throws Exception{
       
        try
        {
            Assert.assertTrue(testDriver.findElement(By.className("error")).getText().isEmpty());
        }
        catch(AssertionFailedError e)
        {
            String randomFileName = createScreenshot(testDriver, testLogger, filename);
            testLogger.info("Message d'erreur trouvé : " + testDriver.findElement(By.className("error")).getText() + " Screenshot correspondant : " + randomFileName);
            Assert.assertTrue("Message d'erreur trouvé : " + testDriver.findElement(By.className("error")).getText() + " Screenshot correspondant : " + randomFileName,testDriver.findElement(By.className("error")).getText().isEmpty());

        }
    }
   
    public static void waitingPage(WebDriver testDriver, final Logger testLogger, int waitingTime){
        testDriver.manage().timeouts().implicitlyWait(waitingTime, TimeUnit.SECONDS);
        WebElement myDynamicElement = (new WebDriverWait(testDriver, waitingTime, 7000)).until(new ExpectedCondition<WebElement>(){
       
        @Override
        public WebElement apply(WebDriver d) {
            testLogger.info("Page d attente");   
            WebElement result = null;
               
               
            if(d.findElement(By.className("message")) != null)
            {
                result = d.findElement(By.className("message"));
            }
            if(d.findElement(By.className("error")) != null)
            {
                result = d.findElement(By.className("error"));
            }
            return result;
        }
    }
       
    );
        testDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    }
   
    public static void waitingLoadingOfPage(final WebDriver testDriver, final Logger testLogger, int waitingTime, final By elementToFind){

       
        FluentWait<WebDriver> wait = new FluentWait<WebDriver>(testDriver)
                    .withTimeout(waitingTime, TimeUnit.SECONDS)
                    .pollingEvery(500, TimeUnit.MILLISECONDS)
                    .ignoring(NoSuchElementException.class);

            wait.until(new ExpectedCondition<WebElement>() {
                public WebElement apply(WebDriver webDriver) {
                    return testDriver.findElement(elementToFind);
                }
            });
       
       
       
    }
   
    public static WebElement findElementOnPage(final WebDriver testDriver, final Logger testLogger, int waitingTime, final By elementToFind) {
        FluentWait<WebDriver> wait = new FluentWait<WebDriver>(testDriver)
                .withTimeout(waitingTime, TimeUnit.SECONDS)
                .pollingEvery(500, TimeUnit.MILLISECONDS)
                .ignoring(NoSuchElementException.class);

        return wait.until(new ExpectedCondition<WebElement>() {
            public WebElement apply(WebDriver webDriver) {
                return testDriver.findElement(elementToFind);
            }
        });
    }
     
   
        public static String createScreenshot(WebDriver testDriver, Logger testLogger, String fileName) throws Exception{
            File screenshot = ((TakesScreenshot)testDriver).getScreenshotAs(OutputType.FILE);
            String randomFileName = System.getProperty("test.screenshot") + File.separator + testLogger.getName() + File.separator + UtilsSelenium.generateRandomFilename() +  "-" + fileName + ".png";
            FileUtils.copyFile(screenshot, new File(randomFileName));
            testLogger.info("Screenshot pris :" + randomFileName);
            return randomFileName;
    }
   
        public static String generateRandomFilename() {
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH)+1;
        String filename = c.get(Calendar.YEAR) +
            "-" + month +
            "-" + c.get(Calendar.DAY_OF_MONTH) +
            "-" + c.get(Calendar.HOUR_OF_DAY) +
            "-" + c.get(Calendar.MINUTE) +
            "-" + c.get(Calendar.SECOND);
        return filename;
    }
   
        public static String generateRandomFilename(Throwable arg0) {
        Calendar c = Calendar.getInstance();
        String filename = arg0.getMessage();
        int i = filename.indexOf('\n');
        int month = c.get(Calendar.MONTH)+1;
        filename = filename.substring(0, i).replaceAll("\\s", "_").replaceAll(":", "") + ".jpg";
        filename = "" + c.get(Calendar.YEAR) +
            "-" + month +
            "-" + c.get(Calendar.DAY_OF_MONTH) +
            "-" + c.get(Calendar.HOUR_OF_DAY) +
            "-" + c.get(Calendar.MINUTE) +
            "-" + c.get(Calendar.SECOND) +
            "-" + filename;
        return filename;
    }
   
    public static void createScreenCaptureJPEG(String filename, Logger testLogger) {
          try {
           BufferedImage img = getScreenAsBufferedImage();
           File output = new File(System.getProperty("test.screenshot") + File.separator + testLogger.getName() + File.separator +filename);
           ImageIO.write(img, "png", output);
           testLogger.info("Screenshot Système pris : " + filename);
          } catch (IOException e) {
           e.printStackTrace();
          }
         }
         
         private static BufferedImage getScreenAsBufferedImage() {
          BufferedImage img = null;
          try {
           Robot r;
           r = new Robot();
           Toolkit t = Toolkit.getDefaultToolkit();
           Rectangle rect = new Rectangle(t.getScreenSize());
           img = r.createScreenCapture(rect);
          } catch (AWTException e) {
           e.printStackTrace();
          }
          return img;
         }
         
         public static void waitForPopUp(final WebDriver driver, final String windowName, int timeoutMs)
         {
            new Wait()
            {
               @Override
               public boolean until()
               {
                  try
                  {
                     driver.switchTo().window(windowName);
                     return true;
                  }
                  catch (SeleniumException ignored) { }
                  return false;
               }
            }.wait(String.format("Timed out waiting for %s. Waited %s",windowName, timeoutMs), timeoutMs);
Reply all
Reply to author
Forward
0 new messages