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

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;
        }
    }

}

数据转换

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;
    }
}

和数据库交互

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

创建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);
       }
    }
}

读取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;
    }
}

更新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);
        }
    }
}

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);
    }
}

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

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

}

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

时间: 2024-08-29 22:18:17

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

总结分享下日常生活中用到的一些功能,很好很强大,功能很多有20个,希望大家喜欢

原文:总结分享下日常生活中用到的一些功能,很好很强大,功能很多有20个,希望大家喜欢 源代码下载地址:http://www.zuidaima.com/share/1590231786228736.htm 言归正传,本篇代码全部是JavaSE相关的. 为什么? 1) 若不分享,这些代码就是躺在电脑里的一堆0和1,虽日久天长也不会发霉,但确实更像是没价值的数字垃圾. 2) 虽然没啥"高科技"的代码,但总有需要它们的人. 有什么? 1)自己写的例子:或是为了在项目中应用某项技术而写的demo

php实现图片缩放功能类

http://www.poluoluo.com/jzxy/201312/255447.html <?php /** * Images类是一个图片处理类 * @package application.controllers * @since 1.0 */ class Images { /** * 缩放图片 * @param $source原图片 * @param $newfile新图片 * @param $pre缩放比例 */ public function thumn($source,$pre,

枚举功能类

enum.php /** * 本类主要是实现枚举的功能 * @param unknown_type $base_class * @param unknown_type $args * @param unknown_type $codeArgs */ function enum($base_class, array $args,array $codeArgs){ $class_parts = preg_split('/\s+/', $base_class); $base_class_name =

【socket】Socket的三个功能类TCPClient、TCPListener 和 UDPClient

Socket的三个功能类TCPClient.TCPListener 和 UDPClient (转) 应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.Sockets.Socket 类的基础之上,负责数据传送的细节.(也就是说TCPClient.TCPListener 和 UDPClient 类是用来简化Socket) TcpClient 和 TcpLi

功能类控件

驰骋工作流引擎将出发各种事件的控件称之为功能类控件,驰骋表单设计器中有控件分类:按钮,鼠标.选择,超连接. 按钮 表单上面的按钮对象,可以处理事件内容. 特别说明:ccBPM所有的事件内容的处理方式都是一致的,目前所涉及的事件有,表单事件.按钮事件.流程事件. 1.总体说明 每个按钮有自己的按钮类型,使用自定义按钮类型. 属性 说明 按钮事件类型 事件类型决定按钮执行的内容. 事件内容 就是要执行的内容,内容里面可以有变量,变量来自与表单.变量的表达方式仍然用@+变量名来决定,比如:@jiner

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

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

thinkphp功能类之Upload.class.php

Thinkphp 中常用功能类(Upload.class.php)构造参数$config = array( 'mimes' => array(), //允许上传的文件MiMe类型 'maxSize' => 0, //上传的文件大小限制 (0-不做限制) 'exts'' => array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 'rootPath' => './Uploads/', //保存根路径 'savePath' => '', /

php加密解密功能类

这两天突发奇想想要用php写一个对日常项目加密以及解密的功能,经过努力简单的封装了一个对php代码进行加密解密的类,一些思想也是来自于网络,初步测试用着还行,可以实现对指定项目的加密以及解密(只针对本类中加密的解密)过程,在这里分享给大家,水平比较有限那里有错误还希望指出,共同提高,一下会给大家列出来实现的思想以及源码. 加密过程:读取源文件,base64_encode进行加密,利用混排得到的52个大小写字母作为秘钥进行替换$c=strtr(密文,对应待替换的字母,要替换成的字母);将两个秘钥和

视频学习笔录---ThinkPHP---TP功能类之分页

(1)核心 数据分页通过limit语法实现 (2)分页类 ThinkPHP里系统封装好了分页类:Page.class.php (3)代码分析 位置:Think/Page.class.php, ①查看相关属性 namespace Think; class Page{ //对外开放属性 public $firstRow; // 起始行数 public $listRows; // 列表每页显示行数 limit(start,rows) public $parameter; // 分页跳转时要带的参数 p