Написание сценария автоматизации для загрузки файла Chromecast APK из Google Play Store - PullRequest
0 голосов
/ 27 января 2020
Writing Automation Script to download Chromecast APK File from Google PlayStore.

I tried on Emulator for Pixel and Nexus both            
**Platform:**
 Appium 1.15.1
 Emulator - Nexus 5X API 29 
 Android 10.0
 CPU - x86
 Eclipse - 2018

 This post has Code, Appium Server logs and the Console message from Eclipse. 

            Code - 
            import io.appium.java_client.AppiumDriver;
            import io.appium.java_client.MobileBy;
            import io.appium.java_client.android.AndroidDriver;
            import io.appium.java_client.remote.MobileCapabilityType;

            import org.openqa.selenium.WebElement;
            import org.openqa.selenium.remote.DesiredCapabilities;
            import org.openqa.selenium.support.ui.ExpectedConditions;
            import org.openqa.selenium.support.ui.WebDriverWait;
            import org.testng.annotations.AfterClass;
            import org.testng.annotations.BeforeClass;

            import java.io.BufferedReader;
            import java.io.IOException;
            import java.io.InputStreamReader;
            import java.net.URL;

            import static org.hamcrest.CoreMatchers.is;
            import static org.junit.Assert.assertThat;

            public class InstallAppfromPlayStore {

                private AppiumDriver driver;
                private WebDriverWait wait;
                private long explicitWaitTimeoutInSeconds = 10L;
                private static long INSTALL_DURATION_IN_SECONDS = 60L;

             // app to install - details
                final String testAppName = "Chromecast";
                final String testAppPackage = "com.google.android.apps.chromecast.app";
            //  final String testAppActivity = ".DiscoveryActivity";

                @BeforeClass
                public void setUp() throws Exception {

                DesiredCapabilities capabilities = DesiredCapabilities.android();
                capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
                capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10");
                capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
                capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");
            //capabilities.setCapability(MobileCapabilityType.APP_ACTIVITY, ".AssetBrowserActivity");
            //capabilities.setCapability(MobileCapabilityType.APP_WAIT_ACTIVITY, ".AssetBrowserActivity");
           //capabilities.setCapability(MobileCapabilityType.DEVICE_READY_TIMEOUT, 40);
                    capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 180);
                    capabilities.setCapability(MobileCapabilityType.APPIUM_VERSION, "1.15.1");
                capabilities.setCapability("deviceOrientation", "portrait");
              this.driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

                    this.wait = new WebDriverWait(driver, explicitWaitTimeoutInSeconds);
                    uninstallApp(testAppPackage);
                }

   @AfterClass
    public void tearDown() throws Exception {
                    driver.quit();
               }

                @org.testng.annotations.Test
                public void installAppFromGooglePlayStore() throws Exception {
                 // wait until search bar is visible, and then tap on it
                  wait.until(ExpectedConditions.visibilityOf(
                  driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().resourceId(\"com.android.vending:id/search_box_idle_text\")"))))
                            .click();
                    // type in the name of the app into the search bar
                    driver.findElement(MobileBy.className("android.widget.EditText")).sendKeys(testAppName);
     // using lowercase because of Google's design choice - they list all suggestions in lower case
                    wait.until(ExpectedConditions.visibilityOf(
                     driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().resourceId(\"com.android.vending:id/suggest_text\").text(\"" + testAppName.toLowerCase() + "\")")))).click();

                    // waiting for the app title to be displayed
                    wait.until(ExpectedConditions.visibilityOf(
                     driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().resourceId(\"com.android.vending:id/li_title\").text(\"" + testAppName + "\")"))));

                    // tapping on the triple dot icon located on the app's tile
                    driver.findElement(MobileBy.xpath("//android.widget.TextView[@content-desc=\"App: " + testAppName + "\"]/following-sibling::android.widget.ImageView[@resource-id=\"com.android.vending:id/li_overflow\"]")).click();

                    // tap on the Install button
                    driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().className(\"android.widget.TextView\").resourceId(\"com.android.vending:id/title\").text(\"Install\")")).click();

                    // tap on accept
                    driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().resourceId(\"com.android.vending:id/continue_button\")")) .click();

                // waiting until "installed" shows up for INSTALL_DURATION_IN_SECONDS
                    new WebDriverWait(driver, INSTALL_DURATION_IN_SECONDS).until(ExpectedConditions.presenceOfElementLocated(
                         MobileBy.xpath("//android.widget.TextView[@content-desc=\"App: " + testAppName + "\"]/following-sibling::android.view.View[@resource-id=\"com.android.vending:id/li_label\"][@content-desc=\"Installed\"]")));
                    // quit current driver instance - this quits the google playstore
                   driver.quit();
                    // launch newly installed app
                    driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), installedAppCaps());
                    driver.launchApp();
                // wait until app loads and an element that should 100% be there is displayed
               // in this case, we're waiting for Google's "privacy and terms"
                    WebElement alertTitle = wait.until(ExpectedConditions.visibilityOf(driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().resourceId(\"android:id/alertTitle\")"))));
                    assertThat(alertTitle.getText(), is("Privacy and terms"));
                }

           // set up capabilities for the test app
          // these are required to start the app you install via playstore
                private DesiredCapabilities installedAppCaps() throws Exception {

                 DesiredCapabilities capabilities = DesiredCapabilities.android();
                  capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
                  capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10");
                  capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
                   capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");
        //capabilities.setCapability(MobileCapabilityType.APP_PACKAGE, testAppPackage);
        //capabilities.setCapability(MobileCapabilityType.APP_ACTIVITY, testAppActivity);
        //capabilities.setCapability(MobileCapabilityType.APP_WAIT_ACTIVITY, testAppActivity);
             capabilities.setCapability(MobileCapabilityType.DEVICE_READY_TIMEOUT, 40);
                    capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 180);
                  capabilities.setCapability(MobileCapabilityType.APPIUM_VERSION, "1.15.1");
                    capabilities.setCapability("deviceOrientation", "portrait");
                    capabilities.setCapability("autoLaunch", "false");
                           return capabilities;
                } 

                //uninstall the app if it's already installed
                //credit where credit is due - code thanks to Craigo - http://stackoverflow.com/a/25735681 AND  Simon-Kaz

                private void uninstallApp(String appPackage) throws IOException, InterruptedException {
                   final Process p = Runtime.getRuntime().exec("adb uninstall " + appPackage);

                   new Thread(new Runnable() {
                        public void run() {
                         BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                            String line = null;
                            try {
                                while ((line = input.readLine()) != null)
                                    System.out.println(line);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    p.waitFor();
                }
            }
------------------        
FROM APPIUM - 
Following is the complete log from the Appium Server.
[Appium]
[Appium] Appium REST http interface listener started on 0.0.0.0:4723
[HTTP] --> POST /wd/hub/session

[HTTP] {"requiredCapabilities": {"newCommandTimeout": 180, "appiumVersion": "1.15.1", "platformVersion": "10", "browserName": "", "deviceOrientation": "портрет", "имя_платформы": "Android", "имя_устройства": "Android эмулятор", "версия": "", "платформа": "ANDROID"}, "возможности": {"firstMatch ": [{" appium: appiumVersion ":" 1.15.1 "," browserName ":" "," appium: deviceName ":" Android Emulator "," deviceOrientation ":" Portrait "," appium: newCommandTimeout ": 180, "platform": "ANDROID", "platformName": "android", "appium: platformVersion": "10", "version": ""}]}} [W3C] Вызов AppiumDriver.createSession ( ) с аргументами: [{"newCommandTimeout": 180, "appiumVersion": "1.15.1", "platformVersion": "10", "browserName": "", "deviceOrientation": "Portrait", "platformName": " Android "," deviceName ":" Android Emulator "," version ":" "," platform ":" ANDROID "}, null, {" firstMatch ": [{" appium: appiumVersion ":" 1.15.1 "," browserName ":" "," appium: deviceName ":" Android Emulator "," deviceOrientation ":" Portrait "," appium: newCommandTimeout ": 180," platform ":" ANDROID " "platformName": "android "," appium: platformVersion ":" 10 "," version ":" "}]}] [BaseDriver] Событие 'newSessionRequested' зарегистрировано в 1580088658409 (14:30:58 GMT + 1300 (летнее время Новой Зеландии)) [ BaseDriver] Возможности ["deviceOrientation", "платформа", "версия"] не являются стандартными возможностями и должны иметь префикс расширения [Appium] [Appium] ================== ================================================== === [Appium] ПРЕДУПРЕЖДЕНИЕ О УСТРАНЕНИИ: [Appium] [Appium] В этом сеансе [Appium] не было предоставлено возможности для автоматизации [Appium] для этого сеанса Android [Appium] [Appium]. По умолчанию для параметра AutomaticName = UiAutomator2 устанавливается значение и с помощью драйвера [Appium] UiAutomator2 [Appium] [Appium] В следующей основной версии Appium (2.x) потребуется возможность [Appium] 'AutomationName', которая будет установлена ​​для всех сеансов на всех [ Платформы Appium [Appium] [Appium] В предыдущих версиях (Appium <= 1.13.x) значением по умолчанию было [Appium] 'automaName = UiAutomator1' [Appium] [Appium] Если вы используете sh для использования этого автома Примените вместо UiAutomator2, пожалуйста, [Appium], добавьте «automaName = UiAutomator1» к вашим желаемым возможностям [Appium] [Appium] Для получения дополнительной информации о драйверах, пожалуйста, посетите [Appium] <a href="http://appium.io/docs/en/about-appium/intro/" rel="nofollow noreferrer">http://appium.io/docs/en/about-appium/intro/ и изучите [Appium ] Меню «Драйверы» [Appium] [Appium] ======================================= =============================== [Appium] [Appium] Appium v1.15.1 создает новую сессию AndroidUiautomator2Driver (v1.37.2) Были предоставлены возможности [BaseDriver] W3 C и требуемые возможности MJSONWP [BaseDriver] Создание сеанса с возможностями W3 C: {[BaseDriver] "AlwaysMatch": {[BaseDriver] "browserName": "", [BaseDriver] "appium : deviceOrientation ":" Portrait ", [BaseDriver]" appium: platform ":" ANDROID ", [BaseDriver]" platformName ":" android ", [BaseDriver]" appium: версия ":" ", [BaseDriver ] "appium: appiumVersion": "1.15.1", [BaseDriver] "appium: deviceName": "Android Emulator", [BaseDriver] "appium: newCommandTimeout": 180, [BaseDriver] "appium: platformVersion": "10" [BaseDriver]}, [BaseDriver] "firstMatch": [[BaseDriver] {} [BaseDriver]] [BaseDriver]} [ BaseDriver] Были предоставлены следующие возможности, но они не распознаются Appium: [BaseDriver] deviceOrientation [BaseDriver] платформа [BaseDriver] версия [BaseDriver] appiumVersion [BaseDriver] Сессия создана с идентификатором сеанса: 19099890-ffc9-4df2-bf42-4f0773a74d33 [ UiAutomator2] Не было установлено ни app, ни appPackage. Запуск UiAutomator2 без целевого приложения [ADB] Найдены 1 папки 'build-tools' в папке 'C: \ Users \ AnoopSha1 \ AppData \ Local \ Android \ Sdk' ​​(сначала новые): [ADB] C: / Users /AnoopSha1/AppData/Local/Android/Sdk/build-tools/29.0.2 [ADB] Использование 'adb.exe' из 'C: \ Users \ AnoopSha1 \ AppData \ Local \ Android \ Sdk \ platform-tools \ \ adb.exe '[AndroidDriver] Получение списка устройств [ADB] Попытка найти подключенное устройство android [ADB] Получение подключенных устройств ... [ADB] Подключенные устройства: [{"udid": "", "state": "unauthorized"}, {"udid": "emulator-5554", "state": "device"}] [AndroidDriver] Поиск устройства с Android '10' [ADB] Установка идентификатора устройства на [ADB] Получение версия платформы устройства [ADB] Выполнение 'C: \ Users \ AnoopSha1 \ AppData \ Local \ Android \ Sdk \ platform-tools \ adb.exe -P 5037 -s оболочка getprop ro.build.version.release' [UiAutomator2] Удаление сеанса UiAutomator2 [BaseDriver] Событие 'newSessionStarted' зарегистрировано в 1580088659582 (14:30:59 GMT + 1300 (летнее время Новой Зеландии)) [W3C] Обнаружено int ernal error running command: Ошибка: Ошибка при получении версии платформы устройства. Исходная ошибка: ошибка при выполнении adbExe c. Исходная ошибка: 'Command' C: \ Users \ AnoopSha1 \ AppData \ Local \ Android \ Sdk \ platform-tools \ adb.exe -P 5037 -s UDHD

        shell getprop ro.build.version.release' exited with code 1'; Stderr: 'error: device unauthorized.
                    [W3C] This adb server's $ADB_VENDOR_KEYS is not set
                    [W3C] Try 'adb kill-server' if that seems wrong.
                    [W3C] Otherwise check for a confirmation dialog on your device.'; Code: '1'
                    [W3C]     at ADB.getPlatformVersion (C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-adb\lib\tools\adb-commands.js:123:11)
                    [HTTP] <-- POST /wd/hub/session 500 1222 ms - 1602

                    From Eclipse Console:
                    [RemoteTestNG] detected TestNG version 7.0.0
                    FAILED CONFIGURATION: @BeforeClass setUp
                    org.openqa.selenium.SessionNotCreatedException: Unable to create a new remote session. Please check the server log for more details. Original error: An unknown server-side error occurred while processing the command. Original error: Error getting device platform version. Original error: Error executing adbExec. Original error: 'Command 'C:\\Users\\AnoopSha1\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe -P 5037 -s shell getprop ro.build.version.release' exited with code 1'; Stderr: 'error: device unauthorized.
                    This adb server's $ADB_VENDOR_KEYS is not set
                    Try 'adb kill-server' if that seems wrong.
                    Otherwise check for a confirmation dialog on your device.'; Code: '1'
                    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
                    System info: host: 'AT9431-P', ip: '10.0.0.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
                    Driver info: driver.version: AndroidDriver
                    remote stacktrace: UnknownError: An unknown server-side error occurred while processing the command. Original error: Error getting device platform version. Original error: Error executing adbExec. Original error: 'Command 'C:\\Users\\AnoopSha1\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe -P 5037 -s shell getprop ro.build.version.release' exited with code 1'; Stderr: 'error: device unauthorized.
                    This adb server's $ADB_VENDOR_KEYS is not set
                    Try 'adb kill-server' if that seems wrong.
                    Otherwise check for a confirmation dialog on your device.'; Code: '1'
                        at getResponseForW3CError (C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\errors.js:804:9)
                        at asyncHandler (C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-base-driver\lib\protocol\protocol.js:388:37)
                        at process._tickCallback (internal/process/next_tick.js:68:7)
                    Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
                    System info: host: 'AT9431-P', ip: '10.0.0.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
                    Driver info: driver.version: AndroidDriver
                        at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:208)
                        at io.appium.java_client.remote.AppiumCommandExecutor.createSession(AppiumCommandExecutor.java:217)
                        at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:239)
                        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
                        at 
             io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:41)
                        at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
                        at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
                        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
                        at io.appium.java_client.AppiumDriver.startSession(AppiumDriver.java:336)
                        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
                        at io.appium.java_client.DefaultGenericMobileDriver.<init>(DefaultGenericMobileDriver.java:37)
                        at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:88)
                        at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:98)
                        at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:94)
                        at InstallAppfromPlayStore.setUp(InstallAppfromPlayStore.java:49)
                        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
                        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
                        at java.lang.reflect.Method.invoke(Unknown Source)
                        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
                        at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)
                        at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:340)
                        at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:294)
                        at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:176)
                        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:122)
                        at java.util.ArrayList.forEach(Unknown Source)
                        at org.testng.TestRunner.privateRun(TestRunner.java:770)
                        at org.testng.TestRunner.run(TestRunner.java:591)
                        at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
                        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
                        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
                        at org.testng.SuiteRunner.run(SuiteRunner.java:304)
                        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
                        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
                        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
                        at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
                        at org.testng.TestNG.runSuites(TestNG.java:1032)
                        at org.testng.TestNG.run(TestNG.java:1000)
                        at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
                        at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
                        at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
                    Caused by: java.lang.reflect.InvocationTargetException
                        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
                        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
                        at java.lang.reflect.Method.invoke(Unknown Source)
                        at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:186)
                        ... 40 more
                    Caused by: org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Error getting device platform version. Original error: Error executing adbExec. Original error: 'Command 'C:\\Users\\AnoopSha1\\AppData\\Local\\Android\\Sdk\\platform-tools\\adb.exe -P 5037 -s shell getprop ro.build.version.release' exited with code 1'; Stderr: 'error: device unauthorized.
                    This adb server's $ADB_VENDOR_KEYS is not set
                    Try 'adb kill-server' if that seems wrong.


How to resolve this issue? Any help is appreciated. Thanks
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...