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

Commit 8c0b45ad authored by Felipe Leme's avatar Felipe Leme
Browse files

Refactored HsumBootUserInitializerDesignateMainUserOnBootTest.junitParametersPassedToConstructor()

Bug: 402486365
Test: atest FrameworksMockingServicesTests:HsumBootUserInitializerDesignateMainUserOnBootTest FrameworksMockingServicesTests:HsumBootUserInitializerNonParameterizedTest
Flag: TEST_ONLY

Change-Id: I866d20b9356976e922168e41968a1a8dd56189f7
parent 5ed75b7a
Loading
Loading
Loading
Loading
+150 −7
Original line number Diff line number Diff line
@@ -17,13 +17,15 @@ package com.android.server.pm;

import static com.android.server.pm.HsumBootUserInitializer.designateMainUserOnBoot;

import android.annotation.Nullable;
import android.util.Log;

import org.junit.Test;
import org.junit.runners.Parameterized.Parameters;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public final class HsumBootUserInitializerDesignateMainUserOnBootTest
        extends AbstractHsumBootUserInitializerConstructorHelpersTestCase {
@@ -36,14 +38,131 @@ public final class HsumBootUserInitializerDesignateMainUserOnBootTest
    private final boolean mConfigIsMainUserPermanentAdmin;
    private final boolean mResult;

    // NOTE: not really "Generated code", but that's the only why to calm down checkstyle, otherwise
    // it will complain they should be all upper case
    // Indices used on cloneBaseline()
    private static final int INDEX_DEBUGGABLE = 0;
    private static final int INDEX_SYSPROP = 1;
    private static final int INDEX_RESULT = 6;

    /**
     * Arguments baseline, i.e., the behavior without emulating using a system property.
     */
    private static final Object[][] BASELINE = {
        // Note: entries below are broken in 3 lines to make them easier to read / maintain:
        // - build type and emulation
        // - input (configs)
        // - expected output

        // original (only 2 configs used)
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(false),
                RESULT(false)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(false),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        // added FLAG and CFG_CREATE_INITIAL
        // FLAG(false), CFG_CREATE_INITIAL(true) - everything but first equals to original
        {
                // This is special case used to guard the config by the flag (RESULT true)
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(false),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(false),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(false), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        // FLAG(true), CFG_CREATE_INITIAL(false) - everything equals to original
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(false),
                RESULT(false)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(false),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        // FLAG(true), CFG_CREATE_INITIAL(true) - everything equals to original
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(false),
                RESULT(false)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(true),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(false),
                RESULT(true)
        },
        {
                DEBUGGABLE(false), SYSPROP(false),
                FLAG(true), CFG_CREATE_INITIAL(true), CFG_DESIGNATE_MAIN(true), CFG_IS_PERM_ADM(true),
                RESULT(true)
        }
    };

    /** Useless javadoc to make checkstyle happy... */
    @Parameters(name =
            "{index}: dbgBuild={0},sysprop={1},flag={2},cfgCreateIU={3},cfgDesignateMU={4},cfgIsMUPermAdm={5},result={6}")
    public static Collection<Object[]> junitParametersPassedToConstructor() {
        // TODO(b/402486365): refactor code below so we define one set (for non-debuggable), then
        // copy it over the other 3 combinations.
    public static List<Object[]> junitParametersPassedToConstructor() {
        List<Object[]> parameters = new ArrayList<>(BASELINE.length * 4);

        // User build, sysprop not set - baseline
        parameters.addAll(Arrays.asList(BASELINE));

        // User build, sysprop not set - everything should be the same as basline
        parameters.addAll(cloneBaseline(DEBUGGABLE(false), SYSPROP(false), /* result= */ null));

        // Debuggable build - result should be value of property (false)
        parameters.addAll(cloneBaseline(DEBUGGABLE(true), SYSPROP(false), RESULT(false)));

        // Debuggable build - result should be value of property (true)
        parameters.addAll(cloneBaseline(DEBUGGABLE(true), SYSPROP(true), RESULT(true)));

        return parameters;
    }

    // TODO(b/402486365): remove on follow-up CL
    static List<Object[]> hardcodedParameters() {
        return Arrays.asList(new Object[][] {
                // Note: entries below are broken in 3 lines to make them easier to read / maintain:
                // - build type and emulation
@@ -138,7 +257,7 @@ public final class HsumBootUserInitializerDesignateMainUserOnBootTest
                        RESULT(true)
                },

                // User build, sysprop set - everything should be the same as above
                // User build, sysprop not set - everything should be the same as above
                {
                        DEBUGGABLE(false), SYSPROP(false),
                        FLAG(false), CFG_CREATE_INITIAL(false), CFG_DESIGNATE_MAIN(false), CFG_IS_PERM_ADM(false),
@@ -422,4 +541,28 @@ public final class HsumBootUserInitializerDesignateMainUserOnBootTest

        expect.withMessage("designateMainUserOnBoot()").that(result).isEqualTo(mResult);
    }

    /**
     * Clones the baseline, changing some values.
     *
     * @param debuggable new value of {@code isDebuggable}
     * @param sysprop new value of {@code sysprop}
     * @param result if not {@code null}, new value of {@code result}
     *
     * @return the clone
     */
    private static List<Object[]> cloneBaseline(boolean debuggable, boolean sysprop,
            @Nullable Boolean result) {
        Object[][] clone = Arrays.stream(BASELINE)
                .map(row -> Arrays.copyOf(row, row.length))
                .toArray(Object[][]::new);
        for (var parameters : clone) {
            parameters[INDEX_DEBUGGABLE] = debuggable;
            parameters[INDEX_SYSPROP] = sysprop;
            if (result != null) {
                parameters[INDEX_RESULT] = result;
            }
        }
        return Arrays.asList(clone);
    }
}
+129 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2025 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.server.pm;

import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;

import static com.google.common.truth.Truth.assertWithMessage;

import android.content.ContentResolver;
import android.content.Context;
import android.os.UserManager;
import android.util.Log;

import com.android.modules.utils.testing.ExtendedMockitoRule;
import com.android.server.am.ActivityManagerService;

import com.google.common.truth.Expect;

import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;

// TODO(b/): rename to HsumBootUserInitializerTest once HsumBootUserInitializerTest itself is
// renamed to HsumBootUserInitializerInitMethodTest
public final class HsumBootUserInitializerNonParameterizedTest {

    private static final String TAG = HsumBootUserInitializerNonParameterizedTest.class
            .getSimpleName();

    @Rule
    public final Expect expect = Expect.create();

    @Rule
    public final ExtendedMockitoRule extendedMockito = new ExtendedMockitoRule.Builder(this)
            .mockStatic(UserManager.class)
            .build();

    @Mock
    private UserManagerService mMockUms;

    @Mock
    private ActivityManagerService mMockAms;

    @Mock
    private PackageManagerService mMockPms;

    @Mock
    private ContentResolver mMockContentResolver;

    // NOTE: not mocking yet, but need a real one because of resources
    private final Context mRealContext = androidx.test.InstrumentationRegistry.getInstrumentation()
            .getTargetContext();

    @Test
    public void testCreateInstance_hsum() {
        mockIsHsum(true);

        var instance = HsumBootUserInitializer.createInstance(mMockUms, mMockAms, mMockPms,
                mMockContentResolver, mRealContext);

        expect.withMessage("result of createInstance()").that(instance).isNotNull();
    }

    @Test
    public void testCreateInstance_nonSsum() {
        mockIsHsum(false);

        var instance = HsumBootUserInitializer.createInstance(mMockUms, mMockAms, mMockPms,
                mMockContentResolver, mRealContext);

        expect.withMessage("result of createInstance()").that(instance).isNull();
    }

    // TODO(b/402486365): remove on follow-up CL
    /** Tests the refactored method on HsumBootUserInitializerDesignateMainUserOnBootTest. */
    @Test
    public void testJunitParametersPassedToConstructor() {
        var expected = HsumBootUserInitializerDesignateMainUserOnBootTest.hardcodedParameters();
        var actual = HsumBootUserInitializerDesignateMainUserOnBootTest
                .junitParametersPassedToConstructor();

        /* NOTE: ideally it should call some built-in Truth assertion like

        expect.withMessage("junitParametersPassedToConstructor()")
                .that(actual)
                .containsExactlyElementsIn(expected).inOrder();

         but that wouldn't work because each element is an Object[], and their equals() would fail.

         There might be another way, but this methods is temporary anyways...
         */
        int size = expected.size();
        assertWithMessage("junitParametersPassedToConstructor()").that(actual).hasSize(size);

        for (int i = 0; i < size; i++) {
            var expectedLine = expected.get(i);
            var actualLine = actual.get(i);
            int expectedLength = expectedLine.length;
            int actualLength = actualLine.length;
            if (actualLength != expectedLength) {
                expect.withMessage("size of line %s (expected %s, actual %s)", i, expectedLength,
                        actualLength).fail();
                continue;
            }
            for (int j = 0; j < actualLength; j++) {
                expect.withMessage("cell[%s, %s]", i, j).that(actualLine[j])
                        .isEqualTo(expectedLine[j]);
            }
        }
    }

    private void mockIsHsum(boolean value) {
        Log.v(TAG, "mockIsHsum(" + value + ")");
        doReturn(value).when(UserManager::isHeadlessSystemUserMode);
    }
}