2015-10-26 3 views
1

Я хотел бы знать, могут ли Selenium и LeanFT играть хорошо вместе. Я не знаю, пытался ли кто-нибудь это сделать, но я думаю, что если он может работать, LeanFT может предоставить некоторые дополнительные преимущества для структуры селена.Совместимость с LeanFT и Selenium?

Как я понимаю, в настоящее время, ограничение селена является:

  • Селена должен открыть начальный браузер признать его
  • Селена должен открыть все всплывающие окна, чтобы распознать их.
  • Selenium WebDriver может стать устаревшим при ожидании процедур, не связанных с селеном.

Я попытался использовать объект UML для предлагаемой модели HP и моей собственной идеи о том, как это может работать.

HP Object Flow

Selenium and LeanFT Object Flow

поток управления будет что-то вроде:

  1. @Before -> globalSetup (LeanFT INIT)
  2. @BeforeClass -> testSetup (LeanFT INIT)
  3. @BeforeClass -> getSeleniumDriver (Selenium)
  4. @Test ->некоторые процедуры селена /**** Чтобы предотвратить селение от смерти. ****/
  5. @test -> Новый -> темы запустить leanFTsnippet1()
  6. @Test - последние шаги>резюме селеном ..
  7. @After -> отчетности, закрытие WebDriver

Вот некоторые из моих текущих кодов из примера Test Class.

@BeforeClass 
public static void beforeLFTClass() throws Exception { 
    globalSetup(CoreFunctionality.class); 
} 

@AfterClass 
public static void afterLFTClass() throws Exception { 
    globalTearDown(); 
} 

