How to use MobileBy.ByImage class of io.appium.java_client package

Best io.appium code snippet using io.appium.java_client.MobileBy.ByImage

BaseTest.java

Source:BaseTest.java Github

copy

Full Screen

1package utils;2import ch.ethz.ssh2.StreamGobbler;3import com.google.common.collect.ImmutableMap;4import com.sun.mail.imap.protocol.Item;5import io.appium.java_client.AppiumDriver;6import io.appium.java_client.android.nativekey.AndroidKey;7import io.appium.java_client.android.nativekey.KeyEvent;8import org.apache.commons.codec.binary.Base64;9import io.appium.java_client.MobileBy;10import io.appium.java_client.MobileElement;11import io.appium.java_client.android.AndroidDriver;12import io.appium.java_client.android.AndroidElement;13import io.appium.java_client.android.AndroidKeyCode;14import io.appium.java_client.imagecomparison.*;15import io.appium.java_client.remote.AndroidMobileCapabilityType;16import io.appium.java_client.remote.MobileCapabilityType;17import io.appium.java_client.service.local.AppiumDriverLocalService;18import io.appium.java_client.service.local.AppiumServiceBuilder;19import io.appium.java_client.service.local.flags.AndroidServerFlag;20import io.appium.java_client.service.local.flags.GeneralServerFlag;21import io.netty.handler.codec.base64.Base64Encoder;22import org.apache.commons.exec.CommandLine;23import org.apache.commons.exec.DefaultExecuteResultHandler;24import org.apache.commons.exec.DefaultExecutor;25import org.apache.commons.exec.PumpStreamHandler;26import org.apache.commons.io.FileUtils;27import org.apache.commons.io.IOUtils;28import org.apache.log4j.LogManager;29import org.apache.log4j.Logger;30import org.aspectj.lang.annotation.After;31import org.openqa.selenium.By;32import org.openqa.selenium.OutputType;33import org.openqa.selenium.TakesScreenshot;34import org.openqa.selenium.logging.LogEntry;35import org.openqa.selenium.remote.DesiredCapabilities;36import org.openqa.selenium.support.ui.ExpectedConditions;37import org.openqa.selenium.support.ui.WebDriverWait;38import org.testng.Assert;39import org.testng.annotations.*;40import utils.FactoryClasses.keyCode;41import java.awt.*;42import java.awt.image.BufferedImage;43import java.awt.image.DataBuffer;44import java.awt.image.DataBufferByte;45import java.io.*;46import java.lang.management.ManagementFactory;47import java.lang.reflect.Field;48import java.net.URISyntaxException;49import java.net.URL;50import java.nio.file.Files;51import java.nio.file.Paths;52import java.text.DateFormat;53import java.text.Format;54import java.text.SimpleDateFormat;55import java.util.*;56import java.util.List;57import java.util.concurrent.Executors;58import java.util.concurrent.TimeUnit;59import java.util.logging.Level;60import java.util.regex.Pattern;61import javax.imageio.ImageIO;62import static org.apache.tools.ant.taskdefs.Antlib.TAG;63import static org.testng.Assert.*;64public class BaseTest {65 public AndroidDriver driver;66 public WebDriverWait wait;67 public String version = " 2.29.8 ifs גירסת ממיר 77 וגירסת ";68 public String ifspackageName = "com.ifeelsmart.smartui";69 public String Eyal = "eyal.avramchik@partner.co.il";70 public String Michael = "Michael.skali1@partner.co.il";71 String Shlomi = "shlomi.mor4@partner.co.il";72 public DesiredCapabilities cap = new DesiredCapabilities();73// public Logger log = LogManager.getLogger(BaseTest.class);74// public BaseTest() throws IOException {75// }76 @Parameters({"Name", "appPackage", "appActivity", "port", "deviceName", "platformVersion", "udid", "bpPort", "ip"})77 //Parameters that reads from testng.xml78 @BeforeClass79 public void Capabilities(String Name, String appActivity, String appPackage, String port, String deviceName, String platformVersion, String udid, String bpPort, String ip) throws Exception {80 cap.setCapability("deviceName", deviceName);81 cap.setCapability("Name", Name);82 cap.setCapability("udid", udid);83 cap.setCapability("port", port);84 cap.setCapability("bpPort", bpPort);85// cap.setCapability("automationName", "UiAutomator2");86// cap.setCapability("allowInvisibleElements",true);87 cap.setCapability("appPackage", appPackage);88 cap.setCapability("appActivity", appActivity);89 cap.setCapability(MobileCapabilityType.NO_RESET, true);90 cap.setCapability("ignoreUnimportantViews ", true);91 cap.setCapability("skipDeviceInitialization", true);92 cap.setCapability("skipServerInstallation", true);93 cap.setCapability("ip", ip);94// KillAppium(port);95// cap.setCapability("deviceReadyTimeout", 30);96// getRefreashRate(ip, deviceName);97// killifs(ip); // //kill the ifs app before starting the session,No clear cache or data, works only with root and debug FW98// checkDevices();99 AppiumServer server = new AppiumServer();100 server.AppiumServer(port, bpPort, Name);101 driver = new AndroidDriver<>(new URL("http://0.0.0.0:" + port + "/wd/hub"), cap);102// driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);103 Thread thread = new Thread(new Runnable() {104 public void run() {105 String packageName = driver.getCurrentPackage();106 Boolean pac = packageName.equals("com.ifeelsmart.smartui");107 while (pac) {108 packageName = driver.getCurrentPackage();109 pac = packageName.equals("com.ifeelsmart.smartui");110// openSTB();111 try {112 DRM(ip);113// memoryTest(ip,deviceName);114// logCatLinux(ip);115// pingSent(ip);116 } catch (Exception ignore) {117 Log.info(ignore.getMessage());118 }119 }120 takeScreenShot();121 try {122 logCatLinux(ip);123 } catch (IOException e) {124 e.printStackTrace();125 } catch (InterruptedException e) {126 e.printStackTrace();127 }128 Runtime rt = Runtime.getRuntime();129 try {130 readLogcat();131// deleteShlomiLogcat();132// rt.exec("taskkill " + logcat);133// logcat.isAlive();134 } catch (IOException e) {135 e.printStackTrace();136 }137 try {138 List<String> adb2 = Arrays.asList("");139 Map<String, Object> ADB = ImmutableMap.of("command", "logcat -t 20000 | grep com.ifeelsmart.smartui", "args", adb2);140 String as = (String) driver.executeScript("mobile: shell", ADB);141 Log.info(" Partner tv is not running in the front, Only package: " + packageName);142// SendEmail.sendmail(as, "eyal.avramchik@partner.co.il", "IFS Just crashed !");143// SendEmail.sendmail(as, "shlomi.mor4@partner.co.il", "IFS Just crashed !");144 if (as.contains("FATAL")) {145 Log.info("FATAL EXCEPTION");146// service.stop();147 } else148 Log.info("No FATAL EXCEPTIONS found in the log file...");149// service.stop();150 } catch (Exception ignore) {151 Log.info(ignore.getMessage());152 }153 }154 });155 thread.start();156// String x = driver.getCapabilities().getCapability("deviceName").toString();157// String y = (driver.getSessionDetails()).toString();158// Log.info(deviceName);159// }160 }161 @AfterClass162 public void after() {163 }164 @AfterTest165 public void afterTest() {166 }167 public void openSTB() {168 try {169 List<String> lsArgs = Arrays.asList("");170 List<String> lsArgs2 = Arrays.asList("");171 Map<String, Object> lsCmd = ImmutableMap.of("command", "dumpsys power | grep state=", "args", lsArgs);172 String lsOutput = (String) driver.executeScript("mobile: shell", lsCmd);173 if (lsOutput.contains("OFF")) {174 Log.info("The STB is closed ... Opening the STB... ");175 Map<String, Object> OFF = ImmutableMap.of("command", "input keyevent 26", "args", lsArgs2);176 String state = (String) driver.executeScript("mobile: shell", OFF);177 }178 if (lsOutput.contains("ON")) {179 }180// } else {181// Log.info("STB is off, Opening STB, please wait a moment ...");182// Map<String, Object> openscreen = ImmutableMap.of("command", "input keyevent 26", "args", lsArgs);183// String OpenScreen = (String) driver.executeScript("mobile: shell", openscreen);184// Log.info(OpenScreen);185 } catch (Exception ignore) {186 Log.info(ignore.getMessage());187 }188 }189 public void read(String FILENAME) {190// final String FILENAME = "C:\\Selenium\\Eyal\\eyal.txt";191 BufferedReader br = null;192 FileReader fr = null;193 try {194 //br = new BufferedReader(new FileReader(FILENAME));195 fr = new FileReader(FILENAME);196 br = new BufferedReader(fr);197 String sCurrentLine;198 int printCount = 0; // Counter to count from 0 to 9 for printing 10 lines.199 boolean foundFatal = false; // Boolean variable to know when we found the fatal.200 while ((sCurrentLine = br.readLine()) != null) {201 if (sCurrentLine.contains("Fatal signal") || (sCurrentLine.contains("FATAL EXCEPTION"))) {202 foundFatal = true; // We found the fatal exception. No need to continue and search for another.203 }204 if (printCount == 9) { // If we reached a counter of 9 we just finished printing 10 lines.205 }206 if (foundFatal) {207 // We found the fatal. Print a line and start counting up to 10 lines.208 Log.info(sCurrentLine);209 //SendEmail.sendmail(sCurrentLine, "eyal.avramchik@partner.co.il", "FATAL EXCEPTION !!!!!!");210 printCount++;211 }212 }213 } catch (IOException e) {214 e.printStackTrace();215 } finally {216 try {217 if (br != null)218 br.close();219 if (fr != null)220 fr.close();221 } catch (IOException ex) {222 ex.printStackTrace();223 }224 }225 }226 @Parameters({"deviceName"})227 public String monitorErrors(String deviceName, String ip) {228// capabilities.setCapability("deviceName", deviceName);229 List<String> adb = Arrays.asList("");230 List<String> adb1 = Arrays.asList("");231 List<String> adb2 = Arrays.asList("");232 List<String> adb3 = Arrays.asList("");233 List<String> adb4 = Arrays.asList("");234 List<String> adb5 = Arrays.asList("");235 List<String> adb6 = Arrays.asList("");236 List<String> adb7 = Arrays.asList("");237 List<String> adb8 = Arrays.asList("");238 List<String> adb9 = Arrays.asList("");239 List<String> adb10 = Arrays.asList("");240 try {241 Map<String, Object> ADB = ImmutableMap.of("command", "logcat -d |grep 'DRM'", "args", adb);242 String AA = (String) this.driver.executeScript("mobile: shell", ADB);243 driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));244 Log.info("--- Zapping up ---");245 Thread.sleep(4000);246// if (AA.contains("teardown/3002")) {247// takeScreenShot();248// Map<String, Object> AD = ImmutableMap.of("command", "logcat -d |grep 'teardown/3002'", "args", adb1);249// String teardown = (String) this.driver.executeScript("mobile: shell", AD);250// Log.info("********** Decoding error from ********** " + deviceName + "'s STB: " + teardown);251// logCatLinux(ip);252// SendEmail.sendmail(teardown, Eyal, "Decoding Error is catched right now");253// Thread.sleep(60000);254// Log.info("Wait 60 seconds before retry mannually");255// } if (AA.contains("error_code:#PBA")) {256// takeScreenShot();257// Map<String, Object> PBA = ImmutableMap.of("command", "logcat -d |grep 'error_code:#PBA'", "args", adb3);258// String pbaerror = (String) this.driver.executeScript("mobile: shell", PBA);259// Log.info("********** PBA Error ********** " + pbaerror);260// logCatLinux(ip);261//// SendEmail.sendmail(pbaerror, "eyal.avramchik@partner.co.il", "PBA Error");262// Thread.sleep(60000);263// Log.info("Wait 60 seconds before retry mannually");264//265// } else if (AA.contains("IFS_RESULT_HOST")) {266// //press ok button to see the mini epg info267// takeScreenShot();268// Map<String, Object> DECODING = ImmutableMap.of("command", "logcat -d|grep 'IFS_RESULT_HOST'", "args", adb4);269// String blackscreen = (String) this.driver.executeScript("mobile: shell", DECODING);270// Log.info("********** SC error ********** " + blackscreen);271// logCatLinux(ip);272// Thread.sleep(60000);273// Log.info("Wait 60 seconds before retry mannually");274//// SendEmail.sendmail(blackscreen, "eyal.avramchik@partner.co.il", "SC Error");275// } else if (AA.contains("fatal")) {276// takeScreenShot();277// Map<String, Object> COACH = ImmutableMap.of("command", "logcat -d|grep 'fatal'", "args", adb5);278// String fatal = (String) this.driver.executeScript("mobile: shell", COACH);279// Log.info("********** fatal catched ********** " + fatal);280// logCatLinux(ip);281// Thread.sleep(60000);282// Log.info("Wait 60 seconds before retry mannually");283// Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);284// this.driver.executeScript("mobile: shell", clearLogcat2);285// }286 if (AA != null) {287 Log.info(AA);288 takeScreenShot();289 Log.info("First screenshot");290 Log.info("DRM Error catched");291 logCatLinux(ip);292 Thread.sleep(60000);293 Log.info("Wait 60 seconds before retry mannually");294 takeScreenShot();295 Log.info("Second screenshot after 60 seconds");296 Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);297 this.driver.executeScript("mobile: shell", clearLogcat2);298 }299// if (AA.contains("Player is paused")) {300//// Map<String, Object> gg = ImmutableMap.of("command", "logcat -d |grep 'Player is paused'", "args", adb8);301//// String pause = (String) this.driver.executeScript("mobile: shell", gg);302// Log.info("********** Player is paused ********** " + deviceName + "'s STB: ");303// } else if (AA.contains("Player is resumed")) {304//// Map<String, Object> bb = ImmutableMap.of("command", "logcat -d |grep 'Player is resumed'", "args", adb9);305//// String pause1 = (String) this.driver.executeScript("mobile: shell", bb);306// Log.info("********** Player is Resumed ********** " + deviceName + "'s STB: ");307// } else if (AA.contains("exoPlayer is buffering")) {308//// Map<String, Object> cc = ImmutableMap.of("command", "logcat -d |grep 'Player is buffering'", "args", adb10);309//// String pause2 = (String) this.driver.executeScript("mobile: shell", cc);310// Log.info("********** Player is Live ********** " + deviceName + "'s STB: ");311// }312 } catch (Exception ignore) {313 }314 return deviceName;315 }316 public void pingSent(String ip) {317 List<String> ping = Arrays.asList("");318 List<String> gate = Arrays.asList("");319 Map<String, Object> DNS = ImmutableMap.of("command", "ping -c1 80.179.52.100 | grep packets", "args", ping);320 String result = (String) this.driver.executeScript("mobile: shell", DNS);321 Map<String, Object> GATE = ImmutableMap.of("command", "ping -c1 80.179.52.100 | grep packets", "args", gate);322 String def = (String) this.driver.executeScript("mobile: shell", GATE);323 if (result.contains("0 received")) {324 Log.info("Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!!!!!Ping Fails!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Ping Fails!!!!!!!!!!!!!!!!!!!!!!!!!!Ping Fails " + result + ip);325 takeScreenShot();326 SendEmail.sendmail(result, "eyal.avramchik@partner.co.il", "Ping fails in Eyal automation !!");327 } else if (def.contains("0 received")) {328 Log.info("Default Gateway Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!!!!! Default Gateway Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Default Gateway Ping Fails !!!!!!!!!!!!!!!!!!!!!!!!!! Default Gateway Ping Fails " + def);329 takeScreenShot();330 SendEmail.sendmail(result, "eyal.avramchik@partner.co.il", "Default Gateway Ping Fails in Eyal automation !!");331 }332 }333 public void PBA() {334 List<String> pba = Arrays.asList("");335 try {336 Map<String, Object> PBAerror = ImmutableMap.of("command", "logcat -d | grep 'IFS_RESULT_HOST'", "args", pba);337 String AA = (String) this.driver.executeScript("mobile: shell", PBAerror);338 if (AA.contains("IFS_RESULT_HOST")) {339 driver.pressKeyCode(23);340 takeScreenShot();341 Log.info(AA);342// SendEmail.sendmail(AA, Eyal, "Black screen catched !!");343 List<String> adb1 = Arrays.asList("");344 Map<String, Object> ADB2 = ImmutableMap.of("command", "logcat -c", "args", adb1);//clear the logcat and get new lines345 String bb = (String) this.driver.executeScript("mobile: shell", ADB2);346 }347 } catch (Exception ignore) {348 }349 }350 public void takeScreenShot() {351 // Set folder name to store screenshots.352 String destDir = "screenshots";353 // Capture screenshot.354 File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);355 Log.info("Screensot is captured");356 // Set date format to set It as screenshot file name.357 SimpleDateFormat date = new SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");358 // Create folder under project with name "screenshots" provided to destDir.359 new File(destDir).mkdirs();360 // Set file name using current date time.361 String destFile = date.format(new Date()) + ".png";362 try {363 // Copy paste file at destination folder location364 FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));365 Log.info("Screenshot added to the folder");366 } catch (IOException e) {367 e.printStackTrace();368 }369 }370// public void p() {371// try {372// Process pr = Runtime.getRuntime().exec("adb" + " logcat -d");373// BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));374// StringBuilder log = new StringBuilder();375// String line = "";376// while ((line = bufferedReader.readLine()) != null) {377// log.append(line);378// Log.info(log.toString());379// }380// } catch (IOException e){}381// }382 public String getIfsPid() {383 List<String> pid = Arrays.asList("");384 Map<String, Object> PID = ImmutableMap.of("command", "pidof com.ifeelsmart.smartui", "args", pid);//clear the logcat and get new lines385 String ifspid = (String) this.driver.executeScript("mobile: shell", PID);386 return ifspid;387 }388 public void killIfsPid() {389 List<String> kill = Arrays.asList("");390 Map<String, Object> KILL = ImmutableMap.of("command", "kill " + getIfsPid(), "args", kill);//clear the logcat and get new lines391 String killifs = (String) this.driver.executeScript("mobile: shell", KILL);392 }393 public void readLogcat() throws IOException {394 BufferedReader reader = null;395 File file = new File("C:\\Users\\OSN20933\\shlomi_crash.txt");396 try {397 reader = new BufferedReader(new FileReader(file));398 for (String next, line = reader.readLine(); line != null; line = next) {399 next = reader.readLine();400//401// Log.info("Current line: " + line);402 Boolean decoding = line.contains("teardown/3002");403 Boolean PBA = line.contains("error_code:#PBA");404 Boolean BlackScreen = line.contains("IFS_RESULT_HOST");405 if (decoding) {406// SendEmail.sendmail("Decoding error is cacthed","eyal.avramchik@partner.co.il","Decoding error is cacthed");407 Log.info("Decoding error catched !!");408 } else if (PBA) {409 SendEmail.sendmail("PBA error is cacthed", "eyal.avramchik@partner.co.il", "PBA error is cacthed");410 } else if (BlackScreen) {411 takeScreenShot();412// SendEmail.sendmail("Black screen error is cacthed", "eyal.avramchik@partner.co.il", "Black screen error is cacthed");413 }414// Log.info("Next line: " + next);415// if (line.contains("IFS_RESULT_HOST")) {416// Log.info("-------- Black screen catched ---------");417// } else if (line.contains("error_code:#PBA")) {418// Log.info("PBA error occures");419// } else if (line.contains("כניסה למצב שינה בתוך 30 שניות")) {420// Log.info("Entering Sleep mode from LogCat");421// } else if (line.contains("Waking up by power key from standby mode")) {422// Log.info("Waking up from LogCat");423// } else if (line.contains("teardown/3002")) {424// Log.info("----------- Decoding error catched -----------");425// } else if (line.contains("STB Information")) {426// Log.info("STB Information");427 }428 } finally {429 if (reader != null) try {430 reader.close();431 } catch (IOException logOrIgnore) {432 }433 }434// File file = new File("C:\\Selenium\\Eyal\\stb.txt");435//436// BufferedReader br = new BufferedReader(new FileReader(file));437//438// String st;439// while ((st = br.readLine()) != null)440// if (st.contains("STB Information"))441// Log.info(st);442// else443// break;444 }445 public void shellCommands() throws IOException {446 try {447 CommandLine cmd = new CommandLine("adb");448 cmd.addArgument("logcat", false).addArgument("-d", false);449 DefaultExecutor exec = new DefaultExecutor();450 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();451 PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);452 exec.setStreamHandler(streamHandler);453 exec.execute(cmd);454 if (outputStream.toString().contains("IFS_RESULT_HOST")) {455 List<String> adb1 = Arrays.asList("");456 Map<String, Object> printtear = ImmutableMap.of("command", "logcat -d |grep 'IFS_RESULT_HOST'", "args", adb1);457 driver.pressKeyCode(23);458 takeScreenShot();459 String coach = (String) this.driver.executeScript("mobile: shell", printtear);460 Log.info(coach);461 } else if (outputStream.toString().contains("error_code:#PBA")) {462 List<String> ad = Arrays.asList("");463 Map<String, Object> ppp = ImmutableMap.of("command", "logcat -d |grep 'error_code:#PBA'", "args", ad);464 driver.pressKeyCode(23);465 takeScreenShot();466 String ccc = (String) this.driver.executeScript("mobile: shell", ppp);467 Log.info(ccc);468 }469 List<String> adb = Arrays.asList("");470 Map<String, Object> clearLogcat = ImmutableMap.of("command", "logcat -c", "args", adb);471 this.driver.executeScript("mobile: shell", clearLogcat);472// else if (outputStream.toString().contains("error_code:#PBA")) {473// List<String> pba = Arrays.asList("");474// Map<String, Object> PBA = ImmutableMap.of("command", "logcat -d |grep 'error_code:#PBA'", "args", pba);475// String pbaerror = (String) this.driver.executeScript("mobile: shell", PBA);476// Log.info(pbaerror);477// }478// cmd.addArgument("shell", false).addArgument("-s", false).addArgument(ip, false).addArgument("kill", false).addArgument(outputStream.toString(), false);479// CommandLine commandline = CommandLine.parse(command);480 } catch481 (Exception ignore) {482 }483 }484 public void deleteShlomiLogcat() {485 try {486 Files.deleteIfExists(Paths.get("C:\\Users\\OSN20933\\shlomi_crash.txt"));487 } catch (IOException e) {488 }489 }490 public void readLogcatRealTime() throws IOException {491 Process logcatread;492 final StringBuilder log = new StringBuilder();493 try {494 logcatread = Runtime.getRuntime().exec(new String[]{"logcat"});495 BufferedReader br = new BufferedReader(new InputStreamReader(logcatread.getInputStream()), 4 * 1024);496 String line;497 String separator = System.getProperty("line.separator");498 while ((line = br.readLine()) != null) {499// log.append(line);500// log.append(separator);501 if (line.contains("Send teardown with metrics end with status code: 204")) {502 log.append(line.contains("Send teardown with metrics end with status code: 204"));503 try {504 Runtime.getRuntime().exec(new String[]{"logcat", "-c"});505 } catch (Exception e1) {506 e1.printStackTrace();507 }508 }509 }510 } catch (511 Exception e) {512 e.printStackTrace();513 }514 }515 public void killifs(String ip) throws IOException {516 try {517 CommandLine cmd = new CommandLine("adb");518 CommandLine cmd1 = new CommandLine("adb");519 cmd.addArgument("-s").addArgument(ip, false).addArgument("shell", false).addArgument("\"kill $(pidof com.ifeelsmart.smartui)\"", false);520 DefaultExecutor exec = new DefaultExecutor();521 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();522 PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);523 exec.setStreamHandler(streamHandler);524 exec.execute(cmd);525 Log.info("Closing ifs from the background, please wait...");526 } catch527 (Exception ignore) {528 System.out.println(ignore);529 }530 }531 public void checkDevices() throws IOException {532 try {533 CommandLine cmd = new CommandLine("adb");534 cmd.addArgument("devices", false);535 DefaultExecutor exec = new DefaultExecutor();536 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();537 PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);538 exec.setStreamHandler(streamHandler);539 exec.execute(cmd);540 if (outputStream.toString().contains("192.168.1.")) {541 Log.info("At least 1 STB is connected, Starting The test ...");542 } else {543 Log.info("No STB devices connected, Aborting the tests !!! " + outputStream.toString());544 System.exit(1);545 }546 } catch547 (Exception ignore) {548 System.out.println(ignore);549 }550 }551 public void StopNodes() throws IOException {552 try {553 CommandLine stop = new CommandLine("taskkill");554 stop.addArgument("/F", false).addArgument("/IM", false).addArgument("node.exe", false);555 DefaultExecutor exec = new DefaultExecutor();556 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();557 PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);558 exec.setStreamHandler(streamHandler);559 exec.execute(stop);560 Log.info(outputStream.toString());561 } catch (Exception e) {562 e.getMessage();563 }564 }565 public void killAppiumServer() {566 try {567 CommandLine killAppium = new CommandLine("netstat");568 killAppium.addArgument("-ano", false).addArgument("|", false).addArgument("find", false).addArgument("\"0.0.0.0:4723\"", false);569 DefaultExecutor exec = new DefaultExecutor();570 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();571 PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);572 exec.setStreamHandler(streamHandler);573 exec.execute(killAppium);574 Log.info(outputStream.toString());575 } catch (Exception e) {576 e.getMessage();577 }578 }579 public void cmd(String port) throws IOException {580 try {581 ProcessBuilder builder = new ProcessBuilder(582 "/bin/bash", "-c", "netstat -nlp | grep :" + port);583 builder.redirectErrorStream(true);584 Process p = builder.start();585 BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));586 String line;587 while (true) {588 line = r.readLine();589 if (line == null) {590 break;591 }592 Log.info(line);593// System.out.println(line.substring(71));594// String AppiumServerPid = line.substring(61);595 String AppiumServerPid = line;596 Log.info("Killing Appium port, Wait a sec...");597 ProcessBuilder builder2 = new ProcessBuilder(598 "/bin/bash", "-c", "taskkill /pid " + AppiumServerPid + " /f");599 builder2.redirectErrorStream(true);600 Process p2 = builder2.start();601 BufferedReader r2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));602 String line2;603 while (true) {604 line2 = r2.readLine();605 if (line2 == null) {606 break;607 }608 System.out.println(line2);609 }610 }611 } catch (Exception ignore) {612 Log.info(ignore.getMessage());613 }614 }615 public void logCatPC(String ip) {616 String dateTime = driver.getDeviceTime().replace(":", "-");617 try {618 Process process = Runtime.getRuntime().exec("adb -s " + ip + " logcat >" + dateTime.substring(0, dateTime.length() - 6).replace("T", " ") + "." + ip);619 int exitCode = process.waitFor();620 if (exitCode == 0) {621 System.out.println("Executed successfully");622 } else {623 System.out.println("Failed ...");624 }625// String dateTime = driver.getDeviceTime().replace(":", "-");626// ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", "adb", "-s", ip, "logcat", ">", dateTime.substring(0, dateTime.length() - 6).replace("T", " ") + "." + ip);627// builder.start();628 Log.info("adb logcat is active, name of the Log:" + dateTime.substring(0, dateTime.length() - 6).replace("T", " ") + " For ip - " + ip);629// long pid = p.pid();630 } catch (Exception e) {631 e.getMessage();632 }633 }634 public void getRefreashRate(String ip, String deviceName) throws IOException {635// List<String> adb = Arrays.asList("");636// Map<String, Object> ADB2 = ImmutableMap.of("command", "dumpsys display |grep DisplayModeRecord", "args", adb);637// String AA = (String) driver.executeScript("mobile: shell", ADB2);638// if (AA.length() >= 69) {639// Log.info("The Refresh Rate is: " + AA.substring(66, AA.length() - 3));640 CommandLine cmd = new CommandLine("adb");641 cmd.addArgument("-s").addArgument(ip, false).addArgument("shell", false).addArgument("dumpsys", false).addArgument("display", false).addArgument("|", false).addArgument("grep", false).addArgument("DisplayModeRecord", false);642 DefaultExecutor exec = new DefaultExecutor();643 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();644 PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);645 exec.setStreamHandler(streamHandler);646 exec.execute(cmd);647 if (outputStream.toString().length() >= 69) {648 Log.info("The Refresh Rate for " + deviceName + " is: " + outputStream.toString().substring(66, outputStream.toString().length() - 4));649 }650 }651 public void findImage() throws IOException {652//653// File black = new File("C:\\Users\\OSN20933\\Pictures\\black_screen.png");654 File start = new File("C:\\Users\\OSN20933\\Pictures\\s.png");655 byte[] fileContent = FileUtils.readFileToByteArray(new File("C:\\Users\\OSN20933\\Pictures\\start.png"));656 String encodedString = Base64.encodeBase64String(fileContent);657//658// byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));659// byte[] partialImage = null;660// OccurrenceMatchingResult result = driver661// .findImageOccurrence(screenshot, partialImage, new OccurrenceMatchingOptions()662// .withEnabledVisualization());663// Assert.assertTrue(result.getVisualization().length >(0));664// assertNotNull(result.getRect());665 boolean el = driver.findElementsByImage(encodedString).size() > 0;666 // takeScreenShot();667// WebDriverWait wait = new WebDriverWait(driver,20);668// wait.until(ExpectedConditions.visibilityOfElementLocated(MobileBy.ByImage.image(encodedString)));669// Log.info("works!!!");670//takeScreenShot();671 //* if (el){672 // Log.info("Exist");673 // }674 // else675 // {676 // Log.info("Not exist");677 }678 public void che() throws IOException, InterruptedException {679// takeScreenShot();680 byte[] pngBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);681 if (IsPngEquals(new File("C:\\Users\\OSN20933\\Pictures\\sleep_black_take.png"), pngBytes)) {682 Log.info("Black screen catched on the screen");683 keyCode keyCode = new keyCode(this.driver);684 keyCode.OK();685 takeScreenShot();686 } else {687 }688 }689 public static boolean IsPngEquals(File pngFile, byte[] pngBytes) throws IOException {690 BufferedImage imageA = ImageIO.read(pngFile);691 ByteArrayInputStream inStreamB = new ByteArrayInputStream(pngBytes);692 BufferedImage imageB = ImageIO.read(inStreamB);693 inStreamB.close();694 DataBufferByte dataBufferA = (DataBufferByte) imageA.getRaster().getDataBuffer();695 DataBufferByte dataBufferB = (DataBufferByte) imageB.getRaster().getDataBuffer();696 if (dataBufferA.getNumBanks() != dataBufferB.getNumBanks()) {697 return false;698 }699 for (int bank = 0; bank < dataBufferA.getNumBanks(); bank++) {700 if (!Arrays.equals(dataBufferA.getData(bank), dataBufferB.getData(bank))) {701 return false;702 }703 }704 return true;705 }706 public void KillAppium(String port) throws IOException {707// String terminalCommand2 = "netstat -nlp | grep :4728" + port;708 String[] args = new String[]{"/bin/bash", "-c", "netstat -nlp | grep :4728", port};709 ProcessBuilder pb = new ProcessBuilder(args);710 String output = IOUtils.toString(pb.start().getInputStream()).substring(80).replace("/node", "");711// String b = output.substring(80).replace("/node","netstat -nlp | grep :" + port);712 Log.info(output);713 String[] args2 = new String[]{"/bin/bash", "-c", "kill ", output};714 Process proc = new ProcessBuilder(args2).start();715 }716 public void logCatLinux(String ip) throws IOException, InterruptedException {717 List<LogEntry> logEntries = driver.manage().logs().get("logcat").getAll();718 for (LogEntry logEntry : logEntries) {719 if (logEntry.toString().contains("DRM")){720 System.out.println(logEntry);721 List<String> adb10 = Arrays.asList("");722 Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);723 this.driver.executeScript("mobile: shell", clearLogcat2);724 Thread.sleep(60000);725 }726 driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));727 Log.info("--- Zapping up ---");728 Thread.sleep(4000);729 }730 }731 public void pause(String ip) throws IOException {732 // String[] args = new String[]{"/bin/bash", "-c", "adb -s " + ip + " logcat | grep 'Player is buffering'"};733 }734 public void pa(String ip) throws IOException {735 String s = null;736 try {737 // run the Unix "ps -ef" command738 // using the Runtime exec method:739// Process c = Runtime.getRuntime().exec("adb -s " + ip + " logcat -c");740 Process p = Runtime.getRuntime().exec("adb -s " + ip + "logcat");741 BufferedReader stdInput = new BufferedReader(new742 InputStreamReader(p.getInputStream()));743 BufferedReader stdError = new BufferedReader(new744 InputStreamReader(p.getErrorStream()));745 // read the output from the command746 while ((s = stdInput.readLine()) != null) {747 if (s.contains("DRM")){748 takeScreenShot();749 Log.info("DRM ERROR" +s);750 SendEmail.sendmail("DRM ERROR " + s,"eyal.avramchik@partner.co.il","DRM ERROR");751 Thread.sleep(60000);752 List<String> adb10 = Arrays.asList("");753 Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);754 this.driver.executeScript("mobile: shell", clearLogcat2);755 }756// else if (s.contains("error_code:#PBA")){757// takeScreenShot();758// Log.info("PBA ERROR");759// SendEmail.sendmail("PBA ERROR","eyal.avramchik@partner.co.il","PBA ERROR");760// Thread.sleep(60000);761// }762// if (s.contains("Player is buffering")) {763// Log.info(" ********** YOU ARE IN A LIVE CHANNEL **********");764// } else if (s.contains("Player is paused")) {765// Log.info(" ********** YOU ARE IN A PAUSE MODE **********");766// } else if (s.contains("Player is resumed")) {767// Log.info(" ********** YOU ARE IN RESUME MODE/PLAY MODE **********");768// } else if (s.contains("keycode=89")) {769// Log.info(" ********** REWIND **********");770// } else if (s.contains("keycode=90")) {771// Log.info(" ********** FAST FORWARD **********");772// }773 driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));774 Log.info("--- Zapping up ---");775 Thread.sleep(3000);776 }777 // read any errors from the attempted command778// System.out.println("Here is the standard error of the command (if any):\n");779// while ((s = stdError.readLine()) != null) {780// System.out.println(s);781// }782// System.exit(0);783 } catch (IOException | InterruptedException e) {784 System.out.println("exception happened - here's what I know: ");785 e.printStackTrace();786 System.exit(-1);787 }788 }789 public void memoryTest(String ip,String deviceName) throws IOException {790 String n = null;791 try {792 // run the Unix "ps -ef" command793 // using the Runtime exec method:794 Process c = Runtime.getRuntime().exec("adb -s " + ip + " logcat -c");795 Process p = Runtime.getRuntime().exec("adb -s " + ip + " shell top -n 1 | grep 'System'");796 BufferedReader stdInput = new BufferedReader(new797 InputStreamReader(p.getInputStream()));798 BufferedReader stdError = new BufferedReader(new799 InputStreamReader(p.getErrorStream()));800 // read the output from the command801 while ((n = stdInput.readLine()) != null) {802 String[] splited = n.split("\\s+");803 String sum = splited[1];804// Integer.parseInt(sum.substring(0,2));805// if (!splited[5].contains("0%")) {806 Log.info(sum);807// Log.info("Total Cpu Usage is: " + splited[5] + " and the STB IP is: "+ ip + " and the STB name is: " + deviceName);808 }809// }810// } else if (n.contains("Player is paused")) {811// Log.info(" ********** YOU ARE IN A PAUSE MODE **********");812//813// }814 // read any errors from the attempted command815// System.out.println("Here is the standard error of the command (if any):\n");816// while ((s = stdError.readLine()) != null) {817// System.out.println(s);818// }819// System.exit(0);820 } catch (IOException e) {821 System.out.println("exception happened - here's what I know: ");822 e.printStackTrace();823 System.exit(-1);824 }825 }826 public void DRM(String ip) {827 ProcessBuilder processBuilder = new ProcessBuilder();//DRM828 processBuilder.command("bash", "-c", "adb -s " + ip + " logcat -d | grep DRM");829 try {830 driver.pressKey(new KeyEvent(AndroidKey.CHANNEL_UP));831 Log.info("--- Zapping up ---");832 Thread.sleep(4000);833 Process process = processBuilder.start();834 StringBuilder output = new StringBuilder();835 BufferedReader reader = new BufferedReader(836 new InputStreamReader(process.getInputStream()));837 String line;838 while ((line = reader.readLine()) != null) {839 System.out.println(output.append(line));840 takeScreenShot();841 Log.info("First screenshot of the DRM error");842 SendEmail.sendmail(output.toString(),"eyal.avramchik@partner.co.il","DRM Error cacthed");843 List<String> adb10 = Arrays.asList("");844 Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);845 this.driver.executeScript("mobile: shell", clearLogcat2);846 }847 int exitVal = process.waitFor();848 if (exitVal == 0) {849 System.out.println("Success!");850// System.out.println(output);851// System.exit(0);852 } else {853 //abnormal...854 }855 } catch (IOException e) {856 e.printStackTrace();857 } catch (InterruptedException e) {858 e.printStackTrace();859 }860 }861 public void pbaError(String ip) {862 ProcessBuilder processBuilder = new ProcessBuilder();//PBA863 processBuilder.command("bash", "-c", "adb -s " + ip + " logcat -d | grep error_code:#PBA");864 try {865 Process process = processBuilder.start();866 StringBuilder output = new StringBuilder();867 BufferedReader reader = new BufferedReader(868 new InputStreamReader(process.getInputStream()));869 String line;870 while ((line = reader.readLine()) != null) {871 System.out.println(output.append(line));872 takeScreenShot();873 Log.info("First screenshot of PBA error before the 60 seconds");874 SendEmail.sendmail(output.toString(),"eyal.avramchik@partner.co.il","PBA Error cacthed");875 List<String> adb10 = Arrays.asList("");876 Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);877 this.driver.executeScript("mobile: shell", clearLogcat2);878 }879 int exitVal = process.waitFor();880 if (exitVal == 0) {881 System.out.println("Success!");882// System.out.println(output);883// System.exit(0);884 } else {885 //abnormal...886 }887 } catch (IOException e) {888 e.printStackTrace();889 } catch (InterruptedException e) {890 e.printStackTrace();891 }892 }893 public void decodingError(String ip) {894 ProcessBuilder processBuilder = new ProcessBuilder();//PBA895 processBuilder.command("bash", "-c", "adb -s " + ip + " logcat -d | grep teardown/3002");896 try {897 Process process = processBuilder.start();898 StringBuilder output = new StringBuilder();899 BufferedReader reader = new BufferedReader(900 new InputStreamReader(process.getInputStream()));901 String line;902 while ((line = reader.readLine()) != null) {903 System.out.println(output.append(line));904 takeScreenShot();905 Log.info("First screenshot of the Decoding error");906 SendEmail.sendmail(output.toString(),"eyal.avramchik@partner.co.il","Decoding Error cacthed");907 List<String> adb10 = Arrays.asList("");908 Map<String, Object> clearLogcat2 = ImmutableMap.of("command", "logcat -c", "args", adb10);909 this.driver.executeScript("mobile: shell", clearLogcat2);910 }911 int exitVal = process.waitFor();912 if (exitVal == 0) {913 System.out.println("Success!");914// System.out.println(output);915// System.exit(0);916 } else {917 //abnormal...918 }919 } catch (IOException e) {920 e.printStackTrace();921 } catch (InterruptedException e) {922 e.printStackTrace();923 }924 }925}926// if (i == 0) System.out.println("Nothing read from input stream");...

Full Screen

Full Screen

MobileBy.java

Source:MobileBy.java Github

copy

Full Screen

1/*2 * Licensed under the Apache License, Version 2.0 (the "License");3 * you may not use this file except in compliance with the License.4 * See the NOTICE file distributed with this work for additional5 * information regarding copyright ownership.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package io.appium.java_client;17import lombok.AccessLevel;18import lombok.Getter;19import org.apache.commons.lang3.StringUtils;20import org.openqa.selenium.By;21import org.openqa.selenium.SearchContext;22import org.openqa.selenium.WebDriverException;23import org.openqa.selenium.WebElement;24import java.io.Serializable;25import java.util.List;26@SuppressWarnings("serial")27public abstract class MobileBy extends By {28 private static final String ERROR_TEXT = "The class %s of the given context "29 + "doesn't implement %s nor %s. Sorry. It is impossible to find something.";30 @Getter(AccessLevel.PROTECTED) private final String locatorString;31 private final MobileSelector selector;32 private static IllegalArgumentException formIllegalArgumentException(Class<?> givenClass,33 Class<?> class1, Class<?> class2) {34 return new IllegalArgumentException(String.format(ERROR_TEXT, givenClass.getCanonicalName(),35 class1.getCanonicalName(), class2.getCanonicalName()));36 }37 protected MobileBy(MobileSelector selector, String locatorString) {38 if (StringUtils.isBlank(locatorString)) {39 throw new IllegalArgumentException("Must supply a not empty locator value.");40 }41 this.locatorString = locatorString;42 this.selector = selector;43 }44 @SuppressWarnings("unchecked")45 @Override public List<WebElement> findElements(SearchContext context) {46 return (List<WebElement>) ((FindsByFluentSelector<?>) context)47 .findElements(selector.toString(), getLocatorString());48 }49 @Override public WebElement findElement(SearchContext context) {50 return ((FindsByFluentSelector<?>) context)51 .findElement(selector.toString(), getLocatorString());52 }53 /**54 * Refer to https://developer.android.com/training/testing/ui-automator55 * @param uiautomatorText is Android UIAutomator string56 * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidUIAutomator}57 */58 public static By AndroidUIAutomator(final String uiautomatorText) {59 return new ByAndroidUIAutomator(uiautomatorText);60 }61 /**62 * About Android accessibility63 * https://developer.android.com/intl/ru/training/accessibility/accessible-app.html64 * About iOS accessibility65 * https://developer.apple.com/library/ios/documentation/UIKit/Reference/66 * UIAccessibilityIdentification_Protocol/index.html67 * @param accessibilityId id is a convenient UI automation accessibility Id.68 * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidUIAutomator}69 */70 public static By AccessibilityId(final String accessibilityId) {71 return new ByAccessibilityId(accessibilityId);72 }73 /**74 * This locator strategy is available in XCUITest Driver mode.75 * @param iOSClassChainString is a valid class chain locator string.76 * See <a href="https://github.com/facebookarchive/WebDriverAgent/wiki/Class-Chain-Queries-Construction-Rules">77 * the documentation</a> for more details78 * @return an instance of {@link io.appium.java_client.MobileBy.ByIosClassChain}79 */80 public static By iOSClassChain(final String iOSClassChainString) {81 return new ByIosClassChain(iOSClassChainString);82 }83 /**84 * This locator strategy is only available in Espresso Driver mode.85 * @param dataMatcherString is a valid json string detailing hamcrest matcher for Espresso onData().86 * See <a href="http://appium.io/docs/en/writing-running-appium/android/espresso-datamatcher-selector/">87 * the documentation</a> for more details88 * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidDataMatcher}89 */90 public static By androidDataMatcher(final String dataMatcherString) {91 return new ByAndroidDataMatcher(dataMatcherString);92 }93 /**94 * This locator strategy is only available in Espresso Driver mode.95 * @param viewMatcherString is a valid json string detailing hamcrest matcher for Espresso onView().96 * See <a href="http://appium.io/docs/en/writing-running-appium/android/espresso-datamatcher-selector/">97 * the documentation</a> for more details98 * @return an instance of {@link io.appium.java_client.MobileBy.ByAndroidViewMatcher}99 */100 public static By androidViewMatcher(final String viewMatcherString) {101 return new ByAndroidViewMatcher(viewMatcherString);102 }103 /**104 * This locator strategy is available in XCUITest Driver mode.105 * @param iOSNsPredicateString is an an iOS NsPredicate String106 * @return an instance of {@link io.appium.java_client.MobileBy.ByIosNsPredicate}107 */108 public static By iOSNsPredicateString(final String iOSNsPredicateString) {109 return new ByIosNsPredicate(iOSNsPredicateString);110 }111 public static By windowsAutomation(final String windowsAutomation) {112 return new ByWindowsAutomation(windowsAutomation);113 }114 /**115 * This locator strategy is available in Espresso Driver mode.116 * @since Appium 1.8.2 beta117 * @param tag is an view tag string118 * @return an instance of {@link ByAndroidViewTag}119 */120 public static By AndroidViewTag(final String tag) {121 return new ByAndroidViewTag(tag);122 }123 /**124 * This locator strategy is available only if OpenCV libraries and125 * NodeJS bindings are installed on the server machine.126 *127 * @see <a href="https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/image-comparison.md">128 * The documentation on Image Comparison Features</a>129 * @see <a href="https://github.com/appium/appium-base-driver/blob/master/lib/basedriver/device-settings.js">130 * The settings available for lookup fine-tuning</a>131 * @since Appium 1.8.2132 * @param b64Template base64-encoded template image string. Supported image formats are the same133 * as for OpenCV library.134 * @return an instance of {@link ByImage}135 */136 public static By image(final String b64Template) {137 return new ByImage(b64Template);138 }139 /**140 * This type of locator requires the use of the 'customFindModules' capability and a141 * separately-installed element finding plugin.142 *143 * @param selector selector to pass to the custom element finding plugin144 * @return an instance of {@link ByCustom}145 * @since Appium 1.9.2146 */147 public static By custom(final String selector) {148 return new ByCustom(selector);149 }150 public static class ByAndroidUIAutomator extends MobileBy implements Serializable {151 public ByAndroidUIAutomator(String uiautomatorText) {152 super(MobileSelector.ANDROID_UI_AUTOMATOR, uiautomatorText);153 }154 /**155 * {@inheritDoc}156 *157 * @throws WebDriverException when current session doesn't support the given selector or when158 * value of the selector is not consistent.159 * @throws IllegalArgumentException when it is impossible to find something on the given160 * {@link SearchContext} instance161 */162 @SuppressWarnings("unchecked")163 @Override164 public List<WebElement> findElements(SearchContext context) throws WebDriverException,165 IllegalArgumentException {166 Class<?> contextClass = context.getClass();167 if (FindsByAndroidUIAutomator.class.isAssignableFrom(contextClass)) {168 return FindsByAndroidUIAutomator.class.cast(context)169 .findElementsByAndroidUIAutomator(getLocatorString());170 }171 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {172 return super.findElements(context);173 }174 throw formIllegalArgumentException(contextClass, FindsByAndroidUIAutomator.class,175 FindsByFluentSelector.class);176 }177 /**178 * {@inheritDoc}179 *180 * @throws WebDriverException when current session doesn't support the given selector or when181 * value of the selector is not consistent.182 * @throws IllegalArgumentException when it is impossible to find something on the given183 * {@link SearchContext} instance184 */185 @Override public WebElement findElement(SearchContext context) throws WebDriverException,186 IllegalArgumentException {187 Class<?> contextClass = context.getClass();188 if (FindsByAndroidUIAutomator.class.isAssignableFrom(contextClass)) {189 return FindsByAndroidUIAutomator.class.cast(context)190 .findElementByAndroidUIAutomator(getLocatorString());191 }192 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {193 return super.findElement(context);194 }195 throw formIllegalArgumentException(contextClass, FindsByAndroidUIAutomator.class,196 FindsByFluentSelector.class);197 }198 @Override public String toString() {199 return "By.AndroidUIAutomator: " + getLocatorString();200 }201 }202 public static class ByAccessibilityId extends MobileBy implements Serializable {203 public ByAccessibilityId(String accessibilityId) {204 super(MobileSelector.ACCESSIBILITY, accessibilityId);205 }206 /**207 * {@inheritDoc}208 *209 * @throws WebDriverException when current session doesn't support the given selector or when210 * value of the selector is not consistent.211 * @throws IllegalArgumentException when it is impossible to find something on the given212 * {@link SearchContext} instance213 */214 @SuppressWarnings("unchecked")215 @Override216 public List<WebElement> findElements(SearchContext context) throws WebDriverException,217 IllegalArgumentException {218 Class<?> contextClass = context.getClass();219 if (FindsByAccessibilityId.class.isAssignableFrom(contextClass)) {220 return FindsByAccessibilityId.class.cast(context)221 .findElementsByAccessibilityId(getLocatorString());222 }223 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {224 return super.findElements(context);225 }226 throw formIllegalArgumentException(contextClass, FindsByAccessibilityId.class,227 FindsByFluentSelector.class);228 }229 /**230 * {@inheritDoc}231 *232 * @throws WebDriverException when current session doesn't support the given selector or when233 * value of the selector is not consistent.234 * @throws IllegalArgumentException when it is impossible to find something on the given235 * {@link SearchContext} instance236 */237 @Override public WebElement findElement(SearchContext context) throws WebDriverException,238 IllegalArgumentException {239 Class<?> contextClass = context.getClass();240 if (FindsByAccessibilityId.class.isAssignableFrom(contextClass)) {241 return FindsByAccessibilityId.class.cast(context)242 .findElementByAccessibilityId(getLocatorString());243 }244 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {245 return super.findElement(context);246 }247 throw formIllegalArgumentException(contextClass, FindsByAccessibilityId.class,248 FindsByFluentSelector.class);249 }250 @Override public String toString() {251 return "By.AccessibilityId: " + getLocatorString();252 }253 }254 public static class ByIosClassChain extends MobileBy implements Serializable {255 protected ByIosClassChain(String locatorString) {256 super(MobileSelector.IOS_CLASS_CHAIN, locatorString);257 }258 /**259 * {@inheritDoc}260 *261 * @throws WebDriverException when current session doesn't support the given selector or when262 * value of the selector is not consistent.263 * @throws IllegalArgumentException when it is impossible to find something on the given264 * {@link SearchContext} instance265 */266 @SuppressWarnings("unchecked")267 @Override public List<WebElement> findElements(SearchContext context) {268 Class<?> contextClass = context.getClass();269 if (FindsByIosClassChain.class.isAssignableFrom(contextClass)) {270 return FindsByIosClassChain.class.cast(context)271 .findElementsByIosClassChain(getLocatorString());272 }273 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {274 return super.findElements(context);275 }276 throw formIllegalArgumentException(contextClass, FindsByIosClassChain.class,277 FindsByFluentSelector.class);278 }279 /**280 * {@inheritDoc}281 *282 * @throws WebDriverException when current session doesn't support the given selector or when283 * value of the selector is not consistent.284 * @throws IllegalArgumentException when it is impossible to find something on the given285 * {@link SearchContext} instance286 */287 @Override public WebElement findElement(SearchContext context) {288 Class<?> contextClass = context.getClass();289 if (FindsByIosClassChain.class.isAssignableFrom(contextClass)) {290 return FindsByIosClassChain.class.cast(context)291 .findElementByIosClassChain(getLocatorString());292 }293 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {294 return super.findElement(context);295 }296 throw formIllegalArgumentException(contextClass, FindsByIosClassChain.class,297 FindsByFluentSelector.class);298 }299 @Override public String toString() {300 return "By.IosClassChain: " + getLocatorString();301 }302 }303 public static class ByAndroidDataMatcher extends MobileBy implements Serializable {304 protected ByAndroidDataMatcher(String locatorString) {305 super(MobileSelector.ANDROID_DATA_MATCHER, locatorString);306 }307 /**308 * {@inheritDoc}309 *310 * @throws WebDriverException when current session doesn't support the given selector or when311 * value of the selector is not consistent.312 * @throws IllegalArgumentException when it is impossible to find something on the given313 * {@link SearchContext} instance314 */315 @SuppressWarnings("unchecked")316 @Override public List<WebElement> findElements(SearchContext context) {317 Class<?> contextClass = context.getClass();318 if (FindsByAndroidDataMatcher.class.isAssignableFrom(contextClass)) {319 return FindsByAndroidDataMatcher.class.cast(context)320 .findElementsByAndroidDataMatcher(getLocatorString());321 }322 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {323 return super.findElements(context);324 }325 throw formIllegalArgumentException(contextClass, FindsByAndroidDataMatcher.class,326 FindsByFluentSelector.class);327 }328 /**329 * {@inheritDoc}330 *331 * @throws WebDriverException when current session doesn't support the given selector or when332 * value of the selector is not consistent.333 * @throws IllegalArgumentException when it is impossible to find something on the given334 * {@link SearchContext} instance335 */336 @Override public WebElement findElement(SearchContext context) {337 Class<?> contextClass = context.getClass();338 if (FindsByAndroidDataMatcher.class.isAssignableFrom(contextClass)) {339 return FindsByAndroidDataMatcher.class.cast(context)340 .findElementByAndroidDataMatcher(getLocatorString());341 }342 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {343 return super.findElement(context);344 }345 throw formIllegalArgumentException(contextClass, FindsByAndroidDataMatcher.class,346 FindsByFluentSelector.class);347 }348 @Override public String toString() {349 return "By.FindsByAndroidDataMatcher: " + getLocatorString();350 }351 }352 public static class ByAndroidViewMatcher extends MobileBy implements Serializable {353 protected ByAndroidViewMatcher(String locatorString) {354 super(MobileSelector.ANDROID_VIEW_MATCHER, locatorString);355 }356 /**357 * {@inheritDoc}358 *359 * @throws WebDriverException when current session doesn't support the given selector or when360 * value of the selector is not consistent.361 * @throws IllegalArgumentException when it is impossible to find something on the given362 * {@link SearchContext} instance363 */364 @SuppressWarnings("unchecked")365 @Override public List<WebElement> findElements(SearchContext context) {366 Class<?> contextClass = context.getClass();367 if (FindsByAndroidViewMatcher.class.isAssignableFrom(contextClass)) {368 return FindsByAndroidViewMatcher.class.cast(context)369 .findElementsByAndroidViewMatcher(getLocatorString());370 }371 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {372 return super.findElements(context);373 }374 throw formIllegalArgumentException(contextClass, FindsByAndroidViewMatcher.class,375 FindsByFluentSelector.class);376 }377 /**378 * {@inheritDoc}379 *380 * @throws WebDriverException when current session doesn't support the given selector or when381 * value of the selector is not consistent.382 * @throws IllegalArgumentException when it is impossible to find something on the given383 * {@link SearchContext} instance384 */385 @Override public WebElement findElement(SearchContext context) {386 Class<?> contextClass = context.getClass();387 if (FindsByAndroidViewMatcher.class.isAssignableFrom(contextClass)) {388 return FindsByAndroidViewMatcher.class.cast(context)389 .findElementByAndroidViewMatcher(getLocatorString());390 }391 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {392 return super.findElement(context);393 }394 throw formIllegalArgumentException(contextClass, FindsByAndroidViewMatcher.class,395 FindsByFluentSelector.class);396 }397 @Override public String toString() {398 return "By.FindsByAndroidViewMatcher: " + getLocatorString();399 }400 }401 public static class ByIosNsPredicate extends MobileBy implements Serializable {402 protected ByIosNsPredicate(String locatorString) {403 super(MobileSelector.IOS_PREDICATE_STRING, locatorString);404 }405 /**406 * {@inheritDoc}407 *408 * @throws WebDriverException when current session doesn't support the given selector or when409 * value of the selector is not consistent.410 * @throws IllegalArgumentException when it is impossible to find something on the given411 * {@link SearchContext} instance412 */413 @SuppressWarnings("unchecked")414 @Override public List<WebElement> findElements(SearchContext context) {415 Class<?> contextClass = context.getClass();416 if (FindsByIosNSPredicate.class.isAssignableFrom(contextClass)) {417 return FindsByIosNSPredicate.class.cast(context)418 .findElementsByIosNsPredicate(getLocatorString());419 }420 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {421 return super.findElements(context);422 }423 throw formIllegalArgumentException(contextClass, FindsByIosNSPredicate.class,424 FindsByFluentSelector.class);425 }426 /**427 * {@inheritDoc}428 *429 * @throws WebDriverException when current session doesn't support the given selector or when430 * value of the selector is not consistent.431 * @throws IllegalArgumentException when it is impossible to find something on the given432 * {@link SearchContext} instance433 */434 @Override public WebElement findElement(SearchContext context) {435 Class<?> contextClass = context.getClass();436 if (FindsByIosNSPredicate.class.isAssignableFrom(contextClass)) {437 return FindsByIosNSPredicate.class.cast(context)438 .findElementByIosNsPredicate(getLocatorString());439 }440 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {441 return super.findElement(context);442 }443 throw formIllegalArgumentException(contextClass, FindsByIosNSPredicate.class,444 FindsByFluentSelector.class);445 }446 @Override public String toString() {447 return "By.IosNsPredicate: " + getLocatorString();448 }449 }450 public static class ByWindowsAutomation extends MobileBy implements Serializable {451 protected ByWindowsAutomation(String locatorString) {452 super(MobileSelector.WINDOWS_UI_AUTOMATION, locatorString);453 }454 /**455 * {@inheritDoc}456 *457 * @throws WebDriverException when current session doesn't support the given selector or when458 * value of the selector is not consistent.459 * @throws IllegalArgumentException when it is impossible to find something on the given460 * {@link SearchContext} instance461 */462 @SuppressWarnings("unchecked")463 @Override public List<WebElement> findElements(SearchContext context) {464 Class<?> contextClass = context.getClass();465 if (FindsByWindowsAutomation.class.isAssignableFrom(contextClass)) {466 return FindsByWindowsAutomation.class.cast(context)467 .findElementsByWindowsUIAutomation(getLocatorString());468 }469 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {470 return super.findElements(context);471 }472 throw formIllegalArgumentException(contextClass, FindsByWindowsAutomation.class,473 FindsByFluentSelector.class);474 }475 /**476 * {@inheritDoc}477 *478 * @throws WebDriverException when current session doesn't support the given selector or when479 * value of the selector is not consistent.480 * @throws IllegalArgumentException when it is impossible to find something on the given481 * {@link SearchContext} instance482 */483 @Override public WebElement findElement(SearchContext context) {484 Class<?> contextClass = context.getClass();485 if (FindsByWindowsAutomation.class.isAssignableFrom(contextClass)) {486 return FindsByWindowsAutomation.class.cast(context)487 .findElementByWindowsUIAutomation(getLocatorString());488 }489 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {490 return super.findElement(context);491 }492 throw formIllegalArgumentException(contextClass, FindsByIosNSPredicate.class,493 FindsByWindowsAutomation.class);494 }495 }496 public static class ByImage extends MobileBy implements Serializable {497 protected ByImage(String b64Template) {498 super(MobileSelector.IMAGE, b64Template);499 }500 /**501 * {@inheritDoc}502 *503 * @throws WebDriverException when current session doesn't support the given selector or when504 * value of the selector is not consistent.505 * @throws IllegalArgumentException when it is impossible to find something on the given506 * {@link SearchContext} instance507 */508 @SuppressWarnings("unchecked")509 @Override public List<WebElement> findElements(SearchContext context) {510 Class<?> contextClass = context.getClass();511 if (FindsByImage.class.isAssignableFrom(contextClass)) {512 return FindsByImage.class.cast(context).findElementsByImage(getLocatorString());513 }514 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {515 return super.findElements(context);516 }517 throw formIllegalArgumentException(contextClass, FindsByImage.class, FindsByFluentSelector.class);518 }519 /**520 * {@inheritDoc}521 *522 * @throws WebDriverException when current session doesn't support the given selector or when523 * value of the selector is not consistent.524 * @throws IllegalArgumentException when it is impossible to find something on the given525 * {@link SearchContext} instance526 */527 @Override public WebElement findElement(SearchContext context) {528 Class<?> contextClass = context.getClass();529 if (FindsByImage.class.isAssignableFrom(contextClass)) {530 return FindsByImage.class.cast(context).findElementByImage(getLocatorString());531 }532 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {533 return super.findElement(context);534 }535 throw formIllegalArgumentException(contextClass, FindsByImage.class, FindsByFluentSelector.class);536 }537 @Override public String toString() {538 return "By.Image: " + getLocatorString();539 }540 }541 public static class ByCustom extends MobileBy implements Serializable {542 protected ByCustom(String selector) {543 super(MobileSelector.CUSTOM, selector);544 }545 /**546 * {@inheritDoc}547 *548 * @throws WebDriverException when current session doesn't support the given selector or when549 * value of the selector is not consistent.550 * @throws IllegalArgumentException when it is impossible to find something on the given551 * {@link SearchContext} instance552 */553 @SuppressWarnings("unchecked")554 @Override public List<WebElement> findElements(SearchContext context) {555 Class<?> contextClass = context.getClass();556 if (FindsByCustom.class.isAssignableFrom(contextClass)) {557 return FindsByCustom.class.cast(context).findElementsByCustom(getLocatorString());558 }559 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {560 return super.findElements(context);561 }562 throw formIllegalArgumentException(contextClass, FindsByCustom.class, FindsByFluentSelector.class);563 }564 /**565 * {@inheritDoc}566 *567 * @throws WebDriverException when current session doesn't support the given selector or when568 * value of the selector is not consistent.569 * @throws IllegalArgumentException when it is impossible to find something on the given570 * {@link SearchContext} instance571 */572 @Override public WebElement findElement(SearchContext context) {573 Class<?> contextClass = context.getClass();574 if (FindsByCustom.class.isAssignableFrom(contextClass)) {575 return FindsByCustom.class.cast(context).findElementByCustom(getLocatorString());576 }577 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {578 return super.findElement(context);579 }580 throw formIllegalArgumentException(contextClass, FindsByCustom.class, FindsByFluentSelector.class);581 }582 @Override public String toString() {583 return "By.Custom: " + getLocatorString();584 }585 }586 public static class ByAndroidViewTag extends MobileBy implements Serializable {587 public ByAndroidViewTag(String tag) {588 super(MobileSelector.ANDROID_VIEWTAG, tag);589 }590 /**591 * {@inheritDoc}592 *593 * @throws WebDriverException when current session doesn't support the given selector or when594 * value of the selector is not consistent.595 * @throws IllegalArgumentException when it is impossible to find something on the given596 * {@link SearchContext} instance597 */598 @SuppressWarnings("unchecked")599 @Override600 public List<WebElement> findElements(SearchContext context) throws WebDriverException,601 IllegalArgumentException {602 Class<?> contextClass = context.getClass();603 if (FindsByAndroidViewTag.class.isAssignableFrom(contextClass)) {604 return FindsByAndroidViewTag.class.cast(context)605 .findElementsByAndroidViewTag(getLocatorString());606 }607 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {608 return super.findElements(context);609 }610 throw formIllegalArgumentException(contextClass, FindsByAndroidViewTag.class,611 FindsByFluentSelector.class);612 }613 /**614 * {@inheritDoc}615 *616 * @throws WebDriverException when current session doesn't support the given selector or when617 * value of the selector is not consistent.618 * @throws IllegalArgumentException when it is impossible to find something on the given619 * {@link SearchContext} instance620 */621 @Override public WebElement findElement(SearchContext context) throws WebDriverException,622 IllegalArgumentException {623 Class<?> contextClass = context.getClass();624 if (FindsByAndroidViewTag.class.isAssignableFrom(contextClass)) {625 return FindsByAndroidViewTag.class.cast(context)626 .findElementByAndroidViewTag(getLocatorString());627 }628 if (FindsByFluentSelector.class.isAssignableFrom(contextClass)) {629 return super.findElement(context);630 }631 throw formIllegalArgumentException(contextClass, FindsByAndroidViewTag.class,632 FindsByFluentSelector.class);633 }634 @Override public String toString() {635 return "By.AndroidViewTag: " + getLocatorString();636 }637 }638}...

