您的位置:首页 > 移动开发 > IOS开发

appium+java+ios自动化环境的搭建部分代码,资料的搜集与整合。

2014-09-26 15:43 639 查看
对环境的需求:
http://appium.io/ 上的说法:
iOS
Mac OSX 10.7+
XCode 4.5+ 和 Command Line Tools
 
https://github.com/appium/appium的说法:
npm 0.8 or greater
Mac OS X 10.7 or higher, 10.8.4 recommended
XCode >= 4.6.3
 

1,

 

2,

03.png
 
 
04.png
 
 
05.png

 

 

备注:

xcode6:没有此信息:

 

 

node.js安装:

第一步,从nodejs.org 中下载Node.js
forMac 安装包,也就是一个6M多的pkg文件,下载之后点击安装即可。
 

 

 
 
     安装完成之后我们关闭窗口,接下来我们打开“终端”,并且输入命令:
 
curl https://npmjs.org/install.sh | sh
    这个npm.js实际上是Node.js的套件管理工具,执行完成之后我们继续执行下面都命令:
 
sudo npmupdate npm -g
 
    这一步是更新npm,全部完成之后我们使用打印版本命令来看一下npm是否安装成功,如果不行大家就多试几次。我的版本输出结果:
 

 
 
 
     我当前版本为1.1.12
 
     最后,还是为大家写一个helloword吧!复制下面代码到记事本。
 
 
var http =require(http); 
http.createServer(function(req, res) { 

  res.writeHead(200, {Content-Type:text/plain}); 

  res.end(Hello World
hahah); 
}).listen(1337,"127.0.0.1"); 

