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

Commit b567b271 authored by TreeHugger Robot's avatar TreeHugger Robot Committed by Android (Google) Code Review
Browse files

Merge changes I4af0d9ba,Ic1923343

* changes:
  Migrate BugreportReceiverTest to JUnit 4.
  Migrate NetworkPolicyManagerServiceTest to JUnit 4.
parents 60673abf 47ec8beb
Loading
Loading
Loading
Loading
+3 −1
Original line number Diff line number Diff line
@@ -8,7 +8,9 @@ LOCAL_SRC_FILES := $(call all-java-files-under, src)

LOCAL_JAVA_LIBRARIES := android.test.runner

LOCAL_STATIC_JAVA_LIBRARIES := ub-uiautomator
LOCAL_STATIC_JAVA_LIBRARIES := \
    android-support-test \
    ub-uiautomator \

LOCAL_PACKAGE_NAME := ShellTests
LOCAL_INSTRUMENTATION_FOR := Shell
+1 −1
Original line number Diff line number Diff line
@@ -36,7 +36,7 @@
        </activity>
    </application>

    <instrumentation android:name="android.test.InstrumentationTestRunner"
    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
        android:targetPackage="com.android.shell"
        android:label="Tests for Shell" />

+54 −9
Original line number Diff line number Diff line
@@ -36,6 +36,13 @@ import static com.android.shell.BugreportProgressService.INTENT_BUGREPORT_STARTE
import static com.android.shell.BugreportProgressService.POLLING_FREQUENCY;
import static com.android.shell.BugreportProgressService.SCREENSHOT_DELAY_SECONDS;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
@@ -56,6 +63,13 @@ import java.util.zip.ZipOutputStream;

import libcore.io.Streams;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Instrumentation;
@@ -68,11 +82,12 @@ import android.os.Bundle;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.service.notification.StatusBarNotification;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.LargeTest;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.LargeTest;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
@@ -96,7 +111,8 @@ import com.android.shell.ActionSendMultipleConsumerActivity.CustomActionSendMult
 * <strong>NOTE</strong>: these tests only work if the device is unlocked.
 */
@LargeTest
public class BugreportReceiverTest extends InstrumentationTestCase {
@RunWith(AndroidJUnit4.class)
public class BugreportReceiverTest {
    private static final String TAG = "BugreportReceiverTest";

    // Timeout for UI operations, in milliseconds.
@@ -149,9 +165,10 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
    private UiBot mUiBot;
    private CustomActionSendMultipleListener mListener;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    @Rule public TestName mName = new TestName();

    @Before
    public void setUp() throws Exception {
        Log.i(TAG, getName() + ".setup()");
        Instrumentation instrumentation = getInstrumentation();
        mContext = instrumentation.getTargetContext();
@@ -181,13 +198,13 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        mUiBot.turnScreenOn();
    }

    @Override
    protected void tearDown() throws Exception {
    @After
    public void tearDown() throws Exception {
        Log.i(TAG, getName() + ".tearDown()");
        cancelExistingNotifications();
        super.tearDown();
    }

    @Test
    public void testProgress() throws Exception {
        resetProperties();
        sendBugreportStarted(1000);
@@ -233,6 +250,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testProgress_cancel() throws Exception {
        resetProperties();
        sendBugreportStarted(1000);
@@ -249,6 +267,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        waitForService(false);
    }

    @Test
    public void testProgress_takeExtraScreenshot() throws Exception {
        resetProperties();
        sendBugreportStarted(1000);
@@ -267,6 +286,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testScreenshotFinishesAfterBugreport() throws Exception {
        resetProperties();

@@ -286,6 +306,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testProgress_changeDetailsInvalidInput() throws Exception {
        resetProperties();
        sendBugreportStarted(1000);
@@ -331,6 +352,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testProgress_cancelBugClosesDetailsDialog() throws Exception {
        resetProperties();
        sendBugreportStarted(1000);
@@ -346,10 +368,12 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testProgress_changeDetailsPlainBugreport() throws Exception {
        changeDetailsTest(true);
    }

    @Test
    public void testProgress_changeDetailsZippedBugreport() throws Exception {
        changeDetailsTest(false);
    }
@@ -383,10 +407,12 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testProgress_changeJustDetailsTouchingDetails() throws Exception {
        changeJustDetailsTest(true);
    }

    @Test
    public void testProgress_changeJustDetailsTouchingNotification() throws Exception {
        changeJustDetailsTest(false);
    }
@@ -410,6 +436,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testProgress_changeJustDetailsIsClearedOnSecondBugreport() throws Exception {
        resetProperties();
        sendBugreportStarted(ID, PID, NAME, 1000);
@@ -453,6 +480,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
     * Tests the scenario where the initial screenshot and dumpstate are finished while the user
     * is changing the info in the details screen.
     */
    @Test
    public void testProgress_bugreportAndScreenshotFinishedWhileChangingDetails() throws Exception {
        bugreportFinishedWhileChangingDetailsTest(false);
    }
@@ -461,6 +489,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
     * Tests the scenario where dumpstate is finished while the user is changing the info in the
     * details screen, but the initial screenshot finishes afterwards.
     */
    @Test
    public void testProgress_bugreportFinishedWhileChangingDetails() throws Exception {
        bugreportFinishedWhileChangingDetailsTest(true);
    }
@@ -500,14 +529,17 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertServiceNotRunning();
    }

    @Test
    public void testBugreportFinished_withWarningFirstTime() throws Exception {
        bugreportFinishedWithWarningTest(null);
    }

    @Test
    public void testBugreportFinished_withWarningUnknownState() throws Exception {
        bugreportFinishedWithWarningTest(STATE_UNKNOWN);
    }

    @Test
    public void testBugreportFinished_withWarningShowAgain() throws Exception {
        bugreportFinishedWithWarningTest(STATE_SHOW);
    }
@@ -560,6 +592,7 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertEquals("Didn't change state", STATE_HIDE, newState);
    }

    @Test
    public void testShareBugreportAfterServiceDies() throws Exception {
        sendBugreportFinished(NO_ID, mPlainTextPath, NO_SCREENSHOT);
        waitForService(false);
@@ -567,21 +600,25 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        assertActionSendMultiple(extras, BUGREPORT_CONTENT, NO_SCREENSHOT);
    }

    @Test
    public void testBugreportFinished_plainBugreportAndScreenshot() throws Exception {
        Bundle extras = sendBugreportFinishedAndGetSharedIntent(mPlainTextPath, mScreenshotPath);
        assertActionSendMultiple(extras, BUGREPORT_CONTENT, SCREENSHOT_CONTENT);
    }

    @Test
    public void testBugreportFinished_zippedBugreportAndScreenshot() throws Exception {
        Bundle extras = sendBugreportFinishedAndGetSharedIntent(mZipPath, mScreenshotPath);
        assertActionSendMultiple(extras, BUGREPORT_CONTENT, SCREENSHOT_CONTENT);
    }

    @Test
    public void testBugreportFinished_plainBugreportAndNoScreenshot() throws Exception {
        Bundle extras = sendBugreportFinishedAndGetSharedIntent(mPlainTextPath, NO_SCREENSHOT);
        assertActionSendMultiple(extras, BUGREPORT_CONTENT, NO_SCREENSHOT);
    }

    @Test
    public void testBugreportFinished_zippedBugreportAndNoScreenshot() throws Exception {
        Bundle extras = sendBugreportFinishedAndGetSharedIntent(mZipPath, NO_SCREENSHOT);
        assertActionSendMultiple(extras, BUGREPORT_CONTENT, NO_SCREENSHOT);
@@ -1001,6 +1038,14 @@ public class BugreportReceiverTest extends InstrumentationTestCase {
        mUiBot.assertNotVisibleById("android:id/alertTitle");
    }

    private String getName() {
        return mName.getMethodName();
    }

    private Instrumentation getInstrumentation() {
        return InstrumentationRegistry.getInstrumentation();
    }

    private static void sleep(long ms) {
        Log.d(TAG, "sleeping for " + ms + "ms");
        SystemClock.sleep(ms);
+49 −49
Original line number Diff line number Diff line
@@ -34,6 +34,12 @@ import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
@@ -74,7 +80,8 @@ import android.os.Binder;
import android.os.INetworkManagementService;
import android.os.PowerManagerInternal;
import android.os.UserHandle;
import android.test.AndroidTestCase;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.text.format.Time;
import android.util.Log;
import android.util.TrustedTime;
@@ -86,6 +93,11 @@ import libcore.io.IoUtils;

import com.google.common.util.concurrent.AbstractFuture;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
@@ -105,7 +117,8 @@ import java.util.concurrent.TimeoutException;
/**
 * Tests for {@link NetworkPolicyManagerService}.
 */
public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
@RunWith(AndroidJUnit4.class)
public class NetworkPolicyManagerServiceTest {
    private static final String TAG = "NetworkPolicyManagerServiceTest";

    private static final long TEST_START = 1194220800000L;
@@ -116,7 +129,6 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {

    private BroadcastInterceptingContext mServiceContext;
    private File mPolicyDir;
    private List<Class<?>> mLocalServices = new ArrayList<>();

    private @Mock IActivityManager mActivityManager;
    private @Mock INetworkStatsService mStatsService;
@@ -124,7 +136,6 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
    private @Mock TrustedTime mTime;
    private @Mock IConnectivityManager mConnManager;
    private @Mock INotificationManager mNotifManager;
    private @Mock UsageStatsManagerInternal mUsageStats;
    private @Mock PackageManager mPackageManager;

    private IUidObserver mUidObserver;
@@ -146,12 +157,20 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {

    private static final String PKG_NAME_A = "name.is.A,pkg.A";

    public void setUp() throws Exception {
        super.setUp();
    @BeforeClass
    public static void registerLocalServices() {
        addLocalServiceMock(PowerManagerInternal.class);
        addLocalServiceMock(DeviceIdleController.LocalService.class);
        final UsageStatsManagerInternal usageStats =
                addLocalServiceMock(UsageStatsManagerInternal.class);
        when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
    }

    @Before
    public void callSystemReady() throws Exception {
        MockitoAnnotations.initMocks(this);

        final Context context = getContext();
        final Context context = InstrumentationRegistry.getContext();

        setCurrentTimeMillis(TEST_START);

@@ -183,10 +202,6 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
            }
        }).when(mActivityManager).registerUidObserver(any(), anyInt());

        addLocalServiceMock(PowerManagerInternal.class);
        addLocalServiceMock(DeviceIdleController.LocalService.class);
        addLocalServiceMock(UsageStatsManagerInternal.class, mUsageStats);

        mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mStatsService,
                mNetworkManager, mTime, mPolicyDir, true);
        mService.bindConnectivityManager(mConnManager);
@@ -216,7 +231,6 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
                .thenReturn(new ApplicationInfo());
        when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
        when(mUsageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
        when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
        expectCurrentTime();

@@ -230,28 +244,17 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        mNetworkObserver = networkObserver.getValue();
    }

    public void tearDown() throws Exception {
    @After
    public void removeFiles() throws Exception {
        for (File file : mPolicyDir.listFiles()) {
            file.delete();
        }
    }

        mServiceContext = null;
        mPolicyDir = null;

        mActivityManager = null;
        mStatsService = null;
        mTime = null;

        mService = null;

        // TODO: must remove services, otherwise next test will fail.
        // JUnit4 would avoid that hack by using a static setup.
        removeLocalServiceMocks();

        // Added by NetworkPolicyManagerService's constructor.
    @After
    public void unregisterLocalServices() throws Exception {
        // Registered by NetworkPolicyManagerService's constructor.
        LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);

        super.tearDown();
    }

    // NOTE: testPolicyChangeTriggersListener() and testUidForeground() are too superficial, they
@@ -259,6 +262,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
    // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
    // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.

    @Test
    public void testPolicyChangeTriggersListener() throws Exception {
        mPolicyListener.expect().onRestrictBackgroundBlacklistChanged(anyInt(), anyBoolean());

@@ -268,6 +272,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        mPolicyListener.waitAndVerify().onRestrictBackgroundBlacklistChanged(APP_ID_A, true);
    }

    @Test
    public void testUidForeground() throws Exception {
        // push all uids into background
        mUidObserver.onUidStateChanged(UID_A, ActivityManager.PROCESS_STATE_SERVICE);
@@ -287,6 +292,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        assertTrue(mService.isUidForeground(UID_B));
    }

    @Test
    public void testLastCycleBoundaryThisMonth() throws Exception {
        // assume cycle day of "5th", which should be in same month
        final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
@@ -298,6 +304,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        assertTimeEquals(expectedCycle, actualCycle);
    }

    @Test
    public void testLastCycleBoundaryLastMonth() throws Exception {
        // assume cycle day of "20th", which should be in last month
        final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
@@ -309,6 +316,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        assertTimeEquals(expectedCycle, actualCycle);
    }

    @Test
    public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
        // assume cycle day of "30th" in february; should go to january
        final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
@@ -320,6 +328,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        assertTimeEquals(expectedCycle, actualCycle);
    }

    @Test
    public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
        // assume cycle day of "30th" in february, which should clamp
        final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
@@ -331,6 +340,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        assertTimeEquals(expectedCycle, actualCycle);
    }

    @Test
    public void testCycleBoundaryLeapYear() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
@@ -354,6 +364,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
                computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
    }

    @Test
    public void testNextCycleTimezoneAfterUtc() throws Exception {
        // US/Central is UTC-6
        final NetworkPolicy policy = new NetworkPolicy(
@@ -362,6 +373,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
                computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
    }

    @Test
    public void testNextCycleTimezoneBeforeUtc() throws Exception {
        // Israel is UTC+2
        final NetworkPolicy policy = new NetworkPolicy(
@@ -370,6 +382,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
                computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
    }

    @Test
    public void testNextCycleSane() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false);
@@ -385,6 +398,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        }
    }

    @Test
    public void testLastCycleSane() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false);
@@ -400,6 +414,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        }
    }

    @Test
    public void testCycleTodayJanuary() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
@@ -419,6 +434,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
                computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
    }

    @Test
    public void testLastCycleBoundaryDST() throws Exception {
        final long currentTime = parseTime("1989-01-02T07:30:00.000");
        final long expectedCycle = parseTime("1988-12-03T02:00:00.000Z");
@@ -429,6 +445,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        assertTimeEquals(expectedCycle, actualCycle);
    }

    @Test
    public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
        NetworkState[] state = null;
        NetworkStats stats = null;
@@ -471,6 +488,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        verifySetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);
    }

    @Test
    public void testOverWarningLimitNotification() throws Exception {
        NetworkState[] state = null;
        NetworkStats stats = null;
@@ -579,6 +597,7 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
        }
    }

    @Test
    public void testMeteredNetworkWithoutLimit() throws Exception {
        NetworkState[] state = null;
        NetworkStats stats = null;
@@ -740,31 +759,12 @@ public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
    /**
     * Creates a mock and registers it to {@link LocalServices}.
     */
    private <T> T addLocalServiceMock(Class<T> clazz) {
    private static <T> T addLocalServiceMock(Class<T> clazz) {
        final T mock = mock(clazz);
        return addLocalServiceMock(clazz, mock);
    }

    /**
     * Registers a mock to {@link LocalServices}.
     */
    private <T> T addLocalServiceMock(Class<T> clazz, T mock) {
        LocalServices.addService(clazz, mock);
        mLocalServices.add(clazz);
        return mock;
    }

    /**
     * Unregisters all mocks from {@link LocalServices}.
     */
    private void removeLocalServiceMocks() {
        for (Class<?> clazz : mLocalServices) {
            Log.d(TAG, "removeLocalServiceMock(): " + clazz.getName());
            LocalServices.removeServiceForTest(clazz);
        }
        mLocalServices.clear();
    }

    /**
     * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
     *