

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# AWS Device Farm 中的自訂測試環境
<a name="custom-test-environments"></a>

AWS Device Farm 可設定自訂環境以進行自動化測試 （自訂模式），這是所有 Device Farm 使用者的建議方法。若要進一步了解 Device Farm 中的環境，請參閱[測試環境](https://docs.aws.amazon.com/devicefarm/latest/developerguide/test-environments.html)。

與標準模式相反的自訂模式優點包括：
+ **更快速end-to-end測試執行**：測試套件不會剖析來偵測套件中的每個測試，避免預先處理/後製處理額外負荷。
+ **即時日誌和影片串流**：使用自訂模式時，您的用戶端測試日誌和影片會進行即時串流。此功能不適用於標準模式。
+ **擷取所有成品**：在主機和裝置上，自訂模式可讓您擷取所有測試成品。這可能無法在標準模式中執行。
+ **更一致且可複製的本機環境**：在標準模式中，將分別為每個個別測試提供成品，這在某些情況下可能會有所幫助。不過，由於 Device Farm 以不同的方式處理每個執行的測試，因此您的本機測試環境可能會偏離原始組態。

  相反地，自訂模式可讓您讓 Device Farm 測試執行環境與本機測試環境一致。

 自訂環境是使用 YAML 格式的測試規格 （測試規格） 檔案來設定。Device Farm 為每種支援的測試類型提供預設測試規格檔案，可依原樣使用或自訂；自訂如測試篩選條件或組態檔案可新增至測試規格。可儲存編輯的測試規格以供未來測試執行使用。

如需詳細資訊，請參閱[使用 和 上傳自訂測試規格 AWS CLI](https://docs.aws.amazon.com/devicefarm/latest/developerguide/how-to-create-test-run.html#how-to-create-test-run-cli-step5)[在 Device Farm 中建立測試執行](how-to-create-test-run.md)。

**Topics**
+ [測試規格參考和語法](custom-test-environment-test-spec.md)
+ [自訂測試環境的主機](custom-test-environments-hosts.md)
+ [使用 IAM 執行角色存取 AWS 資源](custom-test-environments-iam-roles.md)
+ [自訂測試環境的環境變數](custom-test-environment-variables.md)
+ [自訂測試環境執行的最佳實務](custom-test-environments-best-practices.md)
+ [將測試從標準遷移至自訂測試環境](custom-test-environment-migration.md)
+ [在 Device Farm 中擴展自訂測試環境](custom-test-environments-extending.md)

# 測試規格參考和語法
<a name="custom-test-environment-test-spec"></a>

 測試規格 （測試規格） 是您用來定義 Device Farm 中自訂測試環境的檔案。

## 測試規格工作流程
<a name="custom-test-environment-test-spec-workflow"></a>

 Device Farm 測試規格會以預先決定的順序執行階段及其命令，讓您自訂環境的準備和執行方式。執行每個階段時，其命令會依測試規格檔案中列出的順序執行。階段會依下列順序執行 

1. `install` - 這是應該定義下載、安裝和設定工具等動作的位置。

1. `pre_test` - 這是應該定義測試前動作的位置，例如啟動背景程序。

1. `test` - 此處應定義叫用測試的 命令。

1. `post_test` - 此處應定義測試結束後需要執行的任何最終任務，例如測試報告產生和成品檔案彙總。

## 測試規格語法
<a name="custom-test-environment-test-spec-syntax"></a>

以下是測試規格檔案的 YAML 結構描述

```
version: 0.1

android_test_host: "string"
ios_test_host: "string"

phases:
  install:
    commands:
      - "string"
      - "string"
  pre_test:
    commands:
      - "string"
      - "string"
  test:
    commands:
      - "string"
      - "string"
  post_test:
    commands:
      - "string"
      - "string"

artifacts:
    - "string"
    - "string"
```

** `version` **  
 *（必要，數字）*   
 反映 Device Farm 支援的測試規格版本。目前的版本編號為 ` 0.1`。

** `android_test_host` **  
 *（選用，字串）*   
 為在 Android 裝置上執行的測試執行選取的測試主機。在 Android 裝置上執行的測試需要此欄位。如需詳細資訊，請參閱[適用於自訂測試環境的測試主機](custom-test-environments-hosts.md#custom-test-environments-hosts-available)。

** `ios_test_host` **  
 *（選用，字串）*   
 為在 iOS 裝置上執行的測試執行選取的測試主機。在主要版本大於 26 的 iOS 裝置上執行測試時，需要此欄位。如需詳細資訊，請參閱[適用於自訂測試環境的測試主機](custom-test-environments-hosts.md#custom-test-environments-hosts-available)。

** `phases` **  
本節包含在測試執行期間執行的命令群組，其中每個階段都是選用的測試階段名稱為：`install`、`test`、 `pre_test` 和 `post_test`。  
+ `install` - Device Farm 支援之測試架構的預設相依性已安裝。此階段包含 Device Farm 在安裝期間執行的其他命令，如果有的話。
+ `pre_test` - 命令，如果有的話，會在您的自動化測試之前執行。
+ `test` - 在自動測試執行期間執行的命令。如果測試階段中的任何命令失敗 （表示傳回非零結束碼），則測試會標記為失敗
+ `post_test` - 命令，如果有的話，會在自動測試執行之後執行。無論您在`test`階段中的測試成功或失敗，都會執行此操作。  
** `commands` **  
 *（選用，List【string】)*   
 在階段期間以 shell 命令執行的字串清單。

** `artifacts` **  
 *（選用，List【string】)*   
 Device Farm 會從此處指定的位置收集成品，例如自訂報告、日誌檔案和映像。成品位置不支援萬用字元，因此您必須為每個位置指定有效路徑。  
這些測試成品可供測試執行中的每個裝置使用。如需擷取測試成品的詳細資訊，請參閱 [在自訂測試環境中下載成品](using-artifacts-custom.md)。

**重要**  
測試規格的格式必須是有效的 YAML 檔案。如果縮排或空格在您的測試規格中無效，您的測試可能會失敗。YAML 檔案不允許標籤。您可以使用 YAML 驗證程式來測試您的測試規格是否為有效的 YAML 檔案。如需詳細資訊，請參閱 [YAML 網站](http://yaml.org/spec/1.2/spec.html)。

## 測試規格範例
<a name="custom-test-environment-test-spec-example"></a>

 下列範例顯示可在 Device Farm 上執行的測試規格。

------
#### [ Simple Demo ]

 以下是僅記錄`Hello world!`為測試執行成品的範例測試規格檔案。

```
version: 0.1

android_test_host: amazon_linux_2
ios_test_host: macos_sequoia

phases:
  install:
    commands:
      # Setup your environment by installing and/or validating software
      - devicefarm-cli use python 3.11
      - python --version

  pre_test:
    commands:
      # Setup your tests by starting background tasks or setting up
      # additional environment variables.
      - OUTPUT_FILE="/tmp/hello.log"

  test:
    commands:
      # Run your tests within this phase.
      - python -c 'print("Hello world!")' &> $OUTPUT_FILE

  post_test:
    commands:
      # Perform any remaining tasks within this phase, such as copying
      # artifacts to the DEVICEFARM_LOG_DIR for upload
      - cp $OUTPUT_FILE $DEVICEFARM_LOG_DIR

artifacts:
  # By default, Device Farm will collect your artifacts from the $DEVICEFARM_LOG_DIR directory.
  - $DEVICEFARM_LOG_DIR
```

------
#### [  Appium Android  ]

 以下是範例測試規格檔案，可設定在 Android 上執行的 Appium Java TestNG 測試。

```
version: 0.1

# The following fields(s) allow you to select which Device Farm test host is used for your test run. 
android_test_host: amazon_linux_2

phases:

  # The install phase contains commands for installing dependencies to run your tests.
  # Certain frequently used dependencies are preinstalled on the test host to accelerate and 
  # simplify your test setup. To find these dependencies, versions supported and additional 
  # software installation please see: 
  # https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environments-hosts-software.html
  install:
    commands:
      # The Appium server is written using Node.js. In order to run your desired version of Appium,
      # you first need to set up a Node.js environment that is compatible with your version of Appium.
      - devicefarm-cli use node 20
      - node --version

      # Use the devicefarm-cli to select a preinstalled major version of Appium.
      - devicefarm-cli use appium 2
      - appium --version

      # The Device Farm service periodically updates the preinstalled Appium versions over time to
      # incorporate the latest minor and patch versions for each major version. If you wish to
      # select a specific version of Appium, you can use NPM to install it.
      # - npm install -g appium@2.19.0

      # When running Android tests with Appium version 2, the uiautomator2 driver is preinstalled using driver 
      # version 2.44.1 for Appium 2.5.1  If you want to install a different version of the driver, 
      # you can use the Appium extension CLI to uninstall the existing uiautomator2 driver
      # and install your desired version:
      # - |-
      #   if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "Android" ];
      #   then
      #     appium driver uninstall uiautomator2;
      #     appium driver install uiautomator2@2.34.0;
      #   fi;

      # Based on Appium framework's recommendation, we recommend setting the Appium server's 
      # base path explicitly for accepting commands. If you prefer the legacy base path of /wd/hub,
      # please set it here. 
      - export APPIUM_BASE_PATH=

      # Use the devicefarm-cli to setup a Java environment, with which you can run your test suite.
      - devicefarm-cli use java 17
      - java -version

  # The pre-test phase contains commands for setting up your test environment.
  pre_test:
    commands:
      # Setup the CLASSPATH so that Java knows where to find your test classes.
      - export CLASSPATH=$CLASSPATH:$DEVICEFARM_TEST_PACKAGE_PATH/*
      - export CLASSPATH=$CLASSPATH:$DEVICEFARM_TEST_PACKAGE_PATH/dependency-jars/*

      # We recommend starting the Appium server process in the background using the command below.
      # The Appium server log will be written to the $DEVICEFARM_LOG_DIR directory.
      # The environment variables passed as capabilities to the server will be automatically assigned
      # during your test run based on your test's specific device.
      # For more information about which environment variables are set and how they're set, please see
      # https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environment-variables.html
      - |-
        appium --base-path=$APPIUM_BASE_PATH --log-timestamp \
          --log-no-colors --relaxed-security --default-capabilities \
          "{\"appium:deviceName\": \"$DEVICEFARM_DEVICE_NAME\", \
          \"platformName\": \"$DEVICEFARM_DEVICE_PLATFORM_NAME\", \
          \"appium:udid\":\"$DEVICEFARM_DEVICE_UDID\", \
          \"appium:platformVersion\": \"$DEVICEFARM_DEVICE_OS_VERSION\", \
          \"appium:chromedriverExecutableDir\": \"$DEVICEFARM_CHROMEDRIVER_EXECUTABLE_DIR\", \
          \"appium:automationName\": \"UiAutomator2\"}" \
          >> $DEVICEFARM_LOG_DIR/appium.log 2>&1 &;

      # This code snippet is to wait until the Appium server starts.
      - |-
        appium_initialization_time=0;
        until curl --silent --fail "http://0.0.0.0:4723${APPIUM_BASE_PATH}/status"; do
          if [[ $appium_initialization_time -gt 30 ]]; then
            echo "Appium did not start within 30 seconds. Exiting...";
            exit 1;
          fi;
          appium_initialization_time=$((appium_initialization_time + 1));
          echo "Waiting for Appium to start on port 4723...";
          sleep 1;
        done;

  # The test phase contains commands for running your tests.
  test:
    commands:
      # Your test package is downloaded and unpackaged into the $DEVICEFARM_TEST_PACKAGE_PATH directory.
      - echo "Navigate to test package directory"
      - cd $DEVICEFARM_TEST_PACKAGE_PATH
      - echo "Starting the Appium TestNG test"

      # The following command runs your Appium Java TestNG test.
      # For more information, please see TestNG's documentation here:
      # https://testng.org/#_running_testng
      - |-
        java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar \
          -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

      # To run your tests with a testng.xml file that is a part of your test package, 
      # use the following commands instead:

      # - echo "Unzipping the tests JAR file"
      # - unzip *-tests.jar
      # - |-
      #   java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar \
      #     testng.xml -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

  # The post-test phase contains commands that are run after your tests have completed.
  # If you need to run any commands to generating logs and reports on how your test performed,
  # we recommend adding them to this section.
  post_test:
    commands:

# Artifacts are a list of paths on the filesystem where you can store test output and reports.
# All files in these paths will be collected by Device Farm, with certain limits (see limit details
# here: https://docs.aws.amazon.com/devicefarm/latest/developerguide/limits.html#file-limits).
# These files will be available through the ListArtifacts API as your "Customer Artifacts".
artifacts:
  # By default, Device Farm will collect your artifacts from the $DEVICEFARM_LOG_DIR directory.
  - $DEVICEFARM_LOG_DIR
```

------
#### [  Appium iOS  ]

 以下是測試規格檔案範例，可設定在 iOS 上執行的 Appium Java TestNG 測試。

```
version: 0.1

# The following fields(s) allow you to select which Device Farm test host is used for your test run. 
ios_test_host: macos_sequoia

phases:

  # The install phase contains commands for installing dependencies to run your tests.
  # Certain frequently used dependencies are preinstalled on the test host to accelerate and 
  # simplify your test setup. To find these dependencies, versions supported and additional 
  # software installation please see: 
  # https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environments-hosts-software.html
  install:
    commands:
      # The Appium server is written using Node.js. In order to run your desired version of Appium,
      # you first need to set up a Node.js environment that is compatible with your version of Appium.
      - devicefarm-cli use node 20
      - node --version

      # Use the devicefarm-cli to select a preinstalled major version of Appium.
      - devicefarm-cli use appium 2
      - appium --version

      # The Device Farm service periodically updates the preinstalled Appium versions over time to
      # incorporate the latest minor and patch versions for each major version. If you wish to
      # select a specific version of Appium, you can use NPM to install it.
      # - npm install -g appium@2.19.0

      # When running iOS tests with Appium version 2, the XCUITest driver is preinstalled using driver 
      # version 9.10.5 for Appium 2.5.4. If you want to install a different version of the driver,
      # you can use the Appium extension CLI to uninstall the existing XCUITest driver
      # and install your desired version:
      # - |-
      #   if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "iOS" ];
      #   then
      #     appium driver uninstall xcuitest;
      #     appium driver install xcuitest@10.0.0;
      #   fi;

      # Based on Appium framework's recommendation, we recommend setting the Appium server's 
      # base path explicitly for accepting commands. If you prefer the legacy base path of /wd/hub,
      # please set it here. 
      - export APPIUM_BASE_PATH=

      # Use the devicefarm-cli to setup a Java environment, with which you can run your test suite.
      - devicefarm-cli use java 17
      - java -version

  # The pre-test phase contains commands for setting up your test environment.
  pre_test:
    commands:
      # Setup the CLASSPATH so that Java knows where to find your test classes.
      - export CLASSPATH=$CLASSPATH:$DEVICEFARM_TEST_PACKAGE_PATH/*
      - export CLASSPATH=$CLASSPATH:$DEVICEFARM_TEST_PACKAGE_PATH/dependency-jars/*

      # Device Farm provides multiple pre-built versions of WebDriverAgent (WDA), a required 
      # Appium dependency for iOS, where each version corresponds to the XCUITest driver version selected. 
      # If Device Farm cannot find a corresponding version of WDA for your XCUITest driver, 
      # the latest available version is selected by default.
      - |-
        APPIUM_DRIVER_VERSION=$(appium driver list --installed --json | jq -r ".xcuitest.version" | cut -d "." -f 1);
        CORRESPONDING_APPIUM_WDA=$(env | grep "DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V${APPIUM_DRIVER_VERSION}")
        if [[ ! -z "$APPIUM_DRIVER_VERSION" ]] && [[ ! -z "$CORRESPONDING_APPIUM_WDA" ]]; then
          echo "Using Device Farm's prebuilt WDA version ${APPIUM_DRIVER_VERSION}.x, which corresponds with your driver";
          DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH=$(echo $CORRESPONDING_APPIUM_WDA | cut -d "=" -f2)
        else
          LATEST_SUPPORTED_WDA_VERSION=$(env | grep "DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V" | sort -V -r | head -n 1)
          echo "Unknown driver version $APPIUM_DRIVER_VERSION; falling back to the Device Farm default version of $LATEST_SUPPORTED_WDA_VERSION";
          DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH=$(echo $LATEST_SUPPORTED_WDA_VERSION | cut -d "=" -f2)
        fi;

      # For iOS versions 16 and below only, the device unique identifier (UDID) needs to modified for Appium tests
      # on Device Farm to remove the hypens.
      - |-
        if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "iOS" ]; then
          DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$DEVICEFARM_DEVICE_UDID;
          if [ $(echo $DEVICEFARM_DEVICE_OS_VERSION | cut -d "." -f 1) -le 16 ]; then
            DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$(echo $DEVICEFARM_DEVICE_UDID | tr -d "-");
          fi;
        fi;

      # We recommend starting the Appium server process in the background using the command below.
      # The Appium server log will be written to the $DEVICEFARM_LOG_DIR directory.
      # The environment variables passed as capabilities to the server will be automatically assigned
      # during your test run based on your test's specific device.
      # For more information about which environment variables are set and how they're set, please see
      # https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environment-variables.html
      - |-
        appium --base-path=$APPIUM_BASE_PATH --log-timestamp \
          --log-no-colors --relaxed-security --default-capabilities \
          "{\"appium:deviceName\": \"$DEVICEFARM_DEVICE_NAME\", \
          \"platformName\": \"$DEVICEFARM_DEVICE_PLATFORM_NAME\", \
          \"appium:app\": \"$DEVICEFARM_APP_PATH\", \
          \"appium:udid\":\"$DEVICEFARM_DEVICE_UDID_FOR_APPIUM\", \
          \"appium:platformVersion\": \"$DEVICEFARM_DEVICE_OS_VERSION\", \
          \"appium:derivedDataPath\": \"$DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH\", \
          \"appium:usePrebuiltWDA\": true, \
          \"appium:automationName\": \"XCUITest\"}" \
          >> $DEVICEFARM_LOG_DIR/appium.log 2>&1 &

      # This code snippet is to wait until the Appium server starts.
      - |-
        appium_initialization_time=0;
        until curl --silent --fail "http://0.0.0.0:4723${APPIUM_BASE_PATH}/status"; do
          if [[ $appium_initialization_time -gt 30 ]]; then
            echo "Appium did not start within 30 seconds. Exiting...";
            exit 1;
          fi;
          appium_initialization_time=$((appium_initialization_time + 1));
          echo "Waiting for Appium to start on port 4723...";
          sleep 1;
        done;

  # The test phase contains commands for running your tests.
  test:
    commands:
      # Your test package is downloaded and unpackaged into the $DEVICEFARM_TEST_PACKAGE_PATH directory.
      - echo "Navigate to test package directory"
      - cd $DEVICEFARM_TEST_PACKAGE_PATH
      - echo "Starting the Appium TestNG test"

      # The following command runs your Appium Java TestNG test.
      # For more information, please see TestNG's documentation here:
      # https://testng.org/#_running_testng
      - |-
        java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar \
          -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

      # To run your tests with a testng.xml file that is a part of your test package, 
      # use the following commands instead:

      # - echo "Unzipping the tests JAR file"
      # - unzip *-tests.jar
      # - |-
      #   java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar \
      #     testng.xml -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

  # The post-test phase contains commands that are run after your tests have completed.
  # If you need to run any commands to generating logs and reports on how your test performed,
  # we recommend adding them to this section.
  post_test:
    commands:

# Artifacts are a list of paths on the filesystem where you can store test output and reports.
# All files in these paths will be collected by Device Farm, with certain limits (see limit details
# here: https://docs.aws.amazon.com/devicefarm/latest/developerguide/limits.html#file-limits).
# These files will be available through the ListArtifacts API as your "Customer Artifacts".
artifacts:
  # By default, Device Farm will collect your artifacts from the $DEVICEFARM_LOG_DIR directory.
  - $DEVICEFARM_LOG_DIR
```

------
#### [ Appium (Both Platforms) ]

 以下是測試規格檔案範例，可設定在 Android 和 iOS 上執行的 Appium Java TestNG 測試。

```
version: 0.1

# The following fields(s) allow you to select which Device Farm test host is used for your test run. 
android_test_host: amazon_linux_2
ios_test_host: macos_sequoia

phases:

  # The install phase contains commands for installing dependencies to run your tests.
  # Certain frequently used dependencies are preinstalled on the test host to accelerate and 
  # simplify your test setup. To find these dependencies, versions supported and additional 
  # software installation please see: 
  # https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environments-hosts-software.html
  install:
    commands:
      # The Appium server is written using Node.js. In order to run your desired version of Appium,
      # you first need to set up a Node.js environment that is compatible with your version of Appium.
      - devicefarm-cli use node 20
      - node --version

      # Use the devicefarm-cli to select a preinstalled major version of Appium.
      - devicefarm-cli use appium 2
      - appium --version

      # The Device Farm service periodically updates the preinstalled Appium versions over time to
      # incorporate the latest minor and patch versions for each major version. If you wish to
      # select a specific version of Appium, you can use NPM to install it.
      # - npm install -g appium@2.19.0

      # When running Android tests with Appium version 2, the uiautomator2 driver is preinstalled using driver 
      # version 2.44.1 for Appium 2.5.1  If you want to install a different version of the driver, 
      # you can use the Appium extension CLI to uninstall the existing uiautomator2 driver
      # and install your desired version:
      # - |-
      #   if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "Android" ];
      #   then
      #     appium driver uninstall uiautomator2;
      #     appium driver install uiautomator2@2.34.0;
      #   fi;

      # When running iOS tests with Appium version 2, the XCUITest driver is preinstalled using driver 
      # version 9.10.5 for Appium 2.5.4. If you want to install a different version of the driver,
      # you can use the Appium extension CLI to uninstall the existing XCUITest driver
      # and install your desired version:
      # - |-
      #   if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "iOS" ];
      #   then
      #     appium driver uninstall xcuitest;
      #     appium driver install xcuitest@10.0.0;
      #   fi;

      # Based on Appium framework's recommendation, we recommend setting the Appium server's 
      # base path explicitly for accepting commands. If you prefer the legacy base path of /wd/hub,
      # please set it here. 
      - export APPIUM_BASE_PATH=

      # Use the devicefarm-cli to setup a Java environment, with which you can run your test suite.
      - devicefarm-cli use java 17
      - java -version

  # The pre-test phase contains commands for setting up your test environment.
  pre_test:
    commands:
      # Setup the CLASSPATH so that Java knows where to find your test classes.
      - export CLASSPATH=$CLASSPATH:$DEVICEFARM_TEST_PACKAGE_PATH/*
      - export CLASSPATH=$CLASSPATH:$DEVICEFARM_TEST_PACKAGE_PATH/dependency-jars/*

      # Device Farm provides multiple pre-built versions of WebDriverAgent (WDA), a required 
      # Appium dependency for iOS, where each version corresponds to the XCUITest driver version selected. 
      # If Device Farm cannot find a corresponding version of WDA for your XCUITest driver, 
      # the latest available version is selected by default.
      - |-
        if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "iOS" ]; then
          APPIUM_DRIVER_VERSION=$(appium driver list --installed --json | jq -r ".xcuitest.version" | cut -d "." -f 1);
          CORRESPONDING_APPIUM_WDA=$(env | grep "DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V${APPIUM_DRIVER_VERSION}")
          if [[ ! -z "$APPIUM_DRIVER_VERSION" ]] && [[ ! -z "$CORRESPONDING_APPIUM_WDA" ]]; then
            echo "Using Device Farm's prebuilt WDA version ${APPIUM_DRIVER_VERSION}.x, which corresponds with your driver";
            DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH=$(echo $CORRESPONDING_APPIUM_WDA | cut -d "=" -f2)
          else
            LATEST_SUPPORTED_WDA_VERSION=$(env | grep "DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V" | sort -V -r | head -n 1)
            echo "Unknown driver version $APPIUM_DRIVER_VERSION; falling back to the Device Farm default version of $LATEST_SUPPORTED_WDA_VERSION";
            DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH=$(echo $LATEST_SUPPORTED_WDA_VERSION | cut -d "=" -f2)
          fi;
        fi;

      # For iOS versions 16 and below only, the device unique identifier (UDID) needs to modified for Appium tests
      # on Device Farm to remove the hypens.
      - |-
        if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "iOS" ]; then
          DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$DEVICEFARM_DEVICE_UDID;
          if [ $(echo $DEVICEFARM_DEVICE_OS_VERSION | cut -d "." -f 1) -le 16 ]; then
            DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$(echo $DEVICEFARM_DEVICE_UDID | tr -d "-");
          fi;
        fi;

      # We recommend starting the Appium server process in the background using the command below.
      # The Appium server log will be written to the $DEVICEFARM_LOG_DIR directory.
      # The environment variables passed as capabilities to the server will be automatically assigned
      # during your test run based on your test's specific device.
      # For more information about which environment variables are set and how they're set, please see
      # https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environment-variables.html
      - |-
        if [ $DEVICEFARM_DEVICE_PLATFORM_NAME = "Android" ]; then
          appium --base-path=$APPIUM_BASE_PATH --log-timestamp \
            --log-no-colors --relaxed-security --default-capabilities \
            "{\"appium:deviceName\": \"$DEVICEFARM_DEVICE_NAME\", \
            \"platformName\": \"$DEVICEFARM_DEVICE_PLATFORM_NAME\", \
            \"appium:udid\":\"$DEVICEFARM_DEVICE_UDID\", \
            \"appium:platformVersion\": \"$DEVICEFARM_DEVICE_OS_VERSION\", \
            \"appium:chromedriverExecutableDir\": \"$DEVICEFARM_CHROMEDRIVER_EXECUTABLE_DIR\", \
            \"appium:automationName\": \"UiAutomator2\"}" \
            >> $DEVICEFARM_LOG_DIR/appium.log 2>&1 &
        else
          appium --base-path=$APPIUM_BASE_PATH --log-timestamp \
            --log-no-colors --relaxed-security --default-capabilities \
            "{\"appium:deviceName\": \"$DEVICEFARM_DEVICE_NAME\", \
            \"platformName\": \"$DEVICEFARM_DEVICE_PLATFORM_NAME\", \
            \"appium:udid\":\"$DEVICEFARM_DEVICE_UDID_FOR_APPIUM\", \
            \"appium:platformVersion\": \"$DEVICEFARM_DEVICE_OS_VERSION\", \
            \"appium:derivedDataPath\": \"$DEVICEFARM_WDA_DERIVED_DATA_PATH\", \
            \"appium:usePrebuiltWDA\": true, \
            \"appium:automationName\": \"XCUITest\"}" \
            >> $DEVICEFARM_LOG_DIR/appium.log 2>&1 &
        fi;

      # This code snippet is to wait until the Appium server starts.
      - |-
        appium_initialization_time=0;
        until curl --silent --fail "http://0.0.0.0:4723${APPIUM_BASE_PATH}/status"; do
          if [[ $appium_initialization_time -gt 30 ]]; then
            echo "Appium did not start within 30 seconds. Exiting...";
            exit 1;
          fi;
          appium_initialization_time=$((appium_initialization_time + 1));
          echo "Waiting for Appium to start on port 4723...";
          sleep 1;
        done;

  # The test phase contains commands for running your tests.
  test:
    commands:
      # Your test package is downloaded and unpackaged into the $DEVICEFARM_TEST_PACKAGE_PATH directory.
      - echo "Navigate to test package directory"
      - cd $DEVICEFARM_TEST_PACKAGE_PATH
      - echo "Starting the Appium TestNG test"

      # The following command runs your Appium Java TestNG test.
      # For more information, please see TestNG's documentation here:
      # https://testng.org/#_running_testng
      - |-
        java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar \
          -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

      # To run your tests with a testng.xml file that is a part of your test package, 
      # use the following commands instead:

      # - echo "Unzipping the tests JAR file"
      # - unzip *-tests.jar
      # - |-
      #   java -Dappium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar \
      #     testng.xml -d $DEVICEFARM_LOG_DIR/test-output -verbose 10

  # The post-test phase contains commands that are run after your tests have completed.
  # If you need to run any commands to generating logs and reports on how your test performed,
  # we recommend adding them to this section.
  post_test:
    commands:

# Artifacts are a list of paths on the filesystem where you can store test output and reports.
# All files in these paths will be collected by Device Farm, with certain limits (see limit details
# here: https://docs.aws.amazon.com/devicefarm/latest/developerguide/limits.html#file-limits).
# These files will be available through the ListArtifacts API as your "Customer Artifacts".
artifacts:
  # By default, Device Farm will collect your artifacts from the $DEVICEFARM_LOG_DIR directory.
  - $DEVICEFARM_LOG_DIR
```

------

# 自訂測試環境的主機
<a name="custom-test-environments-hosts"></a>

 Device Farm 透過使用測試主機環境，支援一組具有預先設定軟體的作業系統。在測試執行期間，Device Farm 會利用 Amazon 受管執行個體 （主機），以動態方式連線至待測的所選裝置。此執行個體會在執行之間完全清除且不重複使用，並在測試執行結束後以其產生的成品終止。

**Topics**
+ [適用於自訂測試環境的測試主機](#custom-test-environments-hosts-available)
+ [選取自訂測試環境的測試主機](#test-host-selection)
+ [自訂測試環境中支援的軟體](custom-test-environments-hosts-software.md)
+ [Android 裝置的測試環境](custom-test-environments-hosts-android.md)
+ [iOS 裝置的測試環境](custom-test-environments-hosts-ios.md)

## 適用於自訂測試環境的測試主機
<a name="custom-test-environments-hosts-available"></a>

 測試主機完全由 Device Farm 管理。下表列出適用於自訂測試環境的目前可用和支援的 Device Farm 測試主機。


| 裝置平台 | 測試主機 | 作業系統 | Architecture(s) | 支援的裝置 | 
| --- | --- | --- | --- | --- | 
|  Android  |  amazon\$1linux\$12  |  Amazon Linux 2  |  x86\$164  |  Android 6 及更高版本  | 
|  iOS  |  macos\$1sequoia  |  macOS Sequoia （版本 15)  |  arm64  |  iOS 15 到 26  | 

**注意**  
Device Farm 會定期為裝置平台新增測試主機，以支援較新的裝置作業系統版本及其相依性。發生這種情況時，個別裝置平台的較舊測試主機會終止支援。

### 作業系統版本
<a name="test-host-os"></a>

 每個可用的測試主機都會使用 Device Farm 當時支援的特定作業系統版本。雖然我們嘗試使用最新的作業系統版本，但這可能不是最新的公開分散式版本。Device Farm 會定期使用次要版本更新和安全性修補程式來更新作業系統。

 若要了解測試執行期間使用之作業系統的特定版本 （包括次要版本），您可以將下列程式碼片段新增至任何測試規格檔案的階段。

**Example**  

```
phases:
  install:
    commands:
      # The following example prints the instance's operating system version details
      - |-
        if [[ "Darwin" == "$(uname)" ]]; then
          echo "$(sw_vers --productName) $(sw_vers --productVersion) ($(sw_vers --buildVersion))";
        else
          echo "$(. /etc/os-release && echo $PRETTY_NAME) ($(uname -r))";
        fi
```

## 選取自訂測試環境的測試主機
<a name="test-host-selection"></a>

 您可以在測試規格檔案的適當 `android_test_host`和 `ios_test_host`變數中指定 Android 和 iOS 測試主機。 [測試規格語法](custom-test-environment-test-spec.md#custom-test-environment-test-spec-syntax)

 如果您未為指定的裝置平台指定測試主機選擇，則測試將在 Device Farm 已設定為指定裝置和測試組態預設值的測試主機上執行。

**重要**  
在 iOS 18 及更低版本上測試時，若未選取主機，則會使用舊版測試主機。如需詳細資訊，請參閱 上的 主題[舊版 iOS 測試主機](custom-test-environments-hosts-ios.md#legacy-ios-host)。

 舉例來說，請檢閱下列程式碼片段：

**Example**  

```
version: 0.1
android_test_host: amazon_linux_2
ios_test_host: macos_sequoia

phases:
  # ...
```

# 自訂測試環境中支援的軟體
<a name="custom-test-environments-hosts-software"></a>

 Device Farm 使用預先安裝許多必要軟體程式庫的主機機器來執行我們服務支援的測試架構，在啟動時提供準備好的測試環境。Device Farm 透過使用我們的軟體選擇機制支援多種語言，並定期更新環境中包含的語言版本。

如需任何其他必要的軟體，您可以修改測試規格檔案，以從測試套件安裝、從網際網路下載，或存取 VPC 中的私有來源 （如需詳細資訊，請參閱 [VPC ENI](https://docs.aws.amazon.com//devicefarm/latest/developerguide/vpc-eni.html))。如需詳細資訊，請參閱[測試規格範例](custom-test-environment-test-spec.md#custom-test-environment-test-spec-example)。

## 預先設定的軟體
<a name="custom-test-environments-hosts-software-configured"></a>

 為了在每個平台上促進裝置測試，測試主機上提供下列工具：


| 工具 | 裝置平台 (s) | 
| --- | --- | 
|   Android SDK Build-Tools   |   Android   | 
|   Android SDK Platform-Tools （包括 `adb`)   |   Android   | 
|   Xcode   |   iOS   | 

## 可選取的軟體
<a name="custom-test-environments-hosts-software-selection"></a>

 除了主機上的預先設定軟體之外，Device Farm 還提供一種方法，透過 `devicefarm-cli`工具選取特定版本的支援軟體。

 下表包含可選取的軟體和包含這些軟體的測試主機。


| 軟體/工具 | 支援此軟體的主機 | 要在測試規格中使用的命令 | 
| --- | --- | --- | 
|   Java 17   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use java 17`   | 
|   Java 11   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use java 11`   | 
|   Java 8   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use java 8`   | 
|   Node.js 20   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use node 20`   | 
|   Node.js 18   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use node 18`   | 
|   Node.js 16   |   amazon\$1linux\$12   |   `devicefarm-cli use node 16`   | 
|   Python 3.11   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use python 3.11`   | 
|   Python 3.10   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use python 3.10`   | 
|   Python 3.9   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use python 3.9`   | 
|   Python 3.8   |   amazon\$1linux\$12   |   `devicefarm-cli use python 3.8`   | 
|   Ruby 3.2   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use ruby 3.2`   | 
|   Ruby 2.7   |   amazon\$1linux\$12   |   `devicefarm-cli use ruby 2.7`   | 
|   Appium 3   |   amazon\$1linux\$12   |   `devicefarm-cli use appium 3`   | 
|   Appium 2   |   amazon\$1linux\$12   macos\$1sequoia   |   `devicefarm-cli use appium 2`   | 
|   Appium 1   |   amazon\$1linux\$12   |   `devicefarm-cli use appium 1`   | 
|   Xcode 26   |   macos\$1sequoia   |   `devicefarm-cli use xcode 26`   | 
|   Xcode 16   |   macos\$1sequoia   |   `devicefarm-cli use xcode 16`   | 

測試主機也包含每個軟體版本的常用支援工具，例如 `pip`和 `npm`套件管理員 （分別包含在 Python 和 Node.js 中），以及 Appium 等工具的相依性 （例如 Appium UIAutomator2 驅動程式）。這可確保您擁有使用支援的測試架構所需的工具。

# 在自訂測試環境中使用 devicefarm-cli 工具
<a name="custom-test-environments-hosts-software-cli"></a>

測試主機使用稱為 的標準化版本管理工具` devicefarm-cli`來選取軟體版本。此工具與 分開， AWS CLI 僅適用於 Device Farm 測試主機。使用 `devicefarm-cli`，您可以在測試主機上切換到任何預先安裝的軟體版本。這可讓您直接維護 Device Farm 測試規格檔案一段時間，並為您提供可預測的機制，讓您在未來升級軟體版本。

**重要**  
 此命令列工具不適用於舊版 iOS 主機。如需詳細資訊，請參閱 上的 主題[舊版 iOS 測試主機](custom-test-environments-hosts-ios.md#legacy-ios-host)。

以下程式碼片段顯示 的`help`頁面`devicefarm-cli`：

```
$ devicefarm-cli help
 Usage: devicefarm-cli COMMAND [ARGS]
     
     Commands:
         help                         Prints this usage message.
         list                         Lists all versions of software configurable
                                      via this CLI.
         use <software> <version>     Configures the software for usage within the
                                      current shell's environment.
```

讓我們使用 來檢閱幾個範例`devicefarm-cli`。若要使用 工具將測試規格檔案中的 Python 版本從 *3.10* 變更為 *3.9*，請執行下列命令：

```
$ python --version
Python 3.10.12
$ devicefarm-cli use python 3.9
$ python --version
Python 3.9.17
```

若要將 Appium 版本從 *1* 變更為 *2*：

```
$ appium --version
1.22.3
$ devicefarm-cli use appium 2
$ appium --version
2.1.2
```

**提示**  
請注意，當您選取軟體版本時， `devicefarm-cli`也會切換這些語言的支援工具，例如`pip`適用於 Python 和`npm`適用於 NodeJS 的工具。

如需測試主機上預先安裝軟體的詳細資訊，請參閱 [自訂測試環境中支援的軟體](custom-test-environments-hosts-software.md)。

# Android 裝置的測試環境
<a name="custom-test-environments-hosts-android"></a>

AWS Device Farm 利用執行 Amazon Linux 2 的 Amazon Elastic Compute Cloud (EC2) 主機機器來執行 Android 測試。當您排程測試執行時，Device Farm 會為每個裝置配置專用主機，以獨立執行測試。主機機器會在測試執行後與任何產生的成品一起終止。

Amazon Linux 2 主機提供數種優點：
+ **更快、更可靠的測試**：相較於舊版主機，新的測試主機可大幅改善測試速度，尤其是縮短測試開始時間。Amazon Linux 2 主機也會在測試期間展現更高的穩定性和可靠性。
+ 用於**手動測試的增強型遠端存取**：升級至最新的測試主機和改進功能，可降低 Android 手動測試的延遲並改善影片效能。
+ **標準軟體版本選擇**：Device Farm 現在會在測試主機和 Appium 架構版本上標準化主要程式設計語言支援。對於支援的語言 （目前為 Java、Python、Node.js 和 Ruby) 和 Appium，新的測試主機會在啟動後立即提供長期穩定的版本。透過 `devicefarm-cli`工具的集中式版本管理，可讓測試規格檔案開發具有跨架構的一致體驗。

**Topics**
+ [Device Farm 中 Amazon Linux 2 測試環境支援的 IP 範圍](amazon-linux-2-ip-ranges.md)

# Device Farm 中 Amazon Linux 2 測試環境支援的 IP 範圍
<a name="amazon-linux-2-ip-ranges"></a>

客戶通常需要知道 Device Farm 流量來源的 IP 範圍，特別是在設定其防火牆和安全設定時。對於 Amazon EC2 測試主機，IP 範圍包含整個`us-west-2`區域。對於 Amazon Linux 2 測試主機，這是新 Android 執行的預設選項，範圍已受到限制。流量現在來自一組特定的 NAT 閘道，將 IP 範圍限制為下列地址：


****  

| IP 範圍 | 
| --- | 
|  **44.236.137.143**  | 
|  **52.13.151.244**  | 
|  **52.35.189.191**  | 
|  **54.201.250.26**  | 

如需 Device Farm 中 Android 測試環境的詳細資訊，請參閱 [Android 裝置的測試環境](custom-test-environments-hosts-android.md)。

# iOS 裝置的測試環境
<a name="custom-test-environments-hosts-ios"></a>

 Device Farm 利用在測試執行期間動態連線至 iOS 裝置的 Amazon 受管 macOS 執行個體 （主機）。每個主機都已預先設定軟體，可在各種熱門測試平台上進行裝置測試，例如 XCTestUI 和 Appium。

 相較於舊版，iOS 測試主機目前的反覆運算已改善測試體驗，包括：
+  iOS **15 到 iOS 26 的一致主機作業系統和工具體驗 ** 在此之前，測試主機是由使用中的裝置決定，導致在多個 iOS 版本上執行時產生分段的軟體環境。目前的體驗允許簡單的主機選擇，以跨裝置啟用一致的環境。這將使相同的 macOS 版本和工具 （例如 Xcode) 可在每個 iOS 裝置中使用。
+  ** iOS 15 和 16 測試的效能改善 ** 透過更新的基礎設施，iOS 15 和 16 測試的設定時間已大幅改善。
+  ** 受支援相依性的標準化可選取軟體版本 ** 現在在 iOS 和 Android 測試主機上都有`devicefarm-cli`軟體選擇系統，可讓您選取我們支援的相依性的偏好版本。對於支援的相依性 （例如 Java、Python、Node.js、Ruby 和 Appium)，可以透過測試規格選取版本。如需此功能運作方式的概念，請參閱 上的 主題[自訂測試環境中支援的軟體](custom-test-environments-hosts-software.md)。

**重要**  
 如果在 iOS 18 及以下版本上執行，您的測試預設會在舊版測試主機上執行。請參閱以下主題，了解如何從舊版主機遷移。

## 舊版 iOS 測試主機
<a name="legacy-ios-host"></a>

 對於 iOS 18 及以下版本的現有測試，預設會針對自訂測試環境選取舊版測試主機。下表包含由 iOS 裝置版本使用 執行的測試主機版本。


| 作業系統 | Architecture(s) | 裝置的預設 | 
| --- | --- | --- | 
|  macOS Sonoma （第 14 版）  |  arm64  |  iOS 18  | 
|  macOS Ventura （第 13 版） |  arm64  |  iOS 17  | 
|  macOS Monterey （第 12 版） |  x86\$164  |  iOS 16 和以下 | 

 若要選取較新的測試主機，請參閱有關 的主題[將自訂測試環境遷移至新的 iOS 測試主機](ios-host-migration.md)。

## iOS 裝置支援的 軟體
<a name="ios-host-software-support"></a>

 為了支援 iOS 裝置測試，iOS 裝置的 Device Farm 測試主機會預先設定 Xcode 及其相關聯的命令列工具。如需其他可用的軟體，請檢閱有關 的主題[自訂測試環境中支援的軟體](custom-test-environments-hosts-software.md)。

# 將自訂測試環境遷移至新的 iOS 測試主機
<a name="ios-host-migration"></a>

 若要將現有測試從舊版主機遷移到新的 macOS 測試主機，您需要根據現有的測試規格檔案來開發新的測試規格檔案。

 建議的方法是從所需測試類型的範例測試規格檔案開始，然後將相關命令從舊測試規格檔案遷移至新的測試規格檔案。這可讓您利用新主機範例測試規格的新功能和最佳化，同時重複使用現有程式碼片段。

**Topics**
+ [教學課程：使用主控台遷移 iOS 測試規格檔案](#ios-host-migration-console-tutorial)
+ [新測試主機和舊版測試主機之間的差異](#ios-host-migration-differences)

## 教學課程：使用主控台遷移 iOS 測試規格檔案
<a name="ios-host-migration-console-tutorial"></a>

 在此範例中，Device Farm 主控台將用於加入現有的 iOS 裝置測試規格，以使用新的測試主機。

### 步驟 1：使用主控台建立新的測試規格檔案
<a name="ios-host-migration-console-tutorial-step1"></a>

1. 登入 [AWS Device Farm 主控台](https://console.aws.amazon.com/devicefarm)。

1. 導覽至包含自動化測試的 Device Farm 專案。

1. 下載您要加入的現有測試規格副本。

   1. 按一下「專案設定」選項，然後導覽至**上傳**索引標籤。

   1. 導覽至您要加入的測試規格檔案。

   1. 按一下**下載**按鈕來製作此檔案的本機副本。

1. 導覽回專案頁面，然後按一下**建立執行**。

1. 在精靈上填寫選項，就好像您要開始新的執行一樣，但在**選取測試規格**選項中停止。

1. 使用預設選取的 iOS 測試規格，按一下**建立測試規格**按鈕。

1. 修改文字編輯器中*預設*選取的測試規格。

   1.  如果尚未存在，請使用下列方式修改測試規格檔案以選取新的主機：

      ```
      ios_test_host: macos_sequoia
      ```

   1. 從上一個步驟中下載的測試規格副本中，檢閱每個 ` phase`。

   1.  從舊測試規格的階段將命令複製到新測試規格中的每個個別階段，忽略與安裝或選取 Java、Python、Node.js、Ruby、Appium 或 Xcode 相關的命令。

1.  在**另存**為文字方塊中輸入新的檔案名稱。

1.  按一下**另存新**檔按鈕以儲存變更。

 如需可用作參考的測試規格檔案範例，請參閱 中提供的範例[測試規格範例](custom-test-environment-test-spec.md#custom-test-environment-test-spec-example)。

### 步驟 2：選取軟體預先安裝的軟體
<a name="ios-host-migration-console-tutorial-step2"></a>

 在新的測試主機中，會使用稱為 的新標準化版本管理工具來選取預先安裝的軟體版本`devicefarm-cli`。此工具現在是使用我們在測試主機上提供的各種軟體的建議方法。

 例如，您可以新增以下行來使用不同的 JDK 17 您的測試環境：

```
- devicefarm-cli use java 17
```

 如需可用軟體的詳細資訊，請參閱：[自訂測試環境中支援的軟體](custom-test-environments-hosts-software.md)。

### 步驟 3：透過軟體選取工具使用 Appium 及其相依性
<a name="ios-host-migration-console-tutorial-step3"></a>

 新的測試主機僅支援 Appium 2.x 及更高版本。請使用 明確選取 Appium 版本`devicefarm-cli`，同時移除舊版工具，例如 ` avm`。例如：

```
# This line using 'avm' should be removed
# - avm 2.3.1

# And the following lines should be added
- devicefarm-cli use appium 2 # Selects the version
- appium --version            # Prints the version
```

搭配 選取的 Appium 版本`devicefarm-cli`已預先安裝適用於 iOS 的相容 XCUITest 驅動程式版本。

 此外，您將需要更新您的測試規格以使用 ，` DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V9`而非 ` DEVICEFARM_WDA_DERIVED_DATA_PATH`。新的環境變數指向預先建置的 WebDriverAgent 9.x 版本，這是 Appium 2 測試的最新支援版本。

如需詳細資訊，請檢閱 [為 iOS 測試選取 WebDriverAgent 版本](test-types-appium.md#test-types-appium-select-wda)和 [Appium 測試的環境變數](custom-test-environment-variables.md#custom-test-environment-variables-appium)。

## 新測試主機和舊版測試主機之間的差異
<a name="ios-host-migration-differences"></a>

 當您編輯測試規格檔案以使用新的 iOS 測試主機，並從舊版測試主機轉換測試時，請注意下列主要環境差異：
+  ** Xcode 版本：**在舊版測試主機環境中，可用的 Xcode 版本是以用於測試的裝置 iOS 版本為基礎。例如，在 iOS 18 裝置上的測試在舊版主機中使用 Xcode 16，而在 iOS 17 上的測試則使用 Xcode 15。在新的主機環境中，所有裝置都可以存取相同版本的 Xcode，允許在具有不同版本的裝置上進行測試的一致環境。如需目前可用的 Xcode 版本清單，請參閱 [支援的軟體](custom-test-environments-hosts-software.md)。
+  ** 選取軟體版本：**在許多執行個體中，預設軟體版本已變更，因此如果您之前沒有在舊版測試主機中明確選取軟體版本，建議您現在使用 在新的測試主機中指定它[`devicefarm-cli`](custom-test-environments-hosts-software-cli.md)。在絕大多數的使用案例中，我們建議客戶明確選取其使用的軟體版本。透過使用 選取軟體版本`devicefarm-cli`，您將擁有可預測且一致的使用體驗，並在 Device Farm 計劃從測試主機移除該版本時收到大量警告。

   此外，`rvm`已移除 `nvm`、` avm`、 `pyenv`和 等軟體選取工具，以支持新的` devicefarm-cli`軟體選取系統。
+  ** 可用的軟體版本：**已移除許多先前預先安裝的軟體版本，並已新增許多新版本。因此，請務必在使用 `devicefarm-cli` 選取軟體版本時，選取[支援版本清單中的版本](custom-test-environments-hosts-software.md)。
+  ** 已移除 工具`libimobiledevice`套件**，以使用較新的/第一方工具來追蹤目前的 iOS 裝置測試和業界標準。對於 iOS 17 及更高版本，您可以遷移大多數命令來使用類似的 Xcode 工具，稱為 `devicectl`。如需 的資訊`devicectl`，您可以從已安裝 Xcode 的`xcrun devicectl help`機器執行 。
+  在舊版主機測試規格檔案中以絕對**路徑硬式編碼的檔案**路徑，很可能無法如預期在新的測試主機中運作，而且通常不建議用於測試規格檔案。建議您對所有測試規格檔案程式碼使用相對路徑和環境變數。如需詳細資訊，請參閱 上的 主題[自訂測試環境執行的最佳實務](custom-test-environments-best-practices.md)。
+  ** 作業系統版本和架構：**舊版測試主機根據指派的裝置使用各種 macOS 版本和 CPU 架構。因此，使用者可能會在環境中可用的系統程式庫中注意到一些差異。如需舊版主機作業系統的詳細資訊，請參閱 [舊版 iOS 測試主機](custom-test-environments-hosts-ios.md#legacy-ios-host)。
+  **對於 Appium** 使用者，選取 WebDriverAgent 的方式已變更為使用環境變數字首` DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V`，而不是舊字` DEVICEFARM_WDA_DERIVED_DATA_PATH_V`首。如需更新變數的詳細資訊，請檢閱 [Appium 測試的環境變數](custom-test-environment-variables.md#custom-test-environment-variables-appium)。
+  **對於 Appium Java** 使用者，新的測試主機在其類別路徑中不包含任何預先安裝的 JAR 檔案，而先前的主機包含一個用於 TestNG 架構的 JAR 檔案 （透過環境變數 `$DEVICEFARM_TESTNG_JAR`)。我們建議客戶在其測試套件中封裝其測試架構所需的 JAR 檔案，並從其測試規格檔案中移除 `$DEVICEFARM_TESTNG_JAR`變數的執行個體。

 如果您對測試主機與軟體之間的差異有任何意見回饋或問題，我們建議您透過支援案例與服務團隊聯絡。

# 使用 IAM 執行角色存取 AWS 資源
<a name="custom-test-environments-iam-roles"></a>

 Device Farm 支援指定由自訂測試執行期環境在測試執行期間擔任的 IAM 角色。此功能可讓您的測試安全地存取帳戶中的 AWS 資源，例如 Amazon S3 儲存貯體、DynamoDB 資料表或應用程式依賴的其他 AWS 服務。

**Topics**
+ [概觀](#iam-execution-role-overview)
+ [IAM 角色需求](#iam-role-requirements)
+ [設定 IAM 執行角色](#configuring-iam-execution-role)
+ [最佳實務](#iam-role-best-practices)
+ [疑難排解](#troubleshooting-iam-roles)

## 概觀
<a name="iam-execution-role-overview"></a>

 當您指定 IAM 執行角色時，Device Farm 會在測試執行期間擔任此角色，讓您的測試使用角色中定義的許可與 AWS 服務互動。

 IAM 執行角色的常見使用案例包括：
+ 存取存放在 Amazon S3 儲存貯體中的測試資料
+ 將測試成品推送至 Amazon S3 儲存貯體
+ 從 AWS AppConfig 擷取應用程式組態
+ 將測試日誌和指標寫入 Amazon CloudWatch
+ 將測試結果或狀態訊息傳送至 Amazon SQS 佇列
+ 在測試工作流程中呼叫 AWS Lambda 函數

## IAM 角色需求
<a name="iam-role-requirements"></a>

 若要搭配 Device Farm 使用 IAM 執行角色，您的角色必須符合下列要求：
+ **信任關係**：必須信任 Device Farm 服務主體才能擔任該角色。信任政策必須包含 `devicefarm.amazonaws.com`做為信任的實體。
+ **許可**：該角色必須具備必要的許可，才能存取您的測試所需的 AWS 資源。
+ **工作階段持續時間**：只要 Device Farm 專案的任務逾時設定，角色的工作階段持續時間上限必須至少為 。根據預設，Device Farm 專案的任務逾時為 150 分鐘，因此您的角色必須支援至少 150 分鐘的工作階段持續時間。
+ **相同的帳戶需求**：IAM 角色必須與用來呼叫 Device Farm 的 AWS 帳戶位於相同的 AWS 帳戶中。不支援跨帳戶角色假設。
+ **PassRole 許可**：呼叫者必須獲授權，才能透過允許對指定執行角色`iam:PassRole`執行動作的政策傳遞 IAM 角色。

### 範例信任政策
<a name="trust-policy-example"></a>

 下列範例顯示允許 Device Farm 擔任執行角色的信任政策。此信任政策應僅連接至您想要與 Device Farm 搭配使用的特定 IAM 角色，而非您帳戶中的其他角色：

**Example**  

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "devicefarm.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

### 許可政策範例
<a name="permissions-policy-example"></a>

 下列範例顯示許可政策，授予測試中常用 AWS 服務的存取權：

**Example**  

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::my-test-bucket",
        "arn:aws:s3:::my-test-bucket/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "appconfig:GetConfiguration",
        "appconfig:StartConfigurationSession"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:log-group:/devicefarm/test-*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "sqs:SendMessage",
        "sqs:GetQueueUrl"
      ],
      "Resource": "arn:aws:sqs:*:*:test-results-*"
    }
  ]
}
```

## 設定 IAM 執行角色
<a name="configuring-iam-execution-role"></a>

 您可以在專案層級或個別測試執行中指定 IAM 執行角色。在專案層級設定時，該專案內的所有執行都會繼承執行角色。在執行中設定的執行角色將取代其父專案上設定的任何 。

 如需設定執行角色的詳細說明，請參閱：
+ [在 AWS Device Farm 中建立專案](how-to-create-project.md) - 在專案層級設定執行角色
+ [在 Device Farm 中建立測試執行](how-to-create-test-run.md) - 用於設定個別執行的執行角色

 您也可以使用 Device Farm API 設定執行角色。如需詳細資訊，請參閱 [Device Farm API 參考](https://docs.aws.amazon.com/devicefarm/latest/APIReference/)。

## 最佳實務
<a name="iam-role-best-practices"></a>

 為 Device Farm 測試設定 IAM 執行角色時，請遵循下列最佳實務：
+ **最低權限原則**：僅授予測試運作所需的最低許可。避免使用過於廣泛的許可，例如`*`動作或資源。
+ **使用資源特定的許可**：盡可能限制特定資源 （例如特定 S3 儲存貯體或 DynamoDB 資料表） 的許可，而不是類型的所有資源。
+ **獨立測試和生產資源**：使用專用測試資源和角色，以避免在測試期間意外影響生產系統。
+ **定期角色檢閱**：定期檢閱和更新執行角色，以確保其仍符合您的測試需求，並遵循安全最佳實務。
+ **使用條件索引鍵**：考慮使用 IAM 條件索引鍵進一步限制何時及如何使用角色。

## 疑難排解
<a name="troubleshooting-iam-roles"></a>

 如果您遇到 IAM 執行角色的問題，請檢查下列項目：
+ **信任關係**：確認角色的信任政策包含 `devicefarm.amazonaws.com`做為信任的服務。
+ **許可**：檢查角色是否具有測試嘗試存取之 AWS 服務的必要許可。
+ **測試日誌**：檢閱測試執行日誌，了解與 AWS API 呼叫或許可拒絕相關的特定錯誤訊息。

# 自訂測試環境的環境變數
<a name="custom-test-environment-variables"></a>

 Device Farm 會動態設定數個環境變數，做為自訂測試環境執行的一部分。

**Topics**
+ [自訂環境變數](#custom-test-environment-variables-custom)
+ [常見環境變數](#custom-test-environment-variables-common)
+ [Appium 測試的環境變數](#custom-test-environment-variables-appium)
+ [XCUITest 測試的環境變數](#custom-test-environment-variables-xcuitest)

## 自訂環境變數
<a name="custom-test-environment-variables-custom"></a>

 Device Farm 支援在測試主機上套用為環境變數的鍵/值對組態。這些可以在 Device Farm 專案上或在執行建立期間設定；在執行上設定的任何變數都會取代其父專案上可能設定的任何變數。適用以下限制：
+ 舊版 iOS 測試主機不支援自訂環境變數。如需詳細資訊，請參閱[舊版 iOS 測試主機](custom-test-environments-hosts-ios.md#legacy-ios-host)。
+ 以 開頭的變數名稱`$DEVICEFARM_`會保留供內部服務使用。
+ 自訂環境變數可能無法用於在測試規格中設定測試主機運算選擇。

## 常見環境變數
<a name="custom-test-environment-variables-common"></a>

 本節說明 Device Farm 中所有測試常見的環境變數。

** `$DEVICEFARM_DEVICE_NAME` **  
 測試執行所在的裝置。它代表裝置的唯一裝置識別符 (UDID)。

** `$DEVICEFARM_DEVICE_UDID` **  
 裝置的唯一識別符。

** `$DEVICEFARM_DEVICE_PLATFORM_NAME` **  
 裝置平台名稱。它是 `Android`或 `iOS`。

** `$DEVICEFARM_DEVICE_OS_VERSION` **  
 裝置作業系統版本。

** `$DEVICEFARM_APP_PATH` **  
 *（行動應用程式測試）*   
 主機上行動應用程式的路徑，測試會在此處執行。此變數在 Web 測試期間無法使用。

** `$DEVICEFARM_LOG_DIR` **  
 儲存客戶日誌、成品和其他所需檔案的預設目錄路徑，以供日後擷取。使用[範例測試規格](custom-test-environment-test-spec.md#custom-test-environment-test-spec-example)，此目錄中的檔案會封存在 ZIP 檔案中，並在測試執行後做為成品提供。

** `$DEVICEFARM_SCREENSHOT_PATH` **  
 在測試執行期間擷取之螢幕擷取畫面的路徑 (若有)。

** `$DEVICEFARM_PROJECT_ARN` **  
 任務父專案的 ARN。

** `$DEVICEFARM_RUN_ARN` **  
 任務父項執行的 ARN。

** `$DEVICEFARM_DEVICE_ARN` **  
 待測裝置的 ARN。

** `$DEVICEFARM_TOTAL_JOBS` **  
 與其父系 Device Farm 執行相關聯的任務總數。

** `$DEVICEFARM_JOB_NUMBER` **  
 此任務在 中的號碼`$DEVICEFARM_TOTAL_JOBS`。例如，執行可能包含 5 個任務，每個任務都有 0 到 4 之間的唯一`$DEVICEFARM_JOB_NUMBER`範圍。

** `$AWS_REGION` **  
 AWS 區域。服務會將此設定為符合待測裝置所在的區域。如有需要，自訂環境變數可以覆寫它。

** `$ANDROID_HOME` **  
 *（僅限 Android)*   
 Android SDK 安裝目錄的路徑。

## Appium 測試的環境變數
<a name="custom-test-environment-variables-appium"></a>

 本節說明 Device Farm 中自訂測試環境中任何 Appium 測試所使用的環境變數。

** `$DEVICEFARM_CHROMEDRIVER_EXECUTABLE_DIR` **  
 *（僅限 Android)*   
 目錄的位置，其中包含在 Appium Web 和混合測試中使用的必要 ChromeDriver 可執行檔。

** `$DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V<N>` **  
 *（僅限 iOS)*   
 建置在 Device Farm 上執行之 WebDriverAgent 版本的衍生資料路徑。變數上的編號將對應至 WebDriverAgent 的主要版本。例如， `DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V9`會指向 9.x 的 WebDriverAgent 版本。如需詳細資訊，請參閱[為 iOS 測試選取 WebDriverAgent 版本](test-types-appium.md#test-types-appium-select-wda)。  
 `$DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V<N>` 環境變數僅存在於非舊版 iOS 主機上。如需詳細資訊，請參閱[舊版 iOS 測試主機](custom-test-environments-hosts-ios.md#legacy-ios-host)。

** `$DEVICEFARM_WDA_DERIVED_DATA_PATH_V9` **  
 *（僅限 iOS，已棄用）*   
 建置在 Device Farm 上執行之 WebDriverAgent 版本的衍生資料路徑。如需替代命名結構`$DEVICEFARM_APPIUM_WDA_DERIVED_DATA_PATH_V<N>`，請參閱 。

## XCUITest 測試的環境變數
<a name="custom-test-environment-variables-xcuitest"></a>

 本節說明 XCUITest 測試在 Device Farm 的自訂測試環境中使用的環境變數。

** `$DEVICEFARM_XCUITESTRUN_FILE` **  
 Device Farm `.xctestun` 檔案的路徑。該檔案是由您的應用程式和測試套件所產生。

** `$DEVICEFARM_DERIVED_DATA_PATH` **  
Device Farm xcodebuild 輸出的預期路徑。

** `$DEVICEFARM_XCTEST_BUILD_DIRECTORY` **  
測試套件檔案之未解壓縮內容的路徑。

# 自訂測試環境執行的最佳實務
<a name="custom-test-environments-best-practices"></a>

 下列主題涵蓋搭配 Device Farm 使用自訂測試執行的建議最佳實務。

**執行組態**
+  盡可能**依賴 Device Farm 受管軟體和 API 功能來執行組態**，而不是透過測試規格檔案中的 shell 命令套用類似的組態。這包括測試主機和裝置的組態，因為這在測試主機和裝置之間將更具永續性和一致性。

   雖然 Device Farm 鼓勵您盡可能地自訂測試規格檔案以執行測試，但隨著更自訂的命令新增至測試規格檔案，測試規格檔案可能會隨著時間而變得難以維護。使用 Device Farm 受管軟體 （透過 中的工具，例如 ` devicefarm-cli`和預設可用工具`$PATH`)，並使用 受管功能 （例如 [https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_ScheduleRunConfiguration.html#devicefarm-Type-ScheduleRunConfiguration-deviceProxy](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_ScheduleRunConfiguration.html#devicefarm-Type-ScheduleRunConfiguration-deviceProxy)請求參數），透過將維護責任轉移到 Device Farm 本身來簡化測試規格檔案。

**測試規格和測試套件程式碼**
+  **請勿使用絕對路徑或依賴測試規格檔案或測試套件程式碼中的特定次要版本**。Device Farm 會將例行更新套用至選取的測試主機及其包含的軟體版本。使用特定或絕對路徑 （例如 ` /usr/local/bin/python` 而非 `python`) 或需要特定次要版本 （例如 Node.js `20.3.1` 而非僅 ` 20`) 可能會導致您的測試找不到所需的可執行檔 / 檔案。

   作為自訂測試執行的一部分，Device Farm 會設定各種環境變數和 `$PATH`變數，以確保測試在我們的動態環境中具有一致的體驗。如需詳細資訊，請參閱 [自訂測試環境的環境變數](custom-test-environment-variables.md) 和 [自訂測試環境中支援的軟體](custom-test-environments-hosts-software.md)。
+  **在測試執行期間，將產生的或複製的檔案儲存在暫存目錄中。 **今天，我們確保使用者在測試執行期間可以存取臨時目錄 (`/tmp`) （除了受管目錄之外，例如 `$DEVICEFARM_LOG_DIR`)。由於服務或使用中的作業系統的需求，使用者可存取的其他目錄可能會隨著時間而變更。
+  **將您的測試執行日誌儲存至 `$DEVICEFARM_LOG_DIR`**。這是為您的執行提供的預設成品目錄，用於新增執行日誌/成品。我們提供的[測試規格範例](custom-test-environment-test-spec.md#custom-test-environment-test-spec-example)預設會使用此目錄做為成品。
+  **確保您的命令在測試規格的 階段期間失敗時傳回非零代碼**。 `test`我們會檢查`test`階段期間叫用的每個 shell 命令是否有非零的結束碼，以判斷您的執行是否失敗。您應該確保邏輯或測試架構會傳回所有所需案例的非零結束程式碼，這可能需要額外的組態。

   例如，某些測試架構 （例如 JUnit5) 不會將零測試執行視為失敗，這會導致偵測到您的測試已成功執行，即使未執行任何測試也一樣。使用 JUnit5 作為範例，您需要指定命令列選項`--fail-if-no-tests`，以確保此案例以非零的結束代碼結束。
+  **檢閱軟體與您將用於測試執行的裝置作業系統版本和測試主機版本的相容性**。例如，在測試軟體架構 （即 Appium) 中，有些功能可能無法在所測試裝置的所有作業系統版本上如預期般運作。

**安全**
+  ** 避免在測試規格檔案中存放或記錄敏感變數 （例如 AWS 金鑰）。 **測試規格檔案、測試規格產生的指令碼和測試規格指令碼的日誌都會在測試執行結束時以可下載成品的形式提供。這可能會導致帳戶中具有測試執行讀取存取權的其他使用者秘密意外暴露。

# 將測試從標準遷移至自訂測試環境
<a name="custom-test-environment-migration"></a>

您可以從標準測試執行模式切換到 AWS Device Farm 中的自訂執行模式。遷移主要涉及兩種不同的執行形式：

1. **標準模式**：此測試執行模式主要是為了為客戶提供精細的報告和全受管環境。

1. **自訂模式**：此測試執行模式適用於需要更快速執行測試、能夠提升和轉移並實現與其本機環境同位，以及即時影片串流的不同使用案例。

如需 Device Farm 中標準和自訂模式的詳細資訊，請參閱 [在 AWS Device Farm 中測試環境](test-environments.md)和 [AWS Device Farm 中的自訂測試環境](custom-test-environments.md)。

## 移轉時的考量
<a name="considerations-when-migrating"></a>

本節列出遷移至自訂模式時要考慮的一些重要使用案例：

1. **速度**：在標準執行模式中，Device Farm 會使用特定架構的封裝指示，剖析您已封裝和上傳之測試的中繼資料。剖析會偵測套件中的測試數量。之後，Device Farm 會個別執行每個測試，並針對每個測試個別顯示日誌、影片和其他結果成品。不過，這會穩定地新增end-to-end測試執行總時間，因為服務端有測試和結果成品的預處理和後處理。

   相反地，自訂執行模式不會剖析您的測試套件；這表示測試或結果成品沒有預先處理和最少的後製處理。這會導致end-to-end執行時間總計接近您的本機設定。測試的執行格式與在本機機器上執行相同 （與它們相同）。測試結果與您從本機取得的結果相同，可在任務執行結束時下載。

1. **自訂或彈性**：標準執行模式會剖析您的測試套件，以偵測測試數量，然後分別執行每個測試。請注意，無法保證測試將按照您指定的順序執行。因此，需要特定執行序列的測試可能無法如預期般運作。此外，無法自訂主機環境或傳遞可能需要的組態檔案，以特定方式執行測試。

   相反地，自訂模式可讓您設定主機機器環境，包括安裝其他軟體、將篩選條件傳遞至測試、傳遞組態檔案，以及控制測試執行設定。它透過 yaml 檔案 （也稱為 testpec 檔案） 達成此目的，您可以將 shell 命令新增至該檔案。此 yaml 檔案會轉換為在測試主機機器上執行的 shell 指令碼。您可以儲存多個 yaml 檔案，並在排程執行時根據您的需求動態選擇一個。

1. **即時影片和記錄**：標準和自訂執行模式都為您提供測試的影片和日誌。不過，在標準模式中，只有在測試完成後，您才會取得測試的影片和預先定義日誌。

   相反地，自訂模式可讓您即時串流測試的視訊和用戶端日誌。此外，您可以在測試結束時 （測試） 下載影片和其他成品。

**提示**  
如果您的使用案例至少涉及上述其中一個因素，強烈建議切換到自訂執行模式。

## 移轉步驟
<a name="migrating-to-custom"></a>

若要從標準遷移到自訂模式，請執行下列動作：

1. 登入 AWS 管理主控台 並開啟 Device Farm 主控台，網址為 https：//[https://console.aws.amazon.com/devicefarm/](https://console.aws.amazon.com/devicefarm/)。

1. 選擇您的專案，然後啟動新的自動化執行。

1. 上傳您的應用程式 （或選取 `web app`)、選擇您的測試架構類型、上傳您的測試套件，然後在 `Choose your execution environment` 參數下選擇 選項。 `Run your test in a custom environment`

1. 根據預設，Device Farm 的範例測試規格檔案會顯示供您檢視和編輯。此範例檔案可以用作在[自訂環境模式下](https://docs.aws.amazon.com/devicefarm/latest/developerguide/custom-test-environments.html)試用測試的起點。然後，一旦從主控台驗證測試是否正常運作，您就可以變更任何與 Device Farm 的 API、CLI 和管道整合，以在排程測試執行時使用此測試規格檔案做為參數。如需有關如何新增測試規格檔案做為執行參數的資訊，請參閱 API [指南](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_ScheduleRun.html)中的 `ScheduleRun` API `testSpecArn` 參數區段。

## Appium 架構
<a name="custom-test-environment-migration-appium"></a>

在自訂測試環境中，Device Farm 不會插入或覆寫 Appium 架構測試中的任何 Appium 功能。您必須以測試規格 YAML 檔案或測試程式碼指定您測試的 Appium 功能。

## Android 檢測
<a name="custom-test-environment-migration-instrumentation"></a>

您不需要進行任何變更，就可將您的 Android 檢測測試移動到自訂測試環境。

## iOS XCUITest
<a name="custom-test-environment-migration-xcuitest"></a>

您不需要進行任何變更，就可將您的 iOS XCUITest 測試移動到自訂測試環境。

# 在 Device Farm 中擴展自訂測試環境
<a name="custom-test-environments-extending"></a>

AWS Device Farm 啟用設定自訂環境以進行自動測試 （自訂模式），這是所有 Device Farm 使用者的建議方法。Device Farm 自訂模式可讓您執行的不只是測試套件。在本節中，您將了解如何擴展測試套件並最佳化測試。

如需 Device Farm 中自訂測試環境的詳細資訊，請參閱 [AWS Device Farm 中的自訂測試環境](custom-test-environments.md)。

**Topics**
+ [在 Device Farm 中執行測試時設定裝置 PIN](custom-test-environments-extending-set-pin.md)
+ [透過所需的功能加速 Device Farm 中的 Appium 型測試](custom-test-environments-extending-speed.md)
+ [在 Device Farm 中執行測試後，使用 Webhooks APIs](custom-test-environments-extending-webhooks.md)
+ [在 Device Farm 中將額外檔案新增至您的測試套件](custom-test-environments-extending-files.md)

# 在 Device Farm 中執行測試時設定裝置 PIN
<a name="custom-test-environments-extending-set-pin"></a>

 有些應用程式會要求您在裝置上設定 PIN 碼。Device Farm 不支援在原生裝置上設定 PIN。不過，以下警告是可行的：
+ 裝置必須執行 Android 8 或更新版本。
+ 測試完成後，必須移除 PIN 碼。

 若要在測試中設定 PIN，請使用 `pre_test`和 `post_test`階段來設定和移除 PIN，如下所示：

```
phases:
    pre_test:
      - # ... among your pre_test commands
      - DEVICE_PIN_CODE="1234"
      - adb shell locksettings set-pin "$DEVICE_PIN_CODE"
    post_test:
      - # ... Among your post_test commands
      - adb shell locksettings clear --old "$DEVICE_PIN_CODE"
```

 當您的測試套件開始時，會設定 PIN 1234。測試套件結束之後，將會移除 PIN 碼。

**警告**  
如果您在測試完成後沒有從裝置中移除 PIN，裝置和您的帳戶將會隔離。

如需擴展測試套件和最佳化測試的更多方法，請參閱 [在 Device Farm 中擴展自訂測試環境](custom-test-environments-extending.md)。

# 透過所需的功能加速 Device Farm 中的 Appium 型測試
<a name="custom-test-environments-extending-speed"></a>

使用 Appium 時，您可能會發現標準模式測試套件非常慢。這是因為 Device Farm 會套用預設設定，而且不會對您想要如何使用 Appium 環境做出任何假設。雖然這些預設值是以產業最佳實務為基礎建置，但可能不適用於您的情況。若要微調 Appium 伺服器的參數，您可以調整測試規格中的預設 Appium 功能。例如，以下將 iOS 測試套件`true`中的 `usePrebuildWDA`功能設定為 ，以加快初始開始時間：

```
phases:
  pre_test:
    - # ... Start up Appium
    - >-
    appium --log-timestamp
    --default-capabilities "{\"usePrebuiltWDA\": true, \"derivedDataPath\":\"$DEVICEFARM_WDA_DERIVED_DATA_PATH\",
    \"deviceName\": \"$DEVICEFARM_DEVICE_NAME\", \"platformName\":\"$DEVICEFARM_DEVICE_PLATFORM_NAME\", \"app\":\"$DEVICEFARM_APP_PATH\",
    \"automationName\":\"XCUITest\", \"udid\":\"$DEVICEFARM_DEVICE_UDID_FOR_APPIUM\", \"platformVersion\":\"$DEVICEFARM_DEVICE_OS_VERSION\"}"
    >> $DEVICEFARM_LOG_DIR/appiumlog.txt 2>&1 &
```

Appium 功能必須是殼層逸出的 JSON 結構。

下列 Appium 功能是效能改善的常見來源：

`noReset` 和 `fullReset`  
這兩個功能是互斥的，描述每個工作階段完成後 Appium 的行為。當 `noReset` 設為 時`true`，Appium 伺服器不會在 Appium 工作階段結束時從您的應用程式移除資料，實際上不會進行任何清理。 會在工作階段關閉後從裝置`fullReset`解除安裝並清除所有應用程式資料。如需詳細資訊，請參閱 Appium 文件中的[重設策略](http://appium.io/docs/en/writing-running-appium/other/reset-strategies/)。

`ignoreUnimportantViews` （僅限 Android)  
指示 Appium 僅將 Android UI 階層壓縮至測試*的相關*檢視，以加速特定元素查詢。不過，這可能會破壞某些以 XPath 為基礎的測試套件，因為 UI 配置的階層已變更。

`skipUnlock` （僅限 Android)  
通知 Appium 目前未設定 PIN 碼，這會加速螢幕關閉事件或其他鎖定事件之後的測試。

`webDriverAgentUrl` （僅限 iOS)  
指示 Appium 假設基本 iOS 相依性 已在執行`webDriverAgent`中，並可用於在指定的 URL 接受 HTTP 請求。如果 `webDriverAgent` 尚未啟動並執行，則在測試套件開始時，Appium 可能需要一些時間才能啟動 `webDriverAgent`。如果您在啟動 Appium `http://localhost:8100`時`webDriverAgent`自行啟動並將 `webDriverAgentUrl`設定為 ，您可以更快地啟動測試套件。請注意，此功能不應與 `useNewWDA` 功能搭配使用。  
您可以使用下列程式碼`webDriverAgent`從裝置本機連接埠 上的測試規格檔案開始`8100`，然後將其轉送至測試主機的本機連接埠 `8100`（這可讓您將 `webDriverAgentUrl`的值設定為 `http://localhost:8100`)。在定義任何用於設定 Appium 和`webDriverAgent`環境變數的程式碼之後，應該在安裝階段執行此程式碼：  

```
      # Start WebDriverAgent and iProxy
      - >-
        xcodebuild test-without-building -project /usr/local/avm/versions/$APPIUM_VERSION/node_modules/appium/node_modules/appium-webdriveragent/WebDriverAgent.xcodeproj
        -scheme WebDriverAgentRunner -derivedDataPath $DEVICEFARM_WDA_DERIVED_DATA_PATH
        -destination id=$DEVICEFARM_DEVICE_UDID_FOR_APPIUM IPHONEOS_DEPLOYMENT_TARGET=$DEVICEFARM_DEVICE_OS_VERSION
        GCC_TREAT_WARNINGS_AS_ERRORS=0 COMPILER_INDEX_STORE_ENABLE=NO >> $DEVICEFARM_LOG_DIR/webdriveragent_log.txt 2>&1 &
        
        iproxy 8100 8100 >> $DEVICEFARM_LOG_DIR/iproxy_log.txt 2>&1 &
```
然後，您可以將下列程式碼新增至您的測試規格檔案，以確保 成功`webDriverAgent`啟動。在確保 Appium 成功啟動之後，應該在測試前階段結束時執行此程式碼：  

```
      # Wait for WebDriverAgent to start
      - >-
        start_wda_timeout=0;
        while [ true ];
        do
          if [ $start_wda_timeout -gt 60 ];
          then
              echo "WebDriverAgent server never started in 60 seconds.";
              exit 1;
          fi;
          grep -i "ServerURLHere" $DEVICEFARM_LOG_DIR/webdriveragent_log.txt >> /dev/null 2>&1;
          if [ $? -eq 0 ];
          then
              echo "WebDriverAgent REST http interface listener started";
              break;
          else
              echo "Waiting for WebDriverAgent server to start. Sleeping for 1 seconds";
              sleep 1;
              start_wda_timeout=$((start_wda_timeout+1));
          fi;
        done;
```

如需 Appium 支援功能的詳細資訊，請參閱 [Appium 文件中的 Appium 預期功能](http://appium.io/docs/en/writing-running-appium/caps/)。

如需擴展測試套件和最佳化測試的更多方法，請參閱 [在 Device Farm 中擴展自訂測試環境](custom-test-environments-extending.md)。

# 在 Device Farm 中執行測試後，使用 Webhooks APIs
<a name="custom-test-environments-extending-webhooks"></a>

您可以在每個測試套件使用 完成後，讓 Device Farm 呼叫 Webhook**curl**。執行此操作的程序會因目的地和格式而異。如需特定 Webhook，請參閱該 Webhook 的文件。下列範例會在測試套件完成時發佈訊息至 Slack Webhook：

```
phases:
  post_test:
    - curl -X POST -H 'Content-type: application/json' --data '{"text":"Tests on '$DEVICEFARM_DEVICE_NAME' have finished!"}' https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
```

如需搭配 Slack 使用 Webhook 的詳細資訊，請參閱 [Slack API 參考中的使用 Webhook 傳送您的第一個 Slack 訊息](https://api.slack.com/tutorials/slack-apps-hello-world)。

如需擴展測試套件和最佳化測試的更多方法，請參閱 [在 Device Farm 中擴展自訂測試環境](custom-test-environments-extending.md)。

您並非僅限於使用 **curl** 呼叫 Webhook。測試套件可以包含額外的指令碼和工具，只要它們與 Device Farm 執行環境相容。例如，您的測試套件可能包含向其他 APIs輔助指令碼。請確定任何必要的套件都與您的測試套件需求一起安裝。若要新增測試套件完成後執行的指令碼，請在測試套件中包含指令碼，並將下列項目新增至您的測試規格：

```
phases:
  post_test:
    - python post_test.py
```

**注意**  
維護測試套件中使用的任何 API 金鑰或其他身分驗證字符是您的責任。我們建議您將任何形式的安全登入資料保留在來源控制之外、盡可能使用最低權限的登入資料，以及盡可能使用可撤銷的短期權杖。若要驗證安全需求，請參閱您使用的第三方 APIs 文件。

如果您打算使用 AWS 服務做為測試執行套件的一部分，您應該使用測試套件外部產生的 IAM 臨時憑證，並包含在測試套件中。這些登入資料應具有最短的授予許可和最短的生命週期。如需建立臨時登入資料的詳細資訊，請參閱《*IAM 使用者指南*》中的[請求臨時安全登入](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_credentials_temp_request.html)資料。

如需擴展測試套件和最佳化測試的更多方法，請參閱 [在 Device Farm 中擴展自訂測試環境](custom-test-environments-extending.md)。

# 在 Device Farm 中將額外檔案新增至您的測試套件
<a name="custom-test-environments-extending-files"></a>

您可能想要使用其他檔案做為測試的一部分，無論是額外的組態檔案或其他測試資料。您可以將這些額外的檔案新增至測試套件，然後再上傳至 AWS Device Farm，然後從自訂環境模式存取這些檔案。基本上，所有測試套件上傳格式 (ZIP、IPA、APK、JAR 等） 都是支援標準 ZIP 操作的套件封存格式。

您可以使用 AWS Device Farm 下列命令，在將檔案上傳至 之前，將檔案新增至您的測試封存：

```
$ zip zip-with-dependencies.zip extra_file
```

對於額外檔案的目錄：

```
$ zip -r zip-with-dependencies.zip extra_files/
```

這些命令適用於所有測試套件上傳格式，但 IPA 檔案除外。對於 IPA 檔案，特別是與 XCUITests 搭配使用時，我們建議您將任何額外的檔案放在稍微不同的位置，因為 會 AWS Device Farm 重新簽署 iOS 測試套件。建置 iOS 測試時，測試應用程式目錄將位於另一個名為*承載*的目錄中。

例如，以下是這類 iOS 測試目錄的外觀：

```
$ tree
.
└── Payload
    └── ADFiOSReferenceAppUITests-Runner.app
        ├── ADFiOSReferenceAppUITests-Runner
        ├── Frameworks
        │   ├── XCTAutomationSupport.framework
        │   │   ├── Info.plist
        │   │   ├── XCTAutomationSupport
        │   │   ├── _CodeSignature
        │   │   │   └── CodeResources
        │   │   └── version.plist
        │   └── XCTest.framework
        │       ├── Info.plist
        │       ├── XCTest
        │       ├── _CodeSignature
        │       │   └── CodeResources
        │       ├── en.lproj
        │       │   └── InfoPlist.strings
        │       └── version.plist
        ├── Info.plist
        ├── PkgInfo
        ├── PlugIns
        │   ├── ADFiOSReferenceAppUITests.xctest
        │   │   ├── ADFiOSReferenceAppUITests
        │   │   ├── Info.plist
        │   │   └── _CodeSignature
        │   │       └── CodeResources
        │   └── ADFiOSReferenceAppUITests.xctest.dSYM
        │       └── Contents
        │           ├── Info.plist
        │           └── Resources
        │               └── DWARF
        │                   └── ADFiOSReferenceAppUITests
        ├── _CodeSignature
        │   └── CodeResources
        └── embedded.mobileprovision
```

對於這些 XCUITest 套件，請將任何額外的檔案新增至*承載*目錄內以 .*app* 結尾的目錄。例如，下列命令示範如何將檔案新增至此測試套件：

```
$ mv extra_file Payload/*.app/
$ zip -r my_xcui_tests.ipa Payload/
```

當您將檔案新增至測試套件時，您可以 AWS Device Farm 根據檔案的上傳格式，預期 中的互動行為會略有不同。如果上傳使用 ZIP 副檔名， AWS Device Farm 會在測試之前自動解壓縮上傳，並將解壓縮的檔案保留在具有 *\$1DEVICEFARM\$1TEST\$1PACKAGE\$1PATH* 環境變數的位置。（這表示如果您將名為 *extra\$1file* 的檔案新增至封存的根目錄，如第一個範例所示，它將在測試期間位於 *\$1DEVICEFARM\$1TEST\$1PACKAGE\$1PATH/extra\$1file*)。

若要使用更實用的範例，如果您是 Appium TestNG 使用者，想要在測試中包含 *testng.xml* 檔案，您可以使用下列命令將其包含在封存中：

```
$ zip zip-with-dependencies.zip testng.xml
```

然後，您可以在自訂環境模式中將測試命令變更為下列項目：

```
java -D appium.screenshots.dir=$DEVICEFARM_SCREENSHOT_PATH org.testng.TestNG -testjar *-tests.jar -d $DEVICEFARM_LOG_DIR/test-output $DEVICEFARM_TEST_PACKAGE_PATH/testng.xml
```

如果您的測試套件上傳副檔名不是 ZIP （例如 APK、IPA 或 JAR 檔案），則可在 *\$1DEVICEFARM\$1TEST\$1PACKAGE\$1PATH* 找到上傳的套件檔案本身。由於這些檔案仍然是封存格式檔案，因此您可以解壓縮檔案，以便從內部存取其他檔案。例如，下列命令會將測試套件的內容 （適用於 APK、IPA 或 JAR 檔案） 解壓縮至 */tmp* 目錄：

```
unzip $DEVICEFARM_TEST_PACKAGE_PATH -d /tmp
```

如果是 APK 或 JAR 檔案，您會發現額外的檔案解壓縮到 */tmp* 目錄 （例如 */tmp/extra\$1file*)。對於 IPA 檔案，如前所述，額外的檔案會位於 *.app* 結尾資料夾內的略有不同位置，該資料夾位於*承載*目錄內。例如，根據上述 IPA 範例，檔案會位於位置 */tmp/Payload/ADFiOSReferenceAppUITests-Runner.app/extra\$1file* （參考為 */tmp/Payload/\$1.app/extra\$1file)。*

如需擴展測試套件和最佳化測試的更多方法，請參閱 [在 Device Farm 中擴展自訂測試環境](custom-test-environments-extending.md)。