在selenium webdriver中使用md-select和md-option进行下拉选择

时间:2018-03-21 09:17:57

标签: selenium-webdriver drop-down-menu md-select

如何在selenium webdriver中使用md-select和md-option选择下拉列表。

选择不支持的课程。

<md-select placeholder="Filter" class="filter-select md-no-underline ng-pristine ng-valid ng-empty ng-touched" ng-model="$ctrl.dummy" aria-label="Filters" tabindex="0" aria-disabled="false" role="listbox" aria-expanded="false" aria-multiselectable="false" id="select_80" aria-invalid="false" style=""><md-select-value class="md-select-value md-select-placeholder" id="select_value_label_70"><span>Filter</span><span class="md-select-icon" aria-hidden="true"></span></md-select-value><div class="md-select-menu-container" aria-hidden="true" role="presentation" id="select_container_81"><md-select-menu role="presentation" class="_md"><md-content class="_md">
            <!-- ngRepeat: filter in $ctrl.allFilters --><md-option md-option-empty="" ng-repeat="filter in $ctrl.allFilters" ng-click="$ctrl.applyFilter(filter)" ng-keyup="$event.keyCode === 32 ? $ctrl.applyFilter(filter) : null" tabindex="0" class="ng-scope md-ink-ripple" role="option" aria-selected="false" id="select_option_93"><div class="md-text ng-binding">
                Pending
            </div></md-option><!-- end ngRepeat: filter in $ctrl.allFilters --><md-option md-option-empty="" ng-repeat="filter in $ctrl.allFilters" ng-click="$ctrl.applyFilter(filter)" ng-keyup="$event.keyCode === 32 ? $ctrl.applyFilter(filter) : null" tabindex="0" class="ng-scope md-ink-ripple" role="option" aria-selected="false" id="select_option_94"><div class="md-text ng-binding">
                Posted
            </div></md-option><!-- end ngRepeat: filter in $ctrl.allFilters --><md-option md-option-empty="" ng-repeat="filter in $ctrl.allFilters" ng-click="$ctrl.applyFilter(filter)" ng-keyup="$event.keyCode === 32 ? $ctrl.applyFilter(filter) : null" tabindex="0" class="ng-scope md-ink-ripple" role="option" aria-selected="false" id="select_option_95"><div class="md-text ng-binding">
                Checks &amp; eChecks
            </div></md-option><!-- end ngRepeat: filter in $ctrl.allFilters --><md-option md-option-empty="" ng-repeat="filter in $ctrl.allFilters" ng-click="$ctrl.applyFilter(filter)" ng-keyup="$event.keyCode === 32 ? $ctrl.applyFilter(filter) : null" tabindex="0" class="ng-scope md-ink-ripple" role="option" aria-selected="false" id="select_option_96"><div class="md-text ng-binding">
                Deposit
            </div></md-option><!-- end ngRepeat: filter in $ctrl.allFilters --><md-option md-option-empty="" ng-repeat="filter in $ctrl.allFilters" ng-click="$ctrl.applyFilter(filter)" ng-keyup="$event.keyCode === 32 ? $ctrl.applyFilter(filter) : null" tabindex="0" class="ng-scope md-ink-ripple" role="option" aria-selected="false" id="select_option_97"><div class="md-text ng-binding">
                Withdrawal
            </div></md-option><!-- end ngRepeat: filter in $ctrl.allFilters -->
        </md-content></md-select-menu></div></md-select>

5 个答案:

答案 0 :(得分:0)

假设您要从选项中选择Pending。你可以这样做:

WebElement option = driver.findElement(By.id("select_option_93"));
option.click();

答案 1 :(得分:0)

