Best io.appium code snippet using io.appium.java_client.internal.Config.main
AppiumGridSetup.java
Source:AppiumGridSetup.java
...99 100 //Check manually first java -jar selenium-server-standalone-3.0.1.jar -role hub ( http://elementalselenium.com/tips/52-grid )101 /*14:52:12.889 INFO - Selenium build info: version: '3.0.1', revision: '1969d75'102 14:52:12.890 INFO - Launching Selenium Grid hub103 2016-12-22 14:52:13.418:INFO::main: Logging initialized @838ms104 14:52:13.432 INFO - Will listen on 4444105 2016-12-22 14:52:13.483:INFO:osjs.Server:main: jetty-9.2.15.v20160210106 2016-12-22 14:52:13.508:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletContextHandler@33cb5951{/,null,AVAILABLE}107 2016-12-22 14:52:13.532:INFO:osjs.ServerConnector:main: Started ServerConnector@6a396c1e{HTTP/1.1}{0.0.0.0:4444}108 2016-12-22 14:52:13.533:INFO:osjs.Server:main: Started @952ms109 14:52:13.534 INFO - Nodes should register to http://192.168.2.48:4444/grid/register/110 14:52:13.534 INFO - Selenium Grid hub is up and running*/111 //Selenium Users google group - Programmatically open Selenium Hub and Node - ErrorDefaultRemoteProxy unknown version112 Hub hub = null;113 public void startSeleniumHub(){114 try{115 String strIP = "localhost";116 117 GridHubConfiguration config = new GridHubConfiguration();118 //config.setTimeout(30000000);119 //config.setHost(strIP);120 //config.setPort(4444);121 config.newSessionWaitTimeout = 30000000;122 config.host = strIP;123 config.port = 4444;124 //String[] args = new String[] {"-role", "hub"};125 //GridLauncherV3.main(args);126 hub = new Hub(config);127 hub.start();128 129 if(isSeleniumHubRunning(10)){130 System.out.println("Selenium Grid is Running");131 }else{132 System.err.println("*** Selenium Grid is down");133 }134 135 //?? check if hub is started properly ??//136 137 //138/* RegistrationRequest req = new RegistrationRequest();139 req.setRole(GridRole.NODE);140 141 Map<String, Object> nodeConfiguration = new HashMap<>();142 143 nodeConfiguration.put(RegistrationRequest.PROXY_CLASS, DefaultRemoteProxy.class.getName());144 nodeConfiguration.put(RegistrationRequest.MAX_SESSION, 5);145 nodeConfiguration.put(RegistrationRequest.PORT, 5555);146 nodeConfiguration.put(RegistrationRequest.HOST, 4444);147 nodeConfiguration.put(RegistrationRequest.AUTO_REGISTER, true);148 nodeConfiguration.put(RegistrationRequest.REGISTER_CYCLE, 5000);149 nodeConfiguration.put(RegistrationRequest.HUB_HOST, "localhost");150 nodeConfiguration.put(RegistrationRequest.HUB_PORT, 4444);151 nodeConfiguration.put("remoteHost", "http://" + strIP + ":5555");152 nodeConfiguration.put("url", "http://" + strIP + ":5555");153 nodeConfiguration.put("role", "node");154 nodeConfiguration.put("hub", "http://localhost:4444/grid/register");155 156 URL remoteURL = new URL("http://" + strIP + ":5555");157 158 nodeConfiguration.put(RegistrationRequest.REMOTE_HOST, remoteURL.toExternalForm());159 req.setConfiguration(nodeConfiguration);160 161 DesiredCapabilities capabilities2 = DesiredCapabilities.chrome();162 capabilities2.setCapability("browserName", "chrome");163 capabilities2.setCapability("platform", "MAC");164 capabilities2.setCapability("ensureCleanSession", "true");165 capabilities2.setCapability("maxInstances", 5);166 req.addDesiredCapability(capabilities2);167 168 SelfRegisteringRemote remote = new SelfRegisteringRemote(req);169 remote.setRemoteServer(new SeleniumServer(req.getConfiguration()));170 remote.startRemoteServer();171 remote.startRegistrationProcess(); */ 172 173 //Thread.currentThread().join();174 175 }catch(Exception e){176 e.printStackTrace();177 }178 }179 180 public boolean isSeleniumHubRunning(int timeOut){181 int count = 0 ;182 while(count < timeOut){183 try{ 184 Thread.sleep(1000);185 URL u = new URL ( "http://localhost:4444/grid/console");186 HttpURLConnection huc = ( HttpURLConnection ) u.openConnection (); 187 huc.setRequestMethod ("GET"); //OR huc.setRequestMethod ("HEAD"); 188 huc.connect () ; 189 int code = huc.getResponseCode() ;190 System.out.println(code);191 return true;192 }catch(Exception e){193 System.err.println("Selenium Grid is still down....."); 194 count++;195 //return false;196 } 197 }198 System.err.println("Selenium Grid failed to start up even after " + timeOut + " seconds");199 return false;200 }201 202 public void stopAllServers(){203 try{204 String s = null;205 String PID = null;206 Process p = null;207 BufferedReader stdInput = null;208 209 //Stop appium210 p = Runtime.getRuntime().exec("pgrep -f appium");211 212 stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));213 214 while ((s = stdInput.readLine()) != null) {215 System.out.println("Appium Server Found " + s);216 PID = s;217 Runtime.getRuntime().exec("kill -9 " + PID );218 }219 220 //Stop Selenim HUB - Method 1 Not Working221 /*p = Runtime.getRuntime().exec("pgrep -f selenium-server-standalone");222 223 stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));224 225 while ((s = stdInput.readLine()) != null) {226 System.out.println(s);227 PID = s;228 Runtime.getRuntime().exec("kill -9 " + PID);229 }*/230 231 232 //Stop Selenim HUB - Method 2233 if (hub != null) { 234 hub.stop(); 235 }236 237 238 }catch(Exception e){239 e.printStackTrace();240 }241 }242 243 //Check manually if you're able to register node with Hub244 245 //METHOD 1246 //http://www.vimalselvam.com/2016/05/15/selenium-grid-for-appium-mobile-automation/ 247 //appium --nodeconfig EMULATOR_Nexus_4_1.json -p 4723 -bp 4724 248 /*//[Appium] Welcome to Appium v1.6.3249 [Appium] Non-default server args:250 [Appium] nodeconfig: 'EMULATOR_Nexus_4_1.json'251 [debug] [Appium] Starting auto register thread for grid. Will try to register every 10000 ms.252 [Appium] Appium REST http interface listener started on 0.0.0.0:4723253 [debug] [Appium] Appium successfully registered with the grid on 127.0.0.1:4444254 [HTTP] --> GET /wd/hub/status {}*/255 //Selenium HUB output >> Registered a node http://0.0.0.0:4723256 257 //METHOD 2258 //https://mattfritz.github.io/2015/05/08/scale-mobile-testing-using-appium-and-selenium-grid/ 259 //appium --nodeconfig EMULATOR_Nexus_4_2.json -p 4823 -bp 4824 ( UDID is in json file itself )260 /*[Appium] Welcome to Appium v1.6.3261 [Appium] Non-default server args:262 [Appium] port: 4823263 [Appium] bootstrapPort: 4824264 [Appium] nodeconfig: 'EMULATOR_Nexus_4_2.json'265 [debug] [Appium] Starting auto register thread for grid. Will try to register every 10000 ms.266 [Appium] Appium REST http interface listener started on 0.0.0.0:4823267 [debug] [Appium] Appium successfully registered with the grid on 127.0.0.1:4444268 [HTTP] --> GET /wd/hub/status {}*/269 270 //correct json format refer to https://github.com/Tanmoyray/AppiumParallelExecutionSample/tree/master/GITSERVER/JSONS271 272 //https://discuss.appium.io/t/unable-to-start-appium-service-by-appiumdriverlocalserivce/6324/18273 //https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/grid.md274 275 //https://github.com/appium/appium/issues/1704276 //https://github.com/appium/java-client/tree/master/src/main/java/io/appium/java_client/service/local/flags277 278 //http://appium.io/slate/en/master/?ruby#appium-server-arguments - Appium Server Arguments279 //https://github.com/saikrishna321/AppiumTestDistribution/blob/c9b065cb084fa6d83272514784da455f7cf076fe/src/main/java/com/appium/manager/AppiumManager.java280 281 //https://github.com/appium/java-client/blob/master/docs/The-starting-of-an-app-using-Appium-node-server-started-programmatically.md#which-parameters-also-can-be-defined282 //https://github.com/appium/appium/blob/9441a89f7e368f0c621db3a0cf9ab074c045ac3a/docs/en/writing-running-appium/server-args.md283 284 //https://github.com/appium/java-client/issues/544285 286 //online JSON formatter, validator https://jsonformatter.org/287 public boolean generate_node_config(int devicesCount){288 try{289 int localCount = 1;290 int portNumber = 4700;291 292 while(localCount <= devicesCount){293 //?? put sequence is not maintained294 JSONObject capData = new JSONObject(); 295 capData.put("applicationName", "dummy_Android_" + localCount);296 capData.put("browserName", "Android");297 capData.put("platformName", "ANDROID");298 capData.put("maxInstances", 1);299 300 JSONArray capArray = new JSONArray();301 capArray.add(capData);302 303 JSONObject parentData = new JSONObject();304 JSONObject configData = new JSONObject();305 306 configData.put("cleanUpCycle", 2000);307 configData.put("timeout", 30000);308 configData.put("proxy", "org.openqa.grid.selenium.proxy.DefaultRemoteProxy");309 configData.put("host", "127.0.0.1");310 configData.put("port", portNumber);311 configData.put("maxSession", 1);312 configData.put("register", true);313 configData.put("registerCycle", 5000);314 configData.put("hubPort", 4444);315 //configData.put("hubHost", "192.168.178.21"); //?? get this value run time as IP shouldn't be STATIC316 configData.put("hubHost", InetAddress.getLocalHost().getHostAddress());317 318 parentData.put("capabilities", capArray);319 parentData.put("configuration", configData);320 321 try (FileWriter file = new FileWriter(projectDirectory + "/node_configs/device_" + localCount + ".json")) {322 file.write(parentData.toJSONString());323 System.out.println("Successfully Copied JSON Object to File...");324 System.out.println("\nJSON Object: " + parentData);325 } catch (Exception e) {326 e.printStackTrace();327 }328 329 localCount++;330 portNumber++;331 }332 333 System.out.println("generate_node_config is Success"); 334 return true;335 }catch(Exception e){336 e.printStackTrace();337 return false;338 }339 }340 341 //https://github.com/appium/java-client/blob/master/docs/The-starting-of-an-app-using-Appium-node-server-started-programmatically.md342 //http://appium.github.io/java-client/io/appium/java_client/service/local/AppiumServiceBuilder.html#withLogFile-java.io.File-343 public boolean startAppiumServerToRegisterNodeWithSeleniumHUB(int devicesCount){344 try{345 int localCount = 1;346 int portNumber = 4700;347 int bootstrapPortNumber = 4800;348 String UDID = null;349 350 while(localCount <= devicesCount){351 String nodeConfigFilePath = projectDirectory + "/node_configs/device_" + localCount + ".json";352 File logFile = new File( projectDirectory + "/appium_device_log/device_log" + localCount + ".log");353 354 UDID = deviceIds.get(localCount-1);355 356 AppiumDriverLocalService driverLocalService1 = AppiumDriverLocalService357 .buildService(new AppiumServiceBuilder()358 .withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))359 .usingDriverExecutable(new File("/usr/local/bin/node"))360 .usingPort(portNumber)361 .withLogFile(logFile)362 .withArgument(AndroidServerFlag.BOOTSTRAP_PORT_NUMBER, Integer.toString(bootstrapPortNumber) )363 .withArgument(GeneralServerFlag.SESSION_OVERRIDE)364 .withArgument(GeneralServerFlag.LOG_LEVEL, "debug")365 .withArgument(GeneralServerFlag.CONFIGURATION_FILE, nodeConfigFilePath)366 .withArgument(GeneralServerFlag.LOCAL_TIMEZONE) //https://github.com/appium/java-client/issues/694367 .withCapabilities(new DesiredCapabilities(ImmutableMap.of(MobileCapabilityType.UDID, UDID))));368 369 driverLocalService1.start();370 371 assertTrue( checkForAppiumServerNodeFromAppiumServerLog(logFile) );372 ...
BaseTest.java
Source:BaseTest.java
...192 String javaJdkHomeBinPath = "C:\\Program Files\\Java\\jdk1.8.0_311\\bin";193 String androidSdkToolsPath = "C:\\Users\\no4no\\AppData\\Local\\Android\\Sdk\\tools";194 String androidSdkPlatformToolsPath = "C:\\Users\\Acer\\AppData\\Local\\Android\\Sdk\\platform-tools";195 String nodeJsPath = "C:\\Program Files\\nodejs\\node.exe";196 String appiumMainJs = "C:\\Users\\no4no\\AppData\\Roaming\\npm\\node_modules\\appium\\build\\lib\\main.js";197// environment.put("PATH", "/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home/bin:/Users/Om/Library/Android/sdk/tools:/Users/Om/Library/Android/sdk/platform-tools:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" + System.getenv("PATH"));198 environment.put("PATH", javaJdkHomeBinPath.replace("\\", "/") + ":"199 + androidSdkToolsPath.replace("\\", "/") + ":"200 + androidSdkPlatformToolsPath.replace("\\", "/") + ":"201 + System.getenv("PATH"));202 environment.put("ANDROID_HOME", androidHomePath.replace("\\", "/"));203 return AppiumDriverLocalService.buildService(new AppiumServiceBuilder()204// .usingDriverExecutable(new File("/usr/local/bin/node"))205 .usingDriverExecutable(new File(nodeJsPath.replace("\\", "/")))206// .withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))207 .withAppiumJS(new File(appiumMainJs.replace("\\", "/")))208 .usingPort(4723)209 .withArgument(GeneralServerFlag.SESSION_OVERRIDE)210 .withEnvironment(environment)211 .withLogFile(new File("ServerLogs/server.log")));212 }213 214 @Parameters({"emulator", "platformName", "udid", "deviceName", "systemPort", 215 "chromeDriverPort", "wdaLocalPort", "webkitDebugProxyPort"})216 @BeforeTest217 public void beforeTest(@Optional("androidOnly")String emulator, String platformName, String udid, String deviceName, 218 @Optional("androidOnly")String systemPort, @Optional("androidOnly")String chromeDriverPort, 219 @Optional("iOSOnly")String wdaLocalPort, @Optional("iOSOnly")String webkitDebugProxyPort) throws Exception {220 setDateTime(utils.dateTime());...
MobileAgentFactory.java
Source:MobileAgentFactory.java
1/**2 * 3 */4package agent.internal;5import java.io.File;6import java.net.URL;7import org.apache.log4j.Logger;8import org.apache.tools.ant.property.GetProperty;9import org.openqa.selenium.chrome.ChromeOptions;10import org.openqa.selenium.remote.CapabilityType;11import org.openqa.selenium.remote.DesiredCapabilities;12import io.appium.java_client.AppiumDriver;13import io.appium.java_client.MobileElement;14import io.appium.java_client.remote.IOSMobileCapabilityType;15import io.appium.java_client.remote.MobileCapabilityType;16import agent.IAgent;17import central.Configuration;18import central.AppachhiCentral;19import enums.ConfigType;20import enums.Platform;21public class MobileAgentFactory {22 private static Logger logger = AppachhiCentral.getLogger();23 public static IAgent createAgent(Configuration config) throws Exception {24 AppiumDriver<MobileElement> driver = null;25 DesiredCapabilities caps = null;26 Platform platform = config.getPlatform();27 logger.debug("Populating desired capabilities for : " + platform);28 switch (System.getProperty("platform")) {29 case "IOS":30 caps = DesiredCapabilities.iphone();31 break;32 case "IOS_WEB":33 caps = DesiredCapabilities.safari();34 break;35 case"ANDROID":36 caps = DesiredCapabilities.android();37 break;38 case "ANDROID_WEB":39 caps = DesiredCapabilities.chrome();40 break;41 default:42 throwWrongPlatformException(config);43 }44 initCaps(config, caps);45 populatePlatformSpecificCaps(config, caps);46 logger.debug("Creating mobile driver." + caps.asMap());47 driver = new AppiumDriver<MobileElement>(new URL(System.getProperty("appium_url")), caps);48 logger.debug("Successfully created mobile driver.");49 switch (platform) {50 case IOS:51 return new IOSAppAgent(config, driver);52 case IOS_WEB:53 return new IOSAppAgent(config, driver);54 case ANDROID:55 return new AndroidAppAgent(config, driver);56 case ANDROID_WEB:57 return new AndroidWebAgent(config, driver);58 default:59 logger.error("Failed to Create Agent");60 throwWrongPlatformException(config);61 }62 return null;63 }64 private static void throwWrongPlatformException(Configuration config) {65 String msg = String.format("Unsupported platform for mobile automation", config.getPlatform());66 logger.error(msg);67 }68 private static void initCaps(Configuration config, DesiredCapabilities caps) {69 caps.setCapability(MobileCapabilityType.DEVICE_NAME, System.getProperty("device_name"));70 caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, System.getProperty("platform_version"));71 caps.setCapability("newCommandTimeout", 1500);72 caps.setCapability("udid", System.getProperty("mobile_udid"));73 }74 private static void populateAppDetails(Configuration config, DesiredCapabilities caps) throws Exception {75 File appFile = new File(System.getProperty("app_file_path"));76 caps.setCapability("app", appFile.getAbsolutePath());77 caps.setCapability(MobileCapabilityType.NO_RESET, false);78// caps.setCapability(MobileCapabilityType.NO_RESET, config.getValue(ConfigType.NO_RESET));79 }80 private static void populatePlatformSpecificCaps(Configuration config, DesiredCapabilities caps) throws Exception {81 switch (config.getPlatform()) {82 case IOS:83 populateAppDetails(config, caps);84 caps.setCapability(MobileCapabilityType.PLATFORM, Platform.IOS);85 caps.setCapability(IOSMobileCapabilityType.AUTO_ACCEPT_ALERTS, true);86 caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, config.getValue(ConfigType.IOS_AUTOMATION_NAME));87 caps.setCapability(IOSMobileCapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, true);88 caps.setCapability("xcodeConfigFile", config.getValue(ConfigType.XCODE_CONF));89 caps.setCapability("autoAcceptAlerts", true);90 caps.setCapability("autoGrantPermissions", true);91 break;92 case IOS_WEB:93 caps.setCapability(MobileCapabilityType.BROWSER_NAME, System.getProperty("browser"));94 caps.setCapability(MobileCapabilityType.AUTOMATION_NAME, config.getValue(ConfigType.IOS_AUTOMATION_NAME));95 caps.setCapability("xcodeConfigFile", "conf/config.xcconfig");96 caps.setCapability("nativeWebTap", true);// This is for Site Window Pop-up97 caps.setCapability("autoGrantPermissions", true);98 break;99 case ANDROID:100 populateAppDetails(config, caps);101 caps.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.ANDROID);102 caps.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);103 //caps.setCapability("unicodeKeyboard", "True");104 String pkg = config.getValue(ConfigType.APP_PACKAGE);105 caps.setCapability("appPackage", pkg);106 caps.setCapability("appActivity", String.format(config.getValue(ConfigType.ACTIVITY_MAIN), pkg));107 caps.setCapability(MobileCapabilityType.AUTOMATION_NAME,108 config.getValue(ConfigType.ANDROID_AUTOMATION_NAME));109 caps.setCapability("autoGrantPermissions", true);110 break;111 case ANDROID_WEB:112 ChromeOptions options = new ChromeOptions();113 options.addArguments("disable-notifications");114 caps.setCapability(ChromeOptions.CAPABILITY, options);115 caps.setCapability(MobileCapabilityType.PLATFORM_NAME, Platform.ANDROID);116 caps.setCapability(MobileCapabilityType.PLATFORM, Platform.ANDROID);117 // caps.setCapability(MobileCapabilityType.AUTOMATION_NAME,118 // config.getValue(ConfigType.ANDROID_AUTOMATION_NAME));119 caps.setCapability(MobileCapabilityType.BROWSER_NAME, getProperty("browser", config) );120 caps.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, config.getValue(ConfigType.ALERT_BEHAVIOR));121 caps.setCapability("autoDismissAlerts", true);122 caps.setCapability("unicodeKeyboard", true);123 caps.setCapability("resetKeyboard", true);124 caps.setCapability("autoGrantPermissions", true);125 break;126 default:127 throwWrongPlatformException(config);128 }129 }130 131 132 public static String getProperty(String arg, Configuration config) {133 String ret_val="";134 135 if ( arg.equalsIgnoreCase("appium_url") ) {136 if ( System.getProperty("appium_url") != null )137 ret_val=System.getProperty("appium_url");138 else139 ret_val=config.getValue(ConfigType.APPIUM_URL);140 } 141 142 if ( arg.equalsIgnoreCase("device_name") ) {143 if ( System.getProperty("device_name") != null )144 ret_val=System.getProperty("device_name");145 else146 ret_val=config.getValue(ConfigType.DEVICE_NAME);147 } 148 149 if ( arg.equalsIgnoreCase("platform_version") ) {150 if ( System.getProperty("platform_version") != null )151 ret_val=System.getProperty("platform_version");152 else153 ret_val=config.getValue(ConfigType.PLATFORM_VER);154 } 155 156 if ( arg.equalsIgnoreCase("mobile_udid") ) {157 if ( System.getProperty("mobile_udid") != null )158 ret_val=System.getProperty("mobile_udid");159 else160 ret_val=config.getValue(ConfigType.UDID);161 }162 163// if ( arg.equalsIgnoreCase("app_file_path") ) { It has to include in configuration.java164// if ( System.getProperty("app_file_path") != null )165// ret_val=System.getProperty("app_file_path");166// else167// ret_val=config.getValue(ConfigType.UDID);168// } 169 170 if ( arg.equalsIgnoreCase("browser") ) {171 if ( System.getProperty("browser") != null )172 ret_val=System.getProperty("browser");173 else174 ret_val=config.getValue(ConfigType.BROWSER);175 } 176 return ret_val;177 }178}...
Testengine.java
Source:Testengine.java
...50 log = Logger.getLogger("devpinoyLogger");51 log.info("Test Started successfully");52 log.info("Initializing the Config.properties file");53 // Path where Config.properties file is placed54 String propertyFilePath = "src/main/resources/config.properties";55 BufferedReader reader;56 try {57 reader = new BufferedReader(new FileReader(propertyFilePath));58 properties = new Properties();59 try {60 properties.load(reader);61 reader.close();62 log.info("Properties file loaded successfully:");63 // Config file is loaded successfully, now with the help of64 // properties.getProperty(key) we can retrieve the value.65 } catch (IOException ioE) {66 ioE.printStackTrace();67 }68 } catch (FileNotFoundException fnfE) {...
DriverFactory.java
Source:DriverFactory.java
...57 else if (isFireFox) WebDriverManager.firefoxdriver().setup();58 else if (isEdge) WebDriverManager.edgedriver().setup();59 else System.out.printf("Incompatible device name: [%s]%n", Config.getDeviceName());60 if (!seleniumServer.isStarted()) {61 GridLauncherV3.main(new String[] {});62 isFirstServerRun = true;63 if (isChrome) System.setProperty("webdriver.chrome.silentOutput", "true");64 }65 }66 }67 /**68 * Start the Appium Server with default services69 *70 * @return71 */72 public AppiumDriverLocalService startAppiumServer() {73 boolean serverIsNotRunning = checkIfServerIsRunning(4723);74 if (!serverIsNotRunning) {75 service = AppiumDriverLocalService.buildDefaultService();...
AppiumGridBaseTest.java
Source:AppiumGridBaseTest.java
1package STGridSuite.tests.AppiumTests;2import MyMain.Main;3import STGridSuite.GridBaseTest;4import STGridSuite.STGridRunner;5import Utils.Utilities;6import io.appium.java_client.AppiumDriver;7import io.appium.java_client.android.AndroidDriver;8import io.appium.java_client.ios.IOSDriver;9import org.apache.http.client.config.CookieSpecs;10import org.apache.http.client.config.RequestConfig;11import org.apache.http.impl.client.CloseableHttpClient;12import org.apache.http.impl.client.HttpClients;13import org.junit.After;14import org.junit.Assert;15import org.junit.Before;16import org.openqa.selenium.remote.DesiredCapabilities;17import org.openqa.selenium.remote.internal.ApacheHttpClient;18import java.net.URL;19public abstract class AppiumGridBaseTest extends GridBaseTest {20 protected AppiumDriver driver = null;21 protected DesiredCapabilities dc = null;22 abstract public void createCapabilities();23 @Before24 public void setUp(){25 runner = (STGridRunner) Thread.currentThread();26 deviceOS = runner.deviceOS;27 getUser();28 updateDevice();29 createCapabilities();30 dc.setCapability("udid", device);31 dc.setCapability("testName", runner.testName);32 chosenDeviceName = device;33 try {34 if(deviceOS.equals("ios")){35 driver = new IOSDriver(new URL(Main.cs.URL_ADDRESS + "/wd/hub"), url -> {36 RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();37 CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();38 return new ApacheHttpClient(httpclient, url);39 }, dc);40 }else{41 driver = new AndroidDriver(new URL(Main.cs.URL_ADDRESS + "/wd/hub"), url -> {42 RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();43 CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();44 return new ApacheHttpClient(httpclient, url);45 }, dc);46 }47 } catch (Exception e) {48 Utilities.log(runner, "Can't create a grid client!!!");49 Utilities.log(runner, e);50 Assert.fail(e.getMessage());51 }52 getDeviceProperties();53 Utilities.log(runner, "Finished setUp with device - " + deviceName);54 Utilities.log(runner, "Starting test - " + runner.testName);55 }56 public void getDeviceProperties() {57 try {58 deviceName = (String) driver.getCapabilities().getCapability("device.name");59 this.reportURL = (String) driver.getCapabilities().getCapability("reportUrl");60 chosenDeviceName = deviceName;61 deviceOSVersion = (String) driver.getCapabilities().getCapability("device.version");62// device = (String) driver.getCapabilities().getCapability("device.sn");63 }catch (Exception e){64 e.printStackTrace(Main.exceptionWriter);65 Utilities.log(runner, "Can't setup a grid test!!!");66 Utilities.log(runner, e);67 Assert.fail(e.getMessage());68 }69 }70 @After71 public void finish() {72 try {73 driver.quit();74 Utilities.log(runner, "driver was released");75 } catch (Exception e) {76 Utilities.log(runner, "Failed to quit driver!!!! - " + device);77 Utilities.log(runner, e);78 }79 Assert.assertTrue(testPassed);80 Utilities.log(runner, "Ending test - " + runner.testName + " For Device - " + device);81 }82}...
AppiumDriverConfig.java
Source:AppiumDriverConfig.java
...9import java.net.URL;10public class AppiumDriverConfig {11 public final AppiumDriver driver;12 public AppiumDriverConfig() throws MalformedURLException{13 File apk = new File("D:\\Alura\\Cursos\\1820-appium\\projeto-atual\\src\\main\\resources\\alura_esporte.apk");14 DesiredCapabilities configuracoes = new DesiredCapabilities();15 configuracoes.setCapability(MobileCapabilityType.APP, apk.getAbsolutePath());16 configuracoes.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);17 configuracoes.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");18 URL urlConexao = new URL("http://127.0.0.1:4723/wd/hub");19 driver = new AppiumDriver<>(urlConexao,configuracoes);20 }21}...
main
Using AI Code Generation
1import io.appium.java_client.internal.Config;2import org.openqa.selenium.remote.DesiredCapabilities;3public class Appium {4 public static void main(String[] args) {5 DesiredCapabilities capabilities = new DesiredCapabilities();6 capabilities.setCapability("platformName", "Android");7 capabilities.setCapability("deviceName", "Android Emulator");8 capabilities.setCapability("appPackage", "com.android.calculator2");9 capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");10 Config.setCapability(capabilities);11 Config.setPlatformName("Android");12 Config.setDeviceName("Android Emulator");13 Config.setAppPackage("com.android.calculator2");14 Config.setAppActivity("com.android.calculator2.Calculator");15 }16}17from appium import webdriver18from selenium.webdriver.support.ui import WebDriverWait19from selenium.webdriver.support import expected_conditions as EC20from selenium.webdriver.common.by import By21from appium.webdriver.common.touch_action import TouchAction22from appium.webdriver.common.multi_action import MultiAction23from appium.webdriver.common.mobileby import MobileBy24from appium.webdriver.common.touch_action import TouchAction25import time26import os27 def main():28 capabilities = {}29 driver.quit()30 main()31var webdriver = require('selenium-webdriver');32var By = require('selenium-webdriver').By;33var until = require('selenium-webdriver').until;34var driver = new webdriver.Builder()35.forBrowser('chrome')36.build();37driver.findElement(By.name('q')).sendKeys('webdriver');38driver.findElement(By.name('btnG')).click();39driver.wait(until.titleIs('webdriver - Google Search'), 1000);
main
Using AI Code Generation
1package io.appium.java_client.internal;2import java.io.File;3import java.io.IOException;4import java.lang.reflect.InvocationTargetException;5import java.lang.reflect.Method;6import org.apache.commons.io.FileUtils;7import org.openqa.selenium.Platform;8import org.openqa.selenium.WebDriverException;9public class Config {10 public static String getAndroidSDK() {11 String androidHome = System.getenv("ANDROID_HOME");12 if (androidHome == null) {13 throw new WebDriverException(14 "The ANDROID_HOME environment variable must be set to the root of your Android SDK directory.");15 }16 return androidHome;17 }18 public static String getAndroidBootAnimationTimeout() {19 String timeout = System.getenv("ANDROID_BOOT_ANIMATION_TIMEOUT");20 if (timeout == null) {21 return "120000";22 }23 return timeout;24 }25 public static String getAndroidDeviceReadyTimeout() {26 String timeout = System.getenv("ANDROID_DEVICE_READY_TIMEOUT");27 if (timeout == null) {28 return "120000";29 }30 return timeout;31 }32 public static String getAndroidDeviceSocket() {33 String socket = System.getenv("ANDROID_DEVICE_SOCKET");34 if (socket == null) {35 return "appium_bootstrap";36 }37 return socket;38 }39 public static String getAndroidEmulatorPort() {40 String port = System.getenv("ANDROID_EMULATOR_PORT");41 if (port == null) {42 return "5554";43 }44 return port;45 }46 public static String getAndroidEmulatorExecutable() {47 String emulator = System.getenv("ANDROID_EMULATOR_EXECUTABLE");48 if (emulator == null) {49 return getAndroidSDK() + "/tools/emulator";50 }51 return emulator;52 }53 public static String getAndroidAdbExecutable() {54 String adb = System.getenv("ANDROID_ADB_EXECUTABLE");55 if (adb == null) {56 return getAndroidSDK() + "/platform-tools/adb";57 }58 return adb;59 }60 public static String getAndroidToolsPath() {61 return getAndroidSDK() + "/tools";62 }63 public static String getAndroidPlatformToolsPath() {64 return getAndroidSDK() + "/platform-tools";65 }66 public static String getAndroidAppPath() {67 String androidAppPath = System.getenv("ANDROID_APP_PATH");68 if (androidAppPath == null) {69 throw new WebDriverException(
main
Using AI Code Generation
1import io.appium.java_client.internal.Config;2public class Appium {3 public static void main(String[] args) {4 Config.main(args);5 }6}7var appium = require('../lib/main');8appium.main();9import appium10appium.main()11param(12[Parameter(Mandatory=$false)]$serverPort = 4723,13[Parameter(Mandatory=$false)]$bootstrapPort = 4724,14[Parameter(Mandatory=$false)]$selendroidPort = 8080,15[Parameter(Mandatory=$false)]$chromedriverPort = 9515,16[Parameter(Mandatory=$false)]$avd = '',17[Parameter(Mandatory=$false)]$avdArgs = '',18[Parameter(Mandatory=$false)]$avdLaunchTimeout = 90000,19[Parameter(Mandatory=$false)]$avdReadyTimeout = 60000,20[Parameter(Mandatory=$false)]$avdArgs = '',21[Parameter(Mandatory=$false)]$avdLaunchTimeout = 90000,22[Parameter(Mandatory=$false)]$avdReadyTimeout = 60000,23[Parameter(Mandatory=$false)]$suppressKillServer = $false,24[Parameter(Mandatory=$false)]$log = '',25[Parameter(Mandatory=$false)]$logTimestamp = $false,26[Parameter(Mandatory=$false)]$localTimezone = $false,27[Parameter(Mandatory=$false)]$logLevel = 'debug',28[Parameter(Mandatory=$false)]$nodeconfig = '',29[Parameter(Mandatory=$false)]$chromedriverExecutable = '',30[Parameter(Mandatory=$false)]$selendroidPort = 8080,31[Parameter(Mandatory=$false)]$chromedriverPort = 9515,32[Parameter(Mandatory=$false)]$avd = '',33[Parameter(Mandatory=$false)]$
main
Using AI Code Generation
1package io.appium.java_client.internal;2import java.io.FileInputStream;3import java.io.FileNotFoundException;4import java.io.IOException;5import java.io.InputStream;6import java.util.Properties;7public class Config {8 public static void main(String[] args) throws IOException {9 Properties prop = new Properties();10 InputStream input = null;11 input = new FileInputStream("config.properties");12 prop.load(input);13 System.out.println(prop.getProperty("platformName"));14 System.out.println(prop.getProperty("platformVersion"));15 System.out.println(prop.getProperty("deviceName"));16 System.out.println(prop.getProperty("appPackage"));17 System.out.println(prop.getProperty("appActivity"));18 System.out.println(prop.getProperty("app"));19 }20}
main
Using AI Code Generation
1package appium;2import io.appium.java_client.internal.Config;3public class Appium {4 public static void main(String[] args) {5 System.out.println(Config.class.getMethods());6 }7}8package appium;9import io.appium.java_client.internal.JsonToWebElementConverter;10import org.openqa.selenium.remote.RemoteWebElement;11public class Appium {12 public static void main(String[] args) {13 System.out.println(JsonToWebElementConverter.class.getMethods());14 }15}16package appium;17import io.appium.java_client.internal.JsonToWebElementConverter;18import org.openqa.selenium.remote.RemoteWebElement;19public class Appium {20 public static void main(String[] args) {21 System.out.println(JsonToWebElementConverter.class.getMethods());22 }23}24package appium;25import io.appium.java_client.internal.JsonToWebElementConverter;26import org.openqa.selenium.remote.RemoteWebElement;27public class Appium {28 public static void main(String[] args) {29 System.out.println(JsonToWebElementConverter.class.getMethods());30 }31}32package appium;33import io.appium.java_client.internal.JsonToWebElementConverter;34import org.openqa.selenium.remote.RemoteWebElement;35public class Appium {36 public static void main(String[] args) {37 System.out.println(JsonToWebElementConverter.class.getMethods());38 }39}40package appium;41import io.appium.java_client.internal.JsonToWebElementConverter;42import org.openqa.selenium.remote.RemoteWebElement;43public class Appium {44 public static void main(String
main
Using AI Code Generation
1public class Appium {2 public static void main(String[] args) {3 Config.main(new String[] { "appium" });4 }5}6param(7 [Parameter(Position=0)]8import subprocess9import sys10subprocess.call(["java", "-cp", "appium.jar", "appium"] + sys.argv[1:])11var spawn = require('child_process').spawn;12var args = process.argv.slice(2);13var child = spawn('java', ['-cp', 'appium.jar', 'appium'].concat(args), {14});15child.on('close', function (code) {16 process.exit(code);17});18args = ARGV.join(' ')19Open3.popen3("java -cp appium.jar appium #{args}") do |stdin, stdout, stderr, wait_thr|20import (21func main() {22 args := append([]string{"-cp", "appium.jar", "appium"}, os.Args[1:]...)23 cmd := exec.Command("java", args...)24 err := cmd.Run()25 if err != nil {26 fmt.Println("Error: ", err)27 }28}29$command = 'java -cp appium.jar appium';30$command .= ' ' . implode(' ', array_slice($argv, 1));31passthru($command);32import subprocess33import sys34subprocess.call(["java", "-cp", "appium.jar", "appium"] + sys.argv[1:])
main
Using AI Code Generation
1Config config = new Config("C:\\Users\\user\\Desktop\\Appium\\appium.txt");2String appiumServerUrl = config.getAppiumServerUrl();3System.out.println(appiumServerUrl);4PropertySetting propertySetting = new PropertySetting();5propertySetting.setProperty("C:\\Users\\user\\Desktop\\Appium\\appium.txt");6String appiumServerUrl = propertySetting.getAppiumServerUrl();7System.out.println(appiumServerUrl);
main
Using AI Code Generation
1package appium.java;2import java.io.File;3import java.net.MalformedURLException;4import java.net.URL;5import org.openqa.selenium.remote.DesiredCapabilities;6import io.appium.java_client.AppiumDriver;7import io.appium.java_client.MobileElement;8import io.appium.java_client.android.AndroidDriver;9import io.appium.java_client.android.AndroidElement;10import io.appium.java_client.internal.Config;11public class Main {12 public static void main(String[] args) throws MalformedURLException {13 File f=new File("src");14 File fs=new File(f,"ApiDemos-debug.apk");15 DesiredCapabilities cap=new DesiredCapabilities();16 cap.setCapability(Config.CAPABILITY_APP,fs.getAbsolutePath());17 cap.setCapability(Config.CAPABILITY_PLATFORM_NAME,"Android");18 cap.setCapability(Config.CAPABILITY_PLATFORM_VERSION,"7.0");19 cap.setCapability(Config.CAPABILITY_DEVICE_NAME,"Android Emulator");20 cap.setCapability(Config.CAPABILITY_APP_PACKAGE,"io.appium.android.apis");21 cap.setCapability(Config.CAPABILITY_APP_ACTIVITY,".ApiDemos");22 cap.setCapability(Config.CAPABILITY_NO_RESET,true);
main
Using AI Code Generation
1package appium.java;2import io.appium.java_client.internal.Config;3import java.io.File;4import java.io.IOException;5import java.net.MalformedURLException;6import java.net.URL;7import java.util.concurrent.TimeUnit;8import org.openqa.selenium.By;9import org.openqa.selenium.WebDriver;10import org.openqa.selenium.WebElement;11import org.openqa.selenium.remote.DesiredCapabilities;12import org.openqa.selenium.remote.RemoteWebDriver;13import org.testng.annotations.AfterTest;14import org.testng.annotations.BeforeTest;15import org.testng.annotations.Test;16public class AppiumTest {17private static WebDriver driver;18public void setUp() throws MalformedURLException {19DesiredCapabilities capabilities = new DesiredCapabilities();20capabilities.setCapability("BROWSER_NAME", "Android");21capabilities.setCapability("VERSION", "4.4.2");22capabilities.setCapability("deviceName","Android");23capabilities.setCapability("platformName","Android");24capabilities.setCapability("app-package", "com.android.calculator2");25capabilities.setCapability("app-activity", "com.android.calculator2.Calculator");
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!!