qileilove

          blog已經(jīng)轉(zhuǎn)移至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(){
            //當(dāng)前窗口句柄
             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();
            //通過查找頁面內(nèi)容得到新的窗口
            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、一些數(shù)據(jù)類型轉(zhuǎn)換

          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、和數(shù)據(jù)庫交互

          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";
            
            //加載驅(qū)動
            Class.forName(driver);
            //連接數(shù)據(jù)庫
            conn = (Connection) DriverManager.getConnection(url, uname, pwd);
            
            if(!conn.isClosed()){
             //System.out.println("連接成功!");
            }
           }
           
           
           //執(zhí)行查詢操作返回ResultSet類型
           public void  executeSql0(String sql) throws SQLException{
            
            //創(chuàng)建語句對象,用來執(zhí)行sql語句
            stmt = conn.createStatement();
            //執(zhí)行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();
           }
           
           //執(zhí)行查詢操作返回ResultSet類型
           public void  executeSql1(String sql) throws SQLException{
            
            //創(chuàng)建語句對象,用來執(zhí)行sql語句
            stmt = conn.createStatement();
            //執(zhí)行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();
           }
           
           
           //執(zhí)行增刪改操作返回int類型
           public void executeSql2(String sql) throws SQLException{
            stmt = conn.createStatement();
            rs2 = stmt.executeUpdate(sql);
            
            stmt.close();
            conn.close();
           }
          }

           4、創(chuàng)建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"));
                      //  生成名為“第一頁”的工作表,參數(shù)0表示這是第一頁 
                      WritableSheet sheet = book.createSheet("第一頁",0);
                      //  在Label對象的構(gòu)造子中指名單元格位置是第一列第一行(0,0)
                      //  以及單元格內(nèi)容為test 
                      Label label1 = new  Label(0,0,"test");
                      Label label2 = new  Label(1,1,"test");

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

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

                      //  寫入數(shù)據(jù)并關(guān)閉文件 
                     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;

          /*
           * 參數(shù)1:第幾個工作表
           * 參數(shù)2:第幾列
           * 參數(shù)3:第幾行
           * 參數(shù)都從0開始
           * 返回值:當(dāng)前單元格的數(shù)據(jù)
           */
          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;
              }
              
              //返回行數(shù)
              public static int excelNum(int no){
               int col = 0;
               int row = 0;
               try{
                book = Workbook.getWorkbook(new File("test.xls"));
                sheet = book.getSheet(no);
                //得到行數(shù)和列數(shù)
                col = sheet.getColumns(); //列數(shù)
                row = sheet.getRows();  //行數(shù)
                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"));
                      //  打開一個文件的副本,并且指定數(shù)據(jù)寫回到原文件 
                      WritableWorkbook book = Workbook.createWorkbook(new File("test.xls"),wb);
                      //  添加一個工作表 
                      WritableSheet sheet = book.createSheet("第二頁",1);
                      sheet.addCell(new Label(0,0,"第二頁的測試數(shù)據(jù)"));
                      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{
            
            //獲取圖片驗證碼頁面隨機參數(shù)(當(dāng)前時間)
            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);

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

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

                      // 將取得的文件文件流寫入目標(biāo)文件
                      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;
                   }
                   
            //關(guān)閉連接
            hc.getConnectionManager().shutdown();
           }
          }


            9、java遠(yuǎn)程登錄linux并執(zhí)行命令

          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;


          /*
           * 遠(yuǎn)程調(diào)用linux下的vmstat命令,并將結(jié)果完整寫入文件中
           */
          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("當(dāng)前目錄:");
            
            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("運行結(jié)果:"+ses.getExitStatus());
            
            //關(guān)閉文件
            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 閱讀(447) 評論(0)  編輯  收藏 所屬分類: selenium and watir webdrivers 自動化測試學(xué)習(xí)

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

          導(dǎo)航

          統(tǒng)計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 资溪县| 桦川县| 宁化县| 闽侯县| 元江| 黑山县| 韶关市| 栾城县| 鄢陵县| 黎平县| 东莞市| 平果县| 嘉祥县| 祁阳县| 广德县| 土默特右旗| 荃湾区| 门源| 怀柔区| 双桥区| 浮梁县| 潞城市| 舒兰市| 收藏| 忻城县| 阳高县| 汝州市| 淳安县| 广安市| 化隆| 蒙城县| 灌阳县| 洛川县| 垦利县| 富宁县| 广平县| 兰西县| 涡阳县| 建瓯市| 成武县| 祁门县|