copy_or_move_operation_delegate_unittest.cc 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  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.
  4. #include <stddef.h>
  5. #include <stdint.h>
  6. #include <map>
  7. #include <memory>
  8. #include <string>
  9. #include <utility>
  10. #include <vector>
  11. #include "base/bind.h"
  12. #include "base/callback_helpers.h"
  13. #include "base/containers/contains.h"
  14. #include "base/containers/queue.h"
  15. #include "base/containers/span.h"
  16. #include "base/files/file_util.h"
  17. #include "base/files/scoped_temp_dir.h"
  18. #include "base/location.h"
  19. #include "base/memory/raw_ptr.h"
  20. #include "base/memory/scoped_refptr.h"
  21. #include "base/ranges/algorithm.h"
  22. #include "base/run_loop.h"
  23. #include "base/task/single_thread_task_runner.h"
  24. #include "base/test/task_environment.h"
  25. #include "base/threading/thread.h"
  26. #include "base/threading/thread_task_runner_handle.h"
  27. #include "base/time/time.h"
  28. #include "components/services/filesystem/public/mojom/types.mojom.h"
  29. #include "storage/browser/file_system/copy_or_move_file_validator.h"
  30. #include "storage/browser/file_system/copy_or_move_hook_delegate.h"
  31. #include "storage/browser/file_system/copy_or_move_operation_delegate.h"
  32. #include "storage/browser/file_system/file_stream_reader.h"
  33. #include "storage/browser/file_system/file_stream_writer.h"
  34. #include "storage/browser/file_system/file_system_backend.h"
  35. #include "storage/browser/file_system/file_system_context.h"
  36. #include "storage/browser/file_system/file_system_operation.h"
  37. #include "storage/browser/file_system/file_system_url.h"
  38. #include "storage/browser/file_system/file_system_util.h"
  39. #include "storage/browser/quota/quota_manager.h"
  40. #include "storage/browser/test/async_file_test_helper.h"
  41. #include "storage/browser/test/file_system_test_file_set.h"
  42. #include "storage/browser/test/mock_quota_manager.h"
  43. #include "storage/browser/test/mock_quota_manager_proxy.h"
  44. #include "storage/browser/test/mock_special_storage_policy.h"
  45. #include "storage/browser/test/test_file_system_backend.h"
  46. #include "storage/browser/test/test_file_system_context.h"
  47. #include "storage/common/file_system/file_system_mount_option.h"
  48. #include "storage/common/file_system/file_system_types.h"
  49. #include "storage/common/file_system/file_system_util.h"
  50. #include "testing/gmock/include/gmock/gmock.h"
  51. #include "testing/gtest/include/gtest/gtest.h"
  52. #include "third_party/blink/public/common/storage_key/storage_key.h"
  53. #include "url/gurl.h"
  54. #include "url/origin.h"
  55. namespace storage {
  56. namespace {
  57. using FileEntryList = FileSystemOperation::FileEntryList;
  58. constexpr int64_t kDefaultFileSize = 10;
  59. void ExpectOk(const GURL& origin_url,
  60. const std::string& name,
  61. base::File::Error error) {
  62. ASSERT_EQ(base::File::FILE_OK, error);
  63. }
  64. class TestValidatorFactory : public CopyOrMoveFileValidatorFactory {
  65. public:
  66. // A factory that creates validators that accept everything or nothing.
  67. TestValidatorFactory() = default;
  68. ~TestValidatorFactory() override = default;
  69. CopyOrMoveFileValidator* CreateCopyOrMoveFileValidator(
  70. const FileSystemURL& /*src_url*/,
  71. const base::FilePath& /*platform_path*/) override {
  72. // Move arg management to TestValidator?
  73. return new TestValidator(true, true, std::string("2"));
  74. }
  75. private:
  76. class TestValidator : public CopyOrMoveFileValidator {
  77. public:
  78. explicit TestValidator(bool pre_copy_valid,
  79. bool post_copy_valid,
  80. const std::string& reject_string)
  81. : result_(pre_copy_valid ? base::File::FILE_OK
  82. : base::File::FILE_ERROR_SECURITY),
  83. write_result_(post_copy_valid ? base::File::FILE_OK
  84. : base::File::FILE_ERROR_SECURITY),
  85. reject_string_(reject_string) {}
  86. TestValidator(const TestValidator&) = delete;
  87. TestValidator& operator=(const TestValidator&) = delete;
  88. ~TestValidator() override = default;
  89. void StartPreWriteValidation(ResultCallback result_callback) override {
  90. // Post the result since a real validator must do work asynchronously.
  91. base::ThreadTaskRunnerHandle::Get()->PostTask(
  92. FROM_HERE, base::BindOnce(std::move(result_callback), result_));
  93. }
  94. void StartPostWriteValidation(const base::FilePath& dest_platform_path,
  95. ResultCallback result_callback) override {
  96. base::File::Error result = write_result_;
  97. std::string unsafe = dest_platform_path.BaseName().AsUTF8Unsafe();
  98. if (unsafe.find(reject_string_) != std::string::npos) {
  99. result = base::File::FILE_ERROR_SECURITY;
  100. }
  101. // Post the result since a real validator must do work asynchronously.
  102. base::ThreadTaskRunnerHandle::Get()->PostTask(
  103. FROM_HERE, base::BindOnce(std::move(result_callback), result));
  104. }
  105. private:
  106. base::File::Error result_;
  107. base::File::Error write_result_;
  108. std::string reject_string_;
  109. };
  110. };
  111. class CopyOrMoveRecordAndSecurityDelegate : public CopyOrMoveHookDelegate {
  112. public:
  113. // Records method invocations.
  114. struct ProgressRecord {
  115. enum class Type {
  116. kBeginFile = 0,
  117. kBeginDirectory,
  118. kProgress,
  119. kEndCopy,
  120. kEndMove,
  121. kEndRemoveSource,
  122. kError,
  123. } type;
  124. FileSystemURL source_url;
  125. FileSystemURL dest_url;
  126. int64_t size;
  127. base::File::Error error;
  128. };
  129. using StatusCallback = FileSystemOperation::StatusCallback;
  130. // Required callback to check whether a file/directory should be blocked for
  131. // transfer. The callback returns true if the transfer should be blocked.
  132. using ShouldBlockCallback =
  133. base::RepeatingCallback<bool(const FileSystemURL& source_url)>;
  134. explicit CopyOrMoveRecordAndSecurityDelegate(
  135. std::vector<ProgressRecord>& records,
  136. const ShouldBlockCallback& should_block_callback)
  137. : records_(records), should_block_callback_(should_block_callback) {}
  138. ~CopyOrMoveRecordAndSecurityDelegate() override = default;
  139. void OnBeginProcessFile(const FileSystemURL& source_url,
  140. const FileSystemURL& destination_url,
  141. StatusCallback callback) override {
  142. AddRecord(ProgressRecord::Type::kBeginFile, source_url, destination_url, 0,
  143. base::File::FILE_OK);
  144. if (should_block_callback_.Run(source_url)) {
  145. std::move(callback).Run(base::File::FILE_ERROR_SECURITY);
  146. } else {
  147. std::move(callback).Run(base::File::FILE_OK);
  148. }
  149. }
  150. void OnBeginProcessDirectory(const FileSystemURL& source_url,
  151. const FileSystemURL& destination_url,
  152. StatusCallback callback) override {
  153. AddRecord(ProgressRecord::Type::kBeginDirectory, source_url,
  154. destination_url, 0, base::File::FILE_OK);
  155. if (should_block_callback_.Run(source_url)) {
  156. std::move(callback).Run(base::File::FILE_ERROR_SECURITY);
  157. } else {
  158. std::move(callback).Run(base::File::FILE_OK);
  159. }
  160. }
  161. void OnProgress(const FileSystemURL& source_url,
  162. const FileSystemURL& destination_url,
  163. int64_t size) override {
  164. AddRecord(ProgressRecord::Type::kProgress, source_url, destination_url,
  165. size, base::File::FILE_OK);
  166. }
  167. void OnError(const FileSystemURL& source_url,
  168. const FileSystemURL& destination_url,
  169. base::File::Error error) override {
  170. AddRecord(ProgressRecord::Type::kError, source_url, destination_url, 0,
  171. error);
  172. }
  173. void OnEndCopy(const FileSystemURL& source_url,
  174. const FileSystemURL& destination_url) override {
  175. AddRecord(ProgressRecord::Type::kEndCopy, source_url, destination_url, 0,
  176. base::File::FILE_OK);
  177. }
  178. void OnEndMove(const FileSystemURL& source_url,
  179. const FileSystemURL& destination_url) override {
  180. AddRecord(ProgressRecord::Type::kEndMove, source_url, destination_url, 0,
  181. base::File::FILE_OK);
  182. }
  183. void OnEndRemoveSource(const FileSystemURL& source_url) override {
  184. AddRecord(ProgressRecord::Type::kEndRemoveSource, source_url,
  185. FileSystemURL(), 0, base::File::FILE_OK);
  186. }
  187. private:
  188. void AddRecord(ProgressRecord::Type type,
  189. const FileSystemURL& source_url,
  190. const FileSystemURL& dest_url,
  191. int64_t size,
  192. base::File::Error error) {
  193. ProgressRecord record;
  194. record.type = type;
  195. record.source_url = source_url;
  196. record.dest_url = dest_url;
  197. record.size = size;
  198. record.error = error;
  199. records_.push_back(record);
  200. }
  201. // Raw ptr safe here, because the records will be destructed at end of test,
  202. // i.e., after the CopyOrMove operation has finished.
  203. std::vector<ProgressRecord>& records_;
  204. ShouldBlockCallback should_block_callback_;
  205. };
  206. void RecordFileProgressCallback(std::vector<int64_t>* records,
  207. int64_t progress) {
  208. records->push_back(progress);
  209. }
  210. void AssignAndQuit(base::RunLoop* run_loop,
  211. base::File::Error* result_out,
  212. base::File::Error result) {
  213. *result_out = result;
  214. run_loop->Quit();
  215. }
  216. class ScopedThreadStopper {
  217. public:
  218. explicit ScopedThreadStopper(base::Thread* thread) : thread_(thread) {}
  219. ScopedThreadStopper(const ScopedThreadStopper&) = delete;
  220. ScopedThreadStopper& operator=(const ScopedThreadStopper&) = delete;
  221. ~ScopedThreadStopper() {
  222. if (thread_) {
  223. // Give another chance for deleted streams to perform Close.
  224. base::RunLoop run_loop;
  225. thread_->task_runner()->PostTaskAndReply(FROM_HERE, base::DoNothing(),
  226. run_loop.QuitClosure());
  227. run_loop.Run();
  228. thread_->Stop();
  229. }
  230. }
  231. bool is_valid() const { return thread_; }
  232. private:
  233. raw_ptr<base::Thread> thread_;
  234. };
  235. class CopyOrMoveOperationTestHelper {
  236. public:
  237. CopyOrMoveOperationTestHelper(const std::string& origin,
  238. FileSystemType src_type,
  239. FileSystemType dest_type)
  240. : origin_(url::Origin::Create(GURL(origin))),
  241. src_type_(src_type),
  242. dest_type_(dest_type),
  243. special_storage_policy_(
  244. base::MakeRefCounted<MockSpecialStoragePolicy>()),
  245. task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {}
  246. CopyOrMoveOperationTestHelper(const CopyOrMoveOperationTestHelper&) = delete;
  247. CopyOrMoveOperationTestHelper& operator=(
  248. const CopyOrMoveOperationTestHelper&) = delete;
  249. ~CopyOrMoveOperationTestHelper() {
  250. file_system_context_ = nullptr;
  251. quota_manager_ = nullptr;
  252. quota_manager_proxy_ = nullptr;
  253. task_environment_.RunUntilIdle();
  254. }
  255. void SetUp() { SetUp(true, true); }
  256. void SetUpNoValidator() { SetUp(true, false); }
  257. void SetUp(bool require_copy_or_move_validator,
  258. bool init_copy_or_move_validator) {
  259. ASSERT_TRUE(base_.CreateUniqueTempDir());
  260. base::FilePath base_dir = base_.GetPath();
  261. quota_manager_ = base::MakeRefCounted<MockQuotaManager>(
  262. false /* is_incognito */, base_dir, base::ThreadTaskRunnerHandle::Get(),
  263. special_storage_policy_);
  264. quota_manager_proxy_ = base::MakeRefCounted<MockQuotaManagerProxy>(
  265. quota_manager_.get(), base::ThreadTaskRunnerHandle::Get());
  266. file_system_context_ =
  267. CreateFileSystemContextForTesting(quota_manager_proxy_, base_dir);
  268. // Prepare the origin's root directory.
  269. FileSystemBackend* backend =
  270. file_system_context_->GetFileSystemBackend(src_type_);
  271. backend->ResolveURL(
  272. FileSystemURL::CreateForTest(blink::StorageKey(url::Origin(origin_)),
  273. src_type_, base::FilePath()),
  274. OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::BindOnce(&ExpectOk));
  275. backend = file_system_context_->GetFileSystemBackend(dest_type_);
  276. if (dest_type_ == kFileSystemTypeTest) {
  277. TestFileSystemBackend* test_backend =
  278. static_cast<TestFileSystemBackend*>(backend);
  279. auto factory = std::make_unique<TestValidatorFactory>();
  280. test_backend->set_require_copy_or_move_validator(
  281. require_copy_or_move_validator);
  282. if (init_copy_or_move_validator)
  283. test_backend->InitializeCopyOrMoveFileValidatorFactory(
  284. std::move(factory));
  285. }
  286. backend->ResolveURL(
  287. FileSystemURL::CreateForTest(blink::StorageKey(url::Origin(origin_)),
  288. dest_type_, base::FilePath()),
  289. OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::BindOnce(&ExpectOk));
  290. task_environment_.RunUntilIdle();
  291. // Grant relatively big quota initially.
  292. quota_manager_->SetQuota(blink::StorageKey(origin_),
  293. FileSystemTypeToQuotaStorageType(src_type_),
  294. 1024 * 1024);
  295. quota_manager_->SetQuota(blink::StorageKey(origin_),
  296. FileSystemTypeToQuotaStorageType(dest_type_),
  297. 1024 * 1024);
  298. }
  299. int64_t GetSourceUsage() {
  300. int64_t usage = 0;
  301. GetUsageAndQuota(src_type_, &usage, nullptr);
  302. return usage;
  303. }
  304. int64_t GetDestUsage() {
  305. int64_t usage = 0;
  306. GetUsageAndQuota(dest_type_, &usage, nullptr);
  307. return usage;
  308. }
  309. FileSystemURL SourceURL(const std::string& path) {
  310. return file_system_context_->CreateCrackedFileSystemURL(
  311. blink::StorageKey(origin_), src_type_,
  312. base::FilePath::FromUTF8Unsafe(path));
  313. }
  314. FileSystemURL DestURL(const std::string& path) {
  315. return file_system_context_->CreateCrackedFileSystemURL(
  316. blink::StorageKey(origin_), dest_type_,
  317. base::FilePath::FromUTF8Unsafe(path));
  318. }
  319. base::File::Error Copy(const FileSystemURL& src, const FileSystemURL& dest) {
  320. return AsyncFileTestHelper::Copy(file_system_context_.get(), src, dest);
  321. }
  322. base::File::Error CopyWithHookDelegate(
  323. const FileSystemURL& src,
  324. const FileSystemURL& dest,
  325. FileSystemOperation::ErrorBehavior error_behavior,
  326. std::unique_ptr<storage::CopyOrMoveHookDelegate>
  327. copy_or_move_hook_delegate) {
  328. return AsyncFileTestHelper::CopyWithHookDelegate(
  329. file_system_context_.get(), src, dest, error_behavior,
  330. std::move(copy_or_move_hook_delegate));
  331. }
  332. base::File::Error CopyBlockAll(const FileSystemURL& src,
  333. const FileSystemURL& dest) {
  334. CopyOrMoveRecordAndSecurityDelegate::ShouldBlockCallback blocking_callback =
  335. base::BindRepeating(
  336. [](const FileSystemURL& source_url) { return true; });
  337. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord> records;
  338. return CopyWithHookDelegate(
  339. src, dest, FileSystemOperation::ERROR_BEHAVIOR_ABORT,
  340. std::make_unique<CopyOrMoveRecordAndSecurityDelegate>(
  341. records, blocking_callback));
  342. }
  343. // Determines whether a specific `src` should be blocked.
  344. // It uses the relative path of `src` from `root_src` and compares this path
  345. // with the records within `kRegularFileSystemTestCases`. It blocks the `src`
  346. // if the corresponding test case's block_action is `BLOCKED`.
  347. // Additionally, it ensures that this function is not called for test cases
  348. // with block_action `PARENT_BLOCKED`.
  349. static bool ShouldBlockSource(const FileSystemURL& root_src,
  350. const FileSystemURL& src) {
  351. base::FilePath src_relative_path;
  352. if (root_src == src) {
  353. // Don't block root, because we only care about the directories/folders
  354. // within the root.
  355. return false;
  356. }
  357. root_src.virtual_path().AppendRelativePath(src.virtual_path(),
  358. &src_relative_path);
  359. src_relative_path = src_relative_path.NormalizePathSeparators();
  360. const auto records = base::make_span(kRegularFileSystemTestCases,
  361. kRegularFileSystemTestCaseSize);
  362. auto record_it = base::ranges::find(
  363. records, src_relative_path, [](const FileSystemTestCaseRecord& record) {
  364. return base::FilePath(record.path).NormalizePathSeparators();
  365. });
  366. EXPECT_NE(record_it, records.end());
  367. EXPECT_NE(record_it->block_action, TestBlockAction::PARENT_BLOCKED);
  368. return record_it->block_action == TestBlockAction::BLOCKED;
  369. }
  370. // Copy the `root` directory, but block some files that are expected to be
  371. // blocked based on `kRegularFileSystemTestCases`.
  372. base::File::Error CopyBlockSome(
  373. const FileSystemURL& src,
  374. const FileSystemURL& dest,
  375. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord>&
  376. records) {
  377. return CopyWithHookDelegate(
  378. src, dest, FileSystemOperation::ERROR_BEHAVIOR_SKIP,
  379. std::make_unique<CopyOrMoveRecordAndSecurityDelegate>(
  380. records,
  381. base::BindRepeating(
  382. &CopyOrMoveOperationTestHelper::ShouldBlockSource, src)));
  383. }
  384. base::File::Error Move(const FileSystemURL& src, const FileSystemURL& dest) {
  385. return AsyncFileTestHelper::Move(file_system_context_.get(), src, dest);
  386. }
  387. base::File::Error MoveWithHookDelegate(
  388. const FileSystemURL& src,
  389. const FileSystemURL& dest,
  390. FileSystemOperation::ErrorBehavior error_behavior,
  391. std::unique_ptr<storage::CopyOrMoveHookDelegate>
  392. copy_or_move_hook_delegate) {
  393. return AsyncFileTestHelper::MoveWithHookDelegate(
  394. file_system_context_.get(), src, dest, error_behavior,
  395. std::move(copy_or_move_hook_delegate));
  396. }
  397. base::File::Error MoveBlockAll(const FileSystemURL& src,
  398. const FileSystemURL& dest) {
  399. CopyOrMoveRecordAndSecurityDelegate::ShouldBlockCallback blocking_callback =
  400. base::BindRepeating(
  401. [](const FileSystemURL& source_url) { return true; });
  402. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord> records;
  403. return MoveWithHookDelegate(
  404. src, dest, FileSystemOperation::ERROR_BEHAVIOR_ABORT,
  405. std::make_unique<CopyOrMoveRecordAndSecurityDelegate>(
  406. records, blocking_callback));
  407. }
  408. // Move the `root` directory, but block some files that are expected to be
  409. // blocked based on `kRegularFileSystemTestCases`.
  410. base::File::Error MoveBlockSome(
  411. const FileSystemURL& src,
  412. const FileSystemURL& dest,
  413. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord>&
  414. records) {
  415. return MoveWithHookDelegate(
  416. src, dest, FileSystemOperation::ERROR_BEHAVIOR_SKIP,
  417. std::make_unique<CopyOrMoveRecordAndSecurityDelegate>(
  418. records,
  419. base::BindRepeating(
  420. &CopyOrMoveOperationTestHelper::ShouldBlockSource, src)));
  421. }
  422. base::File::Error SetUpTestCaseFiles(
  423. const FileSystemURL& root,
  424. const FileSystemTestCaseRecord* const test_cases,
  425. size_t test_case_size) {
  426. base::File::Error result = base::File::FILE_ERROR_FAILED;
  427. for (size_t i = 0; i < test_case_size; ++i) {
  428. const FileSystemTestCaseRecord& test_case = test_cases[i];
  429. FileSystemURL url = file_system_context_->CreateCrackedFileSystemURL(
  430. root.storage_key(), root.mount_type(),
  431. root.virtual_path().Append(test_case.path));
  432. if (test_case.is_directory)
  433. result = CreateDirectory(url);
  434. else
  435. result = CreateFile(url, test_case.data_file_size);
  436. EXPECT_EQ(base::File::FILE_OK, result) << url.DebugString();
  437. if (result != base::File::FILE_OK)
  438. return result;
  439. }
  440. return result;
  441. }
  442. enum class VerifyDirectoryState {
  443. // Verifies all files.
  444. // Used if no blocking is specified and for the source directory after a
  445. // move.
  446. ALL_FILES_EXIST,
  447. // Verifies that only the blocked files and their ancestors exist.
  448. // Used to check the source for a move.
  449. ONLY_BLOCKED_FILES_AND_PARENTS,
  450. // Verifies that only the allowed files exist.
  451. // Used to check the destination.
  452. ONLY_ALLOWED_FILES,
  453. };
  454. void VerifyTestCaseFiles(const FileSystemURL& root,
  455. const FileSystemTestCaseRecord* const test_cases,
  456. size_t test_case_size,
  457. VerifyDirectoryState check_state) {
  458. std::map<base::FilePath, const FileSystemTestCaseRecord*> test_case_map;
  459. for (size_t i = 0; i < test_case_size; ++i) {
  460. test_case_map[base::FilePath(test_cases[i].path)
  461. .NormalizePathSeparators()] = &test_cases[i];
  462. }
  463. base::queue<FileSystemURL> directories;
  464. FileEntryList entries;
  465. directories.push(root);
  466. while (!directories.empty()) {
  467. FileSystemURL dir = directories.front();
  468. directories.pop();
  469. ASSERT_EQ(base::File::FILE_OK, ReadDirectory(dir, &entries));
  470. for (const filesystem::mojom::DirectoryEntry& entry : entries) {
  471. FileSystemURL url = file_system_context_->CreateCrackedFileSystemURL(
  472. dir.storage_key(), dir.mount_type(),
  473. dir.virtual_path().Append(entry.name));
  474. base::FilePath relative;
  475. root.virtual_path().AppendRelativePath(url.virtual_path(), &relative);
  476. relative = relative.NormalizePathSeparators();
  477. ASSERT_TRUE(base::Contains(test_case_map, relative));
  478. if (entry.type == filesystem::mojom::FsFileType::DIRECTORY) {
  479. EXPECT_TRUE(test_case_map[relative]->is_directory);
  480. directories.push(url);
  481. } else {
  482. EXPECT_FALSE(test_case_map[relative]->is_directory);
  483. EXPECT_TRUE(FileExists(url, test_case_map[relative]->data_file_size));
  484. }
  485. if (check_state ==
  486. VerifyDirectoryState::ONLY_BLOCKED_FILES_AND_PARENTS) {
  487. // We check for remaining blocked files, i.e., all files that are
  488. // actually blocked (BLOCK, PARENT_BLOCKED) and their parent
  489. // directories (CHILD_BLOCKED).
  490. EXPECT_THAT(test_case_map[relative]->block_action,
  491. ::testing::AnyOf(TestBlockAction::CHILD_BLOCKED,
  492. TestBlockAction::BLOCKED,
  493. TestBlockAction::PARENT_BLOCKED))
  494. << "path: " << relative.LossyDisplayName() << "\nblock_action: "
  495. << static_cast<int>(test_case_map[relative]->block_action);
  496. } else if (check_state == VerifyDirectoryState::ONLY_ALLOWED_FILES) {
  497. // We check for allowed files, i.e., all files that were transferred
  498. // and their parent directories (CHILD_BLOCKED, ALLOW).
  499. EXPECT_THAT(test_case_map[relative]->block_action,
  500. ::testing::AnyOf(TestBlockAction::ALLOWED,
  501. TestBlockAction::CHILD_BLOCKED))
  502. << "path: " << relative.LossyDisplayName() << "\nblock_action: "
  503. << static_cast<int>(test_case_map[relative]->block_action);
  504. }
  505. test_case_map.erase(relative);
  506. }
  507. }
  508. if (check_state == VerifyDirectoryState::ALL_FILES_EXIST) {
  509. EXPECT_TRUE(test_case_map.empty());
  510. for (const auto& path_record_pair : test_case_map) {
  511. LOG(ERROR) << "Extra entry: "
  512. << path_record_pair.first.LossyDisplayName();
  513. }
  514. } else {
  515. for (const auto& path_record_pair : test_case_map) {
  516. auto* record = path_record_pair.second;
  517. if (check_state ==
  518. VerifyDirectoryState::ONLY_BLOCKED_FILES_AND_PARENTS) {
  519. EXPECT_THAT(record->block_action,
  520. ::testing::AnyOf(TestBlockAction::ALLOWED))
  521. << "path: " << path_record_pair.first.LossyDisplayName()
  522. << "\nblock_action: " << static_cast<int>(record->block_action);
  523. } else if (check_state == VerifyDirectoryState::ONLY_ALLOWED_FILES) {
  524. EXPECT_THAT(record->block_action,
  525. ::testing::AnyOf(TestBlockAction::BLOCKED,
  526. TestBlockAction::PARENT_BLOCKED))
  527. << "path: " << path_record_pair.first.LossyDisplayName()
  528. << "\nblock_action: " << static_cast<int>(record->block_action);
  529. }
  530. }
  531. }
  532. }
  533. base::File::Error ReadDirectory(const FileSystemURL& url,
  534. FileEntryList* entries) {
  535. return AsyncFileTestHelper::ReadDirectory(file_system_context_.get(), url,
  536. entries);
  537. }
  538. base::File::Error CreateDirectory(const FileSystemURL& url) {
  539. return AsyncFileTestHelper::CreateDirectory(file_system_context_.get(),
  540. url);
  541. }
  542. base::File::Error CreateFile(const FileSystemURL& url, size_t size) {
  543. base::File::Error result =
  544. AsyncFileTestHelper::CreateFile(file_system_context_.get(), url);
  545. if (result != base::File::FILE_OK)
  546. return result;
  547. return AsyncFileTestHelper::TruncateFile(file_system_context_.get(), url,
  548. size);
  549. }
  550. bool FileExists(const FileSystemURL& url, int64_t expected_size) {
  551. return AsyncFileTestHelper::FileExists(file_system_context_.get(), url,
  552. expected_size);
  553. }
  554. bool DirectoryExists(const FileSystemURL& url) {
  555. return AsyncFileTestHelper::DirectoryExists(file_system_context_.get(),
  556. url);
  557. }
  558. private:
  559. void GetUsageAndQuota(FileSystemType type, int64_t* usage, int64_t* quota) {
  560. blink::mojom::QuotaStatusCode status =
  561. AsyncFileTestHelper::GetUsageAndQuota(quota_manager_->proxy(),
  562. blink::StorageKey(origin_), type,
  563. usage, quota);
  564. ASSERT_EQ(blink::mojom::QuotaStatusCode::kOk, status);
  565. }
  566. private:
  567. const url::Origin origin_;
  568. const FileSystemType src_type_;
  569. const FileSystemType dest_type_;
  570. scoped_refptr<MockSpecialStoragePolicy> special_storage_policy_;
  571. base::ScopedTempDir base_;
  572. base::test::TaskEnvironment task_environment_;
  573. scoped_refptr<FileSystemContext> file_system_context_;
  574. scoped_refptr<MockQuotaManagerProxy> quota_manager_proxy_;
  575. scoped_refptr<MockQuotaManager> quota_manager_;
  576. };
  577. } // namespace
  578. class LocalFileSystemCopyOrMoveOperationTest
  579. : public ::testing::TestWithParam<std::tuple</*is_move*/ bool,
  580. /*is_local*/ bool,
  581. /*blocking_enabled*/ bool>> {
  582. protected:
  583. bool IsMove() { return std::get<0>(GetParam()); }
  584. bool IsLocal() { return std::get<1>(GetParam()); }
  585. bool BlockingEnabled() { return std::get<2>(GetParam()); }
  586. };
  587. INSTANTIATE_TEST_SUITE_P(
  588. All,
  589. LocalFileSystemCopyOrMoveOperationTest,
  590. ::testing::Combine(::testing::Bool(), ::testing::Bool(), ::testing::Bool()),
  591. [](const ::testing::TestParamInfo<
  592. LocalFileSystemCopyOrMoveOperationTest::ParamType>& info) {
  593. std::string name;
  594. name += std::get<0>(info.param) ? "Move" : "Copy";
  595. name += std::get<1>(info.param) ? "Local" : "";
  596. name += std::get<2>(info.param) ? "WithBlocking" : "";
  597. return name;
  598. });
  599. TEST_P(LocalFileSystemCopyOrMoveOperationTest, SingleFile) {
  600. CopyOrMoveOperationTestHelper helper(
  601. "http://foo", kFileSystemTypeTemporary,
  602. IsLocal() ? kFileSystemTypeTemporary : kFileSystemTypePersistent);
  603. helper.SetUp();
  604. FileSystemURL src = helper.SourceURL("a");
  605. FileSystemURL dest = helper.DestURL("b");
  606. int64_t src_initial_usage = helper.GetSourceUsage();
  607. // Set up a source file.
  608. ASSERT_EQ(base::File::FILE_OK, helper.CreateFile(src, 10));
  609. int64_t src_increase = helper.GetSourceUsage() - src_initial_usage;
  610. if (IsMove()) {
  611. // Move it.
  612. if (BlockingEnabled()) {
  613. ASSERT_EQ(base::File::FILE_ERROR_SECURITY, helper.MoveBlockAll(src, dest))
  614. << "For single file moves, the last error should be a security "
  615. "error!";
  616. } else {
  617. ASSERT_EQ(base::File::FILE_OK, helper.Move(src, dest));
  618. }
  619. } else {
  620. // Copy it.
  621. if (BlockingEnabled()) {
  622. ASSERT_EQ(base::File::FILE_ERROR_SECURITY, helper.CopyBlockAll(src, dest))
  623. << "For single file copies, the last error should be a security "
  624. "error!";
  625. } else {
  626. ASSERT_EQ(base::File::FILE_OK, helper.Copy(src, dest));
  627. }
  628. }
  629. bool src_should_exist = !IsMove() || BlockingEnabled();
  630. bool dest_should_exist = !BlockingEnabled();
  631. // Verify.
  632. ASSERT_EQ(src_should_exist, helper.FileExists(src, 10));
  633. ASSERT_EQ(dest_should_exist, helper.FileExists(dest, 10));
  634. int64_t src_new_usage = helper.GetSourceUsage();
  635. if (IsMove() || BlockingEnabled()) {
  636. EXPECT_EQ(src_new_usage, src_initial_usage + src_increase);
  637. } else {
  638. EXPECT_EQ(src_new_usage, src_initial_usage + 2 * src_increase);
  639. }
  640. }
  641. TEST_P(LocalFileSystemCopyOrMoveOperationTest, EmptyDirectory) {
  642. CopyOrMoveOperationTestHelper helper(
  643. "http://foo", kFileSystemTypeTemporary,
  644. IsLocal() ? kFileSystemTypeTemporary : kFileSystemTypePersistent);
  645. helper.SetUp();
  646. FileSystemURL src = helper.SourceURL("a");
  647. FileSystemURL dest = helper.DestURL("b");
  648. int64_t src_initial_usage = helper.GetSourceUsage();
  649. // Set up a source directory.
  650. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  651. int64_t src_increase = helper.GetSourceUsage() - src_initial_usage;
  652. if (IsMove()) {
  653. // Move it.
  654. if (BlockingEnabled()) {
  655. ASSERT_EQ(base::File::FILE_ERROR_SECURITY, helper.MoveBlockAll(src, dest))
  656. << "For single directory moves, the last error should be a security "
  657. "error!";
  658. } else {
  659. ASSERT_EQ(base::File::FILE_OK, helper.Move(src, dest));
  660. }
  661. } else {
  662. // Copy it.
  663. if (BlockingEnabled()) {
  664. ASSERT_EQ(base::File::FILE_ERROR_SECURITY, helper.CopyBlockAll(src, dest))
  665. << "For single directory copies, the last error should be a security "
  666. "error!";
  667. } else {
  668. ASSERT_EQ(base::File::FILE_OK, helper.Copy(src, dest));
  669. }
  670. }
  671. bool src_should_exist = !IsMove() || BlockingEnabled();
  672. bool dest_should_exist = !BlockingEnabled();
  673. // Verify.
  674. ASSERT_EQ(src_should_exist, helper.DirectoryExists(src));
  675. ASSERT_EQ(dest_should_exist, helper.DirectoryExists(dest));
  676. int64_t src_new_usage = helper.GetSourceUsage();
  677. if (IsMove() || BlockingEnabled()) {
  678. EXPECT_EQ(src_new_usage, src_initial_usage + src_increase);
  679. } else {
  680. EXPECT_EQ(src_new_usage, src_initial_usage + 2 * src_increase);
  681. }
  682. }
  683. TEST_P(LocalFileSystemCopyOrMoveOperationTest, FilesAndDirectories) {
  684. CopyOrMoveOperationTestHelper helper(
  685. "http://foo", kFileSystemTypeTemporary,
  686. IsLocal() ? kFileSystemTypeTemporary : kFileSystemTypePersistent);
  687. helper.SetUp();
  688. FileSystemURL src = helper.SourceURL("a");
  689. FileSystemURL dest = helper.DestURL("b");
  690. int64_t src_initial_usage = helper.GetSourceUsage();
  691. // Set up a source directory.
  692. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  693. ASSERT_EQ(base::File::FILE_OK,
  694. helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases,
  695. kRegularFileSystemTestCaseSize));
  696. int64_t src_increase = helper.GetSourceUsage() - src_initial_usage;
  697. if (IsMove()) {
  698. // Move it.
  699. if (BlockingEnabled()) {
  700. // Records are not checked in this test.
  701. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord> records;
  702. ASSERT_EQ(base::File::FILE_ERROR_NOT_EMPTY,
  703. helper.MoveBlockSome(src, dest, records))
  704. << "For multi-directory moves, the last error should be "
  705. "FILE_ERROR_NOT_EMPTY because the src directory could not be "
  706. "removed!";
  707. } else {
  708. ASSERT_EQ(base::File::FILE_OK, helper.Move(src, dest));
  709. }
  710. } else {
  711. // Copy it.
  712. if (BlockingEnabled()) {
  713. // For copies, only forbidden file/directory access errors are reported.
  714. // Records are not checked in this test.
  715. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord> records;
  716. ASSERT_EQ(base::File::FILE_ERROR_SECURITY,
  717. helper.CopyBlockSome(src, dest, records))
  718. << "For multi-directory copies, the last error should be "
  719. "FILE_ERROR_SECURITY!";
  720. } else {
  721. ASSERT_EQ(base::File::FILE_OK, helper.Copy(src, dest));
  722. }
  723. }
  724. bool src_should_exist = !IsMove() || BlockingEnabled();
  725. // Verify.
  726. ASSERT_EQ(src_should_exist, helper.DirectoryExists(src));
  727. // For recursive transfers, the destination directory is always created
  728. // (unless the root source directory is blocked, which is not blocked here)!
  729. ASSERT_TRUE(helper.DirectoryExists(dest));
  730. if (!IsMove()) {
  731. // For copies, all files should be there!
  732. helper.VerifyTestCaseFiles(
  733. src, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize,
  734. CopyOrMoveOperationTestHelper::VerifyDirectoryState::ALL_FILES_EXIST);
  735. } else {
  736. if (BlockingEnabled()) {
  737. // For moves, only blocked files should remain.
  738. helper.VerifyTestCaseFiles(
  739. src, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize,
  740. CopyOrMoveOperationTestHelper::VerifyDirectoryState::
  741. ONLY_BLOCKED_FILES_AND_PARENTS);
  742. }
  743. }
  744. // Destination checking is independent of whether the operation is a copy or
  745. // move.
  746. if (BlockingEnabled()) {
  747. helper.VerifyTestCaseFiles(dest, kRegularFileSystemTestCases,
  748. kRegularFileSystemTestCaseSize,
  749. CopyOrMoveOperationTestHelper::
  750. VerifyDirectoryState::ONLY_ALLOWED_FILES);
  751. } else {
  752. helper.VerifyTestCaseFiles(
  753. dest, kRegularFileSystemTestCases, kRegularFileSystemTestCaseSize,
  754. CopyOrMoveOperationTestHelper::VerifyDirectoryState::ALL_FILES_EXIST);
  755. }
  756. // For local operations we can only check the size if there is no blocking
  757. // involved.
  758. if (!BlockingEnabled()) {
  759. int64_t src_new_usage = helper.GetSourceUsage();
  760. if (IsMove()) {
  761. ASSERT_EQ(src_initial_usage + src_increase, src_new_usage);
  762. } else {
  763. // Copies duplicate used size on common file system.
  764. ASSERT_EQ(src_initial_usage + 2 * src_increase, src_new_usage);
  765. }
  766. }
  767. }
  768. TEST(LocalFileSystemCopyOrMoveOperationTest,
  769. MoveDirectoryFailPostWriteValidation) {
  770. CopyOrMoveOperationTestHelper helper("http://foo", kFileSystemTypeTemporary,
  771. kFileSystemTypeTest);
  772. helper.SetUp();
  773. FileSystemURL src = helper.SourceURL("a");
  774. FileSystemURL dest = helper.DestURL("b");
  775. // Set up a source directory.
  776. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  777. ASSERT_EQ(base::File::FILE_OK,
  778. helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases,
  779. kRegularFileSystemTestCaseSize));
  780. // Move it.
  781. helper.Move(src, dest);
  782. // Verify.
  783. ASSERT_TRUE(helper.DirectoryExists(src));
  784. ASSERT_TRUE(helper.DirectoryExists(dest));
  785. // In the move operation, [file 0, file 2, file 3] are processed as LIFO.
  786. // After file 3 is processed, file 2 is rejected by the validator and the
  787. // operation fails. That is, only file 3 should be in dest.
  788. FileSystemTestCaseRecord kMoveDirResultCases[] = {
  789. {false, FILE_PATH_LITERAL("file 3"), 0},
  790. };
  791. helper.VerifyTestCaseFiles(
  792. dest, kMoveDirResultCases, std::size(kMoveDirResultCases),
  793. CopyOrMoveOperationTestHelper::VerifyDirectoryState::ALL_FILES_EXIST);
  794. }
  795. TEST(LocalFileSystemCopyOrMoveOperationTest, CopySingleFileNoValidator) {
  796. CopyOrMoveOperationTestHelper helper("http://foo", kFileSystemTypeTemporary,
  797. kFileSystemTypeTest);
  798. helper.SetUpNoValidator();
  799. FileSystemURL src = helper.SourceURL("a");
  800. FileSystemURL dest = helper.DestURL("b");
  801. // Set up a source file.
  802. ASSERT_EQ(base::File::FILE_OK, helper.CreateFile(src, 10));
  803. // The copy attempt should fail with a security error -- getting
  804. // the factory returns a security error, and the copy operation must
  805. // respect that.
  806. ASSERT_EQ(base::File::FILE_ERROR_SECURITY, helper.Copy(src, dest));
  807. }
  808. TEST_P(LocalFileSystemCopyOrMoveOperationTest, FilesAndDirectoriesProgress) {
  809. CopyOrMoveOperationTestHelper helper(
  810. "http://foo", kFileSystemTypeTemporary,
  811. IsLocal() ? kFileSystemTypeTemporary : kFileSystemTypePersistent);
  812. helper.SetUp();
  813. FileSystemURL src = helper.SourceURL("a");
  814. FileSystemURL dest = helper.DestURL("b");
  815. // Set up a source directory.
  816. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  817. ASSERT_EQ(base::File::FILE_OK,
  818. helper.SetUpTestCaseFiles(src, kRegularFileSystemTestCases,
  819. kRegularFileSystemTestCaseSize));
  820. CopyOrMoveRecordAndSecurityDelegate::ShouldBlockCallback allow_all_callback =
  821. base::BindRepeating(
  822. [](const FileSystemURL& source_url) { return false; });
  823. std::vector<CopyOrMoveRecordAndSecurityDelegate::ProgressRecord> records;
  824. if (IsMove()) {
  825. // Move it.
  826. if (BlockingEnabled()) {
  827. ASSERT_EQ(base::File::FILE_ERROR_NOT_EMPTY,
  828. helper.MoveBlockSome(src, dest, records))
  829. << "For multi-directory moves, the last error should be "
  830. "FILE_ERROR_NOT_EMPTY because the src directory could not be "
  831. "removed!";
  832. } else {
  833. ASSERT_EQ(base::File::FILE_OK,
  834. helper.MoveWithHookDelegate(
  835. src, dest, FileSystemOperation::ERROR_BEHAVIOR_ABORT,
  836. std::make_unique<CopyOrMoveRecordAndSecurityDelegate>(
  837. records, allow_all_callback)));
  838. }
  839. } else {
  840. // Copy it.
  841. if (BlockingEnabled()) {
  842. // For copies, only forbidden file/directory access errors are reported.
  843. ASSERT_EQ(base::File::FILE_ERROR_SECURITY,
  844. helper.CopyBlockSome(src, dest, records))
  845. << "For multi-directory copies, the last error should be "
  846. "FILE_ERROR_SECURITY!";
  847. } else {
  848. ASSERT_EQ(base::File::FILE_OK,
  849. helper.CopyWithHookDelegate(
  850. src, dest, FileSystemOperation::ERROR_BEHAVIOR_ABORT,
  851. std::make_unique<CopyOrMoveRecordAndSecurityDelegate>(
  852. records, allow_all_callback)));
  853. }
  854. }
  855. // Verify that for `src` kBeginFile is called.
  856. // This behavior is expected, because for the src entry, ProcessFile is
  857. // always called independent of whether it is a directory or not. Note: This
  858. // might change if the behavior of RecursiveOperationDelegate is changed.
  859. EXPECT_EQ(
  860. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kBeginFile,
  861. records[0].type);
  862. EXPECT_EQ(dest, records[0].dest_url);
  863. // Verify progress records.
  864. for (size_t i = 0; i < kRegularFileSystemTestCaseSize; ++i) {
  865. const FileSystemTestCaseRecord& test_case = kRegularFileSystemTestCases[i];
  866. FileSystemURL src_url = helper.SourceURL(
  867. std::string("a/") + base::FilePath(test_case.path).AsUTF8Unsafe());
  868. FileSystemURL dest_url = helper.DestURL(
  869. std::string("b/") + base::FilePath(test_case.path).AsUTF8Unsafe());
  870. // Find the first and last progress record.
  871. size_t begin_index = records.size();
  872. size_t end_index = records.size();
  873. for (size_t j = 0; j < records.size(); ++j) {
  874. if (records[j].source_url == src_url) {
  875. if (begin_index == records.size())
  876. begin_index = j;
  877. end_index = j;
  878. }
  879. }
  880. if (BlockingEnabled() &&
  881. test_case.block_action == TestBlockAction::PARENT_BLOCKED) {
  882. // There shouldn't be any record, if the parent is blocked.
  883. ASSERT_EQ(begin_index, records.size());
  884. continue;
  885. }
  886. // The record should be found.
  887. ASSERT_NE(begin_index, records.size());
  888. ASSERT_NE(end_index, records.size());
  889. ASSERT_NE(begin_index, end_index);
  890. if (test_case.is_directory) {
  891. // A directory copy/move starts with kBegin and kEndCopy.
  892. EXPECT_EQ(CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::
  893. kBeginDirectory,
  894. records[begin_index].type);
  895. EXPECT_EQ(dest_url, records[begin_index].dest_url);
  896. if (BlockingEnabled() &&
  897. test_case.block_action == TestBlockAction::BLOCKED) {
  898. EXPECT_EQ(
  899. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kError,
  900. records[begin_index + 1].type);
  901. EXPECT_EQ(base::File::FILE_ERROR_SECURITY,
  902. records[begin_index + 1].error);
  903. EXPECT_EQ(dest_url, records[begin_index + 1].dest_url);
  904. EXPECT_EQ(begin_index + 1, end_index);
  905. continue;
  906. }
  907. EXPECT_EQ(
  908. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kEndCopy,
  909. records[begin_index + 1].type);
  910. EXPECT_EQ(dest_url, records[begin_index + 1].dest_url);
  911. if (IsMove()) {
  912. if (BlockingEnabled() &&
  913. test_case.block_action == TestBlockAction::CHILD_BLOCKED) {
  914. EXPECT_EQ(
  915. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kError,
  916. records[end_index].type);
  917. EXPECT_FALSE(records[end_index].dest_url.is_valid());
  918. EXPECT_EQ(base::File::FILE_ERROR_NOT_EMPTY, records[end_index].error);
  919. EXPECT_NE(records[end_index - 1].source_url, src_url);
  920. continue;
  921. }
  922. // A directory move ends with kEndRemoveSource, after the contents of
  923. // the directory have been copied.
  924. EXPECT_EQ(CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::
  925. kEndRemoveSource,
  926. records[end_index].type);
  927. EXPECT_FALSE(records[end_index].dest_url.is_valid());
  928. } else {
  929. // For directory copy, the progress shouldn't be interlaced.
  930. EXPECT_EQ(begin_index + 1, end_index);
  931. }
  932. } else {
  933. // A file copy/move starts with kBeginFile.
  934. EXPECT_EQ(
  935. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kBeginFile,
  936. records[begin_index].type);
  937. EXPECT_EQ(dest_url, records[begin_index].dest_url);
  938. if (BlockingEnabled() &&
  939. test_case.block_action == TestBlockAction::BLOCKED) {
  940. // If a file is blocked, the second and last record for that file should
  941. // be an error.
  942. EXPECT_EQ(
  943. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kError,
  944. records[begin_index + 1].type);
  945. EXPECT_EQ(base::File::FILE_ERROR_SECURITY,
  946. records[begin_index + 1].error);
  947. EXPECT_EQ(dest_url, records[begin_index + 1].dest_url);
  948. EXPECT_EQ(begin_index + 1, end_index);
  949. continue;
  950. }
  951. // PROGRESS event's size should be ascending order.
  952. int64_t current_size = 0;
  953. size_t end_progress_index = end_index;
  954. if (IsMove() && !IsLocal()) {
  955. end_progress_index = end_index - 1;
  956. }
  957. if (IsMove() && IsLocal()) {
  958. EXPECT_EQ(begin_index, end_progress_index - 1)
  959. << "No progress should be reported for local moves!";
  960. } else {
  961. EXPECT_LT(begin_index, end_progress_index - 1)
  962. << "There should be some progress reported.";
  963. }
  964. for (size_t j = begin_index + 1; j < end_progress_index; ++j) {
  965. if (records[j].source_url == src_url) {
  966. EXPECT_EQ(CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::
  967. kProgress,
  968. records[j].type);
  969. EXPECT_EQ(dest_url, records[j].dest_url);
  970. EXPECT_GE(records[j].size, current_size);
  971. current_size = records[j].size;
  972. }
  973. }
  974. if (IsMove() && IsLocal()) {
  975. // For local moves, we expect kEndMove at the end.
  976. EXPECT_EQ(
  977. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kEndMove,
  978. records[end_index].type);
  979. EXPECT_EQ(dest_url, records[end_index].dest_url);
  980. } else {
  981. // A file move ends with kEndCopy and kEndRemoveSource, a copy with just
  982. // kEndCopy.
  983. size_t end_copy_index = IsMove() ? end_index - 1 : end_index;
  984. EXPECT_EQ(
  985. CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::kEndCopy,
  986. records[end_copy_index].type);
  987. EXPECT_EQ(dest_url, records[end_copy_index].dest_url);
  988. if (IsMove()) {
  989. EXPECT_EQ(CopyOrMoveRecordAndSecurityDelegate::ProgressRecord::Type::
  990. kEndRemoveSource,
  991. records[end_index].type);
  992. EXPECT_FALSE(records[end_index].dest_url.is_valid());
  993. }
  994. }
  995. }
  996. }
  997. }
  998. TEST(LocalFileSystemCopyOrMoveOperationTest, StreamCopyHelper) {
  999. base::ScopedTempDir temp_dir;
  1000. ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  1001. base::FilePath source_path = temp_dir.GetPath().AppendASCII("source");
  1002. base::FilePath dest_path = temp_dir.GetPath().AppendASCII("dest");
  1003. const char kTestData[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  1004. base::WriteFile(source_path, kTestData);
  1005. base::test::SingleThreadTaskEnvironment task_environment(
  1006. base::test::SingleThreadTaskEnvironment::MainThreadType::IO);
  1007. base::Thread file_thread("file_thread");
  1008. ASSERT_TRUE(file_thread.Start());
  1009. ScopedThreadStopper thread_stopper(&file_thread);
  1010. ASSERT_TRUE(thread_stopper.is_valid());
  1011. scoped_refptr<base::SingleThreadTaskRunner> task_runner =
  1012. file_thread.task_runner();
  1013. std::unique_ptr<FileStreamReader> reader =
  1014. FileStreamReader::CreateForLocalFile(task_runner.get(), source_path, 0,
  1015. base::Time());
  1016. std::unique_ptr<FileStreamWriter> writer =
  1017. FileStreamWriter::CreateForLocalFile(task_runner.get(), dest_path, 0,
  1018. FileStreamWriter::CREATE_NEW_FILE);
  1019. std::vector<int64_t> progress;
  1020. CopyOrMoveOperationDelegate::StreamCopyHelper helper(
  1021. std::move(reader), std::move(writer), FlushPolicy::NO_FLUSH_ON_COMPLETION,
  1022. 10, // buffer size
  1023. base::BindRepeating(&RecordFileProgressCallback,
  1024. base::Unretained(&progress)),
  1025. base::TimeDelta()); // For testing, we need all the progress.
  1026. base::File::Error error = base::File::FILE_ERROR_FAILED;
  1027. base::RunLoop run_loop;
  1028. helper.Run(base::BindOnce(&AssignAndQuit, &run_loop, &error));
  1029. run_loop.Run();
  1030. EXPECT_EQ(base::File::FILE_OK, error);
  1031. ASSERT_EQ(5U, progress.size());
  1032. EXPECT_EQ(0, progress[0]);
  1033. EXPECT_EQ(10, progress[1]);
  1034. EXPECT_EQ(20, progress[2]);
  1035. EXPECT_EQ(30, progress[3]);
  1036. EXPECT_EQ(36, progress[4]);
  1037. std::string content;
  1038. ASSERT_TRUE(base::ReadFileToString(dest_path, &content));
  1039. EXPECT_EQ(kTestData, content);
  1040. }
  1041. TEST(LocalFileSystemCopyOrMoveOperationTest, StreamCopyHelperWithFlush) {
  1042. // Testing the same configuration as StreamCopyHelper, but with |need_flush|
  1043. // parameter set to true. Since it is hard to test that the flush is indeed
  1044. // taking place, this test just only verifies that the file is correctly
  1045. // written with or without the flag.
  1046. base::ScopedTempDir temp_dir;
  1047. ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  1048. base::FilePath source_path = temp_dir.GetPath().AppendASCII("source");
  1049. base::FilePath dest_path = temp_dir.GetPath().AppendASCII("dest");
  1050. const char kTestData[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  1051. base::WriteFile(source_path, kTestData);
  1052. base::test::SingleThreadTaskEnvironment task_environment(
  1053. base::test::SingleThreadTaskEnvironment::MainThreadType::IO);
  1054. base::Thread file_thread("file_thread");
  1055. ASSERT_TRUE(file_thread.Start());
  1056. ScopedThreadStopper thread_stopper(&file_thread);
  1057. ASSERT_TRUE(thread_stopper.is_valid());
  1058. scoped_refptr<base::SingleThreadTaskRunner> task_runner =
  1059. file_thread.task_runner();
  1060. std::unique_ptr<FileStreamReader> reader =
  1061. FileStreamReader::CreateForLocalFile(task_runner.get(), source_path, 0,
  1062. base::Time());
  1063. std::unique_ptr<FileStreamWriter> writer =
  1064. FileStreamWriter::CreateForLocalFile(task_runner.get(), dest_path, 0,
  1065. FileStreamWriter::CREATE_NEW_FILE);
  1066. std::vector<int64_t> progress;
  1067. CopyOrMoveOperationDelegate::StreamCopyHelper helper(
  1068. std::move(reader), std::move(writer), FlushPolicy::NO_FLUSH_ON_COMPLETION,
  1069. 10, // buffer size
  1070. base::BindRepeating(&RecordFileProgressCallback,
  1071. base::Unretained(&progress)),
  1072. base::TimeDelta()); // For testing, we need all the progress.
  1073. base::File::Error error = base::File::FILE_ERROR_FAILED;
  1074. base::RunLoop run_loop;
  1075. helper.Run(base::BindOnce(&AssignAndQuit, &run_loop, &error));
  1076. run_loop.Run();
  1077. EXPECT_EQ(base::File::FILE_OK, error);
  1078. ASSERT_EQ(5U, progress.size());
  1079. EXPECT_EQ(0, progress[0]);
  1080. EXPECT_EQ(10, progress[1]);
  1081. EXPECT_EQ(20, progress[2]);
  1082. EXPECT_EQ(30, progress[3]);
  1083. EXPECT_EQ(36, progress[4]);
  1084. std::string content;
  1085. ASSERT_TRUE(base::ReadFileToString(dest_path, &content));
  1086. EXPECT_EQ(kTestData, content);
  1087. }
  1088. TEST(LocalFileSystemCopyOrMoveOperationTest, StreamCopyHelper_Cancel) {
  1089. base::ScopedTempDir temp_dir;
  1090. ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  1091. base::FilePath source_path = temp_dir.GetPath().AppendASCII("source");
  1092. base::FilePath dest_path = temp_dir.GetPath().AppendASCII("dest");
  1093. const char kTestData[] = "abcdefghijklmnopqrstuvwxyz0123456789";
  1094. base::WriteFile(source_path, kTestData);
  1095. base::test::SingleThreadTaskEnvironment task_environment(
  1096. base::test::SingleThreadTaskEnvironment::MainThreadType::IO);
  1097. base::Thread file_thread("file_thread");
  1098. ASSERT_TRUE(file_thread.Start());
  1099. ScopedThreadStopper thread_stopper(&file_thread);
  1100. ASSERT_TRUE(thread_stopper.is_valid());
  1101. scoped_refptr<base::SingleThreadTaskRunner> task_runner =
  1102. file_thread.task_runner();
  1103. std::unique_ptr<FileStreamReader> reader =
  1104. FileStreamReader::CreateForLocalFile(task_runner.get(), source_path, 0,
  1105. base::Time());
  1106. std::unique_ptr<FileStreamWriter> writer =
  1107. FileStreamWriter::CreateForLocalFile(task_runner.get(), dest_path, 0,
  1108. FileStreamWriter::CREATE_NEW_FILE);
  1109. std::vector<int64_t> progress;
  1110. CopyOrMoveOperationDelegate::StreamCopyHelper helper(
  1111. std::move(reader), std::move(writer), FlushPolicy::NO_FLUSH_ON_COMPLETION,
  1112. 10, // buffer size
  1113. base::BindRepeating(&RecordFileProgressCallback,
  1114. base::Unretained(&progress)),
  1115. base::TimeDelta()); // For testing, we need all the progress.
  1116. // Call Cancel() later.
  1117. base::ThreadTaskRunnerHandle::Get()->PostTask(
  1118. FROM_HERE,
  1119. base::BindOnce(&CopyOrMoveOperationDelegate::StreamCopyHelper::Cancel,
  1120. base::Unretained(&helper)));
  1121. base::File::Error error = base::File::FILE_ERROR_FAILED;
  1122. base::RunLoop run_loop;
  1123. helper.Run(base::BindOnce(&AssignAndQuit, &run_loop, &error));
  1124. run_loop.Run();
  1125. EXPECT_EQ(base::File::FILE_ERROR_ABORT, error);
  1126. }
  1127. class CopyOrMoveOperationDelegateTestHelper {
  1128. public:
  1129. CopyOrMoveOperationDelegateTestHelper(
  1130. const std::string& origin,
  1131. FileSystemType src_type,
  1132. FileSystemType dest_type,
  1133. FileSystemOperation::CopyOrMoveOptionSet options)
  1134. : origin_(url::Origin::Create(GURL(origin))),
  1135. src_type_(src_type),
  1136. dest_type_(dest_type),
  1137. options_(options),
  1138. task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {}
  1139. CopyOrMoveOperationDelegateTestHelper(
  1140. const CopyOrMoveOperationDelegateTestHelper&) = delete;
  1141. CopyOrMoveOperationDelegateTestHelper& operator=(
  1142. const CopyOrMoveOperationDelegateTestHelper&) = delete;
  1143. ~CopyOrMoveOperationDelegateTestHelper() {
  1144. file_system_context_ = nullptr;
  1145. task_environment_.RunUntilIdle();
  1146. }
  1147. void SetUp() {
  1148. ASSERT_TRUE(base_.CreateUniqueTempDir());
  1149. base::FilePath base_dir = base_.GetPath();
  1150. quota_manager_ = base::MakeRefCounted<storage::MockQuotaManager>(
  1151. /*is_incognito=*/false, base_dir, base::ThreadTaskRunnerHandle::Get(),
  1152. base::MakeRefCounted<storage::MockSpecialStoragePolicy>());
  1153. quota_manager_proxy_ = base::MakeRefCounted<storage::MockQuotaManagerProxy>(
  1154. quota_manager_.get(), base::ThreadTaskRunnerHandle::Get());
  1155. // Prepare file system.
  1156. file_system_context_ = storage::CreateFileSystemContextForTesting(
  1157. quota_manager_proxy_.get(), base_dir);
  1158. // Prepare the origin's root directory.
  1159. FileSystemBackend* backend =
  1160. file_system_context_->GetFileSystemBackend(src_type_);
  1161. backend->ResolveURL(
  1162. FileSystemURL::CreateForTest(blink::StorageKey(url::Origin(origin_)),
  1163. src_type_, base::FilePath()),
  1164. OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::BindOnce(&ExpectOk));
  1165. backend = file_system_context_->GetFileSystemBackend(dest_type_);
  1166. backend->ResolveURL(
  1167. FileSystemURL::CreateForTest(blink::StorageKey(url::Origin(origin_)),
  1168. dest_type_, base::FilePath()),
  1169. OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT, base::BindOnce(&ExpectOk));
  1170. task_environment_.RunUntilIdle();
  1171. }
  1172. FileSystemURL GenerateSourceUrlFromPath(const std::string& path) {
  1173. return file_system_context_->CreateCrackedFileSystemURL(
  1174. blink::StorageKey(origin_), src_type_,
  1175. base::FilePath::FromUTF8Unsafe(path));
  1176. }
  1177. FileSystemURL GenerateDestinationUrlFromPath(const std::string& path) {
  1178. return file_system_context_->CreateCrackedFileSystemURL(
  1179. blink::StorageKey(origin_), dest_type_,
  1180. base::FilePath::FromUTF8Unsafe(path));
  1181. }
  1182. base::File::Error CreateFile(const FileSystemURL& url, size_t size) {
  1183. base::File::Error result =
  1184. AsyncFileTestHelper::CreateFile(file_system_context_.get(), url);
  1185. if (result != base::File::FILE_OK)
  1186. return result;
  1187. return AsyncFileTestHelper::TruncateFile(file_system_context_.get(), url,
  1188. size);
  1189. }
  1190. base::File::Error CreateDirectory(const FileSystemURL& url) {
  1191. return AsyncFileTestHelper::CreateDirectory(file_system_context_.get(),
  1192. url);
  1193. }
  1194. bool FileExists(const FileSystemURL& url, int64_t expected_size) {
  1195. return AsyncFileTestHelper::FileExists(file_system_context_.get(), url,
  1196. expected_size);
  1197. }
  1198. bool DirectoryExists(const FileSystemURL& url) {
  1199. return AsyncFileTestHelper::DirectoryExists(file_system_context_.get(),
  1200. url);
  1201. }
  1202. // Force Copy or Move error when a given URL is encountered.
  1203. void SetErrorUrl(const FileSystemURL& url) { error_url_ = url; }
  1204. base::File::Error Copy(const FileSystemURL& src, const FileSystemURL& dest) {
  1205. base::RunLoop run_loop;
  1206. base::File::Error result = base::File::FILE_ERROR_FAILED;
  1207. CopyOrMoveOperationDelegate copy_or_move_operation_delegate(
  1208. file_system_context_.get(), src, dest,
  1209. CopyOrMoveOperationDelegate::OPERATION_COPY, options_,
  1210. FileSystemOperation::ERROR_BEHAVIOR_ABORT,
  1211. std::make_unique<storage::CopyOrMoveHookDelegate>(),
  1212. base::BindOnce(&AssignAndQuit, &run_loop, base::Unretained(&result)));
  1213. if (error_url_.is_valid()) {
  1214. copy_or_move_operation_delegate.SetErrorUrlForTest(error_url_);
  1215. }
  1216. copy_or_move_operation_delegate.RunRecursively();
  1217. run_loop.Run();
  1218. return result;
  1219. }
  1220. base::File::Error Move(const FileSystemURL& src, const FileSystemURL& dest) {
  1221. base::RunLoop run_loop;
  1222. base::File::Error result = base::File::FILE_ERROR_FAILED;
  1223. CopyOrMoveOperationDelegate copy_or_move_operation_delegate(
  1224. file_system_context_.get(), src, dest,
  1225. CopyOrMoveOperationDelegate::OPERATION_MOVE, options_,
  1226. FileSystemOperation::ERROR_BEHAVIOR_ABORT,
  1227. std::make_unique<storage::CopyOrMoveHookDelegate>(),
  1228. base::BindOnce(&AssignAndQuit, &run_loop, base::Unretained(&result)));
  1229. if (error_url_.is_valid()) {
  1230. copy_or_move_operation_delegate.SetErrorUrlForTest(error_url_);
  1231. }
  1232. copy_or_move_operation_delegate.RunRecursively();
  1233. run_loop.Run();
  1234. return result;
  1235. }
  1236. private:
  1237. base::ScopedTempDir base_;
  1238. const url::Origin origin_;
  1239. const FileSystemType src_type_;
  1240. const FileSystemType dest_type_;
  1241. FileSystemOperation::CopyOrMoveOptionSet options_;
  1242. FileSystemURL error_url_;
  1243. base::test::TaskEnvironment task_environment_;
  1244. scoped_refptr<storage::MockQuotaManager> quota_manager_;
  1245. scoped_refptr<storage::MockQuotaManagerProxy> quota_manager_proxy_;
  1246. scoped_refptr<FileSystemContext> file_system_context_;
  1247. };
  1248. TEST(CopyOrMoveOperationDelegateTest, StopRecursionOnCopyError) {
  1249. FileSystemOperation::CopyOrMoveOptionSet options;
  1250. CopyOrMoveOperationDelegateTestHelper helper(
  1251. "http://foo", kFileSystemTypePersistent, kFileSystemTypePersistent,
  1252. options);
  1253. helper.SetUp();
  1254. FileSystemURL src = helper.GenerateSourceUrlFromPath("a");
  1255. FileSystemURL src_file_1 = helper.GenerateSourceUrlFromPath("a/file 1");
  1256. FileSystemURL src_file_2 = helper.GenerateSourceUrlFromPath("a/file 2");
  1257. FileSystemURL dest = helper.GenerateDestinationUrlFromPath("b");
  1258. FileSystemURL dest_file_1 = helper.GenerateDestinationUrlFromPath("b/file 1");
  1259. FileSystemURL dest_file_2 = helper.GenerateDestinationUrlFromPath("b/file 2");
  1260. // Set up source files.
  1261. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  1262. ASSERT_EQ(base::File::FILE_OK,
  1263. helper.CreateFile(src_file_1, kDefaultFileSize));
  1264. ASSERT_EQ(base::File::FILE_OK,
  1265. helper.CreateFile(src_file_2, kDefaultFileSize));
  1266. // [file 1, file 2] are processed as a LIFO. An error is returned after
  1267. // copying file 2.
  1268. helper.SetErrorUrl(src_file_2);
  1269. ASSERT_EQ(base::File::FILE_ERROR_FAILED, helper.Copy(src, dest));
  1270. EXPECT_TRUE(helper.DirectoryExists(src));
  1271. EXPECT_TRUE(helper.DirectoryExists(dest));
  1272. // Check: file 2 is copied, even though the copy results in an error.
  1273. EXPECT_TRUE(helper.FileExists(src_file_2, kDefaultFileSize));
  1274. EXPECT_TRUE(
  1275. helper.FileExists(dest_file_2, AsyncFileTestHelper::kDontCheckSize));
  1276. // Check: the recursion has been interrupted after the error, so file 1
  1277. // hasn't been copied.
  1278. EXPECT_TRUE(helper.FileExists(src_file_1, kDefaultFileSize));
  1279. EXPECT_FALSE(
  1280. helper.FileExists(dest_file_1, AsyncFileTestHelper::kDontCheckSize));
  1281. }
  1282. TEST(CopyOrMoveOperationDelegateTest, RemoveDestFileOnCopyError) {
  1283. FileSystemOperation::CopyOrMoveOptionSet options(
  1284. storage::FileSystemOperation::CopyOrMoveOption::
  1285. kRemovePartiallyCopiedFilesOnError);
  1286. CopyOrMoveOperationDelegateTestHelper helper(
  1287. "http://foo", kFileSystemTypePersistent, kFileSystemTypePersistent,
  1288. options);
  1289. helper.SetUp();
  1290. FileSystemURL src = helper.GenerateSourceUrlFromPath("a");
  1291. FileSystemURL src_file_1 = helper.GenerateSourceUrlFromPath("a/file 1");
  1292. FileSystemURL src_file_2 = helper.GenerateSourceUrlFromPath("a/file 2");
  1293. FileSystemURL dest = helper.GenerateDestinationUrlFromPath("b");
  1294. FileSystemURL dest_file_1 = helper.GenerateDestinationUrlFromPath("b/file 1");
  1295. FileSystemURL dest_file_2 = helper.GenerateDestinationUrlFromPath("b/file 2");
  1296. // Set up source files.
  1297. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  1298. ASSERT_EQ(base::File::FILE_OK,
  1299. helper.CreateFile(src_file_1, kDefaultFileSize));
  1300. ASSERT_EQ(base::File::FILE_OK,
  1301. helper.CreateFile(src_file_2, kDefaultFileSize));
  1302. // [file 1, file 2] are processed as a LIFO. An error is returned after
  1303. // copying file 1.
  1304. helper.SetErrorUrl(src_file_1);
  1305. ASSERT_EQ(base::File::FILE_ERROR_FAILED, helper.Copy(src, dest));
  1306. EXPECT_TRUE(helper.DirectoryExists(src));
  1307. EXPECT_TRUE(helper.DirectoryExists(dest));
  1308. // Check: file 2 is properly copied.
  1309. EXPECT_TRUE(helper.FileExists(src_file_2, kDefaultFileSize));
  1310. EXPECT_TRUE(helper.FileExists(dest_file_2, kDefaultFileSize));
  1311. // Check: file 1 has been removed on error after being copied.
  1312. EXPECT_TRUE(helper.FileExists(src_file_1, kDefaultFileSize));
  1313. EXPECT_FALSE(
  1314. helper.FileExists(dest_file_1, AsyncFileTestHelper::kDontCheckSize));
  1315. }
  1316. TEST(CopyOrMoveOperationDelegateTest,
  1317. RemoveDestFileOnCrossFilesystemMoveError) {
  1318. FileSystemOperation::CopyOrMoveOptionSet options(
  1319. storage::FileSystemOperation::CopyOrMoveOption::
  1320. kRemovePartiallyCopiedFilesOnError);
  1321. // Removing destination files on Move errors applies only to cross-filesystem
  1322. // moves.
  1323. CopyOrMoveOperationDelegateTestHelper helper(
  1324. "http://foo", kFileSystemTypeTemporary, kFileSystemTypePersistent,
  1325. options);
  1326. helper.SetUp();
  1327. FileSystemURL src = helper.GenerateSourceUrlFromPath("a");
  1328. FileSystemURL src_file_1 = helper.GenerateSourceUrlFromPath("a/file 1");
  1329. FileSystemURL src_file_2 = helper.GenerateSourceUrlFromPath("a/file 2");
  1330. FileSystemURL dest = helper.GenerateDestinationUrlFromPath("b");
  1331. FileSystemURL dest_file_1 = helper.GenerateDestinationUrlFromPath("b/file 1");
  1332. FileSystemURL dest_file_2 = helper.GenerateDestinationUrlFromPath("b/file 2");
  1333. // Set up source files.
  1334. ASSERT_EQ(base::File::FILE_OK, helper.CreateDirectory(src));
  1335. ASSERT_EQ(base::File::FILE_OK,
  1336. helper.CreateFile(src_file_1, kDefaultFileSize));
  1337. ASSERT_EQ(base::File::FILE_OK,
  1338. helper.CreateFile(src_file_2, kDefaultFileSize));
  1339. // [file 1, file 2] are processed as a LIFO. An error is returned after
  1340. // copying file 1.
  1341. helper.SetErrorUrl(src_file_1);
  1342. ASSERT_EQ(base::File::FILE_ERROR_FAILED, helper.Move(src, dest));
  1343. EXPECT_TRUE(helper.DirectoryExists(src));
  1344. EXPECT_TRUE(helper.DirectoryExists(dest));
  1345. // Check: file 2 is moved.
  1346. EXPECT_FALSE(
  1347. helper.FileExists(src_file_2, AsyncFileTestHelper::kDontCheckSize));
  1348. EXPECT_TRUE(helper.FileExists(dest_file_2, kDefaultFileSize));
  1349. // Check: destination file 1 has been removed on error, and its source still
  1350. // exists.
  1351. EXPECT_TRUE(helper.FileExists(src_file_1, kDefaultFileSize));
  1352. EXPECT_FALSE(
  1353. helper.FileExists(dest_file_1, AsyncFileTestHelper::kDontCheckSize));
  1354. }
  1355. } // namespace storage