Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 13e208cf authored by Atneya Nair's avatar Atneya Nair
Browse files

Add getFutureForIntent

Add helper function which gets a future associated with an intent
broadcast matching a certain action and predicate.

Automatically unregister the listener when the future is completed or
cancelled.

Add unit tests.

Bug: 288333346
Bug: 294636572
Test: atest GetFutureForIntentTest
Change-Id: Ie26487d3f727691d001b3d0392dc0fcdf5b5a2db
parent b9dbeea2
Loading
Loading
Loading
Loading
+5 −1
Original line number Diff line number Diff line
@@ -24,9 +24,13 @@ java_library {

java_library {
    name: "mediatestutils",
    srcs: [
        "java/com/android/media/mediatestutils/TestUtils.java",
    ],
    static_libs: [
        "androidx.concurrent_concurrent-futures",
        "guava",
        "mediatestutils_host",
        "junit",
    ],
    visibility: [
        "//cts/tests/tests/media:__subpackages__",
+7 −0
Original line number Diff line number Diff line
{
  "presubmit": [
    {
      "name": "mediatestutilstests"
    }
  ]
}
+89 −0
Original line number Diff line number Diff line
/*
 * Copyright 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.media.mediatestutils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import androidx.concurrent.futures.CallbackToFutureAdapter;

import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ListenableFuture;

import java.lang.ref.WeakReference;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.Objects;
import java.util.function.Predicate;

/**
 *
 */
public class TestUtils {
    public static final String TAG = "MediaTestUtils";

    public static ListenableFuture<Intent> getFutureForIntent(Context context, String action,
            Predicate<Intent> pred) {
        // These are evaluated async
        Objects.requireNonNull(action);
        Objects.requireNonNull(pred);
        // Doesn't need to be thread safe since the resolver is called inline
        final WeakReference<BroadcastReceiver> wrapper[] = new WeakReference[1];
        ListenableFuture<Intent> future = CallbackToFutureAdapter.getFuture(completer -> {
            var receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    try {
                        if (action.equals(intent.getAction()) && pred.test(intent)) {
                            completer.set(intent);
                        }
                    } catch (Exception e) {
                        completer.setException(e);
                    }
                }
            };
            wrapper[0] = new WeakReference(receiver);
            context.registerReceiver(receiver, new IntentFilter(action),
                    Context.RECEIVER_NOT_EXPORTED);
            return "Intent receiver future for ";
        });
        if (wrapper[0] == null) {
            throw new AssertionError("CallbackToFutureAdapter resolver should be called inline");
        }
        final var weakref = wrapper[0];
        future.addListener(() -> {
            try {
                var recv = weakref.get();
                // If there is no reference left, the receiver has already been unregistered
                if (recv != null) {
                    context.unregisterReceiver(recv);
                    return;
                }
            } catch (IllegalArgumentException e) {
                // Receiver already unregistered, nothing to do.
            }
            Log.d(TAG, "Intent receiver future for action: " + action +
                    "unregistered prior to future completion/cancellation.");
        } , MoreExecutors.directExecutor()); // Direct executor is fine since lightweight
        return future;
    }
}
+22 −0
Original line number Diff line number Diff line
package {
    // See: http://go/android-license-faq
    // A large-scale-change added 'default_applicable_licenses' to import
    // all of the 'license_kinds' from "frameworks_base_license"
    // to get the below license kinds:
    //   SPDX-license-identifier-Apache-2.0
    default_applicable_licenses: ["frameworks_base_license"],
}

android_test {
    name: "mediatestutilstests",
    srcs: ["src/**/*.java"],
    static_libs: [
        "mockito-target-minus-junit4",
        "androidx.test.runner",
        "androidx.test.core",
        "mediatestutils",
        "junit",
        "truth",
    ],
    test_suites: ["general-tests"],
}
+30 −0
Original line number Diff line number Diff line
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2023 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.android.media.mediatestutils">

    <application android:testOnly="false"
                 android:debuggable="true">
        <uses-library android:name="android.test.runner" />
    </application>

    <instrumentation
        android:name="androidx.test.runner.AndroidJUnitRunner"
        android:targetPackage="com.android.media.mediatestutils"
        android:label="mediatestutils tests" />

</manifest>
Loading