Commit 3e46c101 authored by haven@chromium.org's avatar haven@chromium.org

Adds API test for imageWriterPrivate.writeFromFile

Original CL: https://codereview.chromium.org/336923002/

BUG=384650

Review URL: https://codereview.chromium.org/382053004

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282536 0039d316-1c4b-4281-b951-d872f2087c98
parent 91025cc6
......@@ -22,16 +22,12 @@ class ImageWriterDestroyPartitionsOperationTest
TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) {
TestingProfile profile;
MockOperationManager manager(&profile);
scoped_refptr<FakeImageWriterClient> client = FakeImageWriterClient::Create();
scoped_refptr<DestroyPartitionsOperation> operation(
new DestroyPartitionsOperation(manager.AsWeakPtr(),
kDummyExtensionId,
test_device_path_.AsUTF8Unsafe()));
#if !defined(OS_CHROMEOS)
operation->SetUtilityClientForTesting(client);
#endif
new DestroyPartitionsOperation(
manager.AsWeakPtr(),
kDummyExtensionId,
test_utils_.GetDevicePath().AsUTF8Unsafe()));
EXPECT_CALL(
manager,
......@@ -54,10 +50,10 @@ TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) {
base::RunLoop().RunUntilIdle();
#if !defined(OS_CHROMEOS)
client->Progress(0);
client->Progress(50);
client->Progress(100);
client->Success();
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(50);
test_utils_.GetUtilityClient()->Progress(100);
test_utils_.GetUtilityClient()->Success();
base::RunLoop().RunUntilIdle();
#endif
......
......@@ -2,30 +2,54 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop/message_loop.h"
#include "chrome/browser/extensions/api/file_system/file_system_api.h"
#include "chrome/browser/extensions/api/image_writer_private/operation.h"
#include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h"
#include "chrome/browser/extensions/api/image_writer_private/test_utils.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/extensions/api/image_writer_private.h"
#include "content/public/browser/browser_thread.h"
namespace extensions {
using api::image_writer_private::RemovableStorageDevice;
using extensions::image_writer::FakeImageWriterClient;
class ImageWriterPrivateApiTest : public ExtensionApiTest {
public:
virtual void SetUpOnMainThread() OVERRIDE {
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
ExtensionApiTest::SetUpInProcessBrowserTestFixture();
test_utils_.SetUp(true);
ASSERT_TRUE(test_utils_.FillFile(test_utils_.GetImagePath(),
image_writer::kImagePattern,
image_writer::kTestFileSize));
ASSERT_TRUE(test_utils_.FillFile(test_utils_.GetDevicePath(),
image_writer::kDevicePattern,
image_writer::kTestFileSize));
scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList);
RemovableStorageDevice* expected1 = new RemovableStorageDevice();
expected1->vendor = "Vendor 1";
expected1->model = "Model 1";
expected1->capacity = 1 << 20;
expected1->storage_unit_id = "/test/id/1";
expected1->capacity = image_writer::kTestFileSize;
#if defined(OS_WIN)
expected1->storage_unit_id = test_utils_.GetDevicePath().AsUTF8Unsafe();
#else
expected1->storage_unit_id = test_utils_.GetDevicePath().value();
#endif
RemovableStorageDevice* expected2 = new RemovableStorageDevice();
expected2->vendor = "Vendor 2";
expected2->model = "Model 2";
expected2->capacity = 1 << 22;
expected2->storage_unit_id = "/test/id/2";
expected2->capacity = image_writer::kTestFileSize << 2;
#if defined(OS_WIN)
expected2->storage_unit_id = test_utils_.GetDevicePath().AsUTF8Unsafe();
#else
expected2->storage_unit_id = test_utils_.GetDevicePath().value();
#endif
linked_ptr<RemovableStorageDevice> device1(expected1);
device_list->data.push_back(device1);
......@@ -35,9 +59,43 @@ class ImageWriterPrivateApiTest : public ExtensionApiTest {
RemovableStorageProvider::SetDeviceListForTesting(device_list);
}
virtual void CleanUpOnMainThread() OVERRIDE {
virtual void TearDownInProcessBrowserTestFixture() OVERRIDE {
ExtensionApiTest::TearDownInProcessBrowserTestFixture();
test_utils_.TearDown();
RemovableStorageProvider::ClearDeviceListForTesting();
FileSystemChooseEntryFunction::StopSkippingPickerForTest();
}
#if !defined(OS_CHROMEOS)
void ImageWriterUtilityClientCall() {
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&FakeImageWriterClient::Progress,
test_utils_.GetUtilityClient(),
0));
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&FakeImageWriterClient::Progress,
test_utils_.GetUtilityClient(),
50));
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&FakeImageWriterClient::Progress,
test_utils_.GetUtilityClient(),
100));
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&FakeImageWriterClient::Success,
test_utils_.GetUtilityClient()));
}
#endif
protected:
image_writer::ImageWriterTestUtils test_utils_;
};
IN_PROC_BROWSER_TEST_F(ImageWriterPrivateApiTest, TestListDevices) {
......@@ -45,4 +103,23 @@ IN_PROC_BROWSER_TEST_F(ImageWriterPrivateApiTest, TestListDevices) {
<< message_;
}
IN_PROC_BROWSER_TEST_F(ImageWriterPrivateApiTest, TestWriteFromFile) {
FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest(
"test_temp", test_utils_.GetTempDir());
base::FilePath selected_image(test_utils_.GetImagePath());
FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
&selected_image);
#if !defined(OS_CHROMEOS)
test_utils_.GetUtilityClient()->SetWriteCallback(base::Bind(
&ImageWriterPrivateApiTest::ImageWriterUtilityClientCall, this));
test_utils_.GetUtilityClient()->SetVerifyCallback(base::Bind(
&ImageWriterPrivateApiTest::ImageWriterUtilityClientCall, this));
#endif
ASSERT_TRUE(RunPlatformAppTest("image_writer_private/write_from_file"))
<< message_;
}
} // namespace extensions
......@@ -6,6 +6,7 @@
#include "base/file_util.h"
#include "base/files/file_enumerator.h"
#include "base/lazy_instance.h"
#include "base/threading/worker_pool.h"
#include "chrome/browser/extensions/api/image_writer_private/error_messages.h"
#include "chrome/browser/extensions/api/image_writer_private/operation_manager.h"
......@@ -24,6 +25,11 @@ const int kMD5BufferSize = 1024;
const char kChromeOSTempRoot[] = "/var/tmp";
#endif
#if !defined(OS_CHROMEOS)
static base::LazyInstance<scoped_refptr<ImageWriterUtilityClient> >
g_utility_client = LAZY_INSTANCE_INITIALIZER;
#endif
Operation::Operation(base::WeakPtr<OperationManager> manager,
const ExtensionId& extension_id,
const std::string& device_path)
......@@ -61,11 +67,10 @@ image_writer_api::Stage Operation::GetStage() {
}
#if !defined(OS_CHROMEOS)
// static
void Operation::SetUtilityClientForTesting(
scoped_refptr<ImageWriterUtilityClient> client) {
image_writer_client_ = client;
AddCleanUpFunction(
base::Bind(&ImageWriterUtilityClient::Shutdown, image_writer_client_));
g_utility_client.Get() = client;
}
#endif
......@@ -244,6 +249,10 @@ void Operation::CompleteAndContinue(const base::Closure& continuation) {
#if !defined(OS_CHROMEOS)
void Operation::StartUtilityClient() {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
if (g_utility_client.Get()) {
image_writer_client_ = g_utility_client.Get();
return;
}
if (!image_writer_client_) {
image_writer_client_ = new ImageWriterUtilityClient();
AddCleanUpFunction(base::Bind(&Operation::StopUtilityClient, this));
......
......@@ -73,8 +73,10 @@ class Operation : public base::RefCountedThreadSafe<Operation> {
image_writer_api::Stage GetStage();
#if !defined(OS_CHROMEOS)
// Set an ImageWriterClient to use. Should be called only when testing.
void SetUtilityClientForTesting(
// Set an ImageWriterClient to use. Should be called only when testing. This
// does not set up automatic shutdown of the client and it must be shutdown
// manually.
static void SetUtilityClientForTesting(
scoped_refptr<ImageWriterUtilityClient> client);
#endif
......
......@@ -58,8 +58,7 @@ KeyedService* BuildFakeExtensionSystem(content::BrowserContext* profile) {
namespace {
class ImageWriterOperationManagerTest
: public ImageWriterUnitTestBase {
class ImageWriterOperationManagerTest : public ImageWriterUnitTestBase {
public:
void StartCallback(bool success, const std::string& error) {
started_ = true;
......@@ -111,11 +110,11 @@ TEST_F(ImageWriterOperationManagerTest, WriteFromFile) {
OperationManager manager(&test_profile_);
manager.StartWriteFromFile(
kDummyExtensionId,
test_image_path_,
test_device_path_.AsUTF8Unsafe(),
base::Bind(&ImageWriterOperationManagerTest::StartCallback,
base::Unretained(this)));
kDummyExtensionId,
test_utils_.GetImagePath(),
test_utils_.GetDevicePath().AsUTF8Unsafe(),
base::Bind(&ImageWriterOperationManagerTest::StartCallback,
base::Unretained(this)));
EXPECT_TRUE(started_);
EXPECT_TRUE(start_success_);
......@@ -138,7 +137,7 @@ TEST_F(ImageWriterOperationManagerTest, DestroyPartitions) {
manager.DestroyPartitions(
kDummyExtensionId,
test_device_path_.AsUTF8Unsafe(),
test_utils_.GetDevicePath().AsUTF8Unsafe(),
base::Bind(&ImageWriterOperationManagerTest::StartCallback,
base::Unretained(this)));
......
......@@ -71,26 +71,25 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase {
ImageWriterUnitTestBase::SetUp();
// Create the zip file.
base::FilePath image_dir = temp_dir_.path().AppendASCII("zip");
base::FilePath image_dir = test_utils_.GetTempDir().AppendASCII("zip");
ASSERT_TRUE(base::CreateDirectory(image_dir));
ASSERT_TRUE(base::CreateTemporaryFileInDir(image_dir, &image_path_));
FillFile(image_path_, kImagePattern, kTestFileSize);
test_utils_.FillFile(image_path_, kImagePattern, kTestFileSize);
zip_file_ = temp_dir_.path().AppendASCII("test_image.zip");
zip_file_ = test_utils_.GetTempDir().AppendASCII("test_image.zip");
ASSERT_TRUE(zip::Zip(image_dir, zip_file_, true));
// Operation setup.
operation_ = new OperationForTest(manager_.AsWeakPtr(),
kDummyExtensionId,
test_device_path_.AsUTF8Unsafe());
client_ = FakeImageWriterClient::Create();
operation_->SetImagePath(test_image_path_);
operation_ =
new OperationForTest(manager_.AsWeakPtr(),
kDummyExtensionId,
test_utils_.GetDevicePath().AsUTF8Unsafe());
operation_->SetImagePath(test_utils_.GetImagePath());
}
virtual void TearDown() OVERRIDE {
// Ensure all callbacks have been destroyed and cleanup occurs.
client_->Shutdown();
operation_->Cancel();
ImageWriterUnitTestBase::TearDown();
......@@ -102,7 +101,6 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase {
scoped_ptr<TestingProfile> profile_;
MockOperationManager manager_;
scoped_refptr<FakeImageWriterClient> client_;
scoped_refptr<OperationForTest> operation_;
};
......@@ -154,10 +152,6 @@ TEST_F(ImageWriterOperationTest, UnzipZipFile) {
#if defined(OS_LINUX)
TEST_F(ImageWriterOperationTest, WriteImageToDevice) {
#if !defined(OS_CHROMEOS)
operation_->SetUtilityClientForTesting(client_);
#endif
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, _))
......@@ -179,10 +173,10 @@ TEST_F(ImageWriterOperationTest, WriteImageToDevice) {
base::RunLoop().RunUntilIdle();
#if !defined(OS_CHROMEOS)
client_->Progress(0);
client_->Progress(kTestFileSize / 2);
client_->Progress(kTestFileSize);
client_->Success();
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
test_utils_.GetUtilityClient()->Progress(kTestFileSize);
test_utils_.GetUtilityClient()->Success();
base::RunLoop().RunUntilIdle();
#endif
......@@ -194,8 +188,6 @@ TEST_F(ImageWriterOperationTest, WriteImageToDevice) {
// are skipped.
TEST_F(ImageWriterOperationTest, VerifyFileSuccess) {
operation_->SetUtilityClientForTesting(client_);
EXPECT_CALL(manager_, OnError(kDummyExtensionId, _, _, _)).Times(0);
EXPECT_CALL(
manager_,
......@@ -210,7 +202,8 @@ TEST_F(ImageWriterOperationTest, VerifyFileSuccess) {
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, 100))
.Times(AtLeast(1));
FillFile(test_device_path_, kImagePattern, kTestFileSize);
test_utils_.FillFile(
test_utils_.GetDevicePath(), kImagePattern, kTestFileSize);
operation_->Start();
content::BrowserThread::PostTask(content::BrowserThread::FILE,
......@@ -221,17 +214,17 @@ TEST_F(ImageWriterOperationTest, VerifyFileSuccess) {
base::RunLoop().RunUntilIdle();
client_->Progress(0);
client_->Progress(kTestFileSize / 2);
client_->Progress(kTestFileSize);
client_->Success();
#if !defined(OS_CHROMEOS)
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
test_utils_.GetUtilityClient()->Progress(kTestFileSize);
test_utils_.GetUtilityClient()->Success();
#endif
base::RunLoop().RunUntilIdle();
}
TEST_F(ImageWriterOperationTest, VerifyFileFailure) {
operation_->SetUtilityClientForTesting(client_);
EXPECT_CALL(
manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _))
......@@ -246,7 +239,8 @@ TEST_F(ImageWriterOperationTest, VerifyFileFailure) {
OnError(kDummyExtensionId, image_writer_api::STAGE_VERIFYWRITE, _, _))
.Times(1);
FillFile(test_device_path_, kDevicePattern, kTestFileSize);
test_utils_.FillFile(
test_utils_.GetDevicePath(), kDevicePattern, kTestFileSize);
operation_->Start();
content::BrowserThread::PostTask(content::BrowserThread::FILE,
......@@ -257,9 +251,9 @@ TEST_F(ImageWriterOperationTest, VerifyFileFailure) {
base::RunLoop().RunUntilIdle();
client_->Progress(0);
client_->Progress(kTestFileSize / 2);
client_->Error(error::kVerificationFailed);
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(kTestFileSize / 2);
test_utils_.GetUtilityClient()->Error(error::kVerificationFailed);
base::RunLoop().RunUntilIdle();
}
......
......@@ -77,6 +77,9 @@ void FakeImageWriterClient::Write(const ProgressCallback& progress_callback,
progress_callback_ = progress_callback;
success_callback_ = success_callback;
error_callback_ = error_callback;
if (!write_callback_.is_null())
write_callback_.Run();
}
void FakeImageWriterClient::Verify(const ProgressCallback& progress_callback,
......@@ -87,6 +90,9 @@ void FakeImageWriterClient::Verify(const ProgressCallback& progress_callback,
progress_callback_ = progress_callback;
success_callback_ = success_callback;
error_callback_ = error_callback;
if (!verify_callback_.is_null())
verify_callback_.Run();
}
void FakeImageWriterClient::Cancel(const CancelCallback& cancel_callback) {
......@@ -95,35 +101,55 @@ void FakeImageWriterClient::Cancel(const CancelCallback& cancel_callback) {
void FakeImageWriterClient::Shutdown() {
// Clear handlers to not hold any reference to the caller.
success_callback_ = base::Closure();
progress_callback_ = base::Callback<void(int64)>();
error_callback_ = base::Callback<void(const std::string&)>();
cancel_callback_ = base::Closure();
success_callback_.Reset();
progress_callback_.Reset();
error_callback_.Reset();
cancel_callback_.Reset();
write_callback_.Reset();
verify_callback_.Reset();
}
void FakeImageWriterClient::SetWriteCallback(
const base::Closure& write_callback) {
write_callback_ = write_callback;
}
void FakeImageWriterClient::SetVerifyCallback(
const base::Closure& verify_callback) {
verify_callback_ = verify_callback;
}
void FakeImageWriterClient::Progress(int64 progress) {
progress_callback_.Run(progress);
if (!progress_callback_.is_null())
progress_callback_.Run(progress);
}
void FakeImageWriterClient::Success() { success_callback_.Run(); }
void FakeImageWriterClient::Success() {
if (!success_callback_.is_null())
success_callback_.Run();
}
void FakeImageWriterClient::Error(const std::string& message) {
error_callback_.Run(message);
if (!error_callback_.is_null())
error_callback_.Run(message);
}
void FakeImageWriterClient::Cancel() { cancel_callback_.Run(); }
scoped_refptr<FakeImageWriterClient> FakeImageWriterClient::Create() {
return scoped_refptr<FakeImageWriterClient>(new FakeImageWriterClient());
void FakeImageWriterClient::Cancel() {
if (!cancel_callback_.is_null())
cancel_callback_.Run();
}
ImageWriterUnitTestBase::ImageWriterUnitTestBase()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {}
ImageWriterUnitTestBase::~ImageWriterUnitTestBase() {}
ImageWriterTestUtils::ImageWriterTestUtils() {
}
ImageWriterTestUtils::~ImageWriterTestUtils() {
}
void ImageWriterUnitTestBase::SetUp() {
testing::Test::SetUp();
void ImageWriterTestUtils::SetUp() {
SetUp(false);
}
void ImageWriterTestUtils::SetUp(bool is_browser_test) {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.path(),
&test_image_path_));
......@@ -137,11 +163,20 @@ void ImageWriterUnitTestBase::SetUp() {
if (!chromeos::DBusThreadManager::IsInitialized()) {
chromeos::FakeDBusThreadManager* fake_dbus_thread_manager =
new chromeos::FakeDBusThreadManager;
fake_dbus_thread_manager->SetFakeClients();
scoped_ptr<chromeos::ImageBurnerClient>
image_burner_fake(new ImageWriterFakeImageBurnerClient());
fake_dbus_thread_manager->SetImageBurnerClient(image_burner_fake.Pass());
chromeos::DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager);
if (is_browser_test) {
chromeos::DBusThreadManager::SetInstanceForTesting(
fake_dbus_thread_manager);
} else {
chromeos::DBusThreadManager::InitializeForTesting(
fake_dbus_thread_manager);
}
}
FakeDiskMountManager* disk_manager = new FakeDiskMountManager();
chromeos::disks::DiskMountManager::InitializeForTesting(disk_manager);
......@@ -162,30 +197,54 @@ void ImageWriterUnitTestBase::SetUp() {
true,
false);
disk_manager->SetupDefaultReplies();
#else
client_ = new FakeImageWriterClient();
image_writer::Operation::SetUtilityClientForTesting(client_);
#endif
}
void ImageWriterUnitTestBase::TearDown() {
void ImageWriterTestUtils::TearDown() {
#if defined(OS_CHROMEOS)
chromeos::DBusThreadManager::Shutdown();
if (chromeos::DBusThreadManager::IsInitialized()) {
chromeos::DBusThreadManager::Shutdown();
}
chromeos::disks::DiskMountManager::Shutdown();
#else
image_writer::Operation::SetUtilityClientForTesting(NULL);
client_->Shutdown();
#endif
}
bool ImageWriterUnitTestBase::ImageWrittenToDevice(
const base::FilePath& image_path,
const base::FilePath& device_path) {
const base::FilePath& ImageWriterTestUtils::GetTempDir() {
return temp_dir_.path();
}
const base::FilePath& ImageWriterTestUtils::GetImagePath() {
return test_image_path_;
}
const base::FilePath& ImageWriterTestUtils::GetDevicePath() {
return test_device_path_;
}
#if !defined(OS_CHROMEOS)
FakeImageWriterClient* ImageWriterTestUtils::GetUtilityClient() {
return client_.get();
}
#endif
bool ImageWriterTestUtils::ImageWrittenToDevice() {
scoped_ptr<char[]> image_buffer(new char[kTestFileSize]);
scoped_ptr<char[]> device_buffer(new char[kTestFileSize]);
int image_bytes_read =
ReadFile(image_path, image_buffer.get(), kTestFileSize);
ReadFile(test_image_path_, image_buffer.get(), kTestFileSize);
if (image_bytes_read < 0)
return false;
int device_bytes_read =
ReadFile(device_path, device_buffer.get(), kTestFileSize);
ReadFile(test_device_path_, device_buffer.get(), kTestFileSize);
if (image_bytes_read != device_bytes_read)
return false;
......@@ -193,14 +252,30 @@ bool ImageWriterUnitTestBase::ImageWrittenToDevice(
return memcmp(image_buffer.get(), device_buffer.get(), image_bytes_read) == 0;
}
bool ImageWriterUnitTestBase::FillFile(const base::FilePath& file,
const int pattern,
const int length) {
bool ImageWriterTestUtils::FillFile(const base::FilePath& file,
const int pattern,
const int length) {
scoped_ptr<char[]> buffer(new char[length]);
memset(buffer.get(), pattern, length);
return base::WriteFile(file, buffer.get(), length) == length;
}
ImageWriterUnitTestBase::ImageWriterUnitTestBase()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
}
ImageWriterUnitTestBase::~ImageWriterUnitTestBase() {
}
void ImageWriterUnitTestBase::SetUp() {
testing::Test::SetUp();
test_utils_.SetUp();
}
void ImageWriterUnitTestBase::TearDown() {
testing::Test::TearDown();
test_utils_.TearDown();
}
} // namespace image_writer
} // namespace extensions
......@@ -65,20 +65,6 @@ class FakeDiskMountManager : public chromeos::disks::MockDiskMountManager {
virtual void UnmountDeviceRecursively(
const std::string& device_path,
const UnmountDeviceRecursivelyCallbackType& callback) OVERRIDE;
/*
MOCK_METHOD1(AddObserver, void(chromeos::disks::DiskMountManager::Observer*));
MOCK_METHOD1(RemoveObserver,
void(chromeos::disks::DiskMountManager::Observer*));
MOCK_CONST_METHOD0(disks, const DiskMap&());
MOCK_CONST_METHOD1(FindDiskBySourcePath, const Disk*(const std::string&));
MOCK_CONST_METHOD0(mount_points, const MountPointMap&());
MOCK_METHOD0(RequestMountInfoRefresh, void());
MOCK_METHOD4(MountPath, void(const std::string&, const std::string&, const
std::string&, chromeos::MountType));
MOCK_METHOD3(UnmountPath, void(const std::string&, chromeos::UnmountOptions,
const UnmountPathCallback&));
MOCK_METHOD1(FormatMountedDevice, void(const std::string&));
*/
private:
DiskMap disks_;
......@@ -105,11 +91,19 @@ class FakeImageWriterClient : public ImageWriterUtilityClient {
virtual void Shutdown() OVERRIDE;
// Sets a callback for when a Write call is made.
void SetWriteCallback(const base::Closure& write_callback);
// Sets a callback for when a Verify call is made.
void SetVerifyCallback(const base::Closure& verify_callback);
// Triggers the progress callback.
void Progress(int64 progress);
// Triggers the success callback.
void Success();
// Triggers the error callback.
void Error(const std::string& message);
// Triggers the cancel callback.
void Cancel();
static scoped_refptr<FakeImageWriterClient> Create();
private:
virtual ~FakeImageWriterClient();
......@@ -118,23 +112,20 @@ class FakeImageWriterClient : public ImageWriterUtilityClient {
SuccessCallback success_callback_;
ErrorCallback error_callback_;
CancelCallback cancel_callback_;
};
// Base class for unit tests that manages creating image and device files.
class ImageWriterUnitTestBase : public testing::Test {
protected:
ImageWriterUnitTestBase();
virtual ~ImageWriterUnitTestBase();
virtual void SetUp() OVERRIDE;
base::Closure write_callback_;
base::Closure verify_callback_;
};
virtual void TearDown() OVERRIDE;
class ImageWriterTestUtils {
public:
ImageWriterTestUtils();
virtual ~ImageWriterTestUtils();
// Verifies that the data in image_path was written to the file at
// device_path. This is different from base::ContentsEqual because the device
// may be larger than the image.
bool ImageWrittenToDevice(const base::FilePath& image_path,
const base::FilePath& device_path);
bool ImageWrittenToDevice();
// Fills |file| with |length| bytes of |pattern|, overwriting any existing
// data.
......@@ -142,10 +133,47 @@ class ImageWriterUnitTestBase : public testing::Test {
const int pattern,
const int length);
// Set up the test utils, creating temporary folders and such.
// Note that browser tests should use the alternate form and pass "true" as an
// argument.
virtual void SetUp();
// Set up the test utils, creating temporary folders and such. If
// |is_browser_test| is true then it will use alternate initialization
// appropriate for a browser test. This should be run in
// |SetUpInProcessBrowserTestFixture|.
virtual void SetUp(bool is_browser_test);
virtual void TearDown();
const base::FilePath& GetTempDir();
const base::FilePath& GetImagePath();
const base::FilePath& GetDevicePath();
#if !defined(OS_CHROMEOS)
FakeImageWriterClient* GetUtilityClient();
#endif
protected:
base::ScopedTempDir temp_dir_;
base::FilePath test_image_path_;
base::FilePath test_device_path_;
#if !defined(OS_CHROMEOS)
scoped_refptr<FakeImageWriterClient> client_;
#endif
};
// Base class for unit tests that manages creating image and device files.
class ImageWriterUnitTestBase : public testing::Test {
protected:
ImageWriterUnitTestBase();
virtual ~ImageWriterUnitTestBase();
virtual void SetUp() OVERRIDE;
virtual void TearDown() OVERRIDE;
ImageWriterTestUtils test_utils_;
private:
content::TestBrowserThreadBundle thread_bundle_;
};
......
......@@ -27,10 +27,10 @@ TEST_F(ImageWriterFromFileTest, InvalidFile) {
scoped_refptr<WriteFromFileOperation> op =
new WriteFromFileOperation(manager_.AsWeakPtr(),
kDummyExtensionId,
test_image_path_,
test_device_path_.AsUTF8Unsafe());
test_utils_.GetImagePath(),
test_utils_.GetDevicePath().AsUTF8Unsafe());
base::DeleteFile(test_image_path_, false);
base::DeleteFile(test_utils_.GetImagePath(), false);
EXPECT_CALL(manager_, OnProgress(kDummyExtensionId, _, _)).Times(0);
EXPECT_CALL(manager_, OnComplete(kDummyExtensionId)).Times(0);
......@@ -50,13 +50,8 @@ TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) {
scoped_refptr<WriteFromFileOperation> op =
new WriteFromFileOperation(manager_.AsWeakPtr(),
kDummyExtensionId,
test_image_path_,
test_device_path_.AsUTF8Unsafe());
#if !defined(OS_CHROMEOS)
scoped_refptr<FakeImageWriterClient> client = FakeImageWriterClient::Create();
op->SetUtilityClientForTesting(client);
#endif
test_utils_.GetImagePath(),
test_utils_.GetDevicePath().AsUTF8Unsafe());
EXPECT_CALL(manager_,
OnProgress(kDummyExtensionId, image_writer_api::STAGE_WRITE, _))
.Times(AnyNumber());
......@@ -90,15 +85,15 @@ TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) {
base::RunLoop().RunUntilIdle();
#if !defined(OS_CHROMEOS)
client->Progress(0);
client->Progress(50);
client->Progress(100);
client->Success();
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(50);
test_utils_.GetUtilityClient()->Progress(100);
test_utils_.GetUtilityClient()->Success();
base::RunLoop().RunUntilIdle();
client->Progress(0);
client->Progress(50);
client->Progress(100);
client->Success();
test_utils_.GetUtilityClient()->Progress(0);
test_utils_.GetUtilityClient()->Progress(50);
test_utils_.GetUtilityClient()->Progress(100);
test_utils_.GetUtilityClient()->Success();
base::RunLoop().RunUntilIdle();
#endif
}
......
......@@ -77,7 +77,8 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
// Turn on interception and set up our dummy file.
net::URLFetcher::SetEnableInterceptionForTests(true);
get_interceptor_.reset(new GetInterceptor());
get_interceptor_->SetResponse(GURL(kTestImageUrl), test_image_path_);
get_interceptor_->SetResponse(GURL(kTestImageUrl),
test_utils_.GetImagePath());
}
virtual void TearDown() OVERRIDE {
......@@ -95,7 +96,7 @@ class ImageWriterWriteFromUrlOperationTest : public ImageWriterUnitTestBase {
test_profile_.GetRequestContext(),
url,
hash,
test_device_path_.AsUTF8Unsafe()));
test_utils_.GetDevicePath().AsUTF8Unsafe()));
operation->Start();
return operation;
}
......@@ -140,8 +141,8 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
scoped_refptr<OperationForTest> operation =
CreateOperation(GURL(kTestImageUrl), "");
EXPECT_TRUE(
base::CreateTemporaryFileInDir(temp_dir_.path(), &download_target_path));
EXPECT_TRUE(base::CreateTemporaryFileInDir(test_utils_.GetTempDir(),
&download_target_path));
operation->SetImagePath(download_target_path);
EXPECT_CALL(
......@@ -164,7 +165,8 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
runloop.Run();
EXPECT_TRUE(base::ContentsEqual(test_image_path_, operation->GetImagePath()));
EXPECT_TRUE(base::ContentsEqual(test_utils_.GetImagePath(),
operation->GetImagePath()));
EXPECT_EQ(1, get_interceptor_->GetHitCount());
......@@ -173,7 +175,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, DownloadFile) {
TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) {
scoped_ptr<char[]> data_buffer(new char[kTestFileSize]);
base::ReadFile(test_image_path_, data_buffer.get(), kTestFileSize);
base::ReadFile(test_utils_.GetImagePath(), data_buffer.get(), kTestFileSize);
base::MD5Digest expected_digest;
base::MD5Sum(data_buffer.get(), kTestFileSize, &expected_digest);
std::string expected_hash = base::MD5DigestToBase16(expected_digest);
......@@ -194,7 +196,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) {
image_writer_api::STAGE_VERIFYDOWNLOAD,
100)).Times(AtLeast(1));
operation->SetImagePath(test_image_path_);
operation->SetImagePath(test_utils_.GetImagePath());
content::BrowserThread::PostTask(content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&OperationForTest::VerifyDownload,
......
......@@ -1106,6 +1106,7 @@
'browser/extensions/api/idle/idle_apitest.cc',
'browser/extensions/api/idltest/idltest_apitest.cc',
'browser/extensions/api/image_writer_private/image_writer_private_apitest.cc',
'browser/extensions/api/image_writer_private/test_utils.cc',
'browser/extensions/api/input_ime/input_ime_apitest_chromeos.cc',
'browser/extensions/api/management/management_api_browsertest.cc',
'browser/extensions/api/management/management_apitest.cc',
......
......@@ -2,16 +2,17 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// storage_unit_id is skipped because it is generated to point at a temporary
// file.
var expectedDevices = [{
'vendor': 'Vendor 1',
'model': 'Model 1',
'capacity': 1 << 20,
'storageUnitId': '/test/id/1',
'capacity': 1 << 15,
}, {
'vendor': 'Vendor 2',
'model': 'Model 2',
'capacity': 1 << 22,
'storageUnitId': '/test/id/2',
'capacity': 1 << 17,
}];
......@@ -34,7 +35,6 @@ function listRemovableDevicesCallback(deviceList) {
chrome.test.assertEq(expected.vendor, dev.vendor);
chrome.test.assertEq(expected.model, dev.model);
chrome.test.assertEq(expected.capacity, dev.capacity);
chrome.test.assertEq(expected.storageUnitId, dev.storageUnitId);
});
}
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
chrome.app.runtime.onLaunched.addListener(function () {
chrome.app.window.create('test.html');
});
{
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6aedfP5QXnA176+/EKXFwbBoXl3smca9uaO1ytfLCRsH8Ja0xrjJG+/2tvcCL1JzBbc8/31cwWIOiNFawJiIc+nfZAi4rO27yakn4W83kHOhjr7hA4/a+CtmOPTTgpK1DCIpo0Xy+lpzQuqHBKL9/sXMCN4bKqcXMe7XA09VJYD6Rv+CTDfKkgN3oNYhm0KBOwkvJ/P7x7KeBUCusd+UOzJygBP4p2mDgIX/WfUZAuRGq1ty/Eu9dBm29Jhe1YBctFaARyR5FnMsr57Kw/mWrNXkZ2iewrLUzNh1FWLQUbiL4QdqaP9//Xxhsrf+LG1UcJN1HBnn/b0xYLfcH9W7RQIDAQAB",
"name": "Image Writer Private",
"version": "0.1",
"app": {
"background": {
"scripts": ["background.js"]
}
},
"permissions": ["imageWriterPrivate", "fileSystem"]
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function assertNotNullOrUndefined(value, message) {
chrome.test.assertTrue(value !== null, message);
chrome.test.assertTrue(value !== undefined, message);
}
function testWriteFromFile() {
var fileEntry;
var storageDevice;
var currentStage = "none";
var currentProgress = -1;
var started = true;
function chooseEntryCallback(entry) {
fileEntry = entry;
chrome.imageWriterPrivate.listRemovableStorageDevices(
listDevicesCallback);
}
function listDevicesCallback(deviceList) {
chrome.test.assertTrue(deviceList.length >= 1);
storageDevice = deviceList[0];
startWrite();
}
function startWrite() {
assertNotNullOrUndefined(fileEntry, "FileEntry should be defined.");
assertNotNullOrUndefined(
storageDevice.storageUnitId, "Storage Unit should be defined.");
chrome.imageWriterPrivate.writeFromFile(
storageDevice.storageUnitId,
fileEntry,
startWriteCallback);
}
function startWriteCallback() {
started = true;
}
function writeProgressCallback(progressInfo) {
currentProgress = progressInfo.percentComplete;
currentStage = progressInfo.stage;
}
function writeCompleteCallback() {
chrome.test.assertTrue(started, "Complete triggered before being started.");
chrome.test.assertEq(100, currentProgress);
chrome.test.succeed("Write completed successfully.");
}
function writeErrorCallback(message) {
chrome.test.fail("An error occurred during writing.");
}
chrome.imageWriterPrivate.onWriteProgress.
addListener(writeProgressCallback);
chrome.imageWriterPrivate.onWriteComplete.
addListener(writeCompleteCallback);
chrome.imageWriterPrivate.onWriteError.
addListener(writeErrorCallback);
chrome.fileSystem.chooseEntry(chooseEntryCallback);
}
testWriteFromFile();
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment