Best io.appium code snippet using io.appium.java_client.android.options.server.EspressoBuildConfig
BaseDriver.java
Source:BaseDriver.java
1package LDSToolsAppium;2import LDSToolsAppium.Screen.HelpScreen;3import LDSToolsAppium.Screen.LoginPageScreen;4import LDSToolsAppium.Screen.MenuScreen;5import io.appium.java_client.AppiumDriver;6import io.appium.java_client.MobileElement;7import io.appium.java_client.android.AndroidDriver;8import io.appium.java_client.ios.IOSDriver;9import io.cucumber.testng.*;10import org.apache.commons.io.FileUtils;11import org.apache.commons.lang3.StringUtils;12import org.openqa.selenium.OutputType;13import org.openqa.selenium.remote.CapabilityType;14import org.openqa.selenium.remote.DesiredCapabilities;15import org.openqa.selenium.logging.*;16import org.picocontainer.classname.ClassName;17import org.testng.ITest;18import org.testng.ITestContext;19import org.testng.ITestResult;20import org.testng.annotations.*;21import org.testng.annotations.Optional;22import java.io.*;23import java.lang.reflect.Method;24import java.net.Socket;25import java.net.SocketException;26import java.net.URL;27import java.nio.file.Files;28import java.nio.file.Path;29import java.nio.file.Paths;30import java.util.*;31import java.util.logging.LogManager;32import java.util.logging.Logger;33@CucumberOptions()34public class BaseDriver extends AbstractTestNGCucumberTests {35// public static AppiumDriver<MobileElement> driver;36 public static ThreadLocal<AppiumDriver> driver = new ThreadLocal<>();37 public static final Logger LOGGER = Logger.getLogger(ClassName.class.getName());38 public static AppiumDriver<MobileElement> driver2;39 public String deviceSerial = "";40 public String testOS = "";41 public String testngTestDevice = "";42 public int testngStartSleepTime = 200;43 public AppiumService myAppiumService = new AppiumService();44 public TestNGCucumberRunner testNGCucumberRunner;45 46 protected LDSToolsApp app;47 protected MobileDevApp app2;48 public LDSWeb myWeb = new LDSWeb();49 public String accessToken = "5b5e50c533cf4e00aa32c8caf1aa1d8fad972f9414a64f71abdce9d06d6a5248";50 public String stfURL = "http://10.109.45.146:7100";51 public String testDevice = "";52 public String memberLogin = "dsoneil";53 public String unitNumber = "39373";54 public String androidAppPackage = "org.lds.ldstools.alpha";55 public ThreadLocal<String> dataTestName = new ThreadLocal<>();56 static AppiumDriver getDriver() {57 return driver.get();58 }59 @BeforeSuite(alwaysRun = true)60 public void removeFilesBeforeTest() throws Exception {61 //Turn off logging62// LogManager.getLogManager().reset();63// LOGGER.severe("Severe Message");64// LOGGER.warning("Warning Message");65// LOGGER.info("Info Message");66// LOGGER.config("Config Message");67// LOGGER.fine("Fine Message");68// LOGGER.finer("Finer Message");69// LOGGER.finest("Finest Message");70 LOGGER.info("Killing all appium nodes");71 killProcess("main.js");72 testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());73// File reportsDirectory = new File ("/Users/zmaxfield/Documents/workspace/qa-membertools-all/src/test/java/Reports");74// File screenshotDirectory = new File ("/Users/zmaxfield/Documents/workspace/qa-membertools-all/screenshot");75 File reportsDirectory = new File ("src/test/java/Reports");76 File screenshotDirectory = new File ("screenshot");77 File configFiles = new File ("ConfigFiles");78 Path reportsAndroidDirectory = Paths.get("src/test/java/Reports/Android");79 Path reportsiOSDirectory = Paths.get("src/test/java/Reports/iOS");80 LOGGER.info("LOGGER: Start clean directories");81 System.out.println("Start clean directories");82 try {83 FileUtils.cleanDirectory(reportsDirectory);84 FileUtils.cleanDirectory(screenshotDirectory);85 } catch (IOException e) {86 e.printStackTrace();87 }88 File[] configFileList = configFiles.listFiles();89 if (configFileList != null) {90 for (File oneFile : configFileList ) {91 if (oneFile.getName().endsWith(".json")) {92 oneFile.delete();93 }94 }95 }96 Files.createDirectories(reportsAndroidDirectory);97 Files.createDirectories(reportsiOSDirectory);98 }99 // @BeforeTest(alwaysRun = true)100 @BeforeClass(alwaysRun = true)101 @Parameters({"os", "fileName", "testDevice", "startSleepTime", "systemPort"})102 public void setUp(String os, String fileName, String testDevice, int startSleepTime, int systemPort) throws Exception {103 testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());104 int myPort;105 testOS = os;106 testngTestDevice = testDevice;107 testngStartSleepTime = startSleepTime;108 System.out.println("Start of Setup");109// //Sleep so when multiple tests start they don't break110// System.out.println("Sleep Time: " + startSleepTime);111// System.out.println("File Name: " + fileName);112// System.out.println("Test Device: " + testDevice);113// System.out.println("Test Device2: " + testngTestDevice);114 Thread.sleep(startSleepTime);115 //Get Random Port Number116 myPort = getRandomPort(4500, 4999);117 //System.out.println("OS: " + os);118 //System.out.println("Port: " + myPort);119 //Start Appium Server for iOS or Android with the Random Port120 //myAppiumService.startAppiumService(os, myPort);121// AppiumService.startAppiumService(os, myPort);122 AppiumService.startAppiumService(testOS, myPort);123 //AppiumService.startAppiumService(os, myPort);124 if (fileName.contains("android-mobile-dev")) {125// System.out.println("File Name: " + fileName);126// driver2 = appiumCapabilities(os, fileName, testDevice, myPort);127 app2 = new MobileDevApp(driver2);128 } else {129// driver = appiumCapabilities(os, fileName, testDevice, myPort);130 appiumCapabilities(os, fileName, testDevice, myPort, systemPort);131 app = new LDSToolsApp(driver);132 }133 System.out.println("End of Setup");134 135 }136// @BeforeMethod(alwaysRun = true)137// public void BeforeMethodTestName (Method method, Object[] testData, ITestContext ctx) {138// if (testData.length > 0) {139// dataTestName.set(method.getName() + "_" + testData[3]);140// ctx.setAttribute("testName", dataTestName.get());141//// ctx.setAttribute("name", dataTestName.get());142//// System.out.println(Arrays.toString(ctx.getAttributeNames().toArray()));143// } else {144// ctx.setAttribute("testName", method.getName());145// }146//147// }148// @Override149// public String getTestName() {150// return dataTestName.get();151//152// }153 @DataProvider(name = "Members")154 public Iterator<Object []> provider(ITestContext context) throws InterruptedException {155 String myGroup;156 String myFileName = "src/main/java/LDSToolsAppium/membersOne.csv";157 List<String> includedGroups = Arrays.asList(context.getIncludedGroups());158 myGroup = includedGroups.toString();159 System.out.println("GROUP: " + myGroup);160 if (myGroup.contains("smoke")) {161 System.out.println("Found smoke ");162 myFileName = "src/main/java/LDSToolsAppium/membersSmall.csv";163// myFileName = "src/main/java/LDSToolsAppium/membersOne.csv";164 } else if (myGroup.contains("all")) {165 System.out.println("Found all ");166 myFileName = "src/main/java/LDSToolsAppium/members.csv";167 }168 //String myFileName = "src/main/java/LDSToolsAppium/membersOne.csv";169 BufferedReader br = null;170 String line;171 String splitBy = ",";172 String[] data = null;173 List<Object []> testCases = new ArrayList<>();174 try {175 br = new BufferedReader(new FileReader(myFileName));176 while ((line = br.readLine()) != null) {177 data = line.split(splitBy);178 testCases.add(data);179 }180 } catch (IOException e) {181 e.printStackTrace();182 }183 return testCases.iterator();184 }185 @DataProvider(name = "Header")186 public Iterator<Object []> providerHeader(ITestContext context) throws InterruptedException {187 String myFileName = "src/main/java/LDSToolsAppium/header.csv";188 BufferedReader br = null;189 String line;190 String splitBy = ",";191 String[] data = null;192 List<Object []> testCases = new ArrayList<>();193 try {194 br = new BufferedReader(new FileReader(myFileName));195 while ((line = br.readLine()) != null) {196 data = line.split(splitBy);197 testCases.add(data);198 }199 } catch (IOException e) {200 e.printStackTrace();201 }202 return testCases.iterator();203 }204 @AfterMethod(alwaysRun = true)205 public void teardown(ITestResult result) throws Exception {206 BasePage myBasePage = new BasePage(driver);207 String testName;208 System.out.println("After Method - Start teardown");209 // Here will compare if test is failing then only it will enter into if condition210 if(ITestResult.FAILURE==result.getStatus()) {211 //printPageSource();212 testName = result.getName();213 //System.out.println("getName " + result.getName());214 screenshotAndLogs(testName);215 }216 //Trying to figure out why my tests are getting skipped.217 if (ITestResult.SKIP==result.getStatus()) {218 Throwable t = result.getThrowable();219 t.printStackTrace();220 }221 if(getRunningOS().equals("ios")) {222 Thread.sleep(4000);223 System.out.println("Start Reset App");224// driver.removeApp("org.lds.ldstools");225//// driver.installApp(driver.getCapabilities().getCapability("app").toString());226// driver.launchApp();227 getDriver().resetApp();228// driver.resetApp();229 System.out.println("End Reset App");230 Thread.sleep(5000);231 if (myBasePage.checkForElement(myBasePage.allowButton)) {232 myBasePage.allowButton.click();233 }234 } else {235 Thread.sleep(2000);236 System.out.println("Rest App");237 getDriver().resetApp();238// getDriver().quit();239// getDriver().resetApp();240// System.out.println("Clear App");241// adbCommand("clearApp");242// Thread.sleep(5000);243// getDriver().launchApp();244// getDriver().resetApp();245 Thread.sleep(5000);246 System.out.println("SERIAL NUMBER: " + deviceSerial);247 }248// System.out.println("Check to see if web is running");249// if (myWeb.isRunning() == null) {250// System.out.println("Web is not running!");251// } else {252// myWeb.tearDown();253// }254 System.out.println("End teardown");255 }256// @AfterClass(alwaysRun = true)257// public void afterClass() throws Exception {258// if (!getRunningOS().equals("ios")) {259// driver.quit();260// if (!deviceSerial.equals("")) {261//262// STFService mySTFService = new STFService(stfURL, accessToken);263// DeviceApi myDevice = new DeviceApi(mySTFService);264// System.out.println("After Class - SERIAL NUMBER: " + deviceSerial);265// myDevice.releaseDevice(deviceSerial);266// Thread.sleep(3000);267// adbRemoteDisconnect(testDevice);268// myDevice.releaseDevice(deviceSerial);269//270// }271// }272// }273 @AfterSuite(alwaysRun = true)274 public void afterAllTests() throws Exception {275 System.out.println("After Suite - Stopping the driver");276 if (getRunningOS().equals("android")) {277 STFService mySTFService = new STFService(stfURL, accessToken);278 DeviceApi myDevice = new DeviceApi(mySTFService);279 System.out.println("After All Tests - SERIAL NUMBER: " + deviceSerial);280 if (!deviceSerial.isEmpty()) {281 System.out.println("After All Tests - SERIAL NUMBER: " + deviceSerial);282 myDevice.releaseDevice(deviceSerial);283 Thread.sleep(3000);284 killProcess("adb");285 myDevice.releaseDevice(deviceSerial);286 }287 }288 System.out.println("Stopping the Appium Service");289 myAppiumService.stopAppiumService();290 Thread.sleep(1000);291 }292// private AppiumDriver<MobileElement> appiumCapabilities(String os, String fileName, String testDevice, int myPort) throws Exception {293 private void appiumCapabilities(String os, String fileName, String testDevice, int myPort, int systemPort) throws Exception {294 String myAppPackage;295 String myUdid = null;296 int mySystemPort;297 //Android Setup298 if (os.equals("android")) {299 List<String> deviceList;300 if (testDevice.contains("STFZade")) {301 accessToken = "c6c814d0122047ab98c2af2a84eb09022a3dd0e82e944526896e9016eb121844";302 stfURL = "http://10.109.45.162:7100";303 }304 if (testDevice.contains("STFMain")) {305 accessToken = "7a51e3b2af8d4cdca761035facd677569b8c3fa4f04f491ca3ed7591372361c1";306 stfURL = "https://serenity.ldschurch.org";307 }308 if (testDevice.contains("STF")) {309 String deviceIPPort;310 String[] parts = testDevice.split("-");311 // String part1 = parts[0];312 deviceSerial = parts[1];313 System.out.println("SERIAL NUMBER: " + deviceSerial);314 LDSToolsAppium.STFService mySTFService = new LDSToolsAppium.STFService(stfURL, accessToken);315 LDSToolsAppium.DeviceApi myDevice = new LDSToolsAppium.DeviceApi(mySTFService);316 if (deviceSerial.equals("Pool")) {317 deviceList = myDevice.getAvalibleDevices();318 deviceSerial = deviceList.get(new Random().nextInt(deviceList.size()));319 System.out.println("DEVICE TO USE: " + deviceSerial);320 deviceSerial = deviceSerial.replace("\"", "");321 System.out.println("SERIAL NUMBER: " + deviceSerial);322 }323 myDevice.connectDevice(deviceSerial);324 deviceIPPort = myDevice.remoteControl(deviceSerial);325 testDevice = getRemoteIPPort(deviceIPPort);326 adbRemoteConnect(testDevice);327 }328 if (testDevice.contains("WIRELESS")) {329 String deviceIPPort;330 String[] parts = testDevice.split("-");331 // String part1 = parts[0];332 deviceSerial = parts[1];333 System.out.println("SERIAL NUMBER: " + deviceSerial);334 testDevice = deviceSerial;335 adbRemoteConnect(testDevice);336 }337 mySystemPort = systemPort;338 mySystemPort = getRandomPort(8500, 8999);339 // set up appium340 File classpathRoot = new File(System.getProperty("user.dir"));341 //TODO: Need a better path342// File appDir = new File(classpathRoot, "../../../Selenium");343 File appDir = new File(classpathRoot, "/AppUnderTest");344 File app = new File(appDir, fileName);345 DesiredCapabilities capabilities = new DesiredCapabilities();346 capabilities.setCapability("app", app.getAbsolutePath());347 myAppPackage = "org.lds.ldstools.alpha";348// if (fileName.contains("android-mobile-dev")) {349// capabilities.setCapability("appPackage", "org.lds.dev"); // *** ALPHA ***350// myAppPackage = "org.lds.dev";351// } else {352// if (fileName.contains("master")) {353// capabilities.setCapability("appPackage", "org.lds.ldstools.alpha"); // *** ALPHA ***354//// capabilities.setCapability("appPackage", "io.appium.espressoserver.test"); // *** ALPHA ***355// myAppPackage = "org.lds.ldstools.alpha";356// } else {357// capabilities.setCapability("appPackage", "org.lds.ldstools"); //*** BETA and RELEASE ***358// myAppPackage = "org.lds.ldstools";359// }360// }361// capabilities.setCapability("appPackage", "io.appium.espressoserver.test"); // *** ALPHA ***362// myAppPackage = "org.lds.ldstools.alpha";363 androidAppPackage = myAppPackage;364 capabilities.setCapability("deviceName", testDevice);365 capabilities.setCapability("udid", testDevice);366 capabilities.setCapability("platformName", "android");367 capabilities.setCapability("automationName","uiautomator2");368 capabilities.setCapability("noSign", true);369// capabilities.setCapability("automationName","espresso");370// capabilities.setCapability("forceEspressoRebuild",true);371// capabilities.setCapability("espressoServerLaunchTimeout",500000);372// capabilities.setCapability("espressoBuildConfig","/Users/zmaxfield/Documents/workspace/qa-membertools-all/AppUnderTest/espressConfig.json");373 capabilities.setCapability("fullReset", true);374// capabilities.setCapability("autoLaunch", false);375// capabilities.setCapability("noReset", false);376// capabilities.setCapability("appPackage", myAppPackage);377 capabilities.setCapability("newCommandTimeout", 5000);378 capabilities.setCapability("appWaitActivity", "org.lds.ldstools.ux.auth.AuthenticationSignInActivity");379// capabilities.setCapability("appWaitActivity", "org.lds.ldstools.ux.main.MainActivity");380 capabilities.setCapability("appWaitDuration", "300000");381// capabilities.setCapability("normalizeTagNames", true);382 capabilities.setCapability("deviceReadyTimeout", 60);383// capabilities.setCapability("gpsEnabled", true);384 capabilities.setCapability("dontStopAppOnReset", true);385 capabilities.setCapability("appium:clearDeviceLogsOnStart", true);386// capabilities.setCapability("appium:unlockType", "pin");387// capabilities.setCapability("appium:unlockKey", "1133");388// capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");389 capabilities.setCapability("maxTypingFrequency", "8");390// capabilities.setCapability("appActivity", "org.lds.ldstools.alpha.org.lds.ldstools.ui.activity.StartupActivity");391 capabilities.setCapability("androidInstallTimeout", "90000");392// capabilities.setCapability("unicodeKeyboard", "true");393// capabilities.setCapability("resetKeyboard", "true");394 capabilities.setCapability("systemPort", mySystemPort);395 driver.set(new AndroidDriver<>(new URL("http://127.0.0.1:" + myPort + "/wd/hub"), capabilities));396// driver = new AndroidDriver<>(new URL("http://127.0.0.1:" + myPort + "/wd/hub"), capabilities);397 Thread.sleep(2000);398 }399 //Setup for iOS400 if (os.equals("ios")) {401 //String webDriverURL = "http://localhost:";402 //String webDriverPort;403 int tempPort;404 tempPort = myPort + 1000;405 tempPort = getRandomPort(8500, 8999);406 //webDriverPort = String.valueOf(tempPort);407 //webDriverURL = webDriverURL + webDriverPort;408 if (testDevice.contains("REAL")) {409 String[] parts = testDevice.split("-");410 // String part1 = parts[0];411 testDevice = parts[1];412 System.out.println("TEST DEVICE: " + testDevice);413 myUdid = getUDIDfromDeviceName(testDevice);414 //myUdid = deviceUDID();415 }416 if (testDevice.contains("FBSIM")) {417 String[] parts = testDevice.split("-");418 //String part1 = parts[0];419 //Remove all whitespace420 //part1 = part1.trim();421 //part2 = part2.trim();422 testDevice = parts[1];423 myUdid = getUDIDfromDeviceNameFBSIM(testDevice);424 System.out.println("MY UDID: " + myUdid);425 //Start Simulator426 startFbSim(myUdid, tempPort);427 //Just a test428 Thread.sleep(6000);429 }430 DesiredCapabilities capabilities = new DesiredCapabilities();431 if (testDevice.contains("HEADLESS")) {432 String[] parts = testDevice.split("-");433 //String part1 = parts[0];434 //Remove all whitespace435 //part1 = part1.trim();436 //part2 = part2.trim();437 testDevice = parts[1];438 capabilities.setCapability("isHeadless", true);439 }440 System.out.println("Device Name: " + testDevice + " UDID: " + myUdid);441 // set up appium442 File classpathRoot = new File(System.getProperty("user.dir"));443// File appDir = new File(classpathRoot, "../../../Selenium");444 File appDir = new File(classpathRoot, "/AppUnderTest");445 File app = new File(appDir, fileName);446 myAppPackage = "org.lds.ldstools.alpha";447 448 capabilities.setCapability("platformName", "iOS");449 capabilities.setCapability(CapabilityType.BROWSER_NAME, "Safari");450 capabilities.setCapability("appium:deviceName",testDevice);451 capabilities.setCapability("appium:automationName","XCUITest");452 capabilities.setCapability("browserName","");453 capabilities.setCapability("appium:noReset", false);454 capabilities.setCapability("appium:newCommandTimeout", 600);455 capabilities.setCapability("appium:app", app.getAbsolutePath());456 capabilities.setCapability("appium:launchTimeout", 900000);457 capabilities.setCapability("appium:platformVersion", "15.2");458 capabilities.setCapability("appium:nativeInstrumentsLib", false);459 capabilities.setCapability("appium:clearSystemFiles", true);460 //capabilities.setCapability("allowTouchIdEnroll", true);461// capabilities.setCapability("appium:maxTypingFrequency", 20);462// capabilities.setCapability("sendKeyStrategy", "grouped");463// capabilities.setCapability("interKeyDelay", 50);464 //capabilities.setCapability("appPackage", myAppPackage);465 //capabilities.setCapability("simpleIsVisibleCheck", true);466// capabilities.setCapability("connectHardwareKeyboard", false);467 capabilities.setCapability("customSnapshotTimeout", 500);468 capabilities.setCapability("snapshotMaxDepth", 100);469// capabilities.setCapability("fullReset", true);470// capabilities.setCapability("wdaConnectionTimeout", 5000000);471// capabilities.setCapability("appium:waitForQuiescence", false);472 capabilities.setCapability("appium:waitForQuiescence", false);473 //Change this to true for more debug474// capabilities.setCapability("showIOSLog", true);475// capabilities.setCapability("includeNonModalElements", true);476// capabilities.setCapability("shouldUseTestManagerForVisibilityDetection", true);477// capabilities.setCapability("simpleIsVisibleCheck", true);478 capabilities.setCapability("wdaLocalPort", tempPort);479 capabilities.setCapability("locationServicesEnabled", true);480 if (myUdid != null) {481 capabilities.setCapability("xcodeOrgId", "U3SP4KMCK6");482 capabilities.setCapability("xcodeSigningId", "iPhone Developer");483 capabilities.setCapability("udid", myUdid);484 capabilities.setCapability("wdaLocalPort", tempPort);485 capabilities.setCapability("appium:waitForQuiescence", false);486 }487 driver.set(new IOSDriver<>(new URL("http://127.0.0.1:" + myPort + "/wd/hub"),capabilities));488// driver = new IOSDriver<>(new URL("http://127.0.0.1:" + myPort + "/wd/hub"),capabilities);489 }490// return driver;491 }492 private int getRandomPort(int lowPort, int highPort) throws Exception {493 //System.out.println("OS: " + os );494 //System.out.println("File Name: " + fileName);495 //String myUdid = "";496 Random randomPort = new Random();497 int myPort;498// int lowPort = 4500;499// int highPort = 4999;500 //Random randomSleep = new Random();501 //int sleepTime = 1000;502 //int lowSleep = 1000;503 //int highSleep = 9999;504 Boolean portOpen;505 //Check to see if the random port is open506 //If the port is in use try a different port507 do {508 myPort = randomPort.nextInt(highPort - lowPort) + lowPort;509 portOpen = portCheck(myPort);510 } while (portOpen.equals(false));511 //System.out.println("OS: " + os);512 //System.out.println("PORT: " + myPort);513 return myPort;514 }515 private int getRandomPortSystemPort() throws Exception {516 Random randomPort = new Random();517 int myPort;518 int lowPort = 8201;519 int highPort = 8299;520 Boolean portOpen;521 //Check to see if the random port is open522 //If the port is in use try a different port523 do {524 myPort = randomPort.nextInt(highPort - lowPort) + lowPort;525 portOpen = portCheck(myPort);526 } while (portOpen.equals(false));527 return myPort;528 }529 private String getRemoteIPPort(String myText) {530 String myIPPort;531 System.out.println("MY PORT: " + myText);532 String[] ipArray = StringUtils.substringsBetween(myText, "\"", "\"");533 for (String getIP : ipArray) {534 System.out.println("GET IP: " + getIP);535 }536 myIPPort = ipArray[ipArray.length -1];537 return myIPPort;538 }539 private String getAndroidHomePath() throws Exception {540 Runtime run = Runtime.getRuntime();541 Process pr = run.exec(new String[] {"/bin/echo $ANDROID_HOME"});542 //Process pr = run.exec(cmd);543 pr.waitFor();544 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));545 String line;546 line = buf.readLine();547 System.out.println(line);548 return line;549 }550 private void adbRemoteConnect(String ipPort) throws Exception {551 //String pathToADB = "../../../android-sdks/platform-tools/adb";552 //String androidHome = getAndroidHomePath();553 String androidHome = System.getenv("ANDROID_HOME");554 String pathToADB = androidHome + "/platform-tools/adb";555 //String cmd556 // = "adb shell am force-stop org.lds.ldstools.alpha";557 Runtime run = Runtime.getRuntime();558 Process pr = run.exec(new String[] {pathToADB, "connect", ipPort});559 //Process pr = run.exec(cmd);560 pr.waitFor();561 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));562 String line;563 while ((line=buf.readLine())!=null) {564 System.out.println(line);565 }566 }567 private void adbRemoteDisconnect(String ipPort) throws Exception {568 //String pathToADB = "../../../android-sdks/platform-tools/adb";569 //String androidHome = getAndroidHomePath();570 String androidHome = System.getenv("ANDROID_HOME");571 String pathToADB = androidHome + "/platform-tools/adb";572 //String cmd573 // = "adb shell am force-stop org.lds.ldstools.alpha";574 Runtime run = Runtime.getRuntime();575 Process pr = run.exec(new String[] {pathToADB, "disconnect", ipPort});576 //Process pr = run.exec(cmd);577 pr.waitFor();578 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));579 String line;580 while ((line=buf.readLine())!=null) {581 System.out.println(line);582 }583 }584 public void adbProxyStart(String deviceSerial, String proxyUserName) throws Exception {585 //String pathToADB = "../../../android-sdks/platform-tools/adb";586 //String androidHome = getAndroidHomePath();587 String androidHome = System.getenv("ANDROID_HOME");588 String pathToADB = androidHome + "/platform-tools/adb";589 //String cmd590 // = "adb shell am force-stop org.lds.ldstools.alpha";591 Runtime run = Runtime.getRuntime();592 Process pr = run.exec(new String[] { pathToADB, "-s", deviceSerial, "shell", "am", "start", "-a", "android.intent.action.VIEW", "-d", "\"membertools://proxy/" + proxyUserName + "\"" });593 //Process pr = run.exec(cmd);594 pr.waitFor();595 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));596 String line;597 while ((line=buf.readLine())!=null) {598 System.out.println(line);599 }600 }601 public void adbEnterPIN(String deviceSerial) throws Exception {602 //String pathToADB = "../../../android-sdks/platform-tools/adb";603 //String androidHome = getAndroidHomePath();604 String androidHome = System.getenv("ANDROID_HOME");605 String pathToADB = androidHome + "/platform-tools/adb";606 //String cmd607 // = "adb shell am force-stop org.lds.ldstools.alpha";608 Runtime run = Runtime.getRuntime();609 Process pr = run.exec(new String[] { pathToADB, "-s", deviceSerial, "shell", "input", "text", "1133" });610 //Process pr = run.exec(cmd);611 pr.waitFor();612 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));613 String line;614 while ((line=buf.readLine())!=null) {615 System.out.println(line);616 }617 pr = run.exec(new String[] { pathToADB, "-s", deviceSerial, "shell", "input", "keyevent", "66" });618 pr.waitFor();619 buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));620 while ((line=buf.readLine())!=null) {621 System.out.println(line);622 }623 }624 private String getUDIDfbsim(String deviceNameSearch) throws Exception {625 String line;626 //System.out.println("UDID to Test: " + myUDID);627 Runtime run = Runtime.getRuntime();628 deviceNameSearch = "'" + deviceNameSearch + "'";629 System.out.println("EDIT TO SEARCH " + deviceNameSearch);630 //Process pr = run.exec(new String[] {"/bin/bash", "-c", "fbsimctl list ", " | grep", deviceNameSearch});631// Process pr = run.exec(new String[] {"/bin/bash", "-c", "fbsimctl list | grep " + deviceNameSearch});632 Process pr = run.exec(new String[] {"/bin/bash", "-c", "idb list-targets | grep " + deviceNameSearch});633 pr.waitFor();634 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));635 line = buf.readLine();636 System.out.println(line);637 String[] parts = line.split(" | ");638 String simUDID = parts[0];639 String simName = parts[1];640 String simStatus = parts[2];641 String simModel = parts[3]; //This is the udid now642 String simOSVersion = parts[4];643// System.out.println("Part 0: " + simUDID);644// System.out.println("Part 1: " + simName);645// System.out.println("Part 2: " + simStatus);646// System.out.println("Part 3: " + simModel);647// System.out.println("Part 4: " + simOSVersion);648 return simModel;649 }650 private String getUDIDfromDeviceName(String deviceName) throws Exception {651 List<String> connectedUDID;652 String checkDeviceName;653 String returnUDID = "Not Found!";654 //Get UDID from devices655 connectedUDID = multipleDeviceUDID();656 //Match deviceName to UDID657 for(String oneUDID : connectedUDID){658 checkDeviceName = getDeviceName(oneUDID);659 if (checkDeviceName.equals(deviceName)) {660 returnUDID = oneUDID;661 }662 }663 return returnUDID;664 }665 private String deviceUDID() throws IOException{666 ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", "/usr/local/bin/idevice_id -l");667 builder.redirectErrorStream(true);668 Process p = builder.start();669 BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));670 String line;671 line = r.readLine();672 System.out.println(line);673 return line;674 }675 private List<String> multipleDeviceUDID() throws Exception {676 List<String> line = new ArrayList<String>();677 String myLine;678 Runtime run = Runtime.getRuntime();679 Process pr = run.exec(new String[] {"/usr/local/bin/idevice_id", "-l"});680 pr.waitFor();681 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));682 while ((myLine=buf.readLine())!=null) {683 //System.out.println(myLine);684 line.add(myLine);685 }686 return line;687 }688 private String getDeviceName(String myUDID) throws Exception {689 String deviceName;690 String line;691 System.out.println("UDID to Test: " + myUDID);692 Runtime run = Runtime.getRuntime();693 //Process pr = run.exec(new String[] {"/usr/local/bin/ideviceinfo", "--udid", myUDID, "|", "grep", "DeviceName"});694 Process pr = run.exec(new String[] {"/bin/bash", "-c", "/usr/local/bin/ideviceinfo --udid " + myUDID + " | grep DeviceName"});695 pr.waitFor();696 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));697 line = buf.readLine();698 System.out.println(line);699 String[] parts = line.split(" ");700 String part1 = parts[0];701 deviceName = parts[1];702 //System.out.println(deviceName);703 return deviceName;704 }705 private String getUDIDfromDeviceNameFBSIM(String deviceName) throws Exception {706 String simUDID;707// String deviceNameSearch = "| " + deviceName + " |";708 String deviceNameSearch = deviceName + " |";709 System.out.println("TO SEARCH: " + deviceNameSearch);710 simUDID = getUDIDfbsim(deviceNameSearch) ;711 return simUDID;712 }713 private void startFbSim(String myUdid, int tempPort) throws Exception {714 String line;715 String listenPort = Integer.toString(tempPort);716 Runtime run = Runtime.getRuntime();717// Process pr = run.exec(new String[] {"/bin/bash", "-c", "fbsimctl ", myUdid, " boot"});718 Process pr = run.exec(new String[] {"/bin/bash", "-c", "idb", "boot", "--udid", myUdid});719 //Process pr = run.exec(new String[] {"/bin/bash", "-c", "fbsimctl ", myUdid, " boot", "--", "listen", "--http ", listenPort});720 //Process pr = run.exec(new String[] {"/bin/bash", "-c", "fbsimctl ", myUdid });721 pr.waitFor();722 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));723 line = buf.readLine();724 //System.out.println(line);725 }726 private void stopFbSim() throws Exception {727 String line;728 Runtime run = Runtime.getRuntime();729 Process pr = run.exec(new String[] {"/bin/bash", "-c", "fbsimctl shutdown" });730 pr.waitFor();731 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));732 line = buf.readLine();733// System.out.println(line);734 }735 private boolean portCheck(int port) throws IOException {736 // Assume no connection is possible.737 boolean result = false;738 try {739 Socket s = new Socket("localhost", port);740 s.close();741 System.out.println("Port " + port + " is in use.");742 result = false;743 }744 catch(SocketException e) {745 // Could not connect.746 //System.out.println("Port " + port + " is open.");747 result = true;748 }749 return result;750 }751 public void killProcess(String processToKill) throws Exception {752 String line = "";753 Runtime run = Runtime.getRuntime();754 Process pr = run.exec(new String[] {"/usr/bin/pkill", "-9", "-f", "-l", processToKill});755 pr.waitFor();756 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));757 while ((line=buf.readLine())!=null) {758 System.out.println(line);759 }760 }761 public String getRunningOS() {762 String myOs = "";763 if (testOS.equalsIgnoreCase("android")) {764 myOs = "android";765 }766 if (testOS.equalsIgnoreCase("ios")) {767 myOs = "ios";768 }769 myOs = myOs.toLowerCase();770 //System.out.println("MY OS: " + myOs);771 return myOs;772 }773 private void adbCommand(String myCommand) throws Exception {774 String androidHome = System.getenv("ANDROID_HOME");775 String pathToADB = androidHome + "/platform-tools/adb";776 if (myCommand.equals("stopApp")) {777 //String cmd = "adb shell am force-stop org.lds.ldstools.alpha";778 Runtime run = Runtime.getRuntime();779// Process pr = run.exec(new String[] {pathToADB, "shell", "am", "force-stop", "org.lds.ldstools.alpha"});780 Process pr = run.exec(new String[] {pathToADB, "shell", "am", "force-stop", androidAppPackage});781 //Process pr = run.exec(cmd);782 pr.waitFor();783 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));784 String line = "";785 while ((line=buf.readLine())!=null) {786 System.out.println(line);787 }788 }789 if (myCommand.equals("clearApp")) {790 //String cmd = "adb shell am force-stop org.lds.ldstools.alpha";791 Runtime run = Runtime.getRuntime();792 Process pr = run.exec(new String[] { pathToADB, "shell", "pm", "clear", androidAppPackage});793 //Process pr = run.exec(cmd);794 pr.waitFor();795 BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));796 String line = "";797 while ((line=buf.readLine())!=null) {798 System.out.println(line);799 }800 }801 }802 public void takeScreenShot() {803 String imagesLocation = "screenshot/";804 new File(imagesLocation).mkdirs(); // Insure directory is there805 try {806// File srcFile=driver.getScreenshotAs(OutputType.FILE);807 File srcFile=getDriver().getScreenshotAs(OutputType.FILE);808 String filename= UUID.randomUUID().toString();809 System.out.println("Screenshot File: " + filename);810 File targetFile=new File(imagesLocation + filename +".png");811 FileUtils.copyFile(srcFile,targetFile);812 }813 catch(Exception e){814 System.out.println("Warning: Some Other exception");815 }816 }817 private void takeScreenShotDirectory(String filename, String imagesLocation) {818 try {819// File srcFile=driver.getScreenshotAs(OutputType.FILE);820 File srcFile=getDriver().getScreenshotAs(OutputType.FILE);821 System.out.println("Screenshot File: " + filename);822 File targetFile=new File(imagesLocation + filename +".png");823 FileUtils.copyFile(srcFile,targetFile);824 }825 catch(Exception e){826 System.out.println("Warning: Some Other exception");827 }828 }829 private void screenshotAndLogs(String testName) throws Exception {830 LogEntries logEntries;831 List<String> myLogData = new ArrayList<String>();832 List<String> logTypes = new ArrayList<String>();833 //Get Random UUID834 String filename= UUID.randomUUID().toString();835 //Make DIR for random UUID836 String imagesLocation = "screenshot/" + filename +"/";837 String logFile = imagesLocation + testName + ".txt";838 new File(imagesLocation).mkdirs(); // Insure directory is there839 //Take Screen shot840 takeScreenShotDirectory(filename, imagesLocation);841 myLogData.add(testName);842 myLogData.add("******************* LOGS *********************");843// Set<String> sourceSet = getDriver().manage().logs().getAvailableLogTypes();844// logTypes = new ArrayList<>(sourceSet);845 if (getRunningOS().contains("ios")) {846 //logTypes.add("syslog");847 logTypes.add("crashlog");848 logTypes.add("server");849 } else {850 logTypes.add("logcat");851// logTypes.add("bugreport");852 logTypes.add("server");853 logTypes.add("client");854// sendAndroidLog();855 }856 for(String myLog : logTypes) {857 if (!myLog.contains("performance")) {858 System.out.println(myLog);859 myLogData.add(" ******************* " + myLog + " ******************* " );860 logEntries = getDriver().manage().logs().get(myLog);861 for (LogEntry entry : logEntries) {862 myLogData.add(entry.getMessage());863 //System.out.println(entry.getMessage());864 }865 }866 }867 myLogData.add("******************* END LOGS *********************");868 PrintWriter pw = new PrintWriter(new FileOutputStream(logFile));869 for (String logItem : myLogData) {870 pw.println(logItem);871 }872 pw.close();873 }874 private String getIOSToolsLog() throws Exception {875 String myLogs = null;876 MenuScreen myMenu = new MenuScreen(driver);877 BasePage myBase = new BasePage(driver);878 LoginPageScreen myLoginPage = new LoginPageScreen(driver);879 myMenu.selectMenu(myMenu.help);880 myLoginPage.developerButton.click();881 return myLogs;882 }883 public void sendAndroidLog() throws Exception {884 MenuScreen myMenu = new MenuScreen(driver);885 HelpScreen myHelp = new HelpScreen(driver);886 BasePage myBasePage = new BasePage(driver);887 LoginPageScreen myLoginPage = new LoginPageScreen(driver);888 if (myBasePage.checkForElement(myBasePage.alertOK)) {889 myBasePage.alertOK.click();890 Thread.sleep(4000);891// driver.get().launchApp();892// Thread.sleep(4000);893 myLoginPage.overflowMenu.click();894 } else {895 myMenu.selectMenu(myMenu.help);896 }897 myHelp.helpContactUs.click();898 myHelp.contactUsName.sendKeys("Zade");899 myHelp.contactUsEmail.sendKeys("zmaxfield@churchofjesuschrist.org");900 myHelp.contactUsCategory.click();901 myHelp.contactUsDescription.click();902 myHelp.contactUsDescription.sendKeys("sendto:zmaxfield@churchofjesuschrist.org");903 myHelp.helpSendFeedback.click();904 }905 public String getTestOS() {906 return testOS;907 }908 public String getTestngTestDevice() {909 System.out.println("Get Testng Test Device: " + testngTestDevice);910 return testngTestDevice;911 }912 public int getTestngStartSleepTime() {913 return testngStartSleepTime;914 }915}...
OptionsBuildingTest.java
Source:OptionsBuildingTest.java
...18import com.google.common.collect.ImmutableMap;19import io.appium.java_client.android.options.EspressoOptions;20import io.appium.java_client.android.options.UiAutomator2Options;21import io.appium.java_client.android.options.localization.AppLocale;22import io.appium.java_client.android.options.server.EspressoBuildConfig;23import io.appium.java_client.android.options.signing.KeystoreConfig;24import io.appium.java_client.gecko.options.GeckoOptions;25import io.appium.java_client.gecko.options.Verbosity;26import io.appium.java_client.ios.options.XCUITestOptions;27import io.appium.java_client.ios.options.other.CommandTimeouts;28import io.appium.java_client.ios.options.simulator.Permissions;29import io.appium.java_client.mac.options.AppleScriptData;30import io.appium.java_client.mac.options.Mac2Options;31import io.appium.java_client.remote.AutomationName;32import io.appium.java_client.safari.options.SafariOptions;33import io.appium.java_client.safari.options.WebrtcData;34import io.appium.java_client.windows.options.PowerShellData;35import io.appium.java_client.windows.options.WindowsOptions;36import org.junit.Test;37import org.openqa.selenium.Platform;38import java.net.MalformedURLException;39import java.net.URL;40import java.time.Duration;41import static org.junit.Assert.assertEquals;42import static org.junit.Assert.assertFalse;43import static org.junit.Assert.assertNotNull;44import static org.junit.Assert.assertTrue;45@SuppressWarnings("ConstantConditions")46public class OptionsBuildingTest {47 @Test48 public void canBuildXcuiTestOptions() throws MalformedURLException {49 XCUITestOptions options = new XCUITestOptions();50 assertEquals(Platform.IOS, options.getPlatformName());51 assertEquals(AutomationName.IOS_XCUI_TEST, options.getAutomationName().orElse(null));52 options.setNewCommandTimeout(Duration.ofSeconds(10))53 .noReset()54 .setWdaBaseUrl("http://localhost:8000")55 .setPermissions(new Permissions()56 .withAppPermissions("com.apple.MobileSafari",57 ImmutableMap.of("calendar", "YES")))58 .setSafariSocketChunkSize(10)59 .setCommandTimeouts(new CommandTimeouts()60 .withCommandTimeout("yolo", Duration.ofSeconds(1)));61 assertEquals(Duration.ofSeconds(10), options.getNewCommandTimeout().orElse(null));62 assertEquals(new URL("http://localhost:8000"), options.getWdaBaseUrl().orElse(null));63 assertNotNull(options.getPermissions()64 .map((v) -> v.getAppPermissions("com.apple.MobileSafari"))65 .orElse(null));66 assertEquals(10L, (long) options.getSafariSocketChunkSize().orElse(0));67 assertEquals(1L, options.getCommandTimeouts().orElse(null).left()68 .getCommandTimeout("yolo").orElse(null).getSeconds());69 }70 @Test71 public void canBuildUiAutomator2Options() throws MalformedURLException {72 UiAutomator2Options options = new UiAutomator2Options();73 assertEquals(Platform.ANDROID, options.getPlatformName());74 assertEquals(AutomationName.ANDROID_UIAUTOMATOR2, options.getAutomationName().orElse(null));75 options.setNewCommandTimeout(Duration.ofSeconds(10))76 .noReset()77 .setAdbExecTimeout(Duration.ofSeconds(3))78 .suppressKillServer()79 .setMjpegScreenshotUrl(new URL("http://yolo.com"))80 .setKeystoreConfig(new KeystoreConfig("path", "password", "keyAlias", "keyPassword"));81 assertEquals(Duration.ofSeconds(10), options.getNewCommandTimeout().orElse(null));82 assertEquals(Duration.ofSeconds(3), options.getAdbExecTimeout().orElse(null));83 assertEquals(new URL("http://yolo.com"), options.getMjpegScreenshotUrl().orElse(null));84 assertEquals("path", options.getKeystoreConfig().orElse(null).getPath());85 assertEquals("keyAlias", options.getKeystoreConfig().orElse(null).getKeyAlias());86 assertTrue(options.doesSuppressKillServer().orElse(false));87 }88 @Test89 public void canBuildEspressoOptions() {90 EspressoOptions options = new EspressoOptions();91 assertEquals(Platform.ANDROID, options.getPlatformName());92 assertEquals(AutomationName.ESPRESSO, options.getAutomationName().orElse(null));93 options.setNewCommandTimeout(Duration.ofSeconds(10))94 .forceEspressoRebuild()95 .setAppLocale(new AppLocale()96 .withCountry("CN")97 .withLanguage("zh")98 .withVariant("hans"))99 .setEspressoBuildConfig(new EspressoBuildConfig()100 .withAdditionalAppDependencies(ImmutableList.of(101 "com.dep1:1.2.3",102 "com.dep2:1.2.3"103 ))104 );105 assertEquals(Duration.ofSeconds(10), options.getNewCommandTimeout().orElse(null));106 assertEquals("CN", options.getAppLocale().orElse(null).getCountry().orElse(null));107 assertEquals(2, options.getEspressoBuildConfig().orElse(null)108 .left().getAdditionalAppDependencies().orElse(null).size());109 assertTrue(options.doesForceEspressoRebuild().orElse(false));110 }111 @Test112 public void canBuildWindowsOptions() {113 WindowsOptions options = new WindowsOptions();114 assertEquals(Platform.WINDOWS, options.getPlatformName());115 assertEquals(AutomationName.WINDOWS, options.getAutomationName().orElse(null));116 options.setNewCommandTimeout(Duration.ofSeconds(10))117 .setPrerun(new PowerShellData().withScript("yolo prescript"))118 .setPostrun(new PowerShellData().withCommand("yolo command"));119 assertEquals(Duration.ofSeconds(10), options.getNewCommandTimeout().orElse(null));120 assertEquals("yolo prescript", options.getPrerun().orElse(null).getScript().orElse(null));121 assertEquals("yolo command", options.getPostrun().orElse(null).getCommand().orElse(null));...
EspressoBuildConfig.java
Source:EspressoBuildConfig.java
...19import java.util.HashMap;20import java.util.List;21import java.util.Map;22import java.util.Optional;23public class EspressoBuildConfig extends BaseMapOptionData<EspressoBuildConfig> {24 public static final String TOOLS_VERSION = "toolsVersions";25 public static final String ADDITIONAL_APP_DEPENDENCIES = "additionalAppDependencies";26 public static final String ADDITIONAL_ANDROID_TEST_DEPENDENCIES27 = "additionalAndroidTestDependencies";28 public EspressoBuildConfig() {29 super();30 }31 public EspressoBuildConfig(String json) {32 super(json);33 }34 private EspressoBuildConfig assignToolsVersionsField(String name, Object value) {35 Optional<Map<String, Object>> toolsVersionsOptional = getOptionValue(TOOLS_VERSION);36 Map<String, Object> toolsVersions = toolsVersionsOptional.orElseGet(HashMap::new);37 toolsVersions.put(name, value);38 if (!toolsVersionsOptional.isPresent()) {39 assignOptionValue(TOOLS_VERSION, toolsVersions);40 }41 return this;42 }43 private <R> Optional<R> getToolsVersionsFieldValue(String name) {44 Optional<Map<String, Object>> toolsVersionsOptional = getOptionValue(TOOLS_VERSION);45 //noinspection unchecked46 return toolsVersionsOptional.map((v) -> (R) v.getOrDefault(name, null));47 }48 /**49 * Set Gradle version.50 * By default, the version from the build.gradle is used.51 *52 * @param version E.g. "6.3".53 * @return self instance for chaining.54 */55 public EspressoBuildConfig withGradleVersion(String version) {56 return assignToolsVersionsField("gradle", version);57 }58 /**59 * Get Gradle version.60 *61 * @return Gradle version.62 */63 public Optional<String> getGradleVersion() {64 return getToolsVersionsFieldValue("gradle");65 }66 /**67 * Set Gradle plugin version. It must correspond to the Gradle version68 * (if provided). By default, the version from the build.gradle is used.69 *70 * @param version E.g. "4.1.1"71 * @return self instance for chaining.72 */73 public EspressoBuildConfig withAndroidGradlePluginVersion(String version) {74 return assignToolsVersionsField("androidGradlePlugin", version);75 }76 /**77 * Get Gradle plugin version.78 *79 * @return Gradle plugin version.80 */81 public Optional<String> getAndroidGradlePluginVersion() {82 return getToolsVersionsFieldValue("androidGradlePlugin");83 }84 /**85 * Set Android build tools version to compile the server with.86 * By default, the version from the build.gradle is used.87 *88 * @param version E.g. "28.0.3".89 * @return self instance for chaining.90 */91 public EspressoBuildConfig withBuildToolsVersion(String version) {92 return assignToolsVersionsField("buildTools", version);93 }94 /**95 * Get Android build tools version.96 *97 * @return Android build tools version.98 */99 public Optional<String> getBuildToolsVersion() {100 return getToolsVersionsFieldValue("buildTools");101 }102 /**103 * Set Android SDK version to compile the server for.104 * By default, the version from the app build.gradle is used.105 *106 * @param version E.g. "28"107 * @return self instance for chaining.108 */109 public EspressoBuildConfig withCompileSdkVersion(String version) {110 return assignToolsVersionsField("compileSdk", version);111 }112 /**113 * Get the target Android SDK version.114 *115 * @return Android SDK version.116 */117 public Optional<String> getCompileSdkVersion() {118 return getToolsVersionsFieldValue("compileSdk");119 }120 /**121 * Set the minimum Android SDK version to compile the server for.122 * By default, the version from the app build.gradle is used.123 *124 * @param apiLevel E.g. 18.125 * @return self instance for chaining.126 */127 public EspressoBuildConfig withMinSdk(int apiLevel) {128 return assignToolsVersionsField("minSdk", apiLevel);129 }130 /**131 * Get the minimum Android SDK version.132 *133 * @return Minimum Android SDK version.134 */135 public Optional<Integer> getMinSdkVersion() {136 Optional<Object> result = getToolsVersionsFieldValue("minSdk");137 return result.map(CapabilityHelpers::toInteger);138 }139 /**140 * Set the target Android SDK version to compile the server for.141 * By default, the version from the app build.gradle is used.142 *143 * @param apiLevel E.g. 28.144 * @return self instance for chaining.145 */146 public EspressoBuildConfig withTargetSdk(int apiLevel) {147 return assignToolsVersionsField("targetSdk", apiLevel);148 }149 /**150 * Get the target Android SDK version.151 *152 * @return Target Android SDK version.153 */154 public Optional<Integer> getTargetSdkVersion() {155 Optional<Object> result = getToolsVersionsFieldValue("targetSdk");156 return result.map(CapabilityHelpers::toInteger);157 }158 /**159 * Kotlin version to compile the server for.160 * By default, the version from the build.gradle is used.161 *162 * @param version E.g. "1.5.10".163 * @return self instance for chaining.164 */165 public EspressoBuildConfig withKotlinVersion(String version) {166 return assignToolsVersionsField("kotlin", version);167 }168 /**169 * Get the target Kotlin version.170 *171 * @return Kotlin version.172 */173 public Optional<String> getKotlinVersion() {174 return getToolsVersionsFieldValue("kotlin");175 }176 /**177 * Set a non-empty array of dependent module names with their versions.178 * The scripts add all these items as "implementation" lines of dependencies179 * category in the app build.gradle script.180 *181 * @param dependencies E.g. ["xerces.xercesImpl:2.8.0", "xerces.xmlParserAPIs:2.6.2"].182 * @return self instance for chaining.183 */184 public EspressoBuildConfig withAdditionalAppDependencies(List<String> dependencies) {185 return assignOptionValue(ADDITIONAL_APP_DEPENDENCIES, dependencies);186 }187 /**188 * Get the array of dependent application module names with their versions.189 *190 * @return Dependent module names with their versions.191 */192 public Optional<List<String>> getAdditionalAppDependencies() {193 return getOptionValue(ADDITIONAL_APP_DEPENDENCIES);194 }195 /**196 * Set a non-empty array of dependent module names with their versions.197 * The scripts add all these items as "androidTestImplementation" lines of198 * dependencies category in the app build.gradle script.199 *200 * @param dependencies E.g. ["xerces.xercesImpl:2.8.0", "xerces.xmlParserAPIs:2.6.2"].201 * @return self instance for chaining.202 */203 public EspressoBuildConfig withAdditionalAndroidTestDependencies(List<String> dependencies) {204 return assignOptionValue(ADDITIONAL_ANDROID_TEST_DEPENDENCIES, dependencies);205 }206 /**207 * Get the array of dependent Android test module names with their versions.208 *209 * @return Dependent module names with their versions.210 */211 public Optional<List<String>> getAdditionalAndroidTestDependencies() {212 return getOptionValue(ADDITIONAL_ANDROID_TEST_DEPENDENCIES);213 }214}...
SupportsEspressoBuildConfigOption.java
Source:SupportsEspressoBuildConfigOption.java
...18import io.appium.java_client.remote.options.CanSetCapability;19import org.openqa.selenium.Capabilities;20import org.openqa.selenium.internal.Either;21import java.util.Optional;22public interface SupportsEspressoBuildConfigOption<T extends BaseOptions<T>> extends23 Capabilities, CanSetCapability<T> {24 String ESPRESSO_BUILD_CONFIG_OPTION = "espressoBuildConfig";25 /**26 * This config allows to customize several important properties of27 * Espresso server. Refer to28 * https://github.com/appium/appium-espresso-driver#espresso-build-config29 * for more information on how to properly construct such config.30 *31 * @param configPath The path to the config file on the server file system.32 * @return self instance for chaining.33 */34 default T setEspressoBuildConfig(String configPath) {35 return amend(ESPRESSO_BUILD_CONFIG_OPTION, configPath);36 }37 /**38 * This config allows to customize several important properties of39 * Espresso server. Refer to40 * https://github.com/appium/appium-espresso-driver#espresso-build-config41 * for more information on how to properly construct such config.42 *43 * @param config Config instance.44 * @return self instance for chaining.45 */46 default T setEspressoBuildConfig(EspressoBuildConfig config) {47 return amend(ESPRESSO_BUILD_CONFIG_OPTION, config.toString());48 }49 /**50 * Get the Espresso build config.51 *52 * @return Either the config itself or a path to a JSON file on the server FS.53 */54 default Optional<Either<EspressoBuildConfig, String>> getEspressoBuildConfig() {55 return Optional.ofNullable(getCapability(ESPRESSO_BUILD_CONFIG_OPTION))56 .map(String::valueOf)57 .map((v) -> v.trim().startsWith("{")58 ? Either.left(new EspressoBuildConfig(v))59 : Either.right(v)60 );61 }62}...
EspressoBuildConfig
Using AI Code Generation
1import io.appium.java_client.android.options.server.EspressoBuildConfig;2import io.appium.java_client.android.options.server.EspressoServerArguments;3import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;4import io.appium.java_client.android.options.AndroidStopScreenRecordingOptions;5import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;6import io.appium.java_client.android.options.AndroidStopScreenRecordingOptions;7import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;8import io.appium.java_client.android.options.AndroidStopScreenRecordingOptions;9import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;10import io.appium.java_client.android.options.AndroidStopScreenRecordingOptions;11import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;12import io.appium.java_client.android.options.AndroidStopScreenRecordingOptions;13import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;14import io.appium.java_client.android.options.AndroidStopScreenRecordingOptions;15import io.appium.java_client.android.options.AndroidStartScreenRecordingOptions;
EspressoBuildConfig
Using AI Code Generation
1import io.appium.java_client.android.options.server.EspressoBuildConfig;2import io.appium.java_client.android.options.server.EspressoServerArguments;3import io.appium.java_client.android.options.server.AndroidServerFlag;4import io.appium.java_client.android.options.server.AndroidServerArgument;5import io.appium.java_client.android.options.server.AndroidServerOption;6import io.appium.java_client.android.options.server.AndroidServerOptions;7import io.appium.java_client.android.options.server.AndroidServerFlag;8import io.appium.java_client.android.options.server.AndroidServerArgument;9import io.appium.java_client.android.options.server.AndroidServerOption;10import io.appium.java_client.android.options.server.AndroidServerOptions;11import io.appium.java_client.android.options.server.AndroidServerFlag;12import io.appium.java_client.android.options.server.AndroidServerArgument;13import io.appium.java_client.android.options.server.AndroidServerOption;14import io.appium.java_client.android.options.server.AndroidServerOptions;15import io.appium.java_client.android.options.server.AndroidServerFlag;
EspressoBuildConfig
Using AI Code Generation
1import io.appium.java_client.android.options.server.EspressoBuildConfig;2import io.appium.java_client.android.options.server.EspressoServerArgument;3import io.appium.java_client.android.options.server.AndroidServerArguments;4import io.appium.java_client.android.options.server.AndroidServerOption;5import io.appium.java_client.android.options.server.AndroidServerFlags;6import io.appium.java_client.android.options.server.AndroidServerFlag;7import io.appium.java_client.android.options.server.AndroidServerArgument;8import io.appium.java_client.android.options.server.AndroidServerOption;9import io.appium.java_client.android.options.server.AndroidServerFlags;10import io.appium.java_client.android.options.server.AndroidServerFlag;11import io.appium.java_client.android.options.server.AndroidServerArgument;12import io.appium.java_client.android.options.server.AndroidServerOption;13import io.appium.java_client.android.options.server.AndroidServerFlags;14import io.appium.java_client.android.options.server.AndroidServerFlag;15import io.appium.java_client.android.options.server.AndroidServerArgument;16import io.appium.java_client.android.options.server.AndroidServerOption;
EspressoBuildConfig
Using AI Code Generation
1package appium.java;2import io.appium.java_client.android.options.server.EspressoBuildConfig;3import org.openqa.selenium.remote.DesiredCapabilities;4public class AppiumJava {5 public static void main(String[] args) {6 DesiredCapabilities caps = new DesiredCapabilities();7 caps.setCapability("app", "C:\\Users\\myuser\\Downloads\\com.example.android.contactmanager-1.apk");8 caps.setCapability("platformName", "Android");9 caps.setCapability("deviceName", "Android Emulator");10 caps.setCapability("automationName", "Espresso");11 caps.setCapability("espressoBuildConfig", new EspressoBuildConfig().withRemoteAdbHost("
EspressoBuildConfig
Using AI Code Generation
1EspressoBuildConfig config = new EspressoBuildConfig();2config.withKey("key").withValue("value");3EspressoBuildConfig config = new EspressoBuildConfig("key", "value");4EspressoBuildConfig config = new EspressoBuildConfig("key", "value");5EspressoBuildConfig config = new EspressoBuildConfig("key", "value");6EspressoBuildConfig config = new EspressoBuildConfig("key", "value");7EspressoBuildConfig config = new EspressoBuildConfig("key", "value");8EspressoBuildConfig config = new EspressoBuildConfig("key", "value");9EspressoBuildConfig config = new EspressoBuildConfig("key", "value");10EspressoBuildConfig config = new EspressoBuildConfig("key", "value");11EspressoBuildConfig config = new EspressoBuildConfig("key", "value");12EspressoBuildConfig config = new EspressoBuildConfig("key", "value");13EspressoBuildConfig config = new EspressoBuildConfig("key", "value");14EspressoBuildConfig config = new EspressoBuildConfig("key", "value");15EspressoBuildConfig config = new EspressoBuildConfig("key", "value");16EspressoBuildConfig config = new EspressoBuildConfig("key", "value");
EspressoBuildConfig
Using AI Code Generation
1DesiredCapabilities capabilities = new DesiredCapabilities();2capabilities.setCapability("platformName", "Android");3capabilities.setCapability("appPackage", "io.appium.android.apis");4capabilities.setCapability("appActivity", ".ApiDemos");5capabilities.setCapability("automationName", "Espresso");6capabilities.setCapability("espressoBuildConfig", new EspressoBuildConfig().setWithOrchestrator(true));7DesiredCapabilities capabilities = new DesiredCapabilities();8capabilities.setCapability("platformName", "Android");9capabilities.setCapability("appPackage", "io.appium.android.apis");10capabilities.setCapability("appActivity", ".ApiDemos");11capabilities.setCapability("automationName", "Espresso");12capabilities.setCapability("espressoBuildConfig", new EspressoBuildConfig().setWithOrchestrator(true));13DesiredCapabilities capabilities = new DesiredCapabilities();14capabilities.setCapability("platformName", "Android");15capabilities.setCapability("appPackage", "io.appium.android.apis");16capabilities.setCapability("appActivity", ".ApiDemos");17capabilities.setCapability("automationName", "Espresso");18capabilities.setCapability("espressoBuildConfig", new EspressoBuildConfig().setWithOrchestrator(true));19DesiredCapabilities capabilities = new DesiredCapabilities();20capabilities.setCapability("platformName", "Android");21capabilities.setCapability("appPackage", "io.appium.android.apis");22capabilities.setCapability("appActivity", ".ApiDemos");23capabilities.setCapability("automationName", "Espresso");24capabilities.setCapability("espressoBuildConfig", new EspressoBuildConfig().setWithOrchestrator(true));25DesiredCapabilities capabilities = new DesiredCapabilities();26capabilities.setCapability("platformName", "Android");27capabilities.setCapability("appPackage", "io.appium.android.apis");28capabilities.setCapability("appActivity", ".Api
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!