jeudi 5 mars 2015

Remonter des résultats de tests automatisés (Selenium) dans TestLink

Prendre en compte les tests automatisés et leurs résultats dans un outil de gestion de tests est essentiel. Ils doivent être tracés et comptabiliser, avec les tests manuels, dans le calcul des différents métriques. Grâce à son interface de communication XML-RPC, TestLink permet d’automatiser aussi la remontée des résultats des tests automatiques. Le code ci-après l’illustre avec un exemple de test utilisant Selenium. La version utilisée de TestLink est la 1.9.12.

Préalable : un plan de test exécutable, contenant la description du test automatisé correspondant, doit exister dans TestLink. L’usage de XML-RPC doit être activé dans la configuration de TestLink.
Réserves : l’exemple suivant de test simplifié n’est pas un test écrit dans les règles de l’art  pour Selenium. Son objectif est de montrer comment remonter des résultats dans TestLink.
J’utilise TestLink Java API écrite par Bruno P. Kinoshita . Elle encapsule les appels à XML-RPC traduisant les erreurs retournées en une exception. Les noms des fonctions Java correspondent à ceux dans TestLink XML-RPC. Les principes décrits ici peuvent être facilement transposés dans un autre langage et un autre outil d’automatisation de tests.

        


package com.altixio.selenium.example;



import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


import org.apache.commons.codec.binary.Base64;
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.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import br.eti.kinoshita.testlinkjavaapi.TestLinkAPI;
import br.eti.kinoshita.testlinkjavaapi.constants.ExecutionStatus;
import br.eti.kinoshita.testlinkjavaapi.model.Attachment;
import br.eti.kinoshita.testlinkjavaapi.model.ReportTCResultResponse;
import br.eti.kinoshita.testlinkjavaapi.util.TestLinkAPIException;

/**

public class TestAutomation  {
    // Clé API Interface dans TestLink > My Settings
    public static String DEVKEY="8f33d58eaa4cdc4dfeefb056e3ed40e5";
    public static String TL_URL="http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php";
    
    public static void main(String[] args) {
        
        TestLinkAPI api = null;
        URL testlinkURL = null;
        
        try     {
                testlinkURL = new URL(TL_URL);
        } catch ( MalformedURLException mue )   {
                mue.printStackTrace( System.err );
                System.exit(-1);
        }
        
        try     {
            api = new TestLinkAPI(testlinkURL, DEVKEY);
            
            // Verifie si le serveur repond
            System.out.println("TestLink : " + api.ping());
            
            // Verifie si l'utilisateur est reconnu par TestLink
            if (api.checkDevKey(DEVKEY)) {
                System.out.println("Testlink key valid !");
            }
            
        } catch( TestLinkAPIException te) {
            te.printStackTrace( System.err );
            System.exit(-1);
        }
        
        // Cree une instance du Firefox Driver
        
        WebDriver driver = new FirefoxDriver();

        // Visite google
        driver.get("http://www.google.fr");
        

        // Trouve le chanp de saisie de texte par son nom
        WebElement element = driver.findElement(By.name("q"));

        // Entre le texte à rechercher
        element.sendKeys("altixio");

        // Valide le formulaire 
        element.submit();

        
        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());
        
        
        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("altixio");
            }
        });

        
        String notes = "";
        boolean success = true;
        
        ArrayList<File> screenshots = new ArrayList<File>();
        
        
        // Le titre de la fenêtre devrait être : "altixio - Google Search"
        System.out.println("Page title is: " + driver.getTitle());
        // Step 1 Verify that title starts with the search query
        try {
            assert driver.getTitle().toLowerCase().startsWith("altixio");
            notes += "Step 1 : passed.\n";
            success = true;
        }
        catch (AssertionError ae) {
            success = false;
            notes += "Step 1 : failed. Window title is "  + driver.getTitle()
                    + " while altixio - Google Search was expected \n";
            
            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            // Now you can do whatever you need to do with it, for example copy somewhere
            try {
                FileUtils.copyFile(scrFile, new File("./ta_screenshot_step1.png"));
                screenshots.add(scrFile);
            } catch (IOException ioe) {
                // TODO Auto-generated catch block
                ioe.printStackTrace(System.err);
            }
        }
       
        // Parcourir les resultats de recherche
        // Verifier que altixio est le premier résultat de recherche
        List<WebElement> allSearchResults = 
                driver.findElements(By.cssSelector("ol li h3>a"));

         //... en extrayant les titres et les liens. 
        int pos = 1;
        boolean found = false;
        for(WebElement eachResult : allSearchResults) {
            System.out.println("Title : "+eachResult.getText()+", " +
                    "Link : "+ eachResult.getAttribute("href"));
            if (eachResult.getAttribute("href").startsWith("altixio")) {
                if (pos == 1) {
                    notes += "Step 2 : passed.\n";
                    found = true;
                    
                    
                }
                else {
                    notes += "Step 2 : failed. Altixio is not the first result.\n";
                    found = true;
                    success = false;
                }
                break;
            }
            pos++;
        }
        
        if (!found) {
            success = false;
            notes += "Step 2 : failed. Altixio not found in the search results.\nTest failed.";
        }
        
        if (success) {
            notes += "Test passed.\n";
        
        }
        
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        // Now you can do whatever you need to do with it, for example copy somewhere
        try {
            FileUtils.copyFile(scrFile, new File("./ta_screenshot_step2.png"));
            screenshots.add(scrFile);
        } catch (IOException ioe) {
            // TODO Auto-generated catch block
            ioe.printStackTrace(System.err);
        }
        
        System.out.println(notes);
                
        // Reporting des resultats du test dans TestLink
        try {
            // Recuperation du testcaseId
            int id = api.getTestCaseIDByName(
                    "test-auto1" // testCaseName
                    , "google" //testSuiteName
                    , "selenium-demo" //testProjectName, 
                    , null // testCasePathName
                    );
            
            System.out.println("testcaseid :" + id);
            // Enregistrement des resultats dans TestLink
            ReportTCResultResponse response = api.reportTCResult(id,
                    null, 
                    34, 
                    (success) ? ExecutionStatus.PASSED : ExecutionStatus.FAILED, 
                    null, "google-2015", notes, true, null, 
                    null, "Desktop - Ubuntu 12. 10 64 bits", null, true);
            
            System.out.println(response.toString());
            
            
            
                for(File scrShot : screenshots) {

                    String fileContent = null;

                    try {
                        byte[] byteArray = 
                                FileUtils.readFileToByteArray(scrShot);
                        fileContent = new String(Base64.encodeBase64(byteArray));
                    } catch (IOException e) {
                        e.printStackTrace( System.err );
                        System.exit(-1);
                    }

                    Attachment attachment =  api.uploadExecutionAttachment(
                            response.getExecutionId(), //executionId 
                            "Altixio Google Search", //titre
                            "Affichage des resultats de recherche", //description  
                            "screenshot_google_altixio_"+System.currentTimeMillis()+".png", //fileName 
                            "image/png", //fileType
                            fileContent); //content

                    System.out.println("Attachment uploaded " + attachment.getFileName());
                }
            
        } catch (TestLinkAPIException e) {
            
            e.printStackTrace(System.err);
        }
        
        
       // Ferme le navigateur
        driver.quit();
    }
}

Aucun commentaire:

Enregistrer un commentaire