1. 程式人生 > >Appium的一些坑問題錯誤解決 與 技巧集錦

Appium的一些坑問題錯誤解決 與 技巧集錦

問題

1. error: Failed to start an Appium session, err was: Error: Requested a new session but one was in progress

之前的會話沒有關閉,然後你又運行了測試例項,也沒有設定覆蓋
解決
1.
重新停止appium服務,開啟Appium服務 
2.
Genarel Setting那裡設定覆蓋Session,重啟Appium

測試結束在AfterClassdriver.quit()

2. error: Failed to start an Appium session, err was: Error: Command failed: C:\Windows\system32\cmd.exe /s /c "D:\android-sdk-windows\platform-tools\adb.exe -s adb server version (32) doesn't match this client (36); killing…

wait-for-device" 
error: could not install smartsocket listener: cannot bind to 127.0.0.1:5037:

沒有連結上手機或者模擬器,請確認已經連線成功,重新連結

3. error: Android devices must be of API level 17 or higher. Please change your device to Selendroid or upgrade Android on your device.

手機系統低於4.2appium不支援4.2.2以下的系統,請換一個手機或者模擬器來測試。

4. Error: Permission to start activity denied.

 
**activity
在清單檔案裡面沒新增Android:exported="true"的話,你不能直接開啟對應的activity,需要從啟動頁activity開啟。 
exported
屬性就是設定是否允許activity被其它程式呼叫**

5. error: Failed to start an Appium session, err was: Error: Activity used to start app doesn't exist or cannot ve launched! Make usre it exists and is launchable activity

要開啟的activity不存在,activity路徑錯誤,改為完整正確的activity路徑

6. error: Failed to start an Appium session, err was: Error: 'java - version' failed. Error: Command failed: C:\Windows\system32\cmd.exe /s /c "java -version"

 
Java
版本錯誤,請安裝最新的版本

7.> info: [debug] Error: Command failed: C:\Windows\system32\cmd.exe /s /c "D:\android-sdk-windows\platform-tools\adb.exe -s 8806a0b0 shell "echo 'ready'"error: unknown host service

連結手機失敗,重新連結手機即可,我就是重新拔插了一下usb

Error: Command failed: C:\Windows\system32\cmd.exe /s /c "D:\android-sdk-windows\platform-tools\adb.exe -s 8806a0b0 shell "echo 'ping'""

error: unknown host service

adb被突然佔用導致,例如你在執行用例的時候運行了模擬器。

8. UIAutomatorViewer提示: Unable to connect to adb. Check if adb is installed correctly

解決,sdk升級到了25產生的問題。

解決方法:

  1. adb.exe 複製一份到uiautomatorviewer.bat 目錄下
  2. 修改uiautomatorviewer.bat檔案最後一行(改binddir=%prog_dir%為自己的platform-tools本地路徑) 

9 error: Failed to start an Appium session, err was:INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling

When you are at final step to execute test automation script for mobile app testing on a mobile emulator or a virtual device or a real device, you might observe that script execution fails with different kinds of errors, In context to current article you will look at the error and solutions for: INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install io.appium.settings without first uninstalling.

Error in Appium Server:

1

2

3

4

5

6

7

8

Error: Command failed: C:\Windows\system32\cmd.exe /s /c

"C:\Users\{User}\AppData\Local\Android\sdk\platform-tools\adb.exe -s

emulator-5554 install

"C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk""

> Failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\

settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install

io.appium.settings without first uninstalling.]

Error in Android studio run console:

1

2

3

4

5

6

7

8

9

org.openqa.selenium.SessionNotCreatedException: A new session could not be created.