Full Screen

Full Screen

By.java

Source:By.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package com.testpros.fast;18import io.appium.java_client.MobileSelector;19/**20 * Mechanism used to locate elements within a document. In order to create your own locating21 * mechanisms, it is possible to subclass this class and override the protected methods as required,22 * though it is expected that all subclasses rely on the basic finding mechanisms provided23 * through static methods of this class:24 *25 * <code>26 * public WebElement findElement(WebDriver driver) {27 * WebElement element = driver.findElement(By.id(getSelector()));28 * if (element == null)29 * element = driver.findElement(By.name(getSelector());30 * return element;31 * }32 * </code>33 */34//public class By extends io.appium.java_client.MobileBy {35//public abstract class By extends org.openqa.selenium.By {36public class By {37 org.openqa.selenium.By by;38 public By(org.openqa.selenium.By by) {39 this.by = by;40 }41 public org.openqa.selenium.By getBy() {42 return by;43 }44 45 /**46 * @param id The value of the "id" attribute to search for.47 * @return A By which locates elements by the value of the "id" attribute.48 */49 public static By id(String id) {50 return new By(org.openqa.selenium.By.id(id));51 }52 /**53 * @param linkText The exact text to match against.54 * @return A By which locates A elements by the exact text it displays.55 */56 public static By linkText(String linkText) {57 return new By(org.openqa.selenium.By.linkText(linkText));58 }59 /**60 * @param partialLinkText The partial text to match against61 * @return a By which locates elements that contain the given link text.62 */63 public static By partialLinkText(String partialLinkText) {64 return new By(org.openqa.selenium.By.partialLinkText(partialLinkText));65 }66 /**67 * @param name The value of the "name" attribute to search for.68 * @return A By which locates elements by the value of the "name" attribute.69 */70 public static By name(String name) {71 return new By(org.openqa.selenium.By.name(name));72 }73 /**74 * @param tagName The element's tag name.75 * @return A By which locates elements by their tag name.76 */77 public static By tagName(String tagName) {78 return new By(org.openqa.selenium.By.tagName(tagName));79 }80 /**81 * @param xpathExpression The XPath to use.82 * @return A By which locates elements via XPath.83 */84 public static By xpath(String xpathExpression) {85 return new By(org.openqa.selenium.By.xpath(xpathExpression));86 }87 /**88 * Find elements based on the value of the "class" attribute. If an element has multiple classes, then89 * this will match against each of them. For example, if the value is "one two onone", then the90 * class names "one" and "two" will match.91 *92 * @param className The value of the "class" attribute to search for.93 * @return A By which locates elements by the value of the "class" attribute.94 */95 public static By className(String className) {96 return new By(org.openqa.selenium.By.className(className));97 }98 /**99 * Find elements via the driver's underlying W3C Selector engine. If the browser does not100 * implement the Selector API, a best effort is made to emulate the API. In this case, we strive101 * for at least CSS2 support, but offer no guarantees.102 *103 * @param cssSelector CSS expression.104 * @return A By which locates elements by CSS.105 */106 public static By cssSelector(String cssSelector) {107 return new By(org.openqa.selenium.By.cssSelector(cssSelector));108 }109 /**110 * Read http://developer.android.com/intl/ru/tools/testing-support-library/111 * index.html#uia-apis112 *113 * @param uiautomatorText is Android UIAutomator string114 * @return an instance of {@link By.ByAndroidUIAutomator}115 */116 public static By AndroidUIAutomator(final String uiautomatorText) {117 return new By(io.appium.java_client.MobileBy.AndroidUIAutomator(uiautomatorText));118 }119 /**120 * About Android accessibility121 * https://developer.android.com/intl/ru/training/accessibility/accessible-app.html122 * About iOS accessibility123 * https://developer.apple.com/library/ios/documentation/UIKit/Reference/124 * UIAccessibilityIdentification_Protocol/index.html125 *126 * @param accessibilityId id is a convenient UI automation accessibility Id.127 * @return an instance of {@link By.ByAndroidUIAutomator}128 */129 public static By AccessibilityId(final String accessibilityId) {130 return new By(io.appium.java_client.MobileBy.AccessibilityId(accessibilityId));131 }132 /**133 * This locator strategy is available in XCUITest Driver mode.134 *135 * @param iOSClassChainString is a valid class chain locator string.136 * See <a href="https://github.com/facebook/WebDriverAgent/wiki/Queries">137 * the documentation</a> for more details138 * @return an instance of {@link By.ByIosClassChain}139 */140 public static By iOSClassChain(final String iOSClassChainString) {141 return new By(io.appium.java_client.MobileBy.iOSClassChain(iOSClassChainString));142 }143 /**144 * This locator strategy is only available in Espresso Driver mode.145 *146 * @param dataMatcherString is a valid class chain locator string.147 * See <a href="https://github.com/appium/appium-espresso-driver/pull/386">148 * the documentation</a> for more details149 * @return an instance of {@link By.ByAndroidDataMatcher}150 */151 public static By androidDataMatcher(final String dataMatcherString) {152 return new By(io.appium.java_client.MobileBy.androidDataMatcher(dataMatcherString));153 }154 /**155 * This locator strategy is available in XCUITest Driver mode.156 *157 * @param iOSNsPredicateString is an an iOS NsPredicate String158 * @return an instance of {@link By.ByIosNsPredicate}159 */160 public static By iOSNsPredicateString(final String iOSNsPredicateString) {161 return new By(io.appium.java_client.MobileBy.iOSNsPredicateString(iOSNsPredicateString));162 }163 public static By windowsAutomation(final String windowsAutomation) {164 return new By(io.appium.java_client.MobileBy.windowsAutomation(windowsAutomation));165 }166 /**167 * This locator strategy is available in Espresso Driver mode.168 *169 * @param tag is an view tag string170 * @return an instance of {@link ByAndroidViewTag}171 * @since Appium 1.8.2 beta172 */173 public static By AndroidViewTag(final String tag) {174 return new By(io.appium.java_client.MobileBy.AndroidViewTag(tag));175 }176 /**177 * This locator strategy is available only if OpenCV libraries and178 * NodeJS bindings are installed on the server machine.179 *180 * @param b64Template base64-encoded template image string. Supported image formats are the same181 * as for OpenCV library.182 * @return an instance of {@link ByImage}183 * @see <a href="https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/image-comparison.md">184 * The documentation on Image Comparison Features</a>185 * @see <a href="https://github.com/appium/appium-base-driver/blob/master/lib/basedriver/device-settings.js">186 * The settings available for lookup fine-tuning</a>187 * @since Appium 1.8.2188 */189 public static By image(final String b64Template) {190 return new By(io.appium.java_client.MobileBy.image(b64Template));191 }192 /**193 * This type of locator requires the use of the 'customFindModules' capability and a194 * separately-installed element finding plugin.195 *196 * @param selector selector to pass to the custom element finding plugin197 * @return an instance of {@link ByCustom}198 * @since Appium 1.9.2199 */200 public static By custom(final String selector) {201 return new By(io.appium.java_client.MobileBy.custom(selector));202 }203}...