@Test 
public void runLeanFtThread() { 
    // put selenium code here 
      // ... 
      // begin leanft part of test 
    Thread leanftThread = new Thread(new Runnable() { 

     @Override 
     public void run() { 
      try { 
       test(); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    }); 
    leanftThread.start(); 
    try { 
     leanftThread.join(); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 


public void test() throws Exception { 

    //Starting Browser 
    Browser browser = BrowserFactory.attach(new BrowserDescription.Builder().title(driver.getTitle()).build()); 
    Assert.assertEquals(browser.getTitle(), driver.getTitle()); 
} 

В любом случае, это довольно интересная проблема. Было бы очень приятно видеть, что вы, ребята, думаете.

Спасибо!

ответ

1

Они действительно прекрасно играют вместе. Я использую их в своих сценариях, и мне нравится использовать возможности каждого инструмента. То, что я сделал, это создать тестовый шаблон LeanFT и добавить к нему библиотеки Selenium.

Вот пример кода:

using System; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 
using HP.LFT.SDK; 
using HP.LFT.SDK.Web; 
using Search_Regression_Test; 
using TestAutomationReporting; 
using UnifiedFramework; 
using System.Configuration; 
using System.Diagnostics; 
using OpenQA.Selenium; 
using OpenQA.Selenium.Chrome; 
using OpenQA.Selenium.Support.UI; 
using Selenium = OpenQA.Selenium; 
namespace Search_Regression_Test 
{ 
    [TestClass] 
    public class LeanFtTest : UnitTestClassBase<LeanFtTest> 
    {   
     static IBrowser browser;   
     static IWebDriver chromeDriver; 

     [ClassInitialize] 
     public static void ClassInitialize(TestContext context) 
     { 

      GlobalSetup(context);       
      ChromeOptions CO = new ChromeOptions(); 
      CO.AddExtension(@"C:\Program Files (x86)\HP\LeanFT\Installations\Chrome\Agent.crx"); 
      chromeDriver = new ChromeDriver(CO); 
      chromeDriver.Manage().Window.Maximize(); 

      browser = BrowserFactory.Attach(new BrowserDescription 
      { 
       Type = BrowserType.Chrome 
      }); 

.... и так далее.

1

Новая версия LeanFT (14) даже привносит определенную Selenium-интеграцию: вы можете выбрать Selenium в качестве своего SDK для автоматизации в мастере создания проекта, есть специализированный центр идентификации объектов Selenium и некоторые дополнительные локаторы и утилиты , Полная история здесь: LeanFT for Selenium.

0

Я не совсем уверен, почему у этого вопроса еще нет принятого ответа, но я собираюсь ответить на это с помощью образца, который еще раз подчеркивает, что LeanFT и Selenium прекрасно играют вместе

Это написано на Java. Вероятно, его можно немного оптимизировать, но он должен четко показать, как вы можете добиться одновременного взаимодействия с тем же браузером.

(Java-проект был создан из шаблонов LeanFT. Оттуда выходит модуль UnitTestClassBase. Он в основном инициализирует LeanFT и репортера за кулисами. Чтобы обойти его, если вы не хотите его использовать, вам придется звоните SDK.init(), Reporter.init(), Reporter.generateReport() и SDK.cleanup() по мере необходимости - check the docs for details)

AUT используется преимущество покупок: http://advantageonlineshopping.com/

package com.demo; 

import static org.junit.Assert.*; 

import java.io.File; 
import java.util.Calendar; 
import java.util.concurrent.TimeUnit; 

import org.junit.After; 
import org.junit.AfterClass; 
import org.junit.Before; 
import org.junit.BeforeClass; 
import org.junit.Test; 
import org.openqa.selenium.support.ui.ExpectedCondition; 
import org.openqa.selenium.support.ui.ExpectedConditions; 
import org.openqa.selenium.support.ui.WebDriverWait; 
import org.openqa.selenium.Keys; 
import org.openqa.selenium.chrome.*; 
import org.openqa.selenium.firefox.*; 
import org.openqa.selenium.remote.DesiredCapabilities; 

import com.hpe.leanft.selenium.By; 
import com.hp.lft.report.Reporter; 
import com.hp.lft.report.Status; 
import com.hp.lft.sdk.web.*; 
import com.hp.lft.verifications.Verify; 


public class SeleniumTest extends UnitTestClassBase { 
    private ChromeDriver chromeDriver; 
    private Browser browser; 
    public SeleniumTest() { 

     System.setProperty("webdriver.chrome.driver",this.getClass().getResource("/chromedriver.exe").getPath()); 

    } 

    @BeforeClass 
    public static void setUpBeforeClass() throws Exception { 
     instance = new SeleniumTest(); 
     globalSetup(SeleniumTest.class); 
    } 

    @AfterClass 
    public static void tearDownAfterClass() throws Exception { 
     globalTearDown(); 
    } 

    @Before 
    public void setUp() throws Exception { 
     // SELENIUM: Construct and launch the browser with LeanFT agent 
     ChromeOptions options = new ChromeOptions(); 
     File paths = new File("C:\\Program Files (x86)\\HP\\LeanFT\\Installations\\Chrome\\Agent.crx"); 
     options.addExtensions(paths); 

     DesiredCapabilities capabilities = new DesiredCapabilities(); 
     capabilities.setCapability(ChromeOptions.CAPABILITY, options); 

     chromeDriver = new ChromeDriver(options); 

    } 

    @After 
    public void tearDown() throws Exception { 
     // LEANFT: close the browser opened by selenium 
     browser.close(); 
    } 

    @Test 
    public void test() throws Exception { 

     // SELENIUM: Go to the Advantage shopping website and maximize it 
     chromeDriver.get("http://156.152.164.67:8080/#/"); 
     chromeDriver.manage().window().maximize(); 

     // LEANFT: Attach to the browser 
     browser = BrowserFactory.attach(new BrowserDescription.Builder() 
       .type(BrowserType.CHROME).openTitle(" Advantage Shopping") 
       .build()); 


     // LEANFT: Click on tablets button 
     browser.describe(WebElement.class, new WebElementDescription.Builder() 
       .className("categoryCell").tagName("DIV").innerText("TABLETS Shop Now ").build()).click(); 

     // SELENIUM: Expand the display section after it was seen 
     (new WebDriverWait(chromeDriver, 10)) 
      .until(new ExpectedCondition<org.openqa.selenium.WebElement>(){ 
      @Override 
      public org.openqa.selenium.WebElement apply(org.openqa.selenium.WebDriver d) { 
       return d.findElement(By.cssSelector("h4#accordionAttrib0")); 
      }}).click(); 


     // LEANFT: select the preferred display size, click the preferred tablet and add the tablet to the cart 
     browser.describe(CheckBox.class, new CheckBoxDescription.Builder() 
       .type("checkbox").role("").accessibilityName("").tagName("INPUT").name("").index(1).build()).set(true); 

     browser.describe(Image.class, new ImageDescription.Builder() 
       .alt("").type(com.hp.lft.sdk.web.ImageType.NORMAL).tagName("IMG").index(1).build()).click(); 

     browser.describe(Button.class, new ButtonDescription.Builder() 
       .buttonType("submit").tagName("BUTTON").name("ADD TO CART").build()).click(); 

     // SELENIUM: go to cart 
     chromeDriver.get("http://156.152.164.67:8080/#/shoppingCart"); 

     // LEANFT: checkout 
     browser.describe(Button.class, new ButtonDescription.Builder() 
       .buttonType("submit").tagName("BUTTON").name("CHECKOUT ($1,009.00)").build()).click(); 

     // SELENIUM: Register as a new user after the button was seen 
     (new WebDriverWait(chromeDriver, 10)) 
      .until(new ExpectedCondition<org.openqa.selenium.WebElement>(){ 
      @Override 
      public org.openqa.selenium.WebElement apply(org.openqa.selenium.WebDriver d) { 
       return d.findElement(By.xpath("//DIV[@id=\"newClient\"]/DIV[1]/SEC-FORM[1]/SEC-SENDER[1]/BUTTON[@role=\"button\"][1]")); 
      }}).click(); 


     // LEANFT: fill in the user name and email 
     String username = "U" + Calendar.getInstance().getTimeInMillis(); // unique name each time 
     browser.describe(EditField.class, new EditFieldDescription.Builder() 
       .type("text").tagName("INPUT").name("userName").build()).setValue(username); 

     browser.describe(EditField.class, new EditFieldDescription.Builder() 
       .type("text").tagName("INPUT").name("userEmail").build()).setValue("[email protected]"); 

     // SELENIUM: Set password and confirm password 
     chromeDriver.findElementByXPath("//SEC-VIEW/DIV[normalize-space()=\"*Password\"]/INPUT[1]").sendKeys("Password1"); 
     chromeDriver.findElementByXPath("//SEC-VIEW/DIV[normalize-space()=\"*Confirm password\"]/INPUT[1]").sendKeys("Password1"); 

     // LEANFT: check the 'I agree' checkbox and register, then click on next shipping details. 
     browser.describe(CheckBox.class, new CheckBoxDescription.Builder() 
       .type("checkbox").tagName("INPUT").name("registrationAgreement").build()).set(true); 

     browser.describe(Button.class, new ButtonDescription.Builder() 
       .buttonType("button").tagName("BUTTON").name("REGISTER").build()).click(); 

     browser.describe(Button.class, new ButtonDescription.Builder() 
       .buttonType("submit").tagName("BUTTON").name("NEXT").build()).click(); 

     // SELENIUM: confirm the user name and pass 
     chromeDriver.findElementByXPath("//DIV[@id=\"paymentMethod\"]/DIV/DIV/SEC-FORM/SEC-VIEW/DIV[normalize-space()=\"*SafePay username\"]/INPUT[1]").sendKeys(username); 
     chromeDriver.findElementByXPath("//DIV[@id=\"paymentMethod\"]/DIV/DIV/SEC-FORM/SEC-VIEW/DIV[normalize-space()=\"*SafePay password\"]/INPUT[1]").sendKeys("Password1"); 

     // LEANFT: click "Pay now" and confirm payment was done 
     browser.describe(Button.class, new ButtonDescription.Builder() 
       .buttonType("button").role("button").accessibilityName("").tagName("BUTTON").name("PAY NOW").index(0).build()).click(); 
     Verify.isTrue(
       browser.describe(WebElement.class, new WebElementDescription.Builder() 
         .tagName("SPAN").innerText("Thank you for buying with Advantage").build()) 
          .exists()); 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^