編寫分割的 IRemoteTest 測試執行程式

編寫測試執行程式時,請務必考量擴充性。請問自己:「如果測試執行程式必須執行 20 萬個測試案例,需要多久時間?」

資料分割是貿易聯盟提供的解答之一。它需要 將執行器所需的所有測試分成幾個區塊 平行處理

本頁說明如何讓執行程式可供 Tradefed 分割。

要實作的介面

如要讓 TF 將您的模型視為可分割,您必須實作最重要的介面 IShardableTest,其中包含 split(int numShard)split() 這兩種方法。

如果資料分割數量取決於要求的資料分割數量, 應實作 split(int numShard)。否則,請實作 split()

當 TF 測試指令搭配使用區隔參數 --shard-count--shard-index 執行時,TF 會逐一檢查所有 IRemoteTest,尋找實作 IShardableTestIRemoteTest。如果找到,就會呼叫 split 取得新的 IRemoteTest 物件,為特定分割區執行部分測試案例。

關於分割實作,我應該瞭解哪些事項?

  • 您的執行程式只能在某些條件下分割;在這種情況下,如果您未分割,請傳回 null
  • 請盡量多分得: 將跑者分成一根 合理的方式執行程式碼這取決於執行程式。例如:HostTest 是在類別層級進行分割,因此每個測試類別都會放入個別的分割區。
  • 如果可行,請新增一些選項,進一步控制資料分割。 例如:AndroidJUnitTestajur-max-shard,可指定可分割的切片數量上限,無論要求的數量為何。

詳細導入範例

以下是實作 IShardableTest 的程式碼片段範例,供您參考。完整程式碼可在 (https://android.googlesource.com/platform/tools/tradefederation/+/refs/heads/main/test_framework/com/android/tradefed/testtype/InstalledInstrumentationsTest.java) 中找到

/**
 * Runs all instrumentation found on current device.
 */
@OptionClass(alias = "installed-instrumentation")
public class InstalledInstrumentationsTest
        implements IDeviceTest, IResumableTest, IShardableTest {
    ...

    /** {@inheritDoc} */
    @Override
    public Collection<IRemoteTest> split(int shardCountHint) {
        if (shardCountHint > 1) {
            Collection<IRemoteTest> shards = new ArrayList<>(shardCountHint);
            for (int index = 0; index < shardCountHint; index++) {
                shards.add(getTestShard(shardCountHint, index));
            }
            return shards;
        }
        // Nothing to shard
        return null;
    }

    private IRemoteTest getTestShard(int shardCount, int shardIndex) {
        InstalledInstrumentationsTest shard = new InstalledInstrumentationsTest();
        try {
            OptionCopier.copyOptions(this, shard);
        } catch (ConfigurationException e) {
            CLog.e("failed to copy instrumentation options: %s", e.getMessage());
        }
        shard.mShardIndex = shardIndex;
        shard.mTotalShards = shardCount;
        return shard;
    }
    ...
}

這個範例只會建立自身的新例項,並將區塊參數設為該例項。不過,分割邏輯可能與 進行測試;只要確定性不定 即使只有少數幾個子集也沒問題

獨立

分割區必須獨立!在執行程式中實作 split 時建立的兩個區塊,不應彼此依賴或共用資源。

分割區塊必須是確定性的!這也是必要條件,在相同條件下,split 方法應一律傳回完全相同的切片清單,且順序也相同。

注意事項:由於每個資料分割都能在不同的 TF 執行個體上執行,因此請務必 確保 split 邏輯會產生互斥的子集,且 收集完整資料

在本機分割測試

如要在本機 TF 上分割測試,只要在指令列中加入 --shard-count 選項即可。

tf >run host --class com.android.tradefed.UnitTests --shard-count 3

接著,TF 會自動為每個資料分割產生指令,並加以執行。

tf >l i
Command Id  Exec Time  Device          State
3           0m:03      [null-device-2]  running stub on build 0 (shard 1 of 3)
3           0m:03      [null-device-1]  running stub on build 0 (shard 0 of 3)
3           0m:03      [null-device-3]  running stub on build 0 (shard 2 of 3)

測試結果匯總

由於 TF 不會針對分割的叫用作業進行任何測試結果匯總,因此您必須確認報表服務支援這項功能。