Full Screen

Full Screen

MobileBy.ByImage

Using AI Code Generation

copy

Full Screen

1package appium;2import io.appium.java_client.AppiumDriver;3import io.appium.java_client.MobileBy;4import io.appium.java_client.MobileElement;5import io.appium.java_client.android.AndroidDriver;6import io.appium.java_client.remote.MobileCapabilityType;7import org.openqa.selenium.remote.DesiredCapabilities;8import java.net.MalformedURLException;9import java.net.URL;10public class AppiumJavaClient {11 public static void main(String[] args) throws MalformedURLException {12 DesiredCapabilities caps = new DesiredCapabilities();13 caps.setCapability(MobileCapabilityType.DEVICE_NAME, "emulator-5554");14 caps.setCapability(MobileCapabilityType.APP, "C:\\Users\\Rahul\\Downloads\\ApiDemos-debug.apk");15 MobileElement element = driver.findElement(MobileBy.ByImage.image("C:\\Users\\Rahul\\Downloads\\calculator.png"));16 element.click();17 }18}19from appium import webdriver20desired_caps = {'platformName': 'Android', 'platformVersion': '10',21 'deviceName': 'emulator-5554', 'app': 'C:/Users/Rahul/Downloads/ApiDemos-debug.apk'}22element = driver.find_element_by_image("C:/Users/Rahul/Downloads/calculator.png")23element.click()

