[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 = 0; final static int CLICK_TEXT = 1; final static int CLICK_DES = 2; final static int LAUNCH_TIMEOUT = 5000; /** * constructed function * @author liuzhipeng * @return null * @throws null */ public UiAssistant(UiDevice device,String[] path,String logTag){ mDevice = device; mPicPath = path[0]; mLogPath = path[1]; 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 = 0; while(!uiobject.exists() && i < 10){ Thread.sleep(500); if(9 == 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()[2]; 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)+1)+"-" +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(0)), 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(0)), 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 = 0; int number = seconds * 1000 /perwaittime; UiSelector uiselector = null; switch(CLICK){ case 0: uiselector = new UiSelector().resourceId(str); break; case 2: uiselector = new UiSelector().text(str); break; case 3: 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 -1)) { 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 = 0; int number = second * 1000 /perWaitTime; // UiObject object = mDevice.findObject(selector); while(!object.exists() && i < number){ try { Thread.sleep(perWaitTime); } catch (InterruptedException e) { e.printStackTrace(); } if(i== (number -1)) { 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 = 0; 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(1000); } 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(1000)){ try { wakeScreen(); permission.clickAndWaitForNewWindow(); Log.i(mLogTag,"click grant store permission"); } catch (UiObjectNotFoundException e) { e.printStackTrace(); } } File dir = new File(path[0]); deleteDirectory(dir); dir = new File(path[1]); deleteDirectory(dir); printLog("delete \""+path[0]+"\" and \""+path[1]+"\""); 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(1000);} 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(10000); assertTrue("DisplayObj not found", waitUnitObjectExist(2, settingDisplayObj, 20, 200, "check_setting_display")); clickByText(settingDisplayObj); assertTrue("sleep object not found", waitUnitObjectExist(2, sleepObj, 20, 200, "check_sleep")); clickByText(sleepObj); assertTrue("sleep "+ sleepText +" no found",waitUnitObjectExist(2, sleepText, 10, 200, "check_sleep_time")); clickByText(sleepText); Thread.sleep(500); mDevice.pressHome(); printLog("now screenOff timeout is: " + getScreenOffTimeout()+ " seconds"); } /** * get current screenOff timeout * @author liuzhipeng * @return */ public int getScreenOffTimeout(){ int result = 0; 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/1000; } /** * reset screenOff tiemout * @param sleepTimeout * @throws UiObjectNotFoundException * @throws InterruptedException */ public void resetScreenOffTimeout(int sleepTimeout) throws UiObjectNotFoundException, InterruptedException { String sleepText ; switch (sleepTimeout){ case 15: sleepText = "15 seconds"; break; case 30: sleepText = "30 seconds"; break; case 60: sleepText = "1 minute"; break; case 120: sleepText = "2 minutes"; break; case 300: sleepText = "5 minutes"; break; case 600: sleepText = "10 minutes"; break; case 1800: 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 = 0; private UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); private UiAssistant cAssistant = new UiAssistant(mDevice,path,logTag);