(Original error: Command failed: C:\Windows\system32\cmd.exe /s /c

"C:\Users\{User}\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 install

"C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk""

Failed to install C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\

settings_apk-debug.apk: Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install

io.appium.settings without first uninstalling.]

) (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 0 milliseconds

For the first time when you execute the script it might pass, but it will fail with above error when you try to execute the same or any other script multiple times. Or when your test script execution fails on the first attempt for some other reason, and when you fix it and execute it again, you might encounter this new issue.

原因:

The reason for this error is that Appium installs 2 mobile applications before executing the script.

1. io.appium.settings

2. io.appium.unlock

These are the supportive mobile applications appium utilizes to execute the test automation script in Mobile Emulator or virtual device or a real mobile device.

Ideally Appium should remove these files every time at the end of the script execution or termination, if it is intends to install them every time a script is executed, or it should conditionally install these apps / apks to the mobile emulator or mobile device.

In your mobile emulator / Virtual Device / Real device, the 2 mobile applications appear as below:

There are multiple ways to troubleshoot this error and go ahead for a successful test script execution.

解決辦法

Solution 1: ADB's uninstall command to remove the files.

You can open command prompt, assuming that you already had set the environment variables for ANDROID_HOME and Path variables for sdk tools and platform tools.

And execute commands as shown below:

Solution 2: Uninstall manually

You can open the mobile emulator / virtual device / real device and go to apps and uninstall them.

Solution 3: Write code as part of your test automation script.

As part of your selenium test automation script, you could write instructions to execute the commands provided in solution 1 above, so that this issue would not arise.

Hope this article has been helpful and you are able to proceed further with script execution.

Request to kindly share any of your queries in form of comments, we would try our best to provide any solution for you.

10. 出錯資訊裡含有"ps 'uiautomator',具體資訊未 A new session could not be created. (Original error: Command failed: C:\Windows\system32\cmd.exe /s /c "C:\Users\sxie\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "ps 'uiautomator'""

android-appium: A new session could not be created

detail log:
org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Command failed: C:\Windows\system32\cmd.exe /s /c "C:\Users\sxie\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "ps 'uiautomator'""
) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'WL00070299', ip: '10.110.12.39', os.name: 'Windows 8.1', os.arch: 'x86', os.version: '6.3', java.version: '1.8.0_40'
Driver info: driver.version: AndroidDriver
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:215)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:167)
at io.appium.java_client.remote.AppiumProtocolHandShake.createSession(AppiumProtocolHandShake.java:161)
at io.appium.java_client.remote.AppiumProtocolHandShake.createSession(AppiumProtocolHandShake.java:76)
at io.appium.java_client.remote.AppiumCommandExecutor.doExecute(AppiumCommandExecutor.java:111)
at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:162)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
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:250)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:137)
at io.appium.java_client.DefaultGenericMobileDriver.(DefaultGenericMobileDriver.java:38)
at io.appium.java_client.AppiumDriver.(AppiumDriver.java:88)
at io.appium.java_client.AppiumDriver.(AppiumDriver.java:112)
at io.appium.java_client.android.AndroidDriver.(AndroidDriver.java:73)
at com.sky.demo.ContactTest.setUp(ContactTest.java:44)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

==========================================
直接在cmd中執行"C:\Windows\system32\cmd.exe /s /c "C:\Users\sxie\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "ps 'uiautomator'""
bad pid 'uiautomator'", 報錯: bad pid 'uiautomator'

程式碼內容為


public class ContactTest {
private AndroidDriver driver; 
@Before
public void setUp() throws Exception {
//設定apk的路徑
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "apps");
File app = new File(appDir, "ContactManager.apk");

    //設定自動化相關引數
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
    capabilities.setCapability("automationName","Appium");  
    capabilities.setCapability("platformName", "Android");
    capabilities.setCapability("deviceName", "Pixel_XL_API_25");// Galaxy_Nexus_API_25
    capabilities.setCapability("noReset", true);
    capabilities.setCapability("avdReadyTimeout", 300000);
    capabilities.setCapability("sessionOverride", true);    
    //設定安卓系統版本
    capabilities.setCapability("platformVersion", "7.1.1");
    //設定apk路徑
    capabilities.setCapability("app", app.getAbsolutePath()); 
    //設定app的主包名和主類名
    capabilities.setCapability("appPackage", "com.example.android.contactmanager");
    capabilities.setCapability("appActivity", ".ContactManager");
    //初始化
    driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);  
}
@Test
public void addContact(){
    WebElement el = driver.findElement(By.name("Add Contact"));
    el.click();
    List<WebElement> textFieldsList = driver.findElementsByClassName("android.widget.EditText");
    textFieldsList.get(0).sendKeys("feimaoyuzhubaobao");
    textFieldsList.get(2).sendKeys("forever together");
    driver.swipe(100, 500, 100, 100, 2);
    driver.findElementByName("Save").click();
}    
@After
public void tearDown() throws Exception {
    driver.quit();
}

}

解決辦法:

resolved by this way:
adb.js(C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\lib\adb.js) 中1035 行this.shell("ps '" + name + "'", function (err, stdout) {
對應執行的指令是ps 'uiautomator', Android7不支援這個指令格式,所以執行結果是bad pid 'uiautomator'
目前Appium未對此進行處理,所以需要修改此指令的執行方式
即將
this.shell("ps '" + name + "'", function (err, stdout) {
if (err) return cb(err);
替換成
this.shell_grep("ps", name, function (err, stdout) {

if (err) {

logger.debug("No matching processes found");
return cb(null, []);

}

並增加上面用到的shell_grep函式:
ADB.prototype.shell_grep = function (cmd, grep, cb) {
if (cmd.indexOf('"') === -1) {
cmd = '"' + cmd + '"';
}
var execCmd = 'shell ' + cmd + '| grep ' + grep;
this.exec(execCmd, cb);

};

11.Android 7.0系統的手機無法執行appium指令碼的問題

Appium Appium 版本 1.4.16,Android 裝置韌體 7.x,執行指令碼時,報錯使用語言:python報錯如下:
WebDriverException: Message: A new session could not be created. (Original error: Could not extract PIDs from ps output. PIDS: [], Procs: ["bad pid 'uiautomator'"])

這個是因為appium版本1.4.16 使用的 uiatumator1.0不支援的原因導致?如果不升級appium版本,是否有解決方案?

解決辦法

uiautomator1.0應該是不支援7.0,不升版本就換用uiautomator2.0吧,或者用下面的改指令碼的方法使用。

解決Android 7.0系統的手機無法執行appium指令碼的問題,改問題的具體解決方法如下:

  1. 找到appium的安裝目錄下的adb.js檔案,windows版本的目錄如下:Appium\node_modules\appium\node_modules\appium-adb\lib
    2
    開啟adb.js,手動修改該檔案下的內容,此方法我已經試驗成功。

adb.js 中1035 行this.shell("ps '" + name + "'", function (err, stdout) {
對應執行的指令是ps 'uiautomator', Android7不支援這個指令格式,所以執行結果是bad pid 'uiautomator'
目前Appium未對此進行處理,所以需要修改此指令的執行方式
即將
this.shell("ps '" + name + "'", function (err, stdout) {
if (err) return cb(err);
替換成
this.shell_grep("ps", name, function (err, stdout) {

if (err) {

logger.debug("No matching processes found");
return cb(null, []);

}

並增加上面用到的shell_grep函式:
ADB.prototype.shell_grep = function (cmd, grep, cb) {
if (cmd.indexOf('"') === -1) {
cmd = '"' + cmd + '"';
}
var execCmd = 'shell ' + cmd + '| grep ' + grep;
this.exec(execCmd, cb);

};

  1. 網上還有如下的修改解決辦法:以下我未試驗。
    ADB.prototype.getPIDsByName = function (name, cb) {
    logger.debug("Getting all processes with '" + name + "'");
    this.shell("ps '" + name + "'", function (err, stdout) {
    if (err) return cb(err);
    stdout = stdout.trim();
    var procs = [];
    var outlines = stdout.split("\n");
    outlines.shift(); //
    在該處新增此行程式碼
    3
    、重啟appium

技巧

1. 每次測試都重新安裝app

capabilities色設定noResettrue 
capabilities.setCapability("noReset", true);

2. 中文亂碼

這都是編碼問題:

1.方法1:

Android Studio修改檔案編碼的方法,最底部的UTf-8,點選選GBK就可以了,reload檔案。(ps: 先把檔案內容全選複製一下再轉換編碼,再貼上,不然檔案內容就變亂碼了)

2.方法2:

用的是原來的UTF-8編碼,然後在測試modulebuild.gradle裡面新增三行程式碼

tasks.withType(JavaCompile){

options.encoding = 'UTF-8'

}

3. 清除編輯框EditText內容

這個問題好像是看手機系統的,我之前的手機就會出現sendKeys的時候沒有全選去掉本來的內容,現在都會自動全選覆蓋了,這個也不算問題了。

/**

* 逐字刪除編輯框中的文字

* @param element 文字框架控制元件

*/

public void clearText(AndroidElement element){

String className = element.getClass().getSimpleName();

if (className.equals("EditText")){

String text = element.getText();

//跳到最後

driver.pressKeyCode(KEYCODE_MOVE_END);

for (int i = 0; i < text.length(); i ++){

//迴圈後退刪除

driver.pressKeyCode(BACKSPACE);

}

}else {

print("不是文字輸入框架,無法刪除文字");

}

}

1

4. 點選輸入法鍵盤的回車搜尋

方法1: 切換輸入法

利用adb命令先切換為自己的輸入法,按了搜尋再切換為appium的輸入法

檢視當前手機的輸入法

cmd執行下面的的程式碼

adb shell ime list -s

可以看到類似下面的結果,

C:\Users\LITP>adb shell ime list -s

com.baidu.input_mi/.ImeService

com.sohu.inputmethod.sogou.xiaomi/.SogouIME

io.appium.android.ime/.UnicodeIME

C:\Users\LITP>

執行adb命令

先寫好一個執行cmd的方法

/**

* 執行adb命令

* @param s 要執行的命令

*/

private void excuteAdbShell(String s) {

Runtime runtime=Runtime.getRuntime();

try{

runtime.exec(s);

}catch(Exception e){

print("執行命令:"+s+"出錯");

}

}

在需要搜尋的時候執行下面的程式碼,切換的輸入法用自己檢視列表的輸入法內容,我這裡是搜狗輸入法

//使用adb shell 切換輸入法-更改為搜狗拼音,這個看你本來用的什麼輸入法

excuteAdbShell("adb shell ime set com.sohu.inputmethod.sogou.xiaomi/.SogouIME");

//再次點選輸入框,調取鍵盤,軟鍵盤被成功調出

clickView(page.getSearch());

//點選右下角的搜尋,即ENTER鍵

pressKeyCode(AndroidKeyCode.ENTER);

//再次切回 輸入法鍵盤為Appium unicodeKeyboard

excuteAdbShell("adb shell ime set io.appium.android.ime/.UnicodeIME");