Full Screen

Full Screen

MobileBy.ByImage

Using AI Code Generation

copy

Full Screen

1import io.appium.java_client.MobileBy;2import io.appium.java_client.MobileElement;3import io.appium.java_client.android.AndroidDriver;4import io.appium.java_client.android.AndroidElement;5import org.openqa.selenium.By;6import org.openqa.selenium.remote.DesiredCapabilities;7import java.net.MalformedURLException;8import java.net.URL;9import java.util.concurrent.TimeUnit;10public class appium {11 public static void main(String[] args) throws MalformedURLException {12 DesiredCapabilities caps = new DesiredCapabilities();13 caps.setCapability("deviceName", "Pixel 3a API 30");14 caps.setCapability("platformName", "Android");15 caps.setCapability("platformVersion", "11.0");16 caps.setCapability("appPackage", "com.android.calculator2");17 caps.setCapability("appActivity", "com.android.calculator2.Calculator");18 caps.setCapability("noReset", "true");

Full Screen

Full Screen

MobileBy.ByImage

Using AI Code Generation

copy

Full Screen

1MobileBy.ByImage byImage = new MobileBy.ByImage(imageFile, 0.8);2MobileElement element = driver.findElement(byImage);3by_image = ByImage(image_path, threshold=0.8)4element = driver.find_element(by_image)5const byImage = new ByImage(imagePath, 0.8);6const element = await driver.findElement(byImage);7by_image = Appium::Core::Android::ByImage.new(image_path, 0.8)8element = driver.find_element(by_image)9ByImage byImage = new ByImage(imagePath, 0.8);10IWebElement element = driver.FindElement(byImage);11byImage := mobileby.ByImage(imagePath, 0.8)12element, _ := driver.FindElement(byImage)13$byImage = ByImage::byImage($imagePath, 0.8);14$element = $driver->findElement($byImage);15by_image = Appium::Core::Android::ByImage.new(image_path, 0.8)16element = driver.find_element(by_image)17by_image = Appium::Core::Android::ByImage.new(image_path, 0.8)18element = driver.find_element(by_image)19by_image = Appium::Core::Android::ByImage.new(image_path, 0.8)20element = driver.find_element(by_image)

Full Screen

Full Screen

MobileBy.ByImage

Using AI Code Generation

copy

Full Screen

1package appium.java;2import io.appium.java_client.MobileBy;3import io.appium.java_client.android.AndroidDriver;4import io.appium.java_client.android.AndroidElement;5import org.openqa.selenium.By;6import org.openqa.selenium.remote.DesiredCapabilities;7import java.net.MalformedURLException;8import java.net.URL;9import java.util.concurrent.TimeUnit;10public class ByImage {11 public static void main(String[] args) throws MalformedURLException, InterruptedException {12 DesiredCapabilities dc = new DesiredCapabilities();13 dc.setCapability("deviceName", "Android Emulator");14 dc.setCapability("platformName", "Android");15 dc.setCapability("platformVersion", "10.0");16 dc.setCapability("automationName", "UiAutomator2");17 dc.setCapability("appPackage", "com.android.calculator2");18 dc.setCapability("appActivity", "com.android.calculator2.Calculator");19 dc.setCapability("noReset", true);20 dc.setCapability("fullReset", false);

Full Screen

Full Screen

MobileBy.ByImage

Using AI Code Generation

copy

Full Screen

1MobileElement element = (MobileElement) driver.findElementByImage("/path/to/image");2MobileElement element = (MobileElement) driver.findElementByImage("/path/to/image", 0.9);3MobileElement element = (MobileElement) driver.findElementByImage("/path/to/image", 0.9, 0.1);4MobileElement element = (MobileElement) driver.findElementByImage("/path/to/image", 0.9, 0.1, 0.1);5element = driver.find_element_by_image("/path/to/image")6element = driver.find_element_by_image("/path/to/image", 0.9)7element = driver.find_element_by_image("/path/to/image", 0.9, 0.1)8element = driver.find_element_by_image("/path/to/image", 0.9, 0.1, 0.1)9element = driver.find_element_by_image("/path/to/image")10element = driver.find_element_by_image("/path/to/image", 0.9)

Full Screen

Full Screen

MobileBy.ByImage

Using AI Code Generation

copy

Full Screen

1package appium;2import java.net.MalformedURLException;3import java.net.URL;4import org.openqa.selenium.By;5import org.openqa.selenium.remote.DesiredCapabilities;6import io.appium.java_client.MobileBy;7import io.appium.java_client.android.AndroidDriver;8import io.appium.java_client.android.AndroidElement;9public class AppiumByImage {10 public static void main(String[] args) throws MalformedURLException {11 DesiredCapabilities cap = new DesiredCapabilities();12 cap.setCapability("deviceName", "Android Emulator");13 cap.setCapability("platformName", "Android");14 cap.setCapability("platformVersion", "6.0");15 cap.setCapability("appPackage", "com.android.calculator2");16 cap.setCapability("appActivity", "com.android.calculator2.Calculator");

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run io.appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in MobileBy.ByImage

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful