

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Appium を使用してデバイスを操作する
<a name="appium-endpoint-interaction"></a>

[リモートアクセスセッションを作成する](how-to-create-session.md)と、デバイスは Appium テストに使用できます。リモートアクセスセッションの全期間中、デバイス上で必要な数の Appium セッションを実行できます。使用するクライアントに制限はありません。例えば、まず IDE からローカル Appium コードを使用してテストを実行し、Appium Inspector を使用して発生した問題のトラブルシューティングに切り替えることができます。セッションは最大 [150 分](limits.md#service-limits)かかることがありますが、5 分以上アクティビティがない場合 (インタラクティブコンソールまたは Appium エンドポイント経由）、セッションはタイムアウトします。

## Appium セッションでのテストに Apps を使用する
<a name="appium-endpoint-using-apps"></a>

Device Farm では、リモートアクセスセッションの作成リクエストの一部としてアプリを使用することも、リモートアクセスセッション自体中にアプリをインストールすることもできます (複数可）。これらのアプリはテスト対象のデバイスに自動的にインストールされ、Appium セッションリクエストのデフォルト機能として挿入されます。リモートアクセスセッションを作成するときは、アプリ ARN を渡すオプションがあります。これは、後続のすべての Appium セッションの `appium:app`機能としてデフォルトで使用され、補助アプリ ARNs は `appium:otherApps`機能として使用されます。

例えば、アプリをアプリ`com.aws.devicefarm.sample`として使用し、補助アプリの 1 つ`com.aws.devicefarm.other.sample`としてリモートアクセスセッションを作成する場合、Appium セッションを作成するときに次のような機能があります。

```
{
    "value":
    {
        "sessionId": "abcdef123456-1234-5678-abcd-abcdef123456",
        "capabilities":
        {
            "app": "/tmp/com.aws.devicefarm.sample.apk",
            "otherApps": "[\"/tmp/com.aws.devicefarm.other.sample.apk\"]",
            ...
        }
    }
}
```

セッション中に、追加のアプリをインストールできます (コンソール内または [https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_InstallToRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_InstallToRemoteAccessSession.html) API を使用）。これらは、`appium:app`以前に機能として使用された既存のアプリを上書きします。以前に使用したアプリケーションに個別のパッケージ名がある場合は、デバイス上に残り、 `appium:otherApps`機能の一部として使用されます。

たとえば、最初にリモートアクセスセッションの作成`com.aws.devicefarm.sample`時にアプリを使用し、セッション`com.aws.devicefarm.other.sample`中に という名前の新しいアプリをインストールした場合、Appium セッションには次のような機能があります。

```
{
    "value":
    {
        "sessionId": "abcdef123456-1234-5678-abcd-abcdef123456",
        "capabilities":
        {
            "app": "/tmp/com.aws.devicefarm.other.sample.apk",
            "otherApps": "[\"/tmp/com.aws.devicefarm.sample.apk\"]",
            ...
        }
    }
}
```

必要に応じて、アプリ名を使用してアプリの機能を明示的に指定できます (Android および iOS の `appium:appPackage`または `appium:bundleId`機能をそれぞれ使用）。

ウェブアプリケーションをテストする場合は、Appium セッション作成リクエスト`browserName`の機能を指定します。`Chrome` ブラウザはすべての Android デバイスで使用でき、`Safari`ブラウザはすべての iOS デバイスで使用できます。

Device Farm は、リモートアクセスセッション`appium:app`中に にリモート URL またはローカルファイルシステムパスを渡すことをサポートしていません。Device Farm にアプリケーションをアップロードし、代わりにセッションに含めます。

**注記**  
リモートアクセスセッションの一部としてアプリを自動的にアップロードする方法の詳細については、[「アプリのアップロードの自動化」を参照してください。](api-ref.md#upload-example)

## Appium エンドポイントの使用方法
<a name="appium-endpoint-how-to-use"></a>

コンソール、、 AWS CLIおよび AWS SDKs からセッションの Appium エンドポイントにアクセスする手順は次のとおりです。これらのステップには、さまざまな Appium クライアントテストフレームワークを使用してテストの実行を開始する方法が含まれます。

------
#### [ Console ]

1. ウェブブラウザでリモートアクセスセッションページを開きます。  
![\[\]](http://docs.aws.amazon.com/ja_jp/devicefarm/latest/developerguide/images/aws-device-farm-appium-endpoint.png)

1. Appium Inspector を使用してセッションを実行するには、以下を実行します。

   1. **Appium セッションの設定**ボタンをクリックする

   1. Appium Inspector を使用してセッションを開始する方法については、ページの指示に従ってください。

1. ローカル IDE から Appium テストを実行するには、以下を実行します。

   1. **Appium エンドポイント URL **のテキストの横にある「コピー」アイコンをクリックします。

   1. リモートアドレスまたはコマンドエグゼキュターを現在指定しているローカル Appium コードにこの URL を貼り付けます。言語固有の例については、このサンプルウィンドウのいずれかのタブをクリックして任意の言語を選択してください。

------
#### [ AWS CLI ]

まず、[最新バージョンをダウンロードしてインストールして、AWS CLI のバージョンが](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)up-to-dateであることを確認します。

**重要**  
Appium エンドポイントフィールドは、古いバージョンの AWS CLI では使用できません。

セッションが起動して実行されると、[https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html)API への呼び出しに対するレスポンス`remoteDriverEndpoint`で という名前のフィールドを介して Appium エンドポイント URL が使用可能になります。

```
$ aws devicefarm get-remote-access-session \
    --arn "arn:aws:devicefarm:us-west-2:123456789876:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000"
```

これにより、次のような出力が表示されます。

```
{
    "remoteAccessSession": {
        "arn": "arn:aws:devicefarm:us-west-2:111122223333:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000",
        "name": "Google Pixel 8",
        "status": "RUNNING",
        "endpoints": {
            "remoteDriverEndpoint": "https://devicefarm-interactive-global.us-west-2.api.aws/remote-endpoint/ABCD1234...",
        ...
}
```

この URL は、現在リモートアドレスまたはコマンドエグゼキュターを指定しているローカル Appium コードで使用できます。言語固有の例については、このサンプルウィンドウのいずれかのタブをクリックして任意の言語を選択してください。

コマンドラインから直接エンドポイントを操作する方法の例については、[コマンドラインツール curl ](https://curl.se/)を使用して WebDriver エンドポイントを直接呼び出すことができます。

```
$ curl "https://devicefarm-interactive-global.us-west-2.api.aws/remote-endpoint/ABCD1234.../status"
```

これにより、次のような出力が表示されます。

```
{
    "value":
    {
        "ready": true,
        "message": "The server is ready to accept new connections",
        "build":
        {
            "version": "2.5.1"
        }
    }
}
```

------
#### [ Python ]

セッションが起動して実行されると、[https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html)API への呼び出しに対するレスポンス`remoteDriverEndpoint`で という名前のフィールドを介して Appium エンドポイント URL が使用可能になります。

```
# To get the URL
import sys
import boto3
from botocore.exceptions import ClientError

def get_appium_endpoint() -> str:
    session_arn = "arn:aws:devicefarm:us-west-2:111122223333:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000"
    device_farm_client = boto3.client("devicefarm", region_name="us-west-2")

    try:
        resp = device_farm_client.get_remote_access_session(arn=session_arn)
    except ClientError as exc:
        sys.exit(f"Failed to call Device Farm: {exc}")

    remote_access_session = resp.get("remoteAccessSession", {})
    endpoints = remote_access_session.get("endpoints", {})
    endpoint = endpoints.get("remoteDriverEndpoint")

    if not endpoint:
        sys.exit("Device Farm response did not include endpoints.remoteDriverEndpoint")

    return endpoint

# To use the URL
from appium import webdriver
from appium.options.android import UiAutomator2Options

opts = UiAutomator2Options()
driver = webdriver.Remote(get_appium_endpoint(), options=opts)
# ...
driver.quit()
```

------
#### [ Java ]

*注: この例では AWS SDK for Java v2 を使用し、JDK バージョン 11 以降と互換性があります。*

セッションが起動して実行されると、[https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html)API への呼び出しに対するレスポンス`remoteDriverEndpoint`で という名前のフィールドを介して Appium エンドポイント URL が使用可能になります。

```
// To get the URL
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.devicefarm.DeviceFarmClient;
import software.amazon.awssdk.services.devicefarm.model.GetRemoteAccessSessionRequest;
import software.amazon.awssdk.services.devicefarm.model.GetRemoteAccessSessionResponse;

public class AppiumEndpointBuilder {
    public static String getAppiumEndpoint() throws Exception {
        String session_arn = "arn:aws:devicefarm:us-west-2:111122223333:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000";

        try (DeviceFarmClient client = DeviceFarmClient.builder()
                .region(Region.US_WEST_2)
                .credentialsProvider(DefaultCredentialsProvider.create())
                .build()) {

            GetRemoteAccessSessionResponse resp = client.getRemoteAccessSession(
                    GetRemoteAccessSessionRequest.builder().arn(session_arn).build()
            );

            String endpoint = resp.remoteAccessSession().endpoints().remoteDriverEndpoint();
            if (endpoint == null || endpoint.isEmpty()) {
                throw new IllegalStateException("remoteDriverEndpoint missing from response");
            }
            return endpoint;
        }
    }
}

// To use the URL
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.options.UiAutomator2Options;

import java.net.URL;

public class ExampleTest {
    public static void main(String[] args) throws Exception {
        String endpoint = AppiumEndpointBuilder.getAppiumEndpoint();
        UiAutomator2Options options = new UiAutomator2Options();
        AndroidDriver driver = new AndroidDriver(new URL(endpoint), options);

        try {
            // ... your test ...
        } finally {
            driver.quit();
        }
    }
}
```

------
#### [ JavaScript ]

*注: この例では AWS 、SDK for JavaScript v3 と Node 18\$1 を使用する WebdriverIO v8\$1 を使用しています。*

セッションが起動して実行されると、[https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html)API への呼び出しに対するレスポンス`remoteDriverEndpoint`で という名前のフィールドを介して Appium エンドポイント URL が使用可能になります。

```
// To get the URL
import { DeviceFarmClient, GetRemoteAccessSessionCommand } from "@aws-sdk/client-device-farm";

export async function getAppiumEndpoint() {
  const sessionArn = "arn:aws:devicefarm:us-west-2:111122223333:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000";

  const client = new DeviceFarmClient({ region: "us-west-2" });
  const resp = await client.send(new GetRemoteAccessSessionCommand({ arn: sessionArn }));

  const endpoint = resp?.remoteAccessSession?.endpoints?.remoteDriverEndpoint;
  if (!endpoint) throw new Error("remoteDriverEndpoint missing from response");
  return endpoint;
}

// To use the URL with WebdriverIO
import { remote } from "webdriverio";

(async () => {
  const endpoint = await getAppiumEndpoint();
  const u = new URL(endpoint);

  const driver = await remote({
    protocol: u.protocol.replace(":", ""),
    hostname: u.hostname,
    port: u.port ? Number(u.port) : (u.protocol === "https:" ? 443 : 80),
    path: u.pathname + u.search,
    capabilities: {
      platformName: "Android",
      "appium:automationName": "UiAutomator2",
      // ...other caps...
    },
  });

  try {
    // ... your test ...
  } finally {
    await driver.deleteSession();
  }
})();
```

------
#### [ C\$1 ]

セッションが起動して実行されると、[https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html)API への呼び出しに対するレスポンス`remoteDriverEndpoint`で という名前のフィールドを介して Appium エンドポイント URL が使用可能になります。

```
// To get the URL
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.DeviceFarm;
using Amazon.DeviceFarm.Model;

public static class AppiumEndpointBuilder
{
    public static async Task<string> GetAppiumEndpointAsync()
    {
        var sessionArn = "arn:aws:devicefarm:us-west-2:111122223333:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000";

        var config = new AmazonDeviceFarmConfig
        {
            RegionEndpoint = RegionEndpoint.USWest2
        };
        using var client = new AmazonDeviceFarmClient(config);

        var resp = await client.GetRemoteAccessSessionAsync(new GetRemoteAccessSessionRequest { Arn = sessionArn });
        var endpoint = resp?.RemoteAccessSession?.Endpoints?.RemoteDriverEndpoint;

        if (string.IsNullOrWhiteSpace(endpoint))
            throw new InvalidOperationException("RemoteDriverEndpoint missing from response");

        return endpoint;
    }
}

// To use the URL
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;

class Example
{
    static async Task Main()
    {
        var endpoint = await AppiumEndpointBuilder.GetAppiumEndpointAsync();

        var options = new AppiumOptions();
        options.PlatformName = "Android";
        options.AutomationName = "UiAutomator2";

        using var driver = new AndroidDriver(new Uri(endpoint), options);
        try
        {
            // ... your test ...
        }
        finally
        {
            driver.Quit();
        }
    }
}
```

------
#### [ Ruby ]

セッションが起動して実行されると、[https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_GetRemoteAccessSession.html)API への呼び出しに対するレスポンス`remoteDriverEndpoint`で という名前のフィールドを介して Appium エンドポイント URL が使用可能になります。

```
# To get the URL
require 'aws-sdk-devicefarm'

def get_appium_endpoint
  session_arn = "arn:aws:devicefarm:us-west-2:111122223333:session:abcdef123456-1234-5678-abcd-abcdef123456/abcdef123456-1234-5678-abcd-abcdef123456/00000"

  client = Aws::DeviceFarm::Client.new(region: 'us-west-2')
  resp = client.get_remote_access_session(arn: session_arn)
  endpoint = resp.remote_access_session.endpoints.remote_driver_endpoint
  raise "remote_driver_endpoint missing from response" if endpoint.nil? || endpoint.empty?
  endpoint
end

# To use the URL
require 'appium_lib_core'

endpoint = get_appium_endpoint
opts = {
  server_url: endpoint,
  capabilities: {
    'platformName' => 'Android',
    'appium:automationName' => 'UiAutomator2'
  }
}

driver = Appium::Core.for(opts).start_driver
begin
  # ... your test ...
ensure
  driver.quit
end
```

------