以下代码提供了来自selenium驱动程序的完美设备连接

    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import com.perfectomobile.selenium.api.IMobileDevice;
    import com.perfectomobile.selenium.api.IMobileDriver;
    import com.perfectomobile.selenium.api.IMobileWebDriver;
    import com.perfectomobile.selenium.params.analyze.text.MobileTextMatchMode;
    public class BofaApp_app extends PerfectoMobileBasicTest implements Runnable{

        /*
        *
        *   Class Name  : PerfectoMobileBasicTest
        *   Author      : Uzi Eilon <uzie@perfectomobile.com>
        *   Date        : Dec 6th 2013  
        *   
        *   Description :
        *   Mobile Native application test 
        *   The test open the BOFA app (on a real device) and looks for an ATM.
        *   This test contains IMobileWebDriver (extension to webdriver), which allows the to get native and visual objects on mobile app 
        * 
        */


        public BofaApp_app(IMobileDriver driver) {
            super(driver);
        }

        @Override
        public void execTest() {


            IMobileDevice device = ((IMobileDriver) _driver).getDevice(_DeviceId);
            device.open();
            device.home();

            IMobileWebDriver webDriver = _driver.getDevice(_DeviceId).getVisualDriver();
            webDriver.findElement(By.linkText("Bofa")).click();

            IMobileWebDriver init = _driver.getDevice(_DeviceId).getVisualDriver();
            init.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
            init.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
            init.findElement(By.linkText("Account")).click();   

            webDriver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
             webDriver.findElement(By.linkText("Save this online"));
             webDriver.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
             webDriver.findElement(By.linkText("Locations")).click();
             webDriver.findElement(By.linkText("Find Bank of America ATMs"));
             IMobileWebDriver zip = _driver.getDevice(_DeviceId).getVisualDriver();
             zip.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
             zip.findElement(By.linkText("zip code")).click();
             sleep(2000);
             zip.findElement(By.linkText("zip code")).click();
             sleep(2000);
             webDriver.manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
             webDriver.manageMobile().visualOptions().ocrOptions().setLevelsLow(120);
             webDriver.findElement(By.linkText("Code")).sendKeys("02459");

             zip.findElement(By.linkText("Done")).click();
             zip.findElement(By.linkText("Go")).click();
             webDriver.findElement(By.linkText("Newton MA"));


        } 
    }*
    public class Constants
    {
      /** Project Constants */
       public static final String REPORT_LIB = "C:\\Test\\";
       public static final String HTML_REPORT_NAME = "Total.html";
       public static final String PM_USER = "uzie@perfectomobile.com";

       public static final String PM_PASSWORD = "*************";
       public static final String PM_CLOUD = "prerelease.perfectomobile.com";
       }
    public interface ExecutionReporter {


        /*
        *
        *   Class Name  : ExecutionReporter
        *   Author      : Uzi Eilon <uzie@perfectomobile.com>
        *   Date        : Dec 6th 2013  
        *   
        *   Description :
        *   Reporter allows you to build an summary report which aggregate all the executions the results and the link for the specific test report 
        *   You can find an HTML reporter in this project
        *   
        */

        public void reportHeader (String title);

        public void addLine(String testName,String deviceID,String repID,boolean status);

        public void closeRep();

    }
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    /*
    *
    *   Class Name  : HTMLReporter
    *   Author      : Uzi Eilon <uzie@perfectomobile.com>
    *   Date        : Dec 6th 2013  
    *   
    *   Description :
    *   implements ExecutionReporter and create an HTML summary report 
    *   
    */
    public class HTMLReporter implements ExecutionReporter  {

        BufferedWriter _bw = null;
        public HTMLReporter (String title )
        {
            reportHeader(title);
        }

        public void reportHeader (String title)
        {
            String repName = Constants.REPORT_LIB+ Constants.HTML_REPORT_NAME;
            File f = new File (repName) ;
            try {
                _bw = new BufferedWriter(new FileWriter(f));
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                 Calendar cal = Calendar.getInstance();

                _bw.write("<p> Date  :"+dateFormat.format(cal.getTime())+" </p>");
                _bw.write("<p> Test Name: "+title+"</p>");
                _bw.write("<p>");
                _bw.write("<p>");
                _bw.write("<table border=\"1\">");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public void addLine(String testName,String deviceID,String repID,boolean status)
        {
            try {
                _bw.write("<tr>");
                _bw.write("<td>"+testName+"</td>");
                _bw.write("<td>"+deviceID+"</td>");
                _bw.write("<td> <a href=\""+repID+"\">Report</a></td>");

                _bw.write("<td>"+status+"</td>");
                _bw.write("</tr>");


            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        public void closeRep()
        {
            try {
                _bw.write("</table></p></body></html>");
                _bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    import java.lang.reflect.Constructor;
    import com.perfectomobile.selenium.*;
    import com.perfectomobile.selenium.api.*;
    public class MobileTest {


        /*
        *
        *   Class Name  : MobileTest
        *   Author      : Uzi Eilon <uzie@perfectomobile.com>
        *   Date        : Dec 6th 2013  
        *   
        *   Description :
        *   Mobile Executer gets list of test and devices and execute it on the available devices 
        *   in this example the list arrive form array [] [] 
        *   The tests run on real devices in Perfecto Mobile cloud 
            */


        public static void main(String[] args) {
            System.out.println("Script started");
            String host = Constants.PM_CLOUD;
            String user = Constants.PM_USER;
            String password = Constants.PM_PASSWORD;


            String[] [] testcase ={
            //   {"PerfectoTestCheckFlight","3230D2D238BECF6D"},
            //  {"PerfectoTestCheckFlight","4A8203C8DBAB382EE6BB8021B825A736CA734484"},
                 {"BofaApp_app","4A8203C8DBAB382EE6BB8021B825A736CA734484"},
            //       {"usAirways","3230D2D238BECF6D"}

            };

            ExecutionReporter reporter = new HTMLReporter("Regression Test Tesults");
            try {
                for(int i =0; i < testcase.length; i++)
                  {
                    IMobileDriver driver = new MobileDriver(host, user, password);
                    String className = testcase[i][0];
                    String device  = testcase[i][1];

                    PerfectoMobileBasicTest test = null;
                    Constructor con = null;

                    try {
                         con = Class.forName(className).getConstructor(IMobileDriver.class);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    try {
                         test = (PerfectoMobileBasicTest)con.newInstance(driver);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    //PerfectoMobileBasicTest test = new PerfectoTestCheckFlight(driver);
                    test.setDeviceID(device);
                    Thread t = new Thread(test);
                    t.start();
                    reporter.addLine(className,device,test.getRepName(),test.getStatus());
                    }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                reporter.closeRep();
            }
        }


    }
    import java.io.File;
    import java.io.InputStream;
    import com.perfectomobile.httpclient.MediaType;
    import com.perfectomobile.httpclient.utils.FileUtils;
    import com.perfectomobile.selenium.api.IMobileDriver;
    /*
    *
    *   Class Name  : PerfectoMobileBasicTest
    *   Author      : Uzi Eilon <uzie@perfectomobile.com>
    *   Date        : Dec 6th 2013  
    *   
    *   Description :
    Basic abstract perfecto mobile test - Each test need to extend this class and implement the actual test in the PerfectoMobileBasicTest
    *   This basic test handles the driver and the device
    */
    public abstract class PerfectoMobileBasicTest implements Runnable{

        String _DeviceId = null;
        IMobileDriver _driver;
        boolean _status = true; 

        @Override
        public void run() {
            try
            {
                execTest();
            }catch (Exception e)
            {
                _status = false; 
            }

            closeTest();
            getRep(MediaType.HTML);
        }


        public PerfectoMobileBasicTest (IMobileDriver driver)
        {
            _driver = driver;
        } 



        public Boolean getStatus() {
            return _status  ;
        }

        public void setDeviceID(String Device) {
            _DeviceId= Device;
        }

        public String  getRepName() {
            String className = this.getClass().getName();
            String name = Constants.REPORT_LIB+className+_DeviceId+".HTML";
            return  name;

        }
        public void getRep(MediaType Type) {
            InputStream reportStream = ((IMobileDriver) _driver).downloadReport(Type);

            if (reportStream != null) {
                File reportFile = new File(getRepName());
                FileUtils.write(reportStream, reportFile);
            }
        }

        public  void sleep(long millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {
            }
        }

        public  void closeTest( ) {
            _driver.quit();

        }


        public abstract void execTest() throws Exception ;
    }*
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import com.perfectomobile.selenium.api.IMobileDevice;
    import com.perfectomobile.selenium.api.IMobileDriver;
    import com.perfectomobile.selenium.api.IMobileWebDriver;
    /*
    *
    *   Class Name  : PerfectoTestCheckFlight
    *   Author      : Uzi Eilon <uzie@perfectomobile.com>
    *   Date        : Dec 6th 2013  
    *   
    *   Description :
    *   Mobile web test 
    *   the test go to united.com (on a real device) and check the status of flights number 84
    *   it use a web driver which connected to Perfecto Mobile cloud.
    *   the test is based on a  webDriver test 
    */
    public class PerfectoTestCheckFlight extends PerfectoMobileBasicTest implements Runnable{
        public PerfectoTestCheckFlight(IMobileDriver driver) {
            super(driver);
        }

        @Override
        public void execTest() {

            IMobileDevice device = ((IMobileDriver) _driver).getDevice(_DeviceId);
            device.open();
            device.home();

            //device.getScreenText()
            //device.checkpointText("search");
            WebDriver webDriver = device.getDOMDriver ("www.united.com");
            webDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            webDriver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
            //sleep(2000);

             question?
            String url = webDriver.getCurrentUrl();
            String title = webDriver.getTitle();
            System.out.println("url: " + url + ", title: " + title);

            WebElement webElement = webDriver.findElement(By.xpath("(//#text)[53]"));
            webElement.click();

            webElement = webDriver.findElement(By.xpath("(//@id=\"FlightNumber\")[1]"));
            webElement.sendKeys("84");
            webDriver.findElement(By.xpath("(//INPUT)[5]")).click();

        }*

答案 2 :(得分:0)

package test.java;
public class Constants
{
    /** Project Constants */
    public static final String WORK_LIB = "C:\\Jenkins_ex\\";
    //public static final String WORK_LIB = "C:\\api\\";

    // iphone 7 public 
    //public static final String DEVICE = "85C3C17D957CCC302C81F78DDE59C4F71DFF1AAE";
    // iphone 6 public
    //public static final String DEVICE = "1AF1270E544117EBC3E3D4B5AC27A9E34E5F6B54";

    public static final String DEVICE = "4859ABC4B4F7EF8CCD9FF0C4F8A47B9FFC0B5D0A";


//  public static final String APP_NAME = "Southwest.ipa";
    public static final String APP_NAME = "PMIOSDemo.ipa";
    public static final String REPOSITORY_KEY = "PRIVATE:uziHTTPTest/"+APP_NAME;

//  public static final String PM_USER = "uzie@perfectomobile.com";
    public static final String PM_PASSWORD = "PM2563";
    public static final String PM_USER = "uzie@perfectomobile.com";

    public static final String PM_CLOUD = "demo.perfectomobile.com";

    public static final String REPORT_LIB = "c:\\test\\";
//  public static final String REPORT_LIB = ".\";

}
package test.java;

import org.testng.annotations.Test;

public class EmptyTest {
  @Test
  public void f() {
    System.out.println("test!!!");  
  }

ackage test.java;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.perfectomobile.selenium.api.IMobileDevice;
import com.perfectomobile.selenium.api.IMobileWebDriver;
import com.perfectomobile.selenium.options.visual.text.MobileTextMatchMode;

public class PerfectoTest {


    public String checkFlights(IMobileDevice device)
    {
        String text ;
        try
        {
            device.open();
            //device.home();

            // Define to types of web driver 
            // 1. DOM - standard web webdriver works with the DOM objects
            // 2. Visual Driver - allows to validate that text appear on the screen using visual analysis (OCR).
            //    This validation is very important and simulate the real user experience.

            IMobileWebDriver  webDriver = device.getDOMDriver ("www.united.com");
            WebDriver visualDriver = device.getVisualDriver();

            webDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            webDriver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
            //webDriver.clean();
            // press on the button "flight status"
            visualDriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);


            try{
                visualDriver.findElement(By.linkText("Continue to site"));
            }catch (Exception e)
            {
                //no error 
            }
            visualDriver.findElement(By.linkText("Flight Status"));
            List<WebElement> objList  = webDriver.findElements(By.xpath("//*[contains(@class,\"ui-link-inherit\")]"));

            for (int i = 0 ; i <objList.size() ; i++)
            {
                WebElement item = objList.get(i);
                if (item.getText().equals("Flight Status"))
                {
                    item.click();
                    i = objList.size();

                }

            }

            visualDriver.findElement(By.linkText("Search"));


            // press on the button "flight number"
            webDriver.findElement(By.xpath("(//input[@id=\"FlightNumber\"])[1]")).sendKeys("84");



            // press on the button "Search"
            visualDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
            ((IMobileWebDriver) visualDriver).manageMobile().visualOptions().textMatchOptions().setMode(MobileTextMatchMode.LAST);
            visualDriver.findElement(By.linkText("Search"));


            visualDriver.findElement(By.linkText("search")).click();

            //webDriver.findElement(By.xpath("(//INPUT)[5]")).click();

            // visual based validation - validate the text appear on the screen and can be seen by users.
            visualDriver.findElement(By.linkText("New York/Newark"));

            // object based validation - validate the text appear in the as part of the DOM structure 

            text = webDriver.findElement(By.xpath("(.//div[@class='ui-block-b'])[1]")).getAttribute("text");
            System.out.println(">>>>>>>>>>>>>>"+text);

        }catch (Exception e)
        {
            return "error";
        }
        return  text;

    ackage test.java;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

import com.perfectomobile.httpclient.MediaType;
import com.perfectomobile.httpclient.utils.FileUtils;
import com.perfectomobile.selenium.MobileDriver;
import com.perfectomobile.selenium.api.IMobileDevice;
import com.perfectomobile.selenium.api.IMobileDriver;
import com.perfectomobile.selenium.options.MobileDeviceProperty;

public class TestNGUnitedTest {

    String _Device;
    @BeforeMethod
    public void beforeMethod() {

    }

    @BeforeTest
    public void beforeTest() {


    }

    public void afterTest(MobileDriver driver){
        driver.quit();
        InputStream reportStream = ((IMobileDriver) driver).downloadReport(MediaType.HTML);

        if (reportStream != null) {
            try {

                File theDir = new File(Constants.REPORT_LIB);
                if (!theDir.exists()) theDir.mkdir();
                File reportFile = new File(Constants.REPORT_LIB+"TestNG_"+_Device+".HTML");
                FileUtils.write(reportStream, reportFile);
                Reporter.log( Constants.REPORT_LIB+"TestNG_"+_Device+".HTML");

                String filename =Constants.REPORT_LIB+"TestNG_"+_Device+".HTML"  ;
            //  Reporter.log("</br><b>Report:</b> <a href=" + filename +">Report</a>");


                BufferedReader br = new BufferedReader(new FileReader(filename));

                StringBuilder sb = new StringBuilder();
                String line = br.readLine();

                Reporter.log("<DIV valign=\"top\" align=\"left\" style=\"font-family: Verdana; font-style: normal; font-variant: normal; font-weight: normal; font-size: 10pt; color: black; text-indent: 0em; letter-spacing: normal; word-spacing: normal; text-transform: none;margin-top: 0pt; margin-bottom: 20pt; height: 3.146in; width: 10.562in; white-space: normal; line-height: normal\">");

                while (line != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                    line = br.readLine();
                }
                Reporter.log(sb.toString());

                Reporter.log("</DIV>");
                br.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

        }
    }

     @DataProvider(name = "Devices" , parallel = true)
        public Object[][] testSumInput() {
            return new Object[][] { { "Android", "65256B3C" } ,
                         { "Android", "04157DF4C454EC06" } ,
                        {"Iphone","DD992AFA0B69A5E2C2006A7A657690476B0086FE"},
                        {"Iphone","FD9F4CC08F6E4637ADC5D3443193978D7B8E4942"}

            };
        }

    //@Parameters({ "deviceID" })
    @Test (dataProvider="Devices")
    public void CheckFlight(String Type,String deviceID) {
        _Device = deviceID;
        String host = Constants.PM_CLOUD;
        String user = Constants.PM_USER;
        String password = Constants.PM_PASSWORD;
        MobileDriver driver = new MobileDriver(host, user, password);
        Reporter.log("Connect to:"+host);
        System.out.println(" **** new Drivewr  " + deviceID);

        Reporter.log("device:"+deviceID);
        IMobileDevice device = driver.getDevice(deviceID);
        Reporter.log("device MODEL :"+device.getProperty(MobileDeviceProperty.MODEL));
        Reporter.log("device OS :"+device.getProperty(MobileDeviceProperty.OS));

        PerfectoTest t = new PerfectoTest();
        String rc =  t.checkFlights(device);

        //assert rc.equals("New York/Newark, NJ (EWR)") : "Expected  New York/Newark, NJ (EWR)" + rc;
        afterTest(driver);

    }
package test.java;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

import com.perfectomobile.httpclient.MediaType;
import com.perfectomobile.httpclient.utils.FileUtils;
import com.perfectomobile.selenium.MobileDriver;
import com.perfectomobile.selenium.api.IMobileDevice;
import com.perfectomobile.selenium.api.IMobileDriver;
import com.perfectomobile.selenium.options.MobileDeviceProperty;

public class emptyDPTest {

    String _Device;
    MobileDriver driver;
    @BeforeMethod
    public void beforeMethod() {
    }

    @BeforeTest
    public void beforeTest() {

        String host = Constants.PM_CLOUD;
        String user = Constants.PM_USER;
        String password = Constants.PM_PASSWORD;
        driver = new MobileDriver(host, user, password);
        Reporter.log("Connect to:"+host);
    }

    @AfterSuite
    public void afterTest(){
        driver.quit();
        InputStream reportStream = ((IMobileDriver) driver).downloadReport(MediaType.HTML);

        if (reportStream != null) {
            try {
                File reportFile = new File(Constants.REPORT_LIB+"TestNG_"+_Device+".HTML");
                FileUtils.write(reportStream, reportFile);
                Reporter.log( Constants.REPORT_LIB+"TestNG_"+_Device+".HTML");

                String filename =Constants.REPORT_LIB+"TestNG_"+_Device+".HTML"  ;
            //  Reporter.log("</br><b>Report:</b> <a href=" + filename +">Report</a>");


                BufferedReader br = new BufferedReader(new FileReader(filename));

                StringBuilder sb = new StringBuilder();
                String line = br.readLine();

                Reporter.log("<DIV>");

                while (line != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                    line = br.readLine();
                }
                Reporter.log(sb.toString());

                Reporter.log("</DIV>");
                br.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

        }
    }


     @DataProvider(name = "Devices" , parallel = true)
        public Object[][] testSumInput() {
            return new Object[][] { { "Android", "0149BCA71700D01F" }, 
                                    { "Android", "CD6C2ED905F210B1" },
                                    { "Android", "A1A5438E" } };
        }



    //@Parameters({ "deviceID" })
    @Test (dataProvider="Devices" )
     public void testDevices(String type,String deviceID) {
        System.out.println(" ******************* runtest on   " + deviceID);

    }

}
© 2018 GitHub, Inc.

答案 3 :(得分:0)

utility- part 4

  //************* GET EMAIL PROPERTIES *******************

  public static String getEmailAddressFromProperties(){
    return System.getProperty("email.address");
  }

  public static String getEmailUsernameFromProperties(){
    return System.getProperty("email.username");
  }

  public static String getEmailPasswordFromProperties(){
    return System.getProperty("email.password");
  }

  public static String getEmailProtocolFromProperties(){
    return System.getProperty("email.protocol");
  }

  public static int getEmailPortFromProperties(){
    return Integer.parseInt(System.getProperty("email.port"));
  }

  public static String getEmailServerFromProperties(){
    return System.getProperty("email.server");
  }

utility-5

  //************* EMAIL ACTIONS *******************

  public void openEmail(Message message) throws Exception{
    message.getContent();
  }

  public int getNumberOfMessages() throws MessagingException {
    return folder.getMessageCount();
  }

  public int getNumberOfUnreadMessages()throws MessagingException {
    return folder.getUnreadMessageCount();
  }

  /**
   * Gets a message by its position in the folder. The earliest message is indexed at 1.
   */
  public Message getMessageByIndex(int index) throws MessagingException {
    return folder.getMessage(index);
  }

  public Message getLatestMessage() throws MessagingException{
    return getMessageByIndex(getNumberOfMessages());
  }

  /**
   * Gets all messages within the folder
   */
  public Message[] getAllMessages() throws MessagingException {
    return folder.getMessages();
  }

  /**
   * @param maxToGet maximum number of messages to get, starting from the latest. For example, enter 100 to get the last 100 messages received.
   */
  public Message[] getMessages(int maxToGet) throws MessagingException {
    Map<String, Integer> indices = getStartAndEndIndices(maxToGet);
    return folder.getMessages(indices.get("startIndex"), indices.get("endIndex"));
  }

  /**
   * Searches for messages with a specific subject
   * @param subject Subject to search messages for
   * @param unreadOnly Indicate whether to only return matched messages that are unread
   * @param maxToSearch maximum number of messages to search, starting from the latest. For example, enter 100 to search through the last 100 messages.
   */
  public Message[] getMessagesBySubject(String subject, boolean unreadOnly, int maxToSearch) throws Exception{
    Map<String, Integer> indices = getStartAndEndIndices(maxToSearch);

    Message messages[] = folder.search(
        new SubjectTerm(subject),
        folder.getMessages(indices.get("startIndex"), indices.get("endIndex")));

    if(unreadOnly){
      List<Message> unreadMessages = new ArrayList<Message>();
      for (Message message : messages) {
        if(isMessageUnread(message)) {
          unreadMessages.add(message);
        }
      }
      messages = unreadMessages.toArray(new Message[]{});
    }

    return messages;
  }

  /**
   * Returns HTML of the email's content
   */
  public String getMessageContent(Message message) throws Exception {
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
      buffer.append(line);
    }
    return buffer.toString();
  }

  /**
   * Returns all urls from an email message with the linkText specified
   */
  public List<String> getUrlsFromMessage(Message message, String linkText) throws Exception{
    String html = getMessageContent(message);
    List<String> allMatches = new ArrayList<String>();
    Matcher matcher = Pattern.compile("(<a [^>]+>)"+linkText+"</a>").matcher(html);
    while (matcher.find()) {
      String aTag = matcher.group(1);
      allMatches.add(aTag.substring(aTag.indexOf("http"), aTag.indexOf("\">")));
    }
    return allMatches;
  }

  private Map<String, Integer> getStartAndEndIndices(int max) throws MessagingException {
    int endIndex = getNumberOfMessages();
    int startIndex = endIndex - max;

    //In event that maxToGet is greater than number of messages that exist
    if(startIndex < 1){
      startIndex = 1;
    }

    Map<String, Integer> indices = new HashMap<String, Integer>();
    indices.put("startIndex", startIndex);
    indices.put("endIndex", endIndex);

    return indices;
  }

utility- part 6

  /**
   * Searches an email message for a specific string
   */
  public boolean isTextInMessage(Message message, String text) throws Exception {
    String content = getMessageContent(message);

    //Some Strings within the email have whitespace and some have break coding. Need to be the same.
    content = content.replace("&nbsp;", " ");
    return content.contains(text);
  }

  public boolean isMessageInFolder(String subject, boolean unreadOnly) throws Exception {
    int messagesFound = getMessagesBySubject(subject, unreadOnly, getNumberOfMessages()).length;
    return messagesFound > 0;
  }

  public boolean isMessageUnread(Message message) throws Exception {
    return !message.isSet(Flags.Flag.SEEN);
  }
}

Utility -7
Emailutils.java

package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SubjectTerm;



/**
 * Utility for interacting with an Email application
 */
public class EmailUtils {

  private Folder folder;

  public enum EmailFolder {
    INBOX("INBOX"),
    SPAM("SPAM");

    private String text;

    private EmailFolder(String text){
      this.text = text;
    }

    public String getText() {
      return text;
    }
  }

  /**
   * Uses email.username and email.password properties from the properties file. Reads from Inbox folder of the email application
   * @throws MessagingException
   */
  public EmailUtils() throws MessagingException {
    this(EmailFolder.INBOX);
  }

  /**
   * Uses username and password in properties file to read from a given folder of the email application
   * @param emailFolder Folder in email application to interact with
   * @throws MessagingException
   */
  public EmailUtils(EmailFolder emailFolder) throws MessagingException {
    this(getEmailUsernameFromProperties(),
        getEmailPasswordFromProperties(),
        getEmailServerFromProperties(),
        emailFolder);
  }

  /**
   * Connects to email server with credentials provided to read from a given folder of the email application
   * @param username Email username (e.g. janedoe@email.com)
   * @param password Email password
   * @param server Email server (e.g. smtp.email.com)
   * @param emailFolder Folder in email application to interact with
   */
  public EmailUtils(String username, String password, String server, EmailFolder emailFolder) throws MessagingException {
    Properties props = System.getProperties();
    try {
      props.load(new FileInputStream(new File("resources/email.properties")));
    } catch(Exception e) {
      e.printStackTrace();
      System.exit(-1);
    }

    Session session = Session.getInstance(props);
    Store store = session.getStore("imaps");
    store.connect(server, username, password);


    folder = store.getFolder(emailFolder.getText());
    folder.open(Folder.READ_WRITE);
  }



  //************* GET EMAIL PROPERTIES *******************

  public static String getEmailAddressFromProperties(){
    return System.getProperty("email.address");
  }

  public static String getEmailUsernameFromProperties(){
    return System.getProperty("email.username");
  }

  public static String getEmailPasswordFromProperties(){
    return System.getProperty("email.password");
  }

  public static String getEmailProtocolFromProperties(){
    return System.getProperty("email.protocol");
  }

  public static int getEmailPortFromProperties(){
    return Integer.parseInt(System.getProperty("email.port"));
  }

  public static String getEmailServerFromProperties(){
    return System.getProperty("email.server");
  }




  //************* EMAIL ACTIONS *******************

  public void openEmail(Message message) throws Exception{
    message.getContent();
  }

  public int getNumberOfMessages() throws MessagingException {
    return folder.getMessageCount();
  }

  public int getNumberOfUnreadMessages()throws MessagingException {
    return folder.getUnreadMessageCount();
  }

  /**
   * Gets a message by its position in the folder. The earliest message is indexed at 1.
   */
  public Message getMessageByIndex(int index) throws MessagingException {
    return folder.getMessage(index);
  }

  public Message getLatestMessage() throws MessagingException{
    return getMessageByIndex(getNumberOfMessages());
  }

  /**
   * Gets all messages within the folder
   */
  public Message[] getAllMessages() throws MessagingException {
    return folder.getMessages();
  }

  /**
   * @param maxToGet maximum number of messages to get, starting from the latest. For example, enter 100 to get the last 100 messages received.
   */
  public Message[] getMessages(int maxToGet) throws MessagingException {
    Map<String, Integer> indices = getStartAndEndIndices(maxToGet);
    return folder.getMessages(indices.get("startIndex"), indices.get("endIndex"));
  }

  /**
   * Searches for messages with a specific subject
   * @param subject Subject to search messages for
   * @param unreadOnly Indicate whether to only return matched messages that are unread
   * @param maxToSearch maximum number of messages to search, starting from the latest. For example, enter 100 to search through the last 100 messages.
   */
  public Message[] getMessagesBySubject(String subject, boolean unreadOnly, int maxToSearch) throws Exception{
    Map<String, Integer> indices = getStartAndEndIndices(maxToSearch);

    Message messages[] = folder.search(
        new SubjectTerm(subject),
        folder.getMessages(indices.get("startIndex"), indices.get("endIndex")));

    if(unreadOnly){
      List<Message> unreadMessages = new ArrayList<Message>();
      for (Message message : messages) {
        if(isMessageUnread(message)) {
          unreadMessages.add(message);
        }
      }
      messages = unreadMessages.toArray(new Message[]{});
    }

    return messages;
  }

  /**
   * Returns HTML of the email's content
   */
  public String getMessageContent(Message message) throws Exception {
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
    }
    return builder.toString();
  }

  /**
   * Returns all urls from an email message with the linkText specified
   */
  public List<String> getUrlsFromMessage(Message message, String linkText) throws Exception{
    String html = getMessageContent(message);
    List<String> allMatches = new ArrayList<String>();
    Matcher matcher = Pattern.compile("(<a [^>]+>)"+linkText+"</a>").matcher(html);
    while (matcher.find()) {
      String aTag = matcher.group(1);
      allMatches.add(aTag.substring(aTag.indexOf("http"), aTag.indexOf("\">")));
    }
    return allMatches;
  }

  private Map<String, Integer> getStartAndEndIndices(int max) throws MessagingException {
    int endIndex = getNumberOfMessages();
    int startIndex = endIndex - max;

    //In event that maxToGet is greater than number of messages that exist
    if(startIndex < 1){
      startIndex = 1;
    }

    Map<String, Integer> indices = new HashMap<String, Integer>();
    indices.put("startIndex", startIndex);
    indices.put("endIndex", endIndex);

    return indices;
  }

  /**
   * Gets text from the end of a line.
   * In this example, the subject of the email is 'Authorization Code'
   * And the line to get the text from begins with 'Authorization code:'
   * Change these items to whatever you need for your email. This is only an example.
   */
  public String getAuthorizationCode() throws Exception {
    Message email = getMessagesBySubject("Authorization Code", true, 5)[0];
    BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));

    String line;
    String prefix = "Authorization code:";

    while ((line = reader.readLine()) != null) {
      if(line.startsWith(prefix)) {
        return line.substring(line.indexOf(":") + 1);
      }
    }
    return null;
  }

  /**
   * Gets one line of text
   * In this example, the subject of the email is 'Authorization Code'
   * And the line preceding the code begins with 'Authorization code:'
   * Change these items to whatever you need for your email. This is only an example.
   */
  public String getVerificationCode() throws Exception {
    Message email = getMessagesBySubject("Authorization Code", true, 5)[0];
    BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));

    String line;
    while ((line = reader.readLine()) != null) {
      if(line.startsWith("Authorization code:")) {
        return reader.readLine();
      }
    }
    return null;
  }



  //************* BOOLEAN METHODS *******************

  /**
   * Searches an email message for a specific string
   */
  public boolean isTextInMessage(Message message, String text) throws Exception {
    String content = getMessageContent(message);

    //Some Strings within the email have whitespace and some have break coding. Need to be the same.
    content = content.replace("&nbsp;", " ");
    return content.contains(text);
  }

  public boolean isMessageInFolder(String subject, boolean unreadOnly) throws Exception {
    int messagesFound = getMessagesBySubject(subject, unreadOnly, getNumberOfMessages()).length;
    return messagesFound > 0;
  }

  public boolean isMessageUnread(Message message) throws Exception {
    return !message.isSet(Flags.Flag.SEEN);
  }
}

答案 4 :(得分:0)

  private static EmailUtils emailUtils;

  @BeforeClass
  public static void connectToEmail() {
    try {
      emailUtils = new EmailUtils("YOUR_USERNAME@gmail.com", "YOUR_PASSWORD", "smtp.gmail.com", EmailUtils.EmailFolder.INBOX);
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }


part-2

  @Test
  public void testVerificationCode() {
    try {
      //TODO: Execute actions to send verification code to email

      String verificationCode = emailUtils.getAuthorizationCode();

      //TODO: Enter verification code on screen and submit

      //TODO: add assertions

    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }

utils-part 3

  @Test
  public void testVerificationCode() {
    try {
      //TODO: Execute actions to send verification code to email

      String verificationCode = emailUtils.getAuthorizationCode();

      //TODO: Enter verification code on screen and submit

      //TODO: add assertions

    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }

utils- 4
  @Test
  public void testLink() {

    //TODO: apply for a loan using criteria that will result in the application being rejected

    try{
      Message email = emailUtils.getMessagesBySubject("Decision on Your Loan Application", true, 5)[0];
      String link = emailUtils.getUrlsFromMessage(email, "Click here to view the reason").get(0);

      driver.get(link);

      //TODO: continue testing
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }
相关问题