

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

# 教學課程：開發簡單的 IDT 測試套件
<a name="create-custom-tests"></a>

測試套件結合了下列項目：
+ 包含測試邏輯的測試可執行檔
+ 描述測試套件的組態檔案

本教學課程說明如何使用 IDT for AWS IoT Greengrass 來開發包含單一測試案例的 Python 測試套件。在本教學課程中，您將完成下列步驟：

1. [建立測試套件目錄](#test-suite-dir)

1. [建立組態檔案](#test-suite-json)

1. [建立測試案例可執行檔](#test-suite-exe)

1. [執行測試套件](#run-test-suite)

## 先決條件
<a name="prereqs-tutorial-custom"></a><a name="prereqs-list"></a>

為了完成本教學，您需要以下項目：
+ 

**主機電腦需求**
  + 的最新版本 AWS IoT Device Tester
  + [Python](https://www.python.org/downloads/) 3.7 或更新版本

    若要檢查安裝在電腦上的 Python 版本，請執行下列命令：

    ```
    python3 --version
    ```

    在 Windows 上，如果使用此命令傳回錯誤，請`python --version`改用 。如果傳回的版本編號為 3.7 或更新版本，請在 Powershell 終端機中執行下列命令，將 `python3`設定為`python`命令的別名。

    ```
    Set-Alias -Name "python3" -Value "python"
    ```

    如果未傳回版本資訊或版本編號小於 3.7，請遵循[下載 Python](https://wiki.python.org/moin/BeginnersGuide/Download) 中的指示安裝 Python 3.7\$1。如需詳細資訊，請參閱 [Python 文件](https://docs.python.org)。
  + [urllib3](https://urllib3.readthedocs.io/en/latest/)

    若要驗證 `urllib3` 是否正確安裝，請執行下列命令：

    ```
    python3 -c 'import urllib3'
    ```

    如果`urllib3`未安裝 ，請執行下列命令來安裝它：

    ```
    python3 -m pip install urllib3
    ```
+ 

**裝置要求**
  + 具有 Linux 作業系統和與主機電腦相同網路連線的裝置。

    我們建議您將 [Raspberry Pi](https://www.raspberrypi.org/) 與 Raspberry Pi 作業系統搭配使用。請確定您在 Raspberry Pi 上設定 [SSH](https://www.raspberrypi.org/documentation/remote-access/ssh/) 以遠端連線到它。

## 建立測試套件目錄
<a name="test-suite-dir"></a>

IDT 會在邏輯上將測試案例分成每個測試套件內的測試群組。每個測試案例都必須位於測試群組內。在本教學課程中，請建立名為 的資料夾，`MyTestSuite_1.0.0`並在此資料夾中建立下列目錄樹狀目錄：

```
MyTestSuite_1.0.0
└── suite
    └── myTestGroup
        └── myTestCase
```

## 建立組態檔案
<a name="test-suite-json"></a>

您的測試套件必須包含下列必要的[組態檔案](idt-json-config.md)：<a name="required-json"></a>必要的組態檔案

`suite.json`  
包含測試套件的相關資訊。請參閱 [設定 suite.json](idt-json-config.md#suite-json)。

`group.json`  
包含測試群組的相關資訊。您必須為測試套件中的每個測試群組建立`group.json`檔案。請參閱 [設定 group.json](idt-json-config.md#group-json)。

`test.json`  
包含測試案例的相關資訊。您必須為測試套件中的每個測試案例建立`test.json`檔案。請參閱 [設定 test.json](idt-json-config.md#test-json)。

1. 在 `MyTestSuite_1.0.0/suite`資料夾中，建立具有下列結構`suite.json`的檔案：

   ```
   {
       "id": "MyTestSuite_1.0.0",
       "title": "My Test Suite",
       "details": "This is my test suite.",
       "userDataRequired": false
   }
   ```

1. 在 `MyTestSuite_1.0.0/myTestGroup`資料夾中，建立具有下列結構`group.json`的檔案：

   ```
   {
       "id": "MyTestGroup",
       "title": "My Test Group",
       "details": "This is my test group.",
       "optional": false
   }
   ```

1. 在 `MyTestSuite_1.0.0/myTestGroup/myTestCase`資料夾中，建立具有下列結構`test.json`的檔案：

   ```
   {
       "id": "MyTestCase",
       "title": "My Test Case",
       "details": "This is my test case.",
       "execution": {
           "timeout": 300000,
           "linux": {
               "cmd": "python3",
               "args": [
                   "myTestCase.py"
               ]
           },
           "mac": {
               "cmd": "python3",
               "args": [
                   "myTestCase.py"
               ]
           },
           "win": {
               "cmd": "python3",
               "args": [
                   "myTestCase.py"
               ]
           }
       }
   }
   ```

資料夾的目錄樹狀目錄現在`MyTestSuite_1.0.0`看起來應該如下所示：

```
MyTestSuite_1.0.0
└── suite
    ├── suite.json
    └── myTestGroup
        ├── group.json
        └── myTestCase
            └── test.json
```

## 取得 IDT 用戶端 SDK
<a name="add-idt-sdk"></a>

您可以使用 [IDT 用戶端 SDK](create-test-executables.md#idt-client-sdk) 讓 IDT 與待測裝置互動，並報告測試結果。在本教學課程中，您將使用 開發套件的 Python 版本。

從 `<device-tester-extract-location>/sdks/python/` 資料夾，將 `idt_client` 資料夾複製到您的 `MyTestSuite_1.0.0/suite/myTestGroup/myTestCase` 資料夾。

若要確認軟體開發套件已成功複製，請執行下列命令。

```
cd MyTestSuite_1.0.0/suite/myTestGroup/myTestCase
python3 -c 'import idt_client'
```

## 建立測試案例可執行檔
<a name="test-suite-exe"></a>

測試案例可執行檔包含您要執行的測試邏輯。測試套件可以包含多個測試案例可執行檔。在本教學課程中，您只會建立一個測試案例可執行檔。

1. 建立測試套件檔案。

   在 `MyTestSuite_1.0.0/suite/myTestGroup/myTestCase`資料夾中，建立具有下列內容`myTestCase.py`的檔案：

   ```
   from idt_client import *
   
   def main():
       # Use the client SDK to communicate with IDT
       client = Client()
   
   if __name__ == "__main__":
       main()
   ```

1. 使用用戶端 SDK 函數將下列測試邏輯新增至您的 `myTestCase.py` 檔案：

   1. 在待測裝置上執行 SSH 命令。

      ```
      from idt_client import *
      
      def main():
          # Use the client SDK to communicate with IDT
          client = Client()
          
          # Create an execute on device request
          exec_req = ExecuteOnDeviceRequest(ExecuteOnDeviceCommand("echo 'hello world'"))
          
          # Run the command
          exec_resp = client.execute_on_device(exec_req)
          
          # Print the standard output
          print(exec_resp.stdout)
      
      if __name__ == "__main__":
          main()
      ```

   1. 將測試結果傳送至 IDT。

      ```
      from idt_client import *
      
      def main():
          # Use the client SDK to communicate with IDT
          client = Client()
          
          # Create an execute on device request
          exec_req = ExecuteOnDeviceRequest(ExecuteOnDeviceCommand("echo 'hello world'"))
          
          # Run the command
          exec_resp = client.execute_on_device(exec_req)
          
          # Print the standard output
          print(exec_resp.stdout)
      
          # Create a send result request
          sr_req = SendResultRequest(TestResult(passed=True))
           
          # Send the result
          client.send_result(sr_req)
             
      if __name__ == "__main__":
          main()
      ```

## 設定 IDT 的裝置資訊
<a name="configure-idt-sample"></a>

設定您的裝置資訊，讓 IDT 執行測試。您必須使用下列資訊更新位於 `<device-tester-extract-location>/configs` 資料夾的 `device.json` 範本。

```
[
  {
    "id": "pool",
    "sku": "N/A",
    "devices": [
      {
        "id": "<device-id>",
        "connectivity": {
          "protocol": "ssh",
          "ip": "<ip-address>",
          "port": "<port>",
          "auth": {
            "method": "pki | password",
            "credentials": {
              "user": "<user-name>",
              "privKeyPath": "/path/to/private/key",
              "password": "<password>"
            }
          }
        }
      }
    ]
  }
]
```

在 `devices` 物件中，提供下列資訊：

`id`  
您裝置的使用者定義唯一識別符。

`connectivity.ip`  
您裝置的 IP 地址。

`connectivity.port`  
選用。用於裝置 SSH 連線的連接埠號碼。

`connectivity.auth`  
連線的驗證資訊。  
只有當 `connectivity.protocol` 設為 `ssh` 時，才會套用此屬性。    
`connectivity.auth.method`  
用來透過指定的連線通訊協定存取裝置的驗證方法。  
支援的值如下：  
+ `pki`
+ `password`  
`connectivity.auth.credentials`  
用於驗證的燈入資料。    
`connectivity.auth.credentials.user`  
用來登入裝置的使用者名稱。  
`connectivity.auth.credentials.privKeyPath`  
用來登入您裝置之私有金鑰的完整路徑。  
只有當 `connectivity.auth.method` 設為 `pki` 時，才會套用此值。  
`devices.connectivity.auth.credentials.password`  
用於登入您裝置的密碼。  
只有當 `connectivity.auth.method` 設為 `password` 時，才會套用此值。

**注意**  
如果 `method` 是設定為 `pki`，則指定 `privKeyPath`  
如果 `method` 是設定為 `password`，則指定 `password`

## 執行測試套件
<a name="run-test-suite"></a>

建立測試套件之後，您想要確保其如預期般運作。完成下列步驟，以使用您現有的裝置集區執行測試套件。

1. 將您的`MyTestSuite_1.0.0`資料夾複製到 `<device-tester-extract-location>/tests`。

1. 執行下列命令：

   ```
   cd <device-tester-extract-location>/bin
   ./devicetester_[linux | mac | win_x86-64] run-suite --suite-id MyTestSuite
   ```

IDT 會執行您的測試套件，並將結果串流至主控台。當測試完成執行時，您會看到下列資訊：

```
time="2020-10-19T09:24:47-07:00" level=info msg=Using pool: pool
time="2020-10-19T09:24:47-07:00" level=info msg=Using test suite "MyTestSuite_1.0.0" for execution
time="2020-10-19T09:24:47-07:00" level=info msg=b'hello world\n' suiteId=MyTestSuite groupId=myTestGroup testCaseId=myTestCase deviceId=my-device executionId=9a52f362-1227-11eb-86c9-8c8590419f30
time="2020-10-19T09:24:47-07:00" level=info msg=All tests finished. executionId=9a52f362-1227-11eb-86c9-8c8590419f30
time="2020-10-19T09:24:48-07:00" level=info msg=

========== Test Summary ==========
Execution Time:         1s
Tests Completed:        1
Tests Passed:           1
Tests Failed:           0
Tests Skipped:          0
----------------------------------
Test Groups:
    myTestGroup:        PASSED
----------------------------------
Path to IoT Device Tester Report: /path/to/devicetester/results/9a52f362-1227-11eb-86c9-8c8590419f30/awsiotdevicetester_report.xml
Path to Test Execution Logs: /path/to/devicetester/results/9a52f362-1227-11eb-86c9-8c8590419f30/logs
Path to Aggregated JUnit Report: /path/to/devicetester/results/9a52f362-1227-11eb-86c9-8c8590419f30/MyTestSuite_Report.xml
```

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

使用以下資訊來協助解決完成教學課程的任何問題。

**測試案例未成功執行**

如果測試未成功執行，IDT 會將錯誤日誌串流至主控台，以協助您對測試執行進行疑難排解。檢查錯誤日誌之前，請確認下列事項：
+ IDT 用戶端 SDK 位於正確的資料夾中，如[此步驟](#add-idt-sdk)所述。
+ 您符合本教學課程的所有[先決條件](#prereqs-tutorial-custom)。

**無法連線至待測裝置**

請確認下列內容：
+ 您的 `device.json` 檔案包含正確的 IP 地址、連接埠和身分驗證資訊。
+ 您可以從主機電腦透過 SSH 連線至裝置。