1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.content.browser;
7 import android.test.InstrumentationTestCase;
8 import android.test.suitebuilder.annotation.SmallTest;
10 import org.chromium.base.ImportantFileWriterAndroid;
11 import org.chromium.base.library_loader.LibraryLoader;
12 import org.chromium.base.library_loader.ProcessInitException;
13 import org.chromium.base.test.util.Feature;
14 import org.chromium.content_shell_apk.ContentShellApplication;
16 import java.io.DataInputStream;
18 import java.io.FileInputStream;
19 import java.io.IOException;
23 * Tests for {@Link ImportantFileWriterAndroid}
25 * Note that this assumes that the underlying native atomic write functions
26 * work, so is not attempting to test that writes are atomic. Instead it is just
27 * testing that the Java code is calling the native code correctly.
29 public class ImportantFileWriterAndroidTest extends InstrumentationTestCase {
32 getInstrumentation().runOnMainSync(new Runnable() {
35 ContentShellApplication.initializeApplicationParameters();
37 LibraryLoader.ensureInitialized();
38 } catch (ProcessInitException e) {
45 private void checkFile(File testFile, byte[] data) {
46 assertTrue(testFile.exists());
48 byte[] fileData = new byte[(int) testFile.length()];
50 new DataInputStream(new FileInputStream(testFile));
51 dis.readFully(fileData);
53 assertEquals("Data length wrong", data.length, fileData.length);
54 for (int i = 0; i < data.length; i++) {
55 assertEquals("Data byte wrong", data[i], fileData[i]);
57 } catch (IOException e) {
58 fail("Failed to read file");
64 @Feature({"Android-AppBase"})
65 public void testAtomicWrite() {
66 // Try writing a file that can't be created.
67 byte[] data1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
68 assertFalse("Writing bad file succeded",
69 ImportantFileWriterAndroid.writeFileAtomically(
70 "/junk/junk", data1));
71 File dir = getInstrumentation().getTargetContext().getFilesDir();
72 File testFile = new File(dir, "ImportantFileTest");
74 // Make sure the file doesn't already exist
75 if (testFile.exists()) {
76 assertTrue(testFile.delete());
80 assertTrue("Writing new file failed",
81 ImportantFileWriterAndroid.writeFileAtomically(
82 testFile.getAbsolutePath(), data1));
83 checkFile(testFile, data1);
84 byte[] data2 = {10, 20, 30, 40, 50, 60, 70, 80};
86 // Overwrite an existing file
87 assertTrue("Writing exiting file failed",
88 ImportantFileWriterAndroid.writeFileAtomically(
89 testFile.getAbsolutePath(), data2));
90 checkFile(testFile, data2);
93 assertTrue(testFile.delete());
97 public void setUp() throws Exception {