FileDocCategorySizeDatePackage
StorageManagerBaseTest.javaAPI DocAndroid 5.1 API25839Thu Mar 12 22:22:12 GMT 2015android.os.storage

StorageManagerBaseTest

public class StorageManagerBaseTest extends android.test.InstrumentationTestCase

Fields Summary
protected android.content.Context
mContext
protected android.os.storage.StorageManager
mSm
private static String
LOG_TAG
protected static final long
MAX_WAIT_TIME
protected static final long
WAIT_TIME_INCR
protected static String
OBB_FILE_1
protected static String
OBB_FILE_1_CONTENTS_1
protected static String
OBB_FILE_2
protected static String
OBB_FILE_3
protected static String
OBB_FILE_1_PASSWORD
protected static String
OBB_FILE_1_ENCRYPTED
protected static String
OBB_FILE_2_UNSIGNED
protected static String
OBB_FILE_3_PASSWORD
protected static String
OBB_FILE_3_ENCRYPTED
protected static String
OBB_FILE_3_BAD_PACKAGENAME
protected static boolean
FORCE
protected static boolean
DONT_FORCE
private static final String
SAMPLE1_TEXT
private static final String
SAMPLE2_TEXT
Constructors Summary
Methods Summary
private voidcopyRawToFile(int rawResId, java.io.File outFile)
Helper to copy a raw resource file to an actual specified file

param
rawResId The raw resource ID of the OBB resource file
param
outFile A File representing the file we want to copy the OBB to
throws
NotFoundException If the resource file could not be found

        Resources res = mContext.getResources();
        InputStream is = null;
        try {
            is = res.openRawResource(rawResId);
        } catch (NotFoundException e) {
            Log.i(LOG_TAG, "Failed to load resource with id: " + rawResId);
            throw e;
        }
        FileUtils.setPermissions(outFile.getPath(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
                | FileUtils.S_IRWXO, -1, -1);
        assertTrue(FileUtils.copyToFile(is, outFile));
        FileUtils.setPermissions(outFile.getPath(), FileUtils.S_IRWXU | FileUtils.S_IRWXG
                | FileUtils.S_IRWXO, -1, -1);
    
protected java.io.FilecreateObbFile(java.lang.String name, int rawResId)
Creates an OBB file (with the given name), into the app's standard files directory

param
name The name of the OBB file we want to create/write to
param
rawResId The raw resource ID of the OBB file in the package
return
A {@link File} representing the file to write to

        File outFile = null;
        try {
            final File filesDir = mContext.getFilesDir();
            outFile = new File(filesDir, name);
            copyRawToFile(rawResId, outFile);
        } catch (NotFoundException e) {
            if (outFile != null) {
                outFile.delete();
            }
        }
        return outFile;
    
protected java.lang.StringdoMountObb(java.lang.String obbFilePath, java.lang.String key, int expectedState)
Mounts an OBB file without throwing and synchronously waits for it to finish mounting

param
obbFilePath The full path to the OBB file to mount
param
key (optional) The key to use to unencrypt the OBB; pass null for no encryption
param
expectedState The expected state resulting from trying to mount the OBB
return
A {@link String} representing the actual normalized path to OBB file that was mounted, or null if the mounting failed

        Log.i(LOG_TAG, "doMountObb() on " + obbFilePath + " using key: " + key);
        assertTrue ("Null path was passed in for OBB file!", obbFilePath != null);

        ObbListener obbListener = new ObbListener();
        assertTrue("mountObb call failed", mSm.mountObb(obbFilePath, key, obbListener));
        assertTrue("Failed to get OBB mount status change for file: " + obbFilePath,
                doWaitForObbStateChange(obbListener));
        assertEquals("OBB mount state not what was expected!", expectedState, obbListener.state());

        if (OnObbStateChangeListener.MOUNTED == expectedState) {
            assertEquals(obbFilePath, obbListener.officialPath());
            assertTrue("Obb should be mounted, but SM reports it is not!",
                    mSm.isObbMounted(obbListener.officialPath()));
        } else if (OnObbStateChangeListener.UNMOUNTED == expectedState) {
            assertFalse("Obb should not be mounted, but SM reports it is!",
                    mSm.isObbMounted(obbListener.officialPath()));
        }

        assertEquals("Mount state is not what was expected!", expectedState, obbListener.state());
        return obbListener.officialPath();
    
protected java.lang.StringdoMountObb_noThrow(java.lang.String obbFilePath, java.lang.String key, int expectedState)
Synchronously waits for an OBB listener to be signaled of a state change

param
obbListener The listener for the OBB file
return
true if the listener was signaled of a state change by the system; else a fail() is triggered if we timed out

        Log.i(LOG_TAG, "doMountObb() on " + obbFilePath + " using key: " + key);
        assertTrue ("Null path was passed in for OBB file!", obbFilePath != null);
        assertTrue ("Null path was passed in for OBB file!", obbFilePath != null);

        ObbListener obbListener = new ObbListener();
        boolean success = mSm.mountObb(obbFilePath, key, obbListener);
        success &= obbFilePath.equals(doWaitForObbStateChange(obbListener));
        success &= (expectedState == obbListener.state());

        if (OnObbStateChangeListener.MOUNTED == expectedState) {
            success &= obbFilePath.equals(obbListener.officialPath());
            success &= mSm.isObbMounted(obbListener.officialPath());
        } else {
            success &= !mSm.isObbMounted(obbListener.officialPath());
        }

        if (success) {
            return obbListener.officialPath();
        } else {
            return null;
        }
    
protected voiddoValidateIntContents(java.lang.String path, java.lang.String filename, int start, int end)
Helper to validate the contents of an "int" file in an OBB. The format of the files are sequential int's, in the range of: [start..end)

param
path The full path to the file (path to OBB)
param
filename The filename containing the ints to validate
param
start The first int expected to be found in the file
param
end The last int + 1 expected to be found in the file

        File inFile = new File(path, filename);
        DataInputStream inStream = null;
        Log.i(LOG_TAG, "Validating file " + filename + " at " + path);
        try {
            inStream = new DataInputStream(new FileInputStream(inFile));

            for (int i = start; i < end; ++i) {
                if (inStream.readInt() != i) {
                    fail("Unexpected value read in OBB file");
                }
            }
            if (inStream != null) {
                inStream.close();
            }
            Log.i(LOG_TAG, "Successfully validated file " + filename);
        } catch (FileNotFoundException e) {
            fail("File " + inFile + " not found: " + e.toString());
        } catch (IOException e) {
            fail("IOError with file " + inFile + ":" + e.toString());
        }
    
protected voiddoValidateTextContents(java.lang.String path, java.lang.String filename, java.lang.String contents)
Helper to validate the contents of a text file in an OBB

param
path The full path to the file (path to OBB)
param
filename The filename containing the ints to validate
param
contents A {@link String} containing the expected contents of the file

        File inFile = new File(path, filename);
        BufferedReader fileReader = null;
        BufferedReader textReader = null;
        Log.i(LOG_TAG, "Validating file " + filename + " at " + path);
        try {
            fileReader = new BufferedReader(new FileReader(inFile));
            textReader = new BufferedReader(new StringReader(contents));
            String actual = null;
            String expected = null;
            while ((actual = fileReader.readLine()) != null) {
                expected = textReader.readLine();
                if (!actual.equals(expected)) {
                    fail("File " + filename + " in OBB " + path + " does not match expected value");
                }
            }
            fileReader.close();
            textReader.close();
            Log.i(LOG_TAG, "File " + filename + " successfully verified.");
        } catch (IOException e) {
            fail("IOError with file " + inFile + ":" + e.toString());
        }
    
protected voiddoValidateZeroLongFile(java.lang.String path, java.lang.String filename, long size, boolean checkContents)
Helper to validate the contents of a "long" file on our OBBs The format of the files are sequential 0's of type long

param
path The full path to the file (path to OBB)
param
filename The filename containing the ints to validate
param
size The number of zero's expected in the file
param
checkContents If true, the contents of the file are actually verified; if false, we simply verify that the file can be opened

        File inFile = new File(path, filename);
        DataInputStream inStream = null;
        Log.i(LOG_TAG, "Validating file " + filename + " at " + path);
        try {
            inStream = new DataInputStream(new FileInputStream(inFile));

            if (checkContents) {
                for (long i = 0; i < size; ++i) {
                    if (inStream.readLong() != 0) {
                        fail("Unexpected value read in OBB file" + filename);
                    }
                }
            }

            if (inStream != null) {
                inStream.close();
            }
            Log.i(LOG_TAG, "File " + filename + " successfully verified for " + size + " zeros");
        } catch (IOException e) {
            fail("IOError with file " + inFile + ":" + e.toString());
        }
    
protected booleandoWaitForObbStateChange(android.os.storage.StorageManagerBaseTest$ObbListener obbListener)
Synchronously waits for an OBB listener to be signaled of a state change, but does not throw

param
obbListener The listener for the OBB file
return
true if the listener was signaled of a state change by the system, else returns false if we time out.

        synchronized(obbListener) {
            long waitTimeMillis = 0;
            while (!obbListener.isDone()) {
                try {
                    Log.i(LOG_TAG, "Waiting for listener...");
                    obbListener.wait(WAIT_TIME_INCR);
                    Log.i(LOG_TAG, "Awoke from waiting for listener...");
                    waitTimeMillis += WAIT_TIME_INCR;
                    if (waitTimeMillis > MAX_WAIT_TIME) {
                        fail("Timed out waiting for OBB state to change!");
                    }
                } catch (InterruptedException e) {
                    Log.i(LOG_TAG, e.toString());
                }
            }
            return obbListener.isDone();
            }
    
protected java.lang.StringdoWaitForPath(java.lang.String filePath)
Helper to synchronously wait until we can get a path for a given OBB file

param
filePath The full normalized path to the OBB file
return
The mounted path of the OBB, used to access contents in it

        String path = null;

        long waitTimeMillis = 0;
        assertTrue("OBB " + filePath + " is not currently mounted!", mSm.isObbMounted(filePath));
        while (path == null) {
            try {
                Thread.sleep(WAIT_TIME_INCR);
                waitTimeMillis += WAIT_TIME_INCR;
                if (waitTimeMillis > MAX_WAIT_TIME) {
                    fail("Timed out waiting to get path of OBB file " + filePath);
                }
            } catch (InterruptedException e) {
                // do nothing
            }
            path = mSm.getMountedObbPath(filePath);
        }
        Log.i(LOG_TAG, "Got OBB path: " + path);
        return path;
    
protected java.lang.StringmountObb(java.lang.String obbFilePath, java.lang.String key, int expectedState)
Mounts an OBB file

param
obbFilePath The full path to the OBB file to mount
param
key (optional) The key to use to unencrypt the OBB; pass null for no encryption
param
expectedState The expected state resulting from trying to mount the OBB
return
A {@link String} representing the normalized path to OBB file that was mounted

        return doMountObb(obbFilePath, key, expectedState);
    
protected java.lang.StringmountObb(java.lang.String obbFilePath)
Mounts an OBB file with default options (no encryption, mounting succeeds)

param
obbFilePath The full path to the OBB file to mount
return
A {@link String} representing the normalized path to OBB file that was mounted

        return doMountObb(obbFilePath, null, OnObbStateChangeListener.MOUNTED);
    
protected java.io.DataInputStreamopenFileOnMountedObb(java.lang.String obbPath, java.lang.String fileName)
Mounts an OBB file and opens a file located on it

param
obbPath Path to OBB image
param
fileName The full name and path to the file on the OBB to open once the OBB is mounted
return
The {@link DataInputStream} representing the opened file, if successful in opening the file, or null of unsuccessful.


        // get mSm obb mount path
        assertTrue("Cannot open file when OBB is not mounted!", mSm.isObbMounted(obbPath));

        String path = mSm.getMountedObbPath(obbPath);
        assertTrue("Path should not be null!", path != null);

        File inFile = new File(path, fileName);
        DataInputStream inStream = null;
        try {
            inStream = new DataInputStream(new FileInputStream(inFile));
            Log.i(LOG_TAG, "Opened file: " + fileName + " for read at path: " + path);
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString());
            return null;
        } catch (SecurityException e) {
            Log.e(LOG_TAG, e.toString());
            return null;
        }
        return inStream;
    