console.log(Serverrunning at http://127.0.0.1:1337/);
     然后在终端里面敲入命令 nodehe.js
这里都he.js是你javascript文件都路径回车就OK了!终端会显示如图:
 

 
      在浏览器中输入网址与端口并访问,你就可以看到效果了!
 


 

安装:在mac上打开shell
#sudo npm install -g appium  //加上sudo以防Permission的问题
#npm installwd  //这个还不清楚有什么影响??

 

appium 在模拟器中跑,只需要注意:
1:app=path找到编译后app所在的位置,如:注意Release-iphonesimulator这个是模拟器编译后的文件夹
    final File appDir = newFile(System.getProperty("user.dir"),
       "../../../apps/TestApp/build/Release-iphonesimulator");
   final File app = new File(appDir, "TestApp.app");
   capabilities.setCapability("app",
app.getAbsolutePath());
appium真机上运行:
1:运行的时候要将APP安装到真机上面
2:运行的时候,不能再开instrument 
3:命令行里面启动的时候,参数写错了应该是appium -U 3d2cad7288a64a5445aa98a2cc220132f2cddd1c --app io.appium  然后代码里面app=bundleID,如以下例子中: 
capabilities.setCapability("app","io.appium.TestApp");而不是那个很长的路径,其中-U参数后面是真机的uuid,可以打开xcode,在windows下的organise下找到,一般mac连接上ipad后会有绿色圆点
 
 
现在贴上真机上运行python实例:
 
Kingsons-MacBook:Study kingson$appium
-U 1a601f5cd791bc379115095fc81cd69b096582a3
--app com.telenavsoftware.doudouy
info: Welcome to Appium v0.11.4 (REVb04decd191002628c88e9bf475553da1cd04a036)
info: Appium REST http
interface
listener started on
0.0.0.0:4723
  info  - socket.iostarted
debug: Appium request initiated at
/wd/hub/session
debug: Request received with params:{"sessionId":null,"desiredCapabilities":{"device":"iPhone
Simulator","platform":"Mac","browserName":"iOS","version":"7.0","app":"com.telenavsoftware.doudouy"}}
info: App is an iOS bundle, willattempt to run
as pre-existing
info: Creating new appium session a36fdf63-9b22-48a4-bb01-4b44ddb54aff
info: Removing any remaining instruments sockets
info: Cleaned up instruments socket
/
tmp/instruments_sock
info: Cleaning up any tracedirs
info: No tracedirs to clean up
info: Localizable.strings
is not currentlysupported when using real devices.
info: Not setting device
type since we're connected to a device
info: Starting iOS device log capture viaidevicesyslog
debug: Real device specified but no ipa,assuming bundle ID is on device
debug: Creating instruments
info: instruments is:/Applications/Xcode.app/Contents/Developer/usr/bin/instruments
info: [INSTSERVER] Instruments socketserver started at /tmp/instruments_sock
info: Attempting to run app on real devicewith UDID 1a601f5cd791bc379115095fc81cd69b096582a3
info: Spawning instruments with command:/Applications/Xcode.app/Contents/Developer/usr/bin/instruments -t/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate-w
1a601f5cd791bc379115095fc81cd69b096582a3 com.telenavsoftware.doudouy -eUIASCRIPT /usr/local/lib/node_modules/appium/lib/devices/ios/uiauto/bootstrap.js -e UIARESULTSPATH/tmp/appium-instruments/
info: And extra without-delay env: {}
info: And launch timeout: 90000ms
info: [INST STDERR] 2013-12-10 10:40:22.536instruments[53424:507] Connection to the remote device lost while launchingtarget. Aborting...
 
info: [INST STDERR] 2013-12-10 10:40:22.539instruments[53424:507] Recording cancelled : At least one target failed tolaunch; aborting run
 
info: [INST STDERR] Instruments Trace Error: Error Domain=com.apple.instruments Code=1 "Error StartingRecording" UserInfo=0x7ff6d308f220 {NSLocalizedDescription=Error StartingRecording, NSLocalizedRecoverySuggestion=At
least one target failed to launch;aborting run}
Instruments Trace Error : Failed to starttrace.
 
info: [INSTSERVER] Instruments exited withcode 253
error: Instruments did not launchsuccessfully, failing session
info: Cleaning up appium session
error: Failed to start an Appium session, errwas: Error: Instruments did not launch successfully--please check your apppaths or bundle IDs and try again
info: Responding to client with error:{"status":33,"value":{"message":"A newsession could not be created. (Original error: Instruments did not launchsuccessfully--please check your app paths or bundle IDs and tryagain)","origValue":"Instruments
did not launchsuccessfully--please check your app paths or bundle IDs and tryagain"},"sessionId":null}
POST /wd/hub/session 500 6015ms - 342b```
 
我的部分代码片段:
 
 
```python
classTestSequenceFunctions(unittest.TestCase):
 
   def setUp(self):
       # set up appium
       app = "com.telenavsoftware.doudouy"
       #app = os.path.join(os.path.dirname(__file__),
       #                   '../../apps/DDY/build/',
       #                   'DouDouY.app')
       #app = os.path.abspath(app)
       self.driver = webdriver.Remote(
           command_executor='http://127.0.0.1:4723/wd/hub',
           desired_capabilities={
                'browserName': 'iOS',
                'device': 'iPhone Simulator',
                'platform': 'Mac',
                'version': '7.0',
                'app': app
           })```
1.启动Appium时,保证你的Real Device的UDID和你的应用的Bundle
ID正确
2.确保你的应用可以安装到你的真机上
3.安装后请断开与Xcode的连接
4.确保Mac上没有启动Instruments工具
 
 
以下是JAVA真机运行log:
 
devexus-iMac:build devexu$ appium -U3d2cad7288a64a5445aa98a2cc220132f2cddd1c --app io.appium
info: Welcome to Appium v1.1.0 (REVe433bbc31511f199287db7724e1ce692bcb32117)
info: Appium REST http interface listener started on 0.0.0.0:4723
info: socket.io started
info: Non-default server args:{"app":"io.appium","udid":"3d2cad7288a64a5445aa98a2cc220132f2cddd1c"}
debug: Appium request initiated at /wd/hub/session
debug: Request received with params:{"desiredCapabilities":{"platformVersion":"7.1","app":"io.appium.TestApp","platformName":"iOS","deviceName":"iPhoneSimulator","browserName":""}}
info: App is an iOS bundle, will attempt to run as pre-existing
info: Creating new appium session 2bcd619b-b7fb-45f5-b20c-79caff8cd24f
info: Removing any remaining instruments sockets
info: Cleaned up instruments socket /tmp/instruments_sock
info: Cleaning up any tracedirs
info: No tracedirs to clean up
info: Setting Xcode folder
info: Setting Xcode version
info: Setting iOS SDK Version
info: iOS SDK Version set to 7.1
info: Detecting automation tracetemplate
info: Not auto-detecting udid, running on sim
info: Localizable.strings is not currently supported when using realdevices.
info: Not setting locale because we're using a real device
debug: Creating instruments
info: Not setting iOS and app preferences since we're on a real device
info: Starting iOS device log capture via idevicesyslog
info: Not setting device type since we're connected to a device
debug: Real device specified but no ipa or app path, assuming bundle ID ison device
debug: Starting instruments
info: Instruments is at:/Applications/Xcode.app/Contents/Developer/usr/bin/instruments
info: [INSTSERVER] Instruments socket server started at/tmp/instruments_sock
info: Attempting to run app on real device with UDID3d2cad7288a64a5445aa98a2cc220132f2cddd1c
info: Spawning instruments with command: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments-t/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.bundle/Contents/Resources/Automation.tracetemplate-w
3d2cad7288a64a5445aa98a2cc220132f2cddd1c io.appium.TestApp -e UIASCRIPT/usr/local/lib/node_modules/appium/node_modules/appium-uiauto/uiauto/bootstrap.js-e UIARESULTSPATH /tmp/appium-instruments
info: And extra without-delay env: {}
info: And launch timeouts (in ms): {"global":90000}
info: [INST] 2014-07-02 01:29:30 +0000 Start: Bootstrapping uiauto
       
info: [INST] 2014-07-02 01:29:32 +0000 Start: Got user: devexu
       
info: [INST] 2014-07-02 01:29:33 +0000 Start: Not using settings file.
       
info: [INST] 2014-07-02 01:29:33 +0000 Start: isVerbose:false
       
info: [INST] 2014-07-02 01:29:37 +0000 Start: Using node at:/usr/local/bin/node
       
info: [INSTSERVER] Instruments is ready to receive commands
info: Instruments launched. Starting poll loop for new commands.
info: Setting bootstrap config keys/values
info: Pushing command to appium work queue: "setBootstrapConfig:autoAcceptAlerts=false"
debug: Sending command to instruments: setBootstrapConfig:autoAcceptAlerts=false
info: [INSTSERVER] Socket data received (15 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Sending command to instruments: setBootstrapConfig:autoAcceptAlerts=false
info: [INSTSERVER] Socket data received (48 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Got result from instruments:{"status":0,"value":""}
info: Setting initial orientation to PORTRAIT
info: Pushing command to appium work queue:"au.setScreenOrientation('PORTRAIT')"
debug: Sending command to instruments: au.setScreenOrientation('PORTRAIT')
info: [INSTSERVER] Sending command to instruments:au.setScreenOrientation('PORTRAIT')
info: [INST] 2014-07-02 01:29:41 +0000 Debug:target.setDeviceOrientation("1")
       
info: [INSTSERVER] Socket data received (56 bytes)
info: [INSTSERVER] Socket data being routed for 'cmd' event
info: [INSTSERVER] Got result from instruments:{"status":0,"value":"PORTRAIT"}
info: Device launched! Ready for commands
info: Setting command timeout to the default of 60 secs
info: Appium session started with sessionId2bcd619b-b7fb-45f5-b20c-79caff8cd24f
POST /wd/hub/session 303 22483ms - 9b
debug: Appium request initiated at/wd/hub/session/2bcd619b-b7fb-45f5-b20c-79caff8cd24f
debug: Request received with params: {}
info: Responding to client with success: {"status":0,"value":{"webStorageEnabled":false,"locationContextEnabled":false,"browserName":"","platform":"MAC","javascriptEnabled":true,"databaseEnabled":false,"takesScreenshot":true,"warnings":{},"desired":{"platformVersion":"7.1","app":"io.appium.TestApp","platformName":"iOS","deviceName":"iPhoneSimulator","browserName":""},"platformVersion":"7.1","app":"io.appium.TestApp","platformName":"iOS","deviceName":"iPhoneSimulator"},"sessionId":"2bcd619b-b7fb-45f5-b20c-79caff8cd24f"}
..........
java真机运行的代码:
package com.saucelabs.appium;


import staticorg.junit.Assert.assertTrue;
import io.appium.java_client.AppiumDriver;
importio.appium.java_client.MobileBy;


import java.net.URL;
importjava.util.ArrayList;
import java.util.List;
import
java.util.Random;


importorg.junit.After;
import org.junit.Before;
import org.junit.Test;
importorg.openqa.selenium.By;
import org.openqa.selenium.Dimension;
importorg.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
importorg.openqa.selenium.remote.CapabilityType;
importorg.openqa.selenium.remote.DesiredCapabilities;


/**
 *
Simple <ahref="https://github.com/appium/appium">Appium</a> testwhich runs
 * against a local Appium instance deployed with the 'TestApp'iPhone project
 * which is included in the Appium sourcedistribution.
 * 
 * @author Ross Rowe
 */
public classWiMyOffice
{


  private AppiumDriver     driver;


 private List<Integer>    values;


  private static finalint MINIMUM = 0;
  private static final int MAXIMUM = 10;


  privatePoint getCenter(final WebElement element) {


    final PointupperLeft = element.getLocation();
 
  final Dimension dimensions =element.getSize();
    return new Point(upperLeft.getX() +dimensions.getWidth() / 2,
        upperLeft.getY() +dimensions.getHeight() / 2);
  }


  private void populate() {
   // populate text fields with two random number
 
  finalList<WebElement> elems = driver.findElements(By
       .className("UIATextField"));
    final Random random= new Random();
    for (final WebElement elem : elems) {
     final int rndNum = random.nextInt(MAXIMUM - MINIMUM + 1) +MINIMUM;
      elem.sendKeys(String.valueOf(rndNum));
  
  values.add(rndNum);
    }
  }


  @Before
  public void setUp() throws Exception{
    // set up appium


    final DesiredCapabilitiescapabilities = new DesiredCapabilities();
   capabilities.setCapability(CapabilityType.BROWSER_NAME,
"");
   capabilities.setCapability("platformVersion","7.1");
    capabilities.setCapability("platformName","iOS");
    capabilities.setCapability("deviceName","iPhone Simulator");
   capabilities.setCapability("app","io.appium.TestApp");
    driver = new AppiumDriver(newURL("http://127.0.0.1:4723/wd/hub"),
 
     capabilities);
    values = new ArrayList<Integer>();
  }


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


  @Test
  public voidtestHideKeyboard() throws Exception {
   driver.findElement(By.xpath("//UIATextField[1]")).sendKeys("12");


  
final WebElement button = driver.findElement(MobileBy
       .AccessibilityId("Done"));
   assertTrue(button.isDisplayed());


    button.click();
  }


}
 
java上在模拟器上跑的实例:
命令行输入:appium&启动服务就可以了
lsof -i:4723查看端口号有没有被占用,占用就用 kill -9
进程ID

代码:
package com.saucelabs.appium;


importstatic org.junit.Assert.assertTrue;
importio.appium.java_client.AppiumDriver;


import java.io.File;
importjava.net.URL;
import java.util.ArrayList;
import java.util.List;
importjava.util.Random;


import
org.junit.After;
import org.junit.Before;
importorg.junit.Test;
import org.openqa.selenium.By;
importorg.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
importorg.openqa.selenium.WebElement;
importorg.openqa.selenium.remote.CapabilityType;
importorg.openqa.selenium.remote.DesiredCapabilities;


/**
 *
Simple <ahref="https://github.com/appium/appium">Appium</a> testwhich runs
 * against a local Appium instance deployed with the 'TestApp'iPhone project
 * which is included in the Appium source distribution.
 * 
 *@author Ross Rowe
 */
public class SimpleTest
{


  privateAppiumDriver     driver;


  private List<Integer>   values;


  private static final int MINIMUM = 0;
  privatestatic final int MAXIMUM = 10;


  private Point getCenter(finalWebElement element) {


    final Point upperLeft =element.getLocation();
 
  final Dimension dimensions =element.getSize();
    return new Point(upperLeft.getX() +dimensions.getWidth() / 2,
        upperLeft.getY() +dimensions.getHeight() / 2);
  }


  private void populate() {
   // populate text fields with two random number
 
  finalList<WebElement> elems = driver.findElements(By
       .className("UIATextField"));
    final Random random= new Random();
    for (final WebElement elem : elems) {
     final int rndNum = random.nextInt(MAXIMUM - MINIMUM + 1) +MINIMUM;
      elem.sendKeys(String.valueOf(rndNum));
  
  values.add(rndNum);
    }
  }


  @Before
  public void setUp() throws Exception {
   // set up appium
    final File appDir = newFile(System.getProperty("user.dir"),
       "../../../apps/TestApp/build/Release-iphonesimulator");
 
 final File app = new File(appDir, "TestApp.app");
    finalDesiredCapabilities capabilities = new DesiredCapabilities();
   capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
   capabilities.setCapability("platformVersion","7.1");
   capabilities.setCapability("platformName",
"iOS");
   capabilities.setCapability("deviceName", "iPhoneSimulator");
    capabilities.setCapability("app",app.getAbsolutePath());
    driver = new AppiumDriver(newURL("http://127.0.0.1:4723/wd/hub"),
       capabilities);
    values = new ArrayList<Integer>();
 
}


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


  @Test
  public void testActive()throws Exception {
    final WebElement text =driver.findElement(By.xpath("//UIATextField[1]"));
   assertTrue(text.isDisplayed());


 
  final WebElement button =driver.findElement(By.xpath("//UIAButton[1]"));
   assertTrue(button.isDisplayed());
  }
 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: