<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    qileilove

    blog已經轉移至github,大家請訪問 http://qaseven.github.io/

    自動化測試中用到的一些功能類

      1、WebDriver處理一些彈窗

    import java.util.Set;
    import org.openqa.selenium.Alert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoAlertPresentException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebDriverException;
    import org.openqa.selenium.ie.InternetExplorerDriver;

    public class AlertOperate {
     static WebDriver dr = new InternetExplorerDriver();
     
     public static void main(String args[]) throws InterruptedException{
      dr.get("www.baidu.com");
      
      dr.findElement(By.id("lb")).click();
      
      try {
       Thread.sleep(2000);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      
      tanchukuang();
     }
     
     
     //處理潛在的1個alert(javascript彈出框)
     public boolean dealPotentialAlert(WebDriver driver,boolean option) {
      boolean flag = false;
      try {
       Alert alert = driver.switchTo().alert();
       if (null == alert)
        throw new NoAlertPresentException();
       try {
        if (option) {
         alert.accept();
         System.out.println("Accept the alert: " + alert.getText());
        } else {
         alert.dismiss();
         System.out.println("Dismiss the alert: " + alert.getText());
        }
        flag = true;
       } catch (WebDriverException ex) {
        if (ex.getMessage().startsWith("Could not find"))
         System.out.println("There is no alert appear!");
        else
         throw ex;
       }
      } catch (NoAlertPresentException e) {
       System.out.println("There is no alert appear!");
      }
      return flag;
     }
     
     //處理非JS彈窗
     public static boolean testNewWindow(){
      //當前窗口句柄
       String currentHandle = dr.getWindowHandle();
      //得到所有窗口的句柄
       Set<String> handles = dr.getWindowHandles();
       handles.remove(currentHandle);
       if (handles.size() > 0) {
        try{
         dr.switchTo().window(handles.iterator().next());
         //dr.switchTo().window(dr.getWindowHandles().iterator().next());
         return true;
        }catch(Exception e){
         System.out.println(e.getMessage());
         return false;
        }
       }
       System.out.println("Did not find window");
       return false;
     }
     
     //一般彈出窗口
     public static void tanchukuang() throws InterruptedException{
      //得到所有窗口
      Set<String> allWindowsId = dr.getWindowHandles();
      //通過查找頁面內容得到新的窗口
      for(String windowId : allWindowsId){
       dr.switchTo().window(windowId);
       Thread.sleep(1000);
       dr.findElement(By.id("TANGRAM__PSP_10__userName")).sendKeys("test");
       
       //第一個按鈕是確定按鈕
       //dr.findElement(By.xpath("http://button[@type='button']")).click();
       //System.out.println(dr.switchTo().window(windowId).getTitle());
       break;
      }
     }
     
    }



    2、一些數據類型轉換

    public class Chanage {
     //int to String
     public static String IntToString(int i){
      String s = Integer.toString(i);
      return s;
     }
     
     //String to int
     public static int StringToInt(String s){
      int i = Integer.parseInt(s);
      return i;
     }
    }

      3、和數據庫交互

    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    import com.mysql.jdbc.Connection;

    class ConnMySQL {
     Connection conn;
     Statement stmt;
     ResultSet rs1;
     int rs2;

     public void connection() throws Exception{
      String db = "meeting";
      String driver = "com.mysql.jdbc.Driver";
      String url = "jdbc:mysql://172.16.3.9:3306/"+db;
      String uname = "admin";
      String pwd = "itserver";
      
      //加載驅動
      Class.forName(driver);
      //連接數據庫
      conn = (Connection) DriverManager.getConnection(url, uname, pwd);
      
      if(!conn.isClosed()){
       //System.out.println("連接成功!");
      }
     }
     
     
     //執行查詢操作返回ResultSet類型
     public void  executeSql0(String sql) throws SQLException{
      
      //創建語句對象,用來執行sql語句
      stmt = conn.createStatement();
      //執行sql
      rs1 = stmt.executeQuery(sql);

      while(rs1.next()){
       String name = rs1.getString("meetingId");
       String subject = rs1.getString("e164");
       String regionName = rs1.getString("state");
       System.out.println(name+" "+subject+" "+regionName);
      }
      rs1.close();
     }
     
     //執行查詢操作返回ResultSet類型
     public void  executeSql1(String sql) throws SQLException{
      
      //創建語句對象,用來執行sql語句
      stmt = conn.createStatement();
      //執行sql
      rs1 = stmt.executeQuery(sql);
      
      while(rs1.next()){
       String id = rs1.getString("id");
       String subject = rs1.getString("subject");
       String startTime = rs1.getString("startTime");
       String endTime = rs1.getString("endTime");
       String organiger = rs1.getString("organiger");
       String status = rs1.getString("status");
       System.out.println(id+" "+subject+" "+startTime+" "+endTime+" "+organiger+" "+status);
      }
      rs1.close();
      conn.close();
     }
     
     
     //執行增刪改操作返回int類型
     public void executeSql2(String sql) throws SQLException{
      stmt = conn.createStatement();
      rs2 = stmt.executeUpdate(sql);
      
      stmt.close();
      conn.close();
     }
    }

     4、創建EXCEL

    // 生成Excel的類 
    import  java.io.File;

    import  jxl.Workbook;
    import  jxl.write.Label;
    import  jxl.write.WritableSheet;
    import  jxl.write.WritableWorkbook;

    public class CreateExcel{
        public static void main(String args[]){
         //Create_Excel c_e = new Create_Excel();
         //c_e.createexcel();
         //System.out.printf("success!!");
       }
    }

    class Create_Excel{
     public void createexcel(){
      try{
                //  打開文件 
                WritableWorkbook book = Workbook.createWorkbook(new File("test.xls"));
                //  生成名為“第一頁”的工作表,參數0表示這是第一頁 
                WritableSheet sheet = book.createSheet("第一頁",0);
                //  在Label對象的構造子中指名單元格位置是第一列第一行(0,0)
                //  以及單元格內容為test 
                Label label1 = new  Label(0,0,"test");
                Label label2 = new  Label(1,1,"test");

                //  將定義好的單元格添加到工作表中 
                sheet.addCell(label1);
                sheet.addCell(label2);

               /* 
                * 生成一個保存數字的單元格 必須使用Number的完整包路徑,否則有語法歧義 單元格位置是第二列,第一行,值為555
                */ 
               jxl.write.Number number = new jxl.write.Number(1,0,555);
               sheet.addCell(number);

                //  寫入數據并關閉文件 
               book.write();
               book.close();

           }catch(Exception e){
               System.out.println(e);
           }
     }
    }

      5、讀取EXCEL

    // 讀取Excel的類 
    import  java.io.File;

    import  jxl.Cell;
    import  jxl.Sheet;
    import  jxl.Workbook;

    /*
     * 參數1:第幾個工作表
     * 參數2:第幾列
     * 參數3:第幾行
     * 參數都從0開始
     * 返回值:當前單元格的數據
     */
    public class ReadExcel{
     static String result;
     static Workbook book;
     static Sheet sheet;
        public static void main(String args[]){
         //readExcel(0,1,0);
         excelNum(0);
        }
        public static String readExcel(int no,int row,int line){
         try{
                book = Workbook.getWorkbook(new File("test.xls"));
                //  獲得第一個工作表對象 
                sheet = book.getSheet(no);
                //  得到第一列第一行的單元格 
                Cell cell1 = sheet.getCell(row,line);
                result = cell1.getContents();
                System.out.println(result);
                book.close();
             }catch(Exception e){
                System.out.println(e);
             }
      return result;
        }
        
        //返回行數
        public static int excelNum(int no){
         int col = 0;
         int row = 0;
         try{
          book = Workbook.getWorkbook(new File("test.xls"));
          sheet = book.getSheet(no);
          //得到行數和列數
          col = sheet.getColumns(); //列數
          row = sheet.getRows();  //行數
          System.out.println(col+" 列");
          System.out.println(row+" 行");
          book.close();
         }catch(Exception e){
          System.out.println(e);
         }
         return row;
        }
    }


    6、更新EXCEL

    import  java.io.File;
    import  jxl.Workbook;
    import  jxl.write.Label;
    import  jxl.write.WritableSheet;
    import  jxl.write.WritableWorkbook;

    public class UpdateExcel{
        public static void main(String args[]){
            try{
             //  Excel獲得文件 
                Workbook wb = Workbook.getWorkbook(new File("test.xls"));
                //  打開一個文件的副本,并且指定數據寫回到原文件 
                WritableWorkbook book = Workbook.createWorkbook(new File("test.xls"),wb);
                //  添加一個工作表 
                WritableSheet sheet = book.createSheet("第二頁",1);
                sheet.addCell(new Label(0,0,"第二頁的測試數據"));
                book.write();
                book.close();
            }catch(Exception e){
             System.out.println(e);
            }
        } 
    }

      7、WebDriver判斷元素是否存在

    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.ie.InternetExplorerDriver;

    /*
     * 判斷一個元素是否存在
     */
    public class ElementIsExsit {
     //查找一個元素是否存在
     public boolean isElementExsit(WebDriver driver, By locator) {
      boolean flag = false;
      try {
       WebElement element=driver.findElement(locator);
       //flag = true;
       flag=null!=element;
       System.out.println("元素: " + locator.toString()+ " 存在!");
      }catch(NoSuchElementException e) {
       System.out.println("元素: " + locator.toString()+ " 不存在!");
       flag = false;
      }
      return flag;
     }
     
     //如何使用上面的方法
     public void test(){
      WebDriver driver = new InternetExplorerDriver();
      
      //顯性等待
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      
      By locator = By.id("id");
      isElementExsit(driver,locator);
     }
    }

      8、java下載圖片

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;

    import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

    public class Movision_verifyImage {
    private static HttpClient hc = new DefaultHttpClient();
     
     
     public static void main(String args[]) throws ClientProtocolException, IOException, ParseException, URISyntaxException{
      
      //獲取圖片驗證碼頁面隨機參數(當前時間)
      long date = new Date().getTime();
      System.out.println(date);
      
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("random",Long.toString(date)));
      get("http://172.16.3.6/admin/portalVerifyImage",params);

     }
     
     /*
      * 帶參數的GET請求
      * 
      */
     public static void get(String url,List<NameValuePair> params) throws ParseException, UnsupportedEncodingException, IOException, URISyntaxException{
      //get請求
      HttpGet httpget = new HttpGet(url);
      //設置參數
      String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
      httpget.setURI(new URI(httpget.getURI().toString()+"?"+str));
      
      //發送請求
      HttpResponse re = hc.execute(httpget);
      
      //獲取相應實體
      HttpEntity entity = re.getEntity();

      if (entity != null && entity.isStreaming()) {
       File storeFile = new File("F:\\test.jpg");
                FileOutputStream fos = new FileOutputStream(storeFile);

                // 將取得的文件文件流寫入目標文件
                InputStream is = entity.getContent();
                byte[] b = new byte[1024];
                int j = 0;

                while ((j = is.read(b)) != -1) {
                   fos.write(b, 0, j);
                }
                fos.flush();
                fos.close();
             } else {
                System.out.println("[" + url + "] 未找到.");
                return;
             }
             
      //關閉連接
      hc.getConnectionManager().shutdown();
     }
    }


      9、java遠程登錄linux并執行命令

    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;


    /*
     * 遠程調用linux下的vmstat命令,并將結果完整寫入文件中
     */
    public class SSHTest {
     /**
      * @param args
      * @throws IOException
      */
     /*
      * 主機地址、端口、用戶名、密碼
      */
     static String hostName = "172.16.3.9";
     static int port = 2222;
     static String userName = "root";
     static String pwd = "kedats";
     
     
     public static void main(String[] args) throws Exception {
      // TODO Auto-generated method stub
      System.out.println("開始連接主機");
      Connection conn = new Connection(hostName, port);
      conn.connect();
      boolean isdenglu = conn.authenticateWithPassword(userName, pwd);
      if (isdenglu) {
       System.out.println("ssh2登陸成功");
      } else {
       System.out.println("登陸失敗");
      }
      
      //System.out.println("當前目錄:");
      
      Session ses = conn.openSession();
      ses.execCommand("vmstat 2");
      InputStream stdout = new StreamGobbler(ses.getStdout());
      BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

      FileWriter fw = new FileWriter("F:\\vmstat.txt");
      
            while (true)      
            {      
                String line = br.readLine();      
                if (line == null)      
                    break;
                System.out.println(line);
                
          fw.write(line+"\r\n",0,line.length()+2);
          fw.flush();

    //      OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("data2.txt"));
    //      osw.write(line,0,line.length());
    //      osw.flush();
    //      PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true);
    //      pw.println(line);
                
            }
            
      System.out.println("運行結果:"+ses.getExitStatus());
      
      //關閉文件
      fw.close();
      
      ses.close();
      conn.close();
     }

    }

      10、java將控制臺打印寫入日志文件

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;

    public class ToLog {
     
     static GregorianCalendar time = new GregorianCalendar();
    // int year = time.get(Calendar.YEAR);     //得到日期的年份
    // int day = time.get(Calendar.DAY_OF_MONTH);   //得到日期的天
    // int month = time.get(Calendar.MONTH)+1;    //得到日期的月份
    // int weekDay = time.get(Calendar.DAY_OF_WEEK);  //得到日期為星期幾
    // int weekOfYear = time.get(Calendar.WEEK_OF_YEAR); //得到日期為年的第幾周
    // int weekOfMonth = time.get(Calendar.WEEK_OF_MONTH); //得到日期為月的第幾周
     
     private static final String getToday = time.get(Calendar.YEAR)+"-"+(time.get(Calendar.MONTH)+1)+"-"+time.get(Calendar.DAY_OF_MONTH)+"-";
     
     private static final String filePath = "C:\\Documents and Settings\\Administrator\\workspace\\Movision_script\\logs\\"+getToday+"log.html";
     
     //寫入文件
     public void toLog(String message){
      StackTraceElement stack[] = (new Throwable()).getStackTrace();
      StackTraceElement s = stack[1];
      
      String headerMessage = s.getClassName()+"."+s.getMethodName()+"()"+"★LineNum:"+s.getLineNumber()+"<br />★Message:&nbsp;&nbsp;&nbsp;&nbsp;";
      
      headerMessage = addDateTimeHeader(headerMessage);
      message = headerMessage + message + "<br />========================================================================================================================<br /><br />";
      
      FileWriter fw = null;
      File file = null;
      
      try{
       file = new File(filePath);
       fw = new FileWriter(file,true);
       fw.write(message);
      }catch(IOException ie){
       ie.printStackTrace();
      }finally{
       try{
        fw.close();
       }catch(IOException ie){
        ie.printStackTrace();
       }
      }
     }

     @SuppressWarnings("deprecation")
     public String addDateTimeHeader(String headerMessage) {
      String dateTimeHeader = new Date().toLocaleString()+"★";
      return dateTimeHeader += headerMessage;
     }
     
     
    // public static void main(String args[]){
    //  ToLog log = new ToLog();
    //  String message = "這只是測試";
    //  log.toLog(message);
    // }
    }

      寫分享這么多吧~各位,晚安!

    posted on 2013-09-10 11:17 順其自然EVO 閱讀(445) 評論(0)  編輯  收藏 所屬分類: selenium and watir webdrivers 自動化測試學習

    <2013年9月>
    25262728293031
    1234567
    891011121314
    15161718192021
    22232425262728
    293012345

    導航

    統計

    常用鏈接

    留言簿(55)

    隨筆分類

    隨筆檔案

    文章分類

    文章檔案

    搜索

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 亚洲av乱码一区二区三区| a级黄色毛片免费播放视频| 亚洲人午夜射精精品日韩| 免费人成在线观看视频高潮| 亚洲国产美女精品久久| 日韩精品亚洲专区在线观看| 亚洲精品免费观看| 亚洲A∨精品一区二区三区下载 | 国产亚洲精品美女| 中文字幕在线亚洲精品 | 亚洲一本之道高清乱码| 最近高清国语中文在线观看免费| 亚洲视频在线播放| 国产伦一区二区三区免费| 两个人看的www免费视频中文| 亚洲精品国产精品乱码不99| 最新中文字幕电影免费观看| 国产线视频精品免费观看视频| 久久亚洲av无码精品浪潮| 91香焦国产线观看看免费| 日韩精品无码免费视频| 亚洲乱码中文字幕小综合| 曰韩亚洲av人人夜夜澡人人爽| 国产精品福利片免费看| 亚洲1区1区3区4区产品乱码芒果| 免费可以看黄的视频s色| 中文字幕在线视频免费| 亚洲AV无码一区二区三区网址| 性xxxx视频播放免费| 中国videos性高清免费| 亚洲AV成人无码网站| 亚洲白嫩在线观看| 久久亚洲精品中文字幕三区| 国产伦一区二区三区免费| 久久电影网午夜鲁丝片免费| 日本免费人成视频在线观看| 国产区在线免费观看| 青青草97国产精品免费观看| 亚洲精品无码专区在线播放| 亚洲一区中文字幕| 亚洲精品熟女国产|