public voidsetUp()
{@inheritDoc}

        mContext = getInstrumentation().getContext();
        mSm = (StorageManager)mContext.getSystemService(android.content.Context.STORAGE_SERVICE);

    
protected voidunmountObb(java.lang.String obbFilePath, boolean force)
Unmounts an OBB file and synchronously waits for it to finish unmounting

param
obbFilePath The full path to the OBB file to mount
param
force true if we shuold force the unmount, false otherwise

        Log.i(LOG_TAG, "doUnmountObb() on " + obbFilePath);
        assertTrue ("Null path was passed in for OBB file!", obbFilePath != null);

        ObbListener obbListener = new ObbListener();
        assertTrue("unmountObb call failed", mSm.unmountObb(obbFilePath, force, obbListener));

        boolean stateChanged = doWaitForObbStateChange(obbListener);
        if (force) {
            assertTrue("Timed out waiting to unmount OBB file " + obbFilePath, stateChanged);
            assertEquals("OBB failed to unmount", OnObbStateChangeListener.UNMOUNTED,
                    obbListener.state());
            assertFalse("Obb should NOT be mounted, but SM reports it is!", mSm.isObbMounted(
                    obbFilePath));
        }
    
protected booleanunmountObb_noThrow(java.lang.String obbFilePath, boolean force)
Unmounts an OBB file without throwing, and synchronously waits for it to finish unmounting

param
obbFilePath The full path to the OBB file to mount
param
force true if we shuold force the unmount, false otherwise
return
true if the unmount was successful, false otherwise

        Log.i(LOG_TAG, "doUnmountObb_noThrow() on " + obbFilePath);
        assertTrue ("Null path was passed in for OBB file!", obbFilePath != null);
        boolean success = true;

        ObbListener obbListener = new ObbListener();
        assertTrue("unmountObb call failed", mSm.unmountObb(obbFilePath, force, obbListener));

        boolean stateChanged = doWaitForObbStateChange(obbListener);
        if (force) {
            success &= stateChanged;
            success &= (OnObbStateChangeListener.UNMOUNTED == obbListener.state());
            success &= !mSm.isObbMounted(obbFilePath);
        }
        return success;
    
protected voidverifyObb1Contents(java.lang.String filePath)
Verifies the pre-defined contents of our first OBB (OBB_FILE_1) The OBB contains 4 files and no subdirectories

param
filePath The normalized path to the already-mounted OBB file

        String path = null;
        path = doWaitForPath(filePath);

        // Validate contents of 2 files in this obb
        doValidateIntContents(path, "OneToOneThousandInts.bin", 0, 1000);
        doValidateIntContents(path, "SevenHundredInts.bin", 0, 700);
        doValidateZeroLongFile(path, "FiveLongs.bin", 5, true);
    
protected voidverifyObb2Contents(java.lang.String filename)
Verifies the pre-defined contents of our second OBB (OBB_FILE_2) The OBB contains 2 files and no subdirectories

param
filePath The normalized path to the already-mounted OBB file

        String path = null;
        path = doWaitForPath(filename);

        // Validate contents of file
        doValidateTextContents(path, "sample.txt", SAMPLE1_TEXT);
        doValidateTextContents(path, "sample2.txt", SAMPLE2_TEXT);
    
protected voidverifyObb3Contents(java.lang.String filename)
Verifies the pre-defined contents of our third OBB (OBB_FILE_3) The OBB contains nested files and subdirectories

param
filePath The normalized path to the already-mounted OBB file

        String path = null;
        path = doWaitForPath(filename);

        // Validate contents of file
        doValidateIntContents(path, "OneToOneThousandInts.bin", 0, 1000);
        doValidateZeroLongFile(path, "TwoHundredLongs", 200, true);

        // validate subdirectory 1
        doValidateZeroLongFile(path + File.separator + "subdir1", "FiftyLongs", 50, true);

        // validate subdirectory subdir2/
        doValidateIntContents(path + File.separator + "subdir2", "OneToOneThousandInts", 0, 1000);

        // validate subdirectory subdir2/subdir2a/
        doValidateZeroLongFile(path + File.separator + "subdir2" + File.separator + "subdir2a",
                "TwoHundredLongs", 200, true);

        // validate subdirectory subdir2/subdir2a/subdir2a1/
        doValidateIntContents(path + File.separator + "subdir2" + File.separator + "subdir2a"
                + File.separator + "subdir2a1", "OneToOneThousandInts", 0, 1000);