自动化测试中用到的一些功能类

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("//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);
// }
}

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("//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);
// }
}

   

最新内容请见作者的GitHub页:http://qaseven.github.io/

   

时间: 2024-10-22 09:11:11

自动化测试中用到的一些功能类的相关文章

js 退格键:js屏蔽功能类(屏蔽f5,退格键,空格键......)

1.屏蔽功能类1.1 屏蔽键盘所有键<script language="javascript"><!--function document.onkeydown(){event.keycode = 0;event.returnvalue = false;}--></script>1.2 屏蔽鼠标右键在body标签里加上oncontextmenu=self.event.returnvalue=false或者<script language=&quo

vs2012-VS中用自带工具画类结构图

问题描述 VS中用自带工具画类结构图 解决方案 这不是类图,而是流程图. 类图工具在架构工具菜单下 http://developer.51cto.com/art/201004/194599.htm 解决方案二: 这个流程图,用编译器自动生成比较难,一般都是走读代码,熟悉工作流程后,用visio等画图.

app上线后出现BUG怎么处理?开发中用什么方法预防这类问题发生? 跪求大神解答!

问题描述 app上线后出现BUG怎么处理?开发中用什么方法预防这类问题发生? 跪求大神解答! app上线后出现BUG怎么处理?开发中用什么方法预防这类问题发生? 跪求大神解答! 解决方案 出现bug就发布新的版本,客户端自动检查你的服务器,自动下载升级.另外开发过程中注意测试,减少bug

Android实现从缓存中读取图片与异步加载功能类_Android

本文实例讲述了Android实现从缓存中读取图片与异步加载功能类.分享给大家供大家参考,具体如下: 在新浪微博的微博列表中的图片,为了加速其显示也为了加快程序的响应,可以参考该图片异步加载类实现. public class AsyncImageLoader { //SoftReference是软引用,是为了更好的为了系统回收变量 private HashMap<String, SoftReference<Drawable>> imageCache; public AsyncImag

php之框架增加日志记录功能类

<?php /* 思路:给定文件,写入读取(fopen ,fwrite--) 如果大于1M 则重写备份 传给一个内容, 判断大小,如果大于1M,备份 小于则写入 */ class Log{ //定义一个常量,创建一个文件的名称 const LOGFILE = 'curr.log'; //写入文件 public static function write($cont){ $cont .="\r\n"; $log = self::isBak(); //计算文件的地址,判断大小 $fh

PHP封装的数据库保存session功能类_php技巧

本文实例讲述了PHP封装的数据库保存session功能类.分享给大家供大家参考,具体如下: PHP用数据库保存session类: <?php class SafeSessionHandler implements SessionHandlerInterface { public $save_path; public $session_name; public $table; public function __construct() { $this->table = new Table(&qu

Android实现从缓存中读取图片与异步加载功能类

本文实例讲述了Android实现从缓存中读取图片与异步加载功能类.分享给大家供大家参考,具体如下: 在新浪微博的微博列表中的图片,为了加速其显示也为了加快程序的响应,可以参考该图片异步加载类实现. public class AsyncImageLoader { //SoftReference是软引用,是为了更好的为了系统回收变量 private HashMap<String, SoftReference<Drawable>> imageCache; public AsyncImag

从一个很简单的文件上传来品味面向对象的大局观(抽象类和功能类)

/// <summary>     /// 文件上传的模块     /// </summary>     public enum FileModelType     {         /// <summary>         /// 头像         /// </summary>         User,         /// <summary>         /// 产品图像         /// </summary>

AS打造的复制粘贴等功能类_Flash As

主要代码: 复制代码 代码如下: //定义公共函数...  class ClipBoard extends Object {  static var $contents:Object;  static var $operation:String;  function ClipBoard() {  }  //定义当选择剪切时的效果...  public static function cut(obj) {  obj._alpha = 50;  $contents = obj;  $operatio