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

Commit e30554d2 authored by Bo Majewski's avatar Bo Majewski
Browse files

[AL, Search]: Expanding test coverage.

Converts SearchLoaderTest to be a parametrized test. Adds data class for
test parametrization. Uses the class to generate searches that vary
query and modified time.

Change-Id: I4be5c9226173ddfe8067d0de5f4df6d2fc2e1d91
Test: increasing test coverage
Flag: com.android.documentsui.flags.use_search_v2
Bug: 378590632
parent 91e1ae55
Loading
Loading
Loading
Loading
+14 −4
Original line number Diff line number Diff line
@@ -40,7 +40,8 @@ public class TestModel extends Model {
        Document.COLUMN_FLAGS,
        Document.COLUMN_DISPLAY_NAME,
        Document.COLUMN_SIZE,
        Document.COLUMN_MIME_TYPE
        Document.COLUMN_MIME_TYPE,
        Document.COLUMN_LAST_MODIFIED
    };

    public final UserId mUserId;
@@ -104,7 +105,7 @@ public class TestModel extends Model {
    }

    public DocumentInfo createDocumentForUser(String name, String mimeType, int flags,
            UserId userId) {
            long lastModified, UserId userId) {
        DocumentInfo doc = new DocumentInfo();
        doc.userId = userId;
        doc.authority = mAuthority;
@@ -114,6 +115,7 @@ public class TestModel extends Model {
        doc.mimeType = mimeType;
        doc.flags = flags;
        doc.size = mRand.nextInt();
        doc.lastModified = lastModified;

        addToCursor(doc);

@@ -121,7 +123,7 @@ public class TestModel extends Model {
    }

    public DocumentInfo createDocument(String name, String mimeType, int flags) {
        return createDocumentForUser(name, mimeType, flags, mUserId);
        return createDocumentForUser(name, mimeType, flags, System.currentTimeMillis(), mUserId);
    }

    private void addToCursor(DocumentInfo doc) {
@@ -133,9 +135,17 @@ public class TestModel extends Model {
        row.add(Document.COLUMN_MIME_TYPE, doc.mimeType);
        row.add(Document.COLUMN_FLAGS, doc.flags);
        row.add(Document.COLUMN_SIZE, doc.size);
        row.add(Document.COLUMN_LAST_MODIFIED, doc.lastModified);
    }

    private static String guessMimeType(String name) {
    /**
     * Attempts to guess the MIME type of the file based on its name. If unable to guess, returns
     * "text/plain".
     *
     * @param name The name of the file whose MIME type is guessed.
     * @return A guessed MIME type of "text/plain".
     */
    public static String guessMimeType(String name) {
        int i = name.indexOf('.');

        while(i != -1) {
+1 −1
Original line number Diff line number Diff line
@@ -142,7 +142,7 @@ public class QuickViewIntentBuilderTest {
    public void testBuild_twoProfiles_containsOnlyPreviewDocument() {
        mEnv.model.reset();
        mEnv.model.createDocumentForUser("a.txt", "text/plain", 0,
                TestProvidersAccess.OtherUser.USER_ID);
                System.currentTimeMillis(), TestProvidersAccess.OtherUser.USER_ID);
        DocumentInfo previewDoc = mEnv.model.createFile("b.png", 0);
        mEnv.model.createFile("c.png", 0);
        mEnv.model.update();
+35 −1
Original line number Diff line number Diff line
@@ -16,15 +16,20 @@
package com.android.documentsui.loaders

import android.os.Parcel
import android.provider.DocumentsContract
import com.android.documentsui.DirectoryResult
import com.android.documentsui.TestActivity
import com.android.documentsui.TestConfigStore
import com.android.documentsui.base.DocumentInfo
import com.android.documentsui.base.UserId
import com.android.documentsui.sorting.SortModel
import com.android.documentsui.testing.ActivityManagers
import com.android.documentsui.testing.TestEnv
import com.android.documentsui.testing.TestModel
import com.android.documentsui.testing.UserManagers
import java.time.Duration
import java.util.Locale
import kotlin.time.Duration.Companion.hours
import org.junit.Before

/**
@@ -32,6 +37,20 @@ import org.junit.Before
 */
fun getFileCount(result: DirectoryResult?) = result?.cursor?.count ?: -1

/**
 * A data class that holds parameters that can be varied for the loader test. The last
 * value, expectedCount, can be used for simple tests that check that the number of
 * returned files matches the expectations.
 */
data class LoaderTestParams(
    // A query, matched against file names. May be empty.
    val query: String,
    // The delta from now that indicates maximum age of matched files.
    val lastModifiedDelta: Duration?,
    // The number of files that are expected, for the above parameters, to be found by a loader.
    val expectedCount: Int
)

/**
 * Common base class for search and folder loaders.
 */
@@ -54,11 +73,26 @@ open class BaseLoaderTest {
        mActivity.userManager = UserManagers.create()
    }

    /**
     * Creates a text, PNG, MP4 and MPG files named sample-000x, for x in 0 .. count - 1.
     * Each file gets a matching extension. The 0th file is modified 1h, 1st 2 hours, .. etc., ago.
     */
    fun createDocuments(count: Int): Array<DocumentInfo> {
        val extensionList = arrayOf("txt", "png", "mp4", "mpg")
        val now = System.currentTimeMillis()
        val flags = (DocumentsContract.Document.FLAG_SUPPORTS_WRITE
                or DocumentsContract.Document.FLAG_SUPPORTS_DELETE
                or DocumentsContract.Document.FLAG_SUPPORTS_RENAME)
        return Array<DocumentInfo>(count) { i ->
            val id = String.format(Locale.US, "%05d", i)
            mEnv.model.createFile("sample-$id.${extensionList[i % extensionList.size]}")
            val name = "sample-$id.${extensionList[i % extensionList.size]}"
            mEnv.model.createDocumentForUser(
                name,
                TestModel.guessMimeType(name),
                flags,
                now - 1.hours.inWholeMilliseconds * i,
                UserId.DEFAULT_USER
            )
        }
    }
}
+30 −4
Original line number Diff line number Diff line
@@ -20,18 +20,44 @@ import com.android.documentsui.ContentLock
import com.android.documentsui.base.DocumentInfo
import com.android.documentsui.testing.TestFileTypeLookup
import com.android.documentsui.testing.TestProvidersAccess
import java.time.Duration
import junit.framework.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters

private const val TOTAL_FILE_COUNT = 10

@RunWith(Parameterized::class)
@SmallTest
class FolderLoaderTest : BaseLoaderTest() {
class FolderLoaderTest(private val testParams: LoaderTestParams) : BaseLoaderTest() {
    companion object {
        @JvmStatic
        @Parameters(name = "with parameters {0}")
        fun data() = listOf(
            LoaderTestParams("", null, TOTAL_FILE_COUNT),
            // The first file is at NOW, the second at NOW - 1h, etc.
            LoaderTestParams("", Duration.ofMinutes(1L), 1),
            LoaderTestParams("", Duration.ofMinutes(60L + 1), 2),
            LoaderTestParams("", Duration.ofMinutes(TOTAL_FILE_COUNT * 60L + 1), TOTAL_FILE_COUNT),
        )
    }

    @Test
    fun testLoadInBackground() {
        val mockProvider = mEnv.mockProviders[TestProvidersAccess.DOWNLOADS.authority]
        val docs = createDocuments(5)
        val docs = createDocuments(TOTAL_FILE_COUNT)
        mockProvider!!.setNextChildDocumentsReturns(*docs)
        val userIds = listOf(TestProvidersAccess.DOWNLOADS.userId)
        val queryOptions = QueryOptions(10, null, null, true, arrayOf<String>("*/*"))
        val queryOptions =
            QueryOptions(
                TOTAL_FILE_COUNT,
                testParams.lastModifiedDelta,
                null,
                true,
                arrayOf<String>("*/*")
            )
        val contentLock = ContentLock()
        // TODO(majewski): Is there a better way to create Downloads root folder DocumentInfo?
        val rootFolderInfo = DocumentInfo()
@@ -50,6 +76,6 @@ class FolderLoaderTest : BaseLoaderTest() {
                mEnv.state.sortModel
            )
        val directoryResult = loader.loadInBackground()
        assertEquals(docs.size, getFileCount(directoryResult))
        assertEquals(testParams.expectedCount, getFileCount(directoryResult))
    }
}
+35 −7
Original line number Diff line number Diff line
@@ -15,19 +15,41 @@
 */
package com.android.documentsui.loaders

import androidx.test.filters.SmallTest
import com.android.documentsui.ContentLock
import com.android.documentsui.LockingContentObserver
import com.android.documentsui.base.DocumentInfo
import com.android.documentsui.testing.TestFileTypeLookup
import com.android.documentsui.testing.TestProvidersAccess
import java.time.Duration
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import junit.framework.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters

class SearchLoaderTest : BaseLoaderTest() {
    lateinit var mExecutor: ExecutorService
private const val TOTAL_FILE_COUNT = 8

@RunWith(Parameterized::class)
@SmallTest
class SearchLoaderTest(private val testParams: LoaderTestParams) : BaseLoaderTest() {
    private lateinit var mExecutor: ExecutorService

    companion object {
        @JvmStatic
        @Parameters(name = "with parameters {0}")
        fun data() = listOf(
            LoaderTestParams("sample", null, TOTAL_FILE_COUNT),
            LoaderTestParams("txt", null, 2),
            LoaderTestParams("foozig", null, 0),
            // The first file is at NOW, the second at NOW - 1h; expect 2.
            LoaderTestParams("sample", Duration.ofMinutes(60 + 1), 2),
            // TODO(b:378590632): Add test for recents.
        )
    }

    @Before
    override fun setUp() {
@@ -38,10 +60,17 @@ class SearchLoaderTest : BaseLoaderTest() {
    @Test
    fun testLoadInBackground() {
        val mockProvider = mEnv.mockProviders[TestProvidersAccess.DOWNLOADS.authority]
        val docs = createDocuments(8)
        val docs = createDocuments(TOTAL_FILE_COUNT)
        mockProvider!!.setNextChildDocumentsReturns(*docs)
        val userIds = listOf(TestProvidersAccess.DOWNLOADS.userId)
        val queryOptions = QueryOptions(10, null, null, true, arrayOf("*/*"))
        val queryOptions =
            QueryOptions(
                TOTAL_FILE_COUNT + 1,
                testParams.lastModifiedDelta,
                null,
                true,
                arrayOf("*/*")
            )
        val contentLock = ContentLock()
        val rootIds = listOf(TestProvidersAccess.DOWNLOADS)
        val observer = LockingContentObserver(contentLock) {
@@ -59,13 +88,12 @@ class SearchLoaderTest : BaseLoaderTest() {
                TestFileTypeLookup(),
                observer,
                rootIds,
                "txt",
                testParams.query,
                queryOptions,
                mEnv.state.sortModel,
                mExecutor,
            )
        val directoryResult = loader.loadInBackground()
        // Expect only 2 text files to match txt.
        assertEquals(2, getFileCount(directoryResult))
        assertEquals(testParams.expectedCount, getFileCount(directoryResult))
    }
}
Loading