Visualizzazione post con etichetta Selenium. Mostra tutti i post
Visualizzazione post con etichetta Selenium. Mostra tutti i post

martedì 22 maggio 2012

Selenium: The 5 Minute Getting Started Guide


http://code.google.com/p/selenium/wiki/GettingStarted

WebDriver is a tool for automating testing web applications, and in particular to verify that they work as expected. It aims to provide a friendly API that's easy to explore and understand, which will help make your tests easier to read and maintain. It's not tied to any particular test framework, so it can be used equally well with JUnit, TestNG or from a plain old "main" method. This "Getting Started" guide introduces you to WebDriver's Java API and helps get you started becoming familiar with it.
Start by downloading the latest binaries and unpack them into a directory. A safe choice is the latest version of selenium-server-standalone-x.y.z.jar x, y and z will be digits e.g. 2.4.0 at the time of writing. From now on, we'll refer to this directory as $WEBDRIVER_HOME. Now, open your favourite IDE and:
  • Start a new Java project in your favourite IDE
  • Add all the JAR files under $WEBDRIVER_HOME to the CLASSPATH
You can see that WebDriver acts just as a normal Java library does: it's entirely self-contained, and you don't need to remember to start any additional processes or run any installers before using it.
You're now ready to write some code. An easy way to get started is this example, which searches for the term "Cheese" on Google and then outputs the result page's title to the console. You'll start by using the HtmlUnitDriver. This is a pure Java driver that runs entirely in-memory. Because of this, you won't see a new browser window open.
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example  {
    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
    }
}
Compile and run it. You should see a line with the title of the Google search results as output. Congratulations, you've managed to get started with WebDriver!
In this next example, let's use a page that requires Javascript to work properly, such as Google Suggest. You will also be using the FirefoxDriver. Make sure that Firefox is installed on your machine and is in the normal location for your OS.
Once that's done, create a new class called GoogleSuggest, which looks like:
package org.openqa.selenium.example;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSuggest {
    public static void main(String[] args) throws Exception {
        // The Firefox driver supports javascript 
        WebDriver driver = new FirefoxDriver();
        
        // Go to the Google Suggest home page
        driver.get("http://www.google.com/webhp?complete=1&hl=en");
        
        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("Cheese");

        // Sleep until the div we want is visible or 5 seconds is over
        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
            WebElement resultsDiv = driver.findElement(By.className("gac_m"));

            // If results have been returned, the results are displayed in a drop down.
            if (resultsDiv.isDisplayed()) {
              break;
            }
        }

        // And now list the suggestions
        List<WebElement> allSuggestions = driver.findElements(By.xpath("//td[@class='gac_c']"));
        
        for (WebElement suggestion : allSuggestions) {
            System.out.println(suggestion.getText());
        }
     }
}
When you run this program, you'll see the list of suggestions being printed to the console. That's all there is to using WebDriver!
Hopefully, this will have whet your appetite for more. In the NextSteps page, you will learn how more about how to use WebDriver. It covers aspects such as navigating forward and backward in your browser's history, how to use frames and windows and it provides a more complete discussion of the examples than has been done as you've been GettingStarted. If you're ready, let's take the NextSteps!

lunedì 21 maggio 2012

Selenium e Bugzilla

Introduzione

Nella guida su BugzillaQA ( https://wiki.mozilla.org/Bugzilla:QA) si spiega come eseguire dei test automatici con Selenium su Bugzilla.


La procedura di configurazione, per un neofita come me, è lunga e tediosa e a conti fatti non so se vale la pena il tempo e la fatica impiegata.
Scopo finale di tuta questo penoso cammino è quello di mettersi in condizioni per scrivere ed eseguire degli script di testing in Perl, linguaggio ch enon conosco e che a prima vista neanche mi piace.
E' come intraprendere un impervio sentiero sotto la pioggia (l'installazione e configurazione di selenium, perl, e quanto ne consegue) che ti porta finalmente a scalare una montagna ostile (perl) alla cui vetta ti attendono nubi e freddo (testscript per bugzilla)...non proprio invitante.


Cmq ormai sono giunto alla fine di questo cammino e scrivo delle note come promemoria.


Si parte dalla guida di BugzillaQA ( https://wiki.mozilla.org/Bugzilla:QA) che ci dice per prima cosa di scaricare gli script già pronti per testare BZ tramite Selenium Server.

Bazaar

I sorgenti con gli script sono archiviati su Bazaar.
Si tratta di un sistem di gestione delle versioni. Per potervi accedere e scaricare il codice occorre installare il client da Bazaar
ATTENZIONE, non è immediato da usare come lo è Tortoise, io ho fatto un po' di confusione e ancora non ne son venuto fuori, ho un sacco di cartelle con un'icona con il punto interrogativo, alcune con un baffo verde e non so come a rimettere a posto le cose.
Quindi consiglio di dare un'occhiata alla documentazione prima di avventurarsi troppo oltre.
Comunque si riesce abbastanza agevolmente a scaricare gli script con il comando:
bzr co bzr://bzr.mozilla.org/bugzilla/qa/4.0
Una volta scaricato il tutto, nella cartella \config si covrebbero trovare 2 file:
- selenium_test.conf
- generate_test_data.pl

Prima si deve configurare il primo file, non sono sicuro di quali parametri debbano essere riempiti, di certo io non li ho riempiti tutti, limitandomi a quelli che mi parevano principali.

Poi si lancia il secondo e...

C:\Bazaar\4.0\config>generate_test_data.pl
reading the config file...
creating user accounts...


permanent_user@my.company is now set up as an administrator.
creating bugs...
creating classifications...
creating products...
creating groups...
Creating group Master...
adding users to groups...
restricting products to groups...
creating flag types...
creating custom fields...
Adding new table cf_qa_status...
Adding new table bug_cf_qa_status...
Adding foreign key: bug_cf_qa_status.value -> cf_qa_status.value...
Adding foreign key: bug_cf_qa_status.bug_id -> bugs.bug_id...
Adding new column 'cf_single_select' to the 'bugs' table...
Adding new table cf_single_select...
** Parameters have been modified by this script. Please re-run
** checksetup.pl to set file permissions on data/params correctly.


Creating private bug(s)...
creating attachments...
creating keywords...
installation and configuration complete!

 Alla fine il nostro DB è miracolosamente popolato con ben 2 bugs!

A questo punto la cosa è un po' meno complessa di come l'avevo affrontata ieri, non occorre ricompilare tutto Selenium Server.

Selenium Server

 Per avviare Selenium Server basta scaricare il jar Selenium Server (formerly the Selenium RC Server)
dal sito: http://seleniumhq.org/download/ (attualmente la versione 2.21.0).
Io l'ho ffrettolosamnete messa in C:\Users\Duccio\Documents\Software\Selenium.
A questo punto per avviare il server basta digitare:
java -jar C:\Users\Duccio\Documents\Software\Selenium\selenium-server-standalone-2.21.0.jar
Sembra essere andato tutto bene:

C:\Perl64>java -jar C:\Users\Duccio\Documents\Software\Selenium\selenium-server-
standalone-2.21.0.jar
mag 22, 2012 12:23:56 AM org.openqa.grid.selenium.GridLauncher main
Informazioni: Launching a standalone server
00:23:57.640 INFO - Java: Oracle Corporation 21.1-b02
00:23:57.660 INFO - OS: Windows 7 6.1 amd64
00:23:57.677 INFO - v2.21.0, with Core v2.21.0. Built from revision 16552
00:23:58.022 INFO - RemoteWebDriver instances should connect to: http://127.0.0.
1:4444/wd/hub
00:23:58.028 INFO - Version Jetty/5.1.x
00:23:58.030 INFO - Started HttpContext[/selenium-server/driver,/selenium-server
/driver]
00:23:58.031 INFO - Started HttpContext[/selenium-server,/selenium-server]
00:23:58.031 INFO - Started HttpContext[/,/]
00:23:58.177 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@2d510b
03
00:23:58.182 INFO - Started HttpContext[/wd,/wd]
00:23:58.191 INFO - Started SocketListener on 0.0.0.0:4444
00:23:58.193 INFO - Started org.openqa.jetty.jetty.Server@1a60232c

 Test::WWW::Selenium

A questo punto siamo pronti per lanciare gli script? Non ancora!
Se si prova a lanciare gli script con prove -v --timer *.tsi ottiene una bella serie di segnalazioni tipo questa:

QA/Util.pm line 9.
BEGIN failed--compilation aborted at lib/QA/Util.pm line 9.
Compilation failed in require at webservice_bug_fields.t line 7.
BEGIN failed--compilation aborted at webservice_bug_fields.t line 7.
Dubious, test returned 2 (wstat 512, 0x200)
No subtests run
[00:27:31] webservice_bug_get_bugs.t ................. Can't locate Test/WWW/Sel
enium.pm in @INC (@INC contains: lib C:/Perl64/site/lib C:/Perl64/lib .) at lib/
QA/Util.pm line 9.
BEGIN failed--compilation aborted at lib/QA/Util.pm line 9.
Compilation failed in require at webservice_bug_get_bugs.t line 10.
BEGIN failed--compilation aborted at webservice_bug_get_bugs.t line 10.
Dubious, test returned 2 (wstat 512, 0x200)
No subtests run
[00:27:31] webservice_bug_history.t .................. Can't locate Test/WWW/Sel
enium.pm in @INC (@INC contains: lib C:/Perl64/site/lib C:/Perl64/lib .) at lib/
QA/Util.pm line 9.

La spiegazione si trova subito sotto nella guida, dove si legge:

 Note that the Test::WWW::Selenium Perl module must be installed in order for the scripts to execute. It is the interface between Perl and Selenium!


Questa frasettina apparentemente innocua nasconde diverse insidie.
Il modulo in questione si scarica da qui:

http://search.cpan.org/~lukec/Test-WWW-Selenium/lib/Test/WWW/Selenium.pm


ma non è un semplice file da scaricare ed installare, sulla pagina a destra, c'è infatti il link per il download un bel .tar.gz da compilarsi a mano.

Anche stavolta l'ho scompattato molto pigramente in:          C:\Users\Duccio\Documents\Software\Selenium\Test-WWW-Selenium-1.33


A questo bene sarebbe bene cercare di capire bene come ci si comporta con questi moduli.
Qui di seguito riporto un paio di guide che ho trovato e ricopiato in questo blog:
Riassumento si scopre che per compilare il modulo in Windows7 occorre prima scaricarsi 2 eseguibili fondamentali:
Se provo a compilare il modulo senza GCC ho questo messaggio di errore:
It looks like you don't have a C compiler on your PATH, so you will not be
able to compile C or XS extension modules.  You can install GCC from the
MinGW package using the Perl Package Manager by running:
    ppm install MinGW


Se provo ad usare ppm install MinGW ho l'errore:

C:\Users\Duccio\Documents\Software\Selenium\Test-WWW-Selenium-1.33>ppm install M
inGW
Downloading ActiveState Package Repository packlist...done
Updating ActiveState Package Repository database...done
ppm install failed: Can't find any package that provides MinGW

Messaggi analoghi si hanno per nmake e dmake.


A questo punto si può procedere a compilare il modulo così:

C:\Users\Duccio\Documents\Software\Selenium\Test-WWW-Selenium-1.33> perl Makefile.PL
C:\Users\Duccio\Documents\Software\Selenium\Test-WWW-Selenium-1.33> dmake
C:\Users\Duccio\Documents\Software\Selenium\Test-WWW-Selenium-1.33> dmake test
C:\Users\Duccio\Documents\Software\Selenium\Test-WWW-Selenium-1.33> dmake install


Esecuzione

Adesso si può procedere con l'esecuzione degli script di test.
ci si posiziona nella cartella dove ho scaricato gli script per Bugzilla, stavolta invece che in \conf si accede alla cartella \t (nel mio caso C:\Bazaar\4.0\t)
poi si digita:
prove -v --timer *.t

In questo modo parte l'esecuzione degli script.
L'avanzamenteo si vede dal propmpt dos che mostra l'avanzamento degli scipt in \t
l'altra finestra dos è quella del server selenium
l'istanza firefox inferiore mostra l'esecuzione dello script
mentre quella superiore è Selenium Remote Control.



Non ho capito come ottenere un report delle esecuzioni fatte, infatti i risultati posso vederli solo dalla finestra DOS.
Inoltre no capisco da dove posso bloccare e riprendere l'esecuzione, dato che da Selenium Remote Control non posso fare assolutamente nulla.
L'unico modo che ho trovato per fermare l'esecuzione è chiudere ilprompt dos.

domenica 20 maggio 2012

Compilare Selenium Server

Occorre  scaricare e installare Maven dal sito:
http://maven.apache.org/download.html

Per configurare Maven fare riferimento alla guida sulla stessa pagina che indica:

Windows 2000/XP

  1. Unzip the distribution archive, i.e. apache-maven-3.0.4-bin.zip to the directory you wish to install Maven 3.0.4. These instructions assume you chose C:\Program Files\Apache Software Foundation. The subdirectory apache-maven-3.0.4 will be created from the archive.
  2. Add the M2_HOME environment variable by opening up the system properties (WinKey + Pause), selecting the "Advanced" tab, and the "Environment Variables" button, then adding the M2_HOME variable in the user variables with the value C:\Program Files\Apache Software Foundation\apache-maven-3.0.4. Be sure to omit any quotation marks around the path even if it contains spaces. Note: For Maven < 2.0.9, also be sure that the M2_HOME doesn't have a '\' as last character.
  3. In the same dialog, add the M2 environment variable in the user variables with the value %M2_HOME%\bin.
  4. Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.
  5. In the same dialog, update/create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line.
  6. In the same dialog, make sure that JAVA_HOME exists in your user variables or in the system variables and it is set to the location of your JDK, e.g. C:\Program Files\Java\jdk1.5.0_02 and that %JAVA_HOME%\bin is in your Path environment variable.
  7. Open a new command prompt (Winkey + R then type cmd) and run mvn --version to verify that it is correctly installed.
attenzione:
nel mio caso ho docuto aggiungere la variabile di ambiente path, a quelle di sistema e non a quelle utente.

Una volta eseguita con successo la verifica con  mvn --version, ho provato a creare un nuovo file pom.xml, semplicemene copiando l'esempio proposto nella guida di selenium:

l'unica verifica che ho fatto è stata sulla versione di selenium da scaricare, per il resto ho copiato e basta.

Ho lanciato "mvn clean install" ed ho ricevuto un errore, sitrattava di FoxyProxy video Utility che già in passato mi aveva dato noie. L'ho disinstallata e ho creato il progetto.
Un paio di volte il processo di download e creazione del progrtto si è interrotto, ma riprovando alla fine ho ottenuto tutto quanto: compresa la cartella target con il jar.


Ho lanciato "mvn eclipse:eclipse" ed ho creato il progetto eclipse senza problemi.
Quando ho provato a caricarlo però ho ricevuto una serie di errori:

Unbound classpath variable: 'M2_REPO/cglib/cglib-nodep/2.1_3/cglib-nodep-2.1_3.jar' in project 'selenium-server-standalone-2.21.0'

A quanto pare basta seguire le indicazioni di:

e aggiungere una variabile di ambiente:

Define and add M2_REPO classpath variable manually into Eclipse IDE. Follow below steps :
  1. Eclipse IDE, menu bar
  2. Select Window > Preferences
  3. Select Java > Build Path > Classpath Variables
  4. Click on the new button > defined a new M2_REPO variable and point it to your local Maven repository
  5. Done.
ATTENZIONE! quale path devo associare ad M2_REPO?