[uiautomator篇] 基类
package com.softwinner.performance.benchmark; /**
* UiAssistant public class
* @author liuzhipeng
*/
import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.UiWatcher;
import android.support.test.uiautomator.Until;
import android.util.Log; import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar; import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; public class UiAssistant {
private UiDevice mDevice;
private String mPicPath;
private String mLogPath;
private String mLogTag;
final static int CLICK_ID = ;
final static int CLICK_TEXT = ;
final static int CLICK_DES = ;
final static int LAUNCH_TIMEOUT = ;
/**
* constructed function
* @author liuzhipeng
* @return null
* @throws null
*/
public UiAssistant(UiDevice device,String[] path,String logTag){
mDevice = device;
mPicPath = path[];
mLogPath = path[];
mLogTag = logTag;
}
/**
* clickByID
* @author liuzhipeng
* @return true if find object by resourceid success And Click object success else false
* @throws InterruptedException, UiObjectNotFoundException
*/
public boolean clickByID(String id) throws InterruptedException, UiObjectNotFoundException {
return clickByInfo(CLICK_ID, id);
}
/**
* clickByDes
* @author liuzhipeng
* @return true if find object by description success And Click object success else false
* @throws InterruptedException, UiObjectNotFoundException
*/
public boolean clickByDes(String des) throws UiObjectNotFoundException, InterruptedException {
return clickByInfo(CLICK_DES, des);
}
/**
* clickByText
* @author liuzhipeng
* @return true if find object by text success And Click object success else false
* @throws InterruptedException, UiObjectNotFoundException
*/
public boolean clickByText(String text) throws UiObjectNotFoundException, InterruptedException {
return clickByInfo(CLICK_TEXT, text);
}
/**
* clickByInfo
* @author liuzhipeng
* @return true if find object success And Click object success else false
* @throws InterruptedException, UiObjectNotFoundException
*/
private boolean clickByInfo(int CLICK, String str) throws InterruptedException {
UiSelector uiselector = null;
wakeScreen();
switch (CLICK) {
case CLICK_ID:
uiselector = new UiSelector().resourceId(str);
break;
case CLICK_TEXT:
uiselector = new UiSelector().text(str);
break;
case CLICK_DES:
uiselector = new UiSelector().description(str);
break;
default:
return false;
}
UiObject uiobject = mDevice.findObject(uiselector);
int i = ;
while(!uiobject.exists() && i < ){
Thread.sleep();
if( == i){
printLog("find [ui:"+str+"] fail");
return false;
}
uiobject = mDevice.findObject(uiselector);
i++;
}
try {
if(!uiobject.clickAndWaitForNewWindow()){
printLog("click "+str+" return error");
return false;
}
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
}
return true;
}
/**
* screencap ;picture saved as mPicPath, print log to logcat and local file
* @author liuzhipeng
* @return null
* @throws null
*/
public void takeScreen(String logString, String picname) {
//String screenpath = "/sdcard/UITest/Screens/";
String screenpath = mPicPath;
File Screendir = new File(screenpath);
if(!Screendir.exists() && !Screendir.isDirectory())
{
printLog("Create new folder:"+screenpath);
boolean result = Screendir.mkdirs();
if(result == false) {
printLog("mkdirs: "+Screendir+"/ fail");
}
}
// String timeStr = getTimeString();
String pictureStr = Screendir+"/"+picname+"."+"png";
File files = new File(pictureStr);
if(!files.exists()){
try {
boolean result = files.createNewFile();
System.out.println("make files:"+result);
} catch (IOException e) {
e.printStackTrace();
}
}
wakeScreen();
mDevice.takeScreenshot(files);
printLog(logString);
printLog("picture save to:"+pictureStr);
}
/**
* write log into file
* @author liuzhipeng
* @return null
* @throws null
*/
private void logInfo(String level, String str) {
//String Logpath = "/sdcard/UITest/TestLog/";
String logPath = mLogPath;
File screenDir = new File(logPath);
if(!screenDir.exists() && !screenDir.isDirectory())
{
System.out.println("Create new folder:"+logPath);
boolean result = screenDir.mkdirs();
if(result == false)
System.out.println("mkdir: "+screenDir+"/ fail");
}
String datestr = getTimeString();
FileWriter fwlog = null;
StackTraceElement stack = new Throwable().getStackTrace()[];
String temp = "["+stack.getClassName() +"."
+ stack.getMethodName()+":"
+ stack.getLineNumber()+"]";
String slevel = "["+level+"]";
String locationString = String.format("%-25s %-50s %-8s ",datestr,temp,slevel);
try
{
fwlog = new FileWriter(logPath+"log.txt",true);
fwlog.write(locationString+str+"\r\n");
System.out.println(datestr+str);
fwlog.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null != fwlog) fwlog.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* getTimeString
* @author liuzhipeng
* @return time String
* @throws InterruptedException, UiObjectNotFoundException
*/
private String getTimeString() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return calendar.get(Calendar.YEAR)+"-"
+(calendar.get(Calendar.MONTH)+)+"-"
+calendar.get(Calendar.DAY_OF_MONTH)+"_"
+calendar.get(Calendar.HOUR_OF_DAY)+":"
+calendar.get(Calendar.MINUTE)+":"
+calendar.get(Calendar.SECOND)+":"
+calendar.get(Calendar.MILLISECOND);
}
/**
* wake up screen
* @author liuzhipeng
* @return null
* @throws null
*/
public void wakeScreen() {
try {
if(!mDevice.isScreenOn())
{
mDevice.wakeUp();
}
} catch (RemoteException e) {
e.printStackTrace();
} }
/**
* open application
* @author liuzhipeng
* @return null
* @throws RemoteException
*/
public void openApplication(String packageNameStr){
wakeScreen();
/* Start from the home screen*/
mDevice.pressHome(); final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage,notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth()),
LAUNCH_TIMEOUT); // launch the app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(packageNameStr);
// Clear out any previous instances
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent); // Wait for the app to appear
// try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
wakeScreen();
mDevice.wait(Until.hasObject(By.pkg(packageNameStr).depth()),
LAUNCH_TIMEOUT);
}
/**
* quit application
* @author liuzhipeng
* @return null
* @throws IOException
*/
public void quitApplication(String sPackageName) throws IOException {
wakeScreen();
mDevice.executeShellCommand("am force-stop "+sPackageName);
// printLog("quit "+sPackageName);
// logInfo("Debug","quit "+sPackageName); }
/**
* waitfor until object exist
* @author liuzhipeng
* @return true else false
* @throws null
*/
public boolean waitUnitObjectExist(int CLICK, String str, int seconds, int perwaittime, String picname){
int i = ;
int number = seconds * /perwaittime;
UiSelector uiselector = null;
switch(CLICK){
case :
uiselector = new UiSelector().resourceId(str);
break;
case :
uiselector = new UiSelector().text(str);
break;
case :
uiselector = new UiSelector().description(str);
break;
default:
// logInfo("Error","str not support");
printLog("not support find "+str);
return false;
}
UiObject object = mDevice.findObject(uiselector);
while(!object.exists() && i < number){
try {
Thread.sleep(perwaittime);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i== (number -))
{
takeScreen(str+" find fail",picname);
return false;
}
wakeScreen();
object = mDevice.findObject(uiselector);
i++;
}
printLog("find [ui:"+str+"] successfully");
return true;
} /**
*
* @param object
* @param second
* @param perWaitTime
* @param picName
*/
public boolean waitUnitObjExistsBySec(UiObject object, int second, int perWaitTime, String picName){ int i = ;
int number = second * /perWaitTime;
// UiObject object = mDevice.findObject(selector);
while(!object.exists() && i < number){
try {
Thread.sleep(perWaitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i== (number -))
{
takeScreen("find fail",picName);
return false;
}
wakeScreen();
// object = mDevice.findObject(selector);
i++;
}
// printLog("find [ui:"+str+"] successfully");
return true; } /**
* Get UI xmlInfo
* @author liuzhipeng
* @return true else false
* @throws IOException
*/
public boolean getXmlInfo(String path) {
File file = new File(path);
wakeScreen();
try {
mDevice.dumpWindowHierarchy(file);
} catch (IOException e) {
e.printStackTrace();
// return false;
}
return true;
}
/**
* delete folder
* @author liuzhipeng
* @return true else false
* @throws null
*/
public boolean deleteDirectory(File dir){
if(!dir.exists())
{
printLog(dir +" is not exist");
return true;
}
if(dir.isFile())
{
return dir.delete();
}
File[] children = dir.listFiles();
for(int i = ; i < children.length; i++)
{
deleteDirectory(children[i]);
}
return dir.delete();
}
/**
* set up : grant permission and clean folder
* @author liuzhipeng
* @return null
* @throws null
*/
public void setup(String[] path,String logTag){
// wakeScreen();
openApplication("com.softwinner.performance.frameratetest");
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i(mLogTag,"after open mark3d success, grant stored permission");
wakeScreen();
UiObject permission = mDevice.findObject(new UiSelector()
.resourceId("com.android.packageinstaller:id/permission_allow_button")
);
if(permission.waitForExists()){
try {
wakeScreen();
permission.clickAndWaitForNewWindow();
Log.i(mLogTag,"click grant store permission");
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
}
}
File dir = new File(path[]);
deleteDirectory(dir);
dir = new File(path[]);
deleteDirectory(dir);
printLog("delete \""+path[]+"\" and \""+path[]+"\"");
printLog("setup finish"); }
/**
* print log to logcat and local file
* @author liuzhipeng
* @return null
* @throws null
*/
public void printLog(String log){
Log.i(mLogTag,log);
logInfo(mLogTag,log);
}
/**
* when find ui fail,will call watcher to handle normal popup windows
* @author liuzhipeng
* @return null
* Usage:
* before test,add cAssistant.watcherNormalWindows(String,Uiselector);
* in teardown,add mDeveice.removeWatcher(String watcherName)
* before removeWatcher,call mDevice.hasWatcherTriggered(String watcherName) check watcherName triggered status
* before removeWatcher,call mDevice.hasAnyWatcherTriggered()
*/
public void watcherNormalWindows(final String watcherName, final UiSelector watchSelector){ mDevice.registerWatcher(watcherName, new UiWatcher() {
@Override
public boolean checkForCondition() {
UiObject watchObj = mDevice.findObject(watchSelector);
if(watchObj.exists())
{
printLog(watcherName + " has Triggered");
try {Thread.sleep();} catch (InterruptedException e) {e.printStackTrace();}
try {
watchObj.clickAndWaitForNewWindow();
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
}
printLog(watcherName + " has handled");
return true;
}
return false;
}
}); } /**
* set screenOff timeout
* @author liuzhipeng
* @param sleepText
* @throws InterruptedException
* @throws UiObjectNotFoundException
*/
public void setScreenOffTimeout(String sleepText) throws InterruptedException, UiObjectNotFoundException {
String settingPackageName = "com.android.settings";
String settingDisplayObj = "Display";
String sleepObj = "Sleep";
openApplication(settingPackageName);
try {mDevice.setOrientationNatural();} catch (RemoteException e) {e.printStackTrace();}
Thread.sleep();
assertTrue("DisplayObj not found", waitUnitObjectExist(, settingDisplayObj, , , "check_setting_display"));
clickByText(settingDisplayObj);
assertTrue("sleep object not found", waitUnitObjectExist(, sleepObj, , , "check_sleep"));
clickByText(sleepObj);
assertTrue("sleep "+ sleepText +" no found",waitUnitObjectExist(, sleepText, , , "check_sleep_time"));
clickByText(sleepText);
Thread.sleep();
mDevice.pressHome();
printLog("now screenOff timeout is: " + getScreenOffTimeout()+ " seconds");
} /**
* get current screenOff timeout
* @author liuzhipeng
* @return
*/
public int getScreenOffTimeout(){
int result = ;
Context context = InstrumentationRegistry.getContext();
try {
result = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT);
// Log.i(mLogTag, "sleep timeout = " + result/1000 + " seconds");
// Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 10*60*1000); } catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return result/;
} /**
* reset screenOff tiemout
* @param sleepTimeout
* @throws UiObjectNotFoundException
* @throws InterruptedException
*/
public void resetScreenOffTimeout(int sleepTimeout) throws UiObjectNotFoundException, InterruptedException {
String sleepText ;
switch (sleepTimeout){
case :
sleepText = "15 seconds";
break;
case :
sleepText = "30 seconds";
break;
case :
sleepText = "1 minute";
break;
case :
sleepText = "2 minutes";
break;
case :
sleepText = "5 minutes";
break;
case :
sleepText = "10 minutes";
break;
case :
sleepText = "30 minutes";
break;
default:
sleepText = "30 minutes";
break;
}
setScreenOffTimeout(sleepText);
} }
实例化:
public class AuTutuVideoTest{
String packName = "com.antutu.videobench";
String path[]={
"/sdcard/performance/antutuvideo/screen/",
"/sdcard/performance/antutuvideo/log/"
};
// private String startTestPage = "com.antutu.videobench:id/test_movieplayBT";
// private String score_page = "com.antutu.videobench:id/main_titleTV" ;
private String support_video_page = "com.antutu.videobench:id/hard_ok_rl";
String logTag = "antutuvideo";
int TestNumber = ;
private UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
private UiAssistant cAssistant = new UiAssistant(mDevice,path,logTag);
[uiautomator篇] 基类的更多相关文章
- 无线客户端框架设计(3):基类的设计(iOS篇)
本文代码:YoungHeart-Chapter-03.zip 没有基类的App都不是好App. 因为iOS使用的是mvc模式的开发模式,所以,业务逻辑基本都在每个页面相应的ViewController ...
- 本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善(转)
本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善 namespace Web.Mvc.Extensions { #region 验证基类 /// <summary ...
- Farseer.net轻量级开源框架 中级篇:BasePage、BaseController、BaseHandler、BaseMasterPage、BaseControls基类使用
导航 目 录:Farseer.net轻量级开源框架 目录 上一篇:Farseer.net轻量级开源框架 中级篇: UrlRewriter 地址重写 下一篇:Farseer.net轻量级开源框架 中 ...
- C# Stream篇(—) -- Stream基类-----转载
C# Stream篇(—) -- Stream基类 写在前头: Stream系列文章共收录7篇,本着备忘和归纳的目的本着备忘和归纳的目的,全部收录于本分类中. 下面是有原文连接,望各位看官还是到原作者 ...
- C# Stream篇(—) -- Stream基类
写在前头: Stream系列文章共收录7篇,本着备忘和归纳的目的本着备忘和归纳的目的,全部收录于本分类中. 下面是有原文连接,望各位看官还是到原作者处学习,毕竟CV过来的文字难免有走样之处. 原始连接 ...
- salesforce 零基础学习(四十八)自定义列表分页之Pagination基类封装 ※※※
我们知道,salesforce中系统标准列表页面提供了相应的分页功能,如果要使用其分页功能,可以访问http://www.cnblogs.com/zero-zyq/p/5343287.html查看相关 ...
- Java如何解决脆弱基类(基类被冻结)问题
概述 大多数好的设计者象躲避瘟疫一样来避免使用实现继承(extends 关系).实际上80%的代码应该完全用interfaces写,而不是通过extends.“JAVA设计模式”一书详细阐述了怎样用 ...
- 【转载】 C++多继承中重写不同基类中相同原型的虚函数
本篇随笔为转载,原文地址:C++多继承中重写不同基类中相同原型的虚函数. 在C++多继承体系当中,在派生类中可以重写不同基类中的虚函数.下面就是一个例子: class CBaseA { public: ...
- 构建自己的PHP框架--抽象Controller的基类
上一篇博客中,我们将简单的路由解析和执行,从入口文件public/index.php中移入到框架中.入口文件顿时变得清爽无比-- 但是,去我们的controller里看一下,会看到如下的code: p ...
随机推荐
- 利用nodejs读取数据库数据生成树结构的json数据
在做后台管理界面的时候,几乎少不了的一个结构就是树形结构,用来做菜单导航: 那么,最希望的就是树结构的所有数据都是读取的数据库,而不是直接代码当中写死,那我们就一步一步来看: 一,建表 字段通常包括: ...
- PeopleSoft FSCM Production Support 案例分析之一重大紧急事故发生时的应对策略
案例背景: 今天一大早用户打电话来讲昨天上传的银行的forex payment return file好像没有被处理到,我一听就觉得纳闷,因为昨天晚上operator也没有给我打电话啊(如果有job ...
- Azure 8 月新公布
Azure 8 月新发布:Cosmos DB 每分钟请求单位,存储的托管磁盘及促销,高级和标准磁盘存储大尺寸磁盘,高级磁盘存储小尺寸磁盘. Azure Cosmos DB:每分钟请求单位为您降低成本, ...
- vue.js与react.js相比较的优势
vue.js的简介 vue.js是一个javascript mvvm库,它是以数据驱动和组件化的思想构建的.我们平时多用js去操作dom,vue.js则是使用了数据绑定驱动来操作dom的,也就是说创建 ...
- 洛谷 2299 Mzc和体委的争夺战
题目背景 mzc与djn第四弹. 题目描述 mzc家很有钱(开玩笑),他家有n个男家丁(做过前三弹的都知道).但如此之多的男家丁吸引来了我们的体委(矮胖小伙),他要来与mzc争夺男家丁. mzc很生气 ...
- 刷新本地DNS缓存的方法
http://www.cnblogs.com/rubylouvre/archive/2012/08/31/2665859.html 常有人问到域名解析了不是即时生效的嘛,怎么还是原来的呢?答案就是在本 ...
- js 双向绑定
//双向绑定实例 <input name="" ng-bind-123="name" /> function DataBinder( object_ ...
- leetcode 4.两个排序数组的中位数
题目: 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 . 请找出这两个有序数组的中位数.要求算法的时间复杂度为 O(log (m+n)) . 你可以假设 nums1 和 nums ...
- UVA - 1658 Admiral (最小费用最大流)
最短路对应费用,路径数量对应流量.为限制点经过次数,拆点为边.跑一次流量为2的最小费用最大流. 最小费用最大流和最大流EK算法是十分相似的,只是把找增广路的部分换成了求费用的最短路. #include ...
- hrbust-1545-基础数据结构——顺序表(2)
http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1545 基础数据结构——顺序表(2) ...