summaryrefslogtreecommitdiffstats
path: root/dom/fs/test/gtest/parent/datamodel/TestFileSystemDataManagerVersion001.cpp
blob: f08132221b73426627a9a2e05e183afde2da43fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <algorithm>

#include "ErrorList.h"
#include "FileSystemDataManager.h"
#include "FileSystemDatabaseManagerVersion001.h"
#include "FileSystemFileManager.h"
#include "FileSystemHashSource.h"
#include "ResultStatement.h"
#include "SchemaVersion001.h"
#include "TestHelpers.h"
#include "gtest/gtest.h"
#include "mozIStorageService.h"
#include "mozStorageCID.h"
#include "mozStorageHelper.h"
#include "mozilla/Array.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/Result.h"
#include "mozilla/dom/FileSystemTypes.h"
#include "mozilla/dom/PFileSystemManager.h"
#include "mozilla/dom/quota/CommonMetadata.h"
#include "mozilla/dom/quota/test/QuotaManagerDependencyFixture.h"
#include "nsContentUtils.h"
#include "nsIFile.h"
#include "nsLiteralString.h"
#include "nsNetCID.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsTArray.h"
#include "nsTHashSet.h"

namespace mozilla::dom::fs::test {

using data::FileSystemDatabaseManagerVersion001;
using data::FileSystemFileManager;

// This is a minimal mock  to allow us to safely call the lock methods
// while avoiding assertions
class MockFileSystemDataManager final : public data::FileSystemDataManager {
 public:
  MockFileSystemDataManager(const quota::OriginMetadata& aOriginMetadata,
                            MovingNotNull<nsCOMPtr<nsIEventTarget>> aIOTarget,
                            MovingNotNull<RefPtr<TaskQueue>> aIOTaskQueue)
      : FileSystemDataManager(aOriginMetadata, nullptr, std::move(aIOTarget),
                              std::move(aIOTaskQueue)) {}

  virtual ~MockFileSystemDataManager() {
    // Need to avoid assertions
    mState = State::Closed;
  }
};

static void MakeDatabaseManagerVersion001(
    RefPtr<MockFileSystemDataManager>& aDataManager,
    FileSystemDatabaseManagerVersion001*& aDatabaseManager) {
  TEST_TRY_UNWRAP(auto storageService,
                  MOZ_TO_RESULT_GET_TYPED(nsCOMPtr<mozIStorageService>,
                                          MOZ_SELECT_OVERLOAD(do_GetService),
                                          MOZ_STORAGE_SERVICE_CONTRACTID));

  const auto flags = mozIStorageService::CONNECTION_DEFAULT;
  ResultConnection connection;

  nsresult rv = storageService->OpenSpecialDatabase(kMozStorageMemoryStorageKey,
                                                    VoidCString(), flags,
                                                    getter_AddRefs(connection));
  ASSERT_NSEQ(NS_OK, rv);

  const Origin& testOrigin = GetTestOrigin();

  TEST_TRY_UNWRAP(
      DatabaseVersion version,
      SchemaVersion001::InitializeConnection(connection, testOrigin));
  ASSERT_EQ(1, version);

  TEST_TRY_UNWRAP(EntryId rootId, data::GetRootHandle(GetTestOrigin()));

  auto fmRes = FileSystemFileManager::CreateFileSystemFileManager(
      GetTestOriginMetadata());
  ASSERT_FALSE(fmRes.isErr());

  QM_TRY_UNWRAP(auto streamTransportService,
                MOZ_TO_RESULT_GET_TYPED(nsCOMPtr<nsIEventTarget>,
                                        MOZ_SELECT_OVERLOAD(do_GetService),
                                        NS_STREAMTRANSPORTSERVICE_CONTRACTID),
                QM_VOID);

  quota::OriginMetadata originMetadata = GetTestOriginMetadata();

  nsCString taskQueueName("OPFS "_ns + originMetadata.mOrigin);

  RefPtr<TaskQueue> ioTaskQueue =
      TaskQueue::Create(do_AddRef(streamTransportService), taskQueueName.get());

  aDataManager = MakeRefPtr<MockFileSystemDataManager>(
      originMetadata, WrapMovingNotNull(streamTransportService),
      WrapMovingNotNull(ioTaskQueue));

  aDatabaseManager = new FileSystemDatabaseManagerVersion001(
      aDataManager, std::move(connection),
      MakeUnique<FileSystemFileManager>(fmRes.unwrap()), rootId);
}

class TestFileSystemDatabaseManagerVersion001
    : public quota::test::QuotaManagerDependencyFixture {
 public:
  void SetUp() override { ASSERT_NO_FATAL_FAILURE(InitializeFixture()); }

  void TearDown() override {
    ASSERT_NO_FATAL_FAILURE(ClearStoragesForOrigin(GetTestOriginMetadata()));
    ASSERT_NO_FATAL_FAILURE(ShutdownFixture());
  }

  static ContentType sContentType;
};

ContentType TestFileSystemDatabaseManagerVersion001::sContentType = "psid"_ns;

TEST_F(TestFileSystemDatabaseManagerVersion001,
       smokeTestCreateRemoveDirectories) {
  auto ioTask = []() {
    nsresult rv = NS_OK;
    // Ensure that FileSystemDataManager lives for the lifetime of the test
    RefPtr<MockFileSystemDataManager> dataManager;
    FileSystemDatabaseManagerVersion001* rdm = nullptr;
    ASSERT_NO_FATAL_FAILURE(MakeDatabaseManagerVersion001(dataManager, rdm));
    UniquePtr<FileSystemDatabaseManagerVersion001> dm(rdm);
    // if any of these exit early, we have to close
    auto autoClose = MakeScopeExit([rdm] { rdm->Close(); });

    TEST_TRY_UNWRAP(EntryId rootId, data::GetRootHandle(GetTestOrigin()));

    FileSystemChildMetadata firstChildMeta(rootId, u"First"_ns);
    TEST_TRY_UNWRAP_ERR(
        rv, dm->GetOrCreateDirectory(firstChildMeta, /* create */ false));
    ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

    TEST_TRY_UNWRAP(EntryId firstChild, dm->GetOrCreateDirectory(
                                            firstChildMeta, /* create */ true));

    int32_t dbVersion = 0;
    TEST_TRY_UNWRAP(FileSystemDirectoryListing entries,
                    dm->GetDirectoryEntries(rootId, dbVersion));
    ASSERT_EQ(1u, entries.directories().Length());
    ASSERT_EQ(0u, entries.files().Length());

    const auto& firstItemRef = entries.directories()[0];
    ASSERT_TRUE(u"First"_ns == firstItemRef.entryName())
    << firstItemRef.entryName();
    ASSERT_EQ(firstChild, firstItemRef.entryId());

    TEST_TRY_UNWRAP(
        EntryId firstChildClone,
        dm->GetOrCreateDirectory(firstChildMeta, /* create */ true));
    ASSERT_EQ(firstChild, firstChildClone);

    FileSystemChildMetadata secondChildMeta(firstChild, u"Second"_ns);
    TEST_TRY_UNWRAP(
        EntryId secondChild,
        dm->GetOrCreateDirectory(secondChildMeta, /* create */ true));

    FileSystemEntryPair shortPair(firstChild, secondChild);
    TEST_TRY_UNWRAP(Path shortPath, dm->Resolve(shortPair));
    ASSERT_EQ(1u, shortPath.Length());
    ASSERT_EQ(u"Second"_ns, shortPath[0]);

    FileSystemEntryPair longPair(rootId, secondChild);
    TEST_TRY_UNWRAP(Path longPath, dm->Resolve(longPair));
    ASSERT_EQ(2u, longPath.Length());
    ASSERT_EQ(u"First"_ns, longPath[0]);
    ASSERT_EQ(u"Second"_ns, longPath[1]);

    FileSystemEntryPair wrongPair(secondChild, rootId);
    TEST_TRY_UNWRAP(Path emptyPath, dm->Resolve(wrongPair));
    ASSERT_TRUE(emptyPath.IsEmpty());

    PageNumber page = 0;
    TEST_TRY_UNWRAP(FileSystemDirectoryListing fEntries,
                    dm->GetDirectoryEntries(firstChild, page));
    ASSERT_EQ(1u, fEntries.directories().Length());
    ASSERT_EQ(0u, fEntries.files().Length());

    const auto& secItemRef = fEntries.directories()[0];
    ASSERT_TRUE(u"Second"_ns == secItemRef.entryName())
    << secItemRef.entryName();
    ASSERT_EQ(secondChild, secItemRef.entryId());

    TEST_TRY_UNWRAP_ERR(
        rv, dm->RemoveDirectory(firstChildMeta, /* recursive */ false));
    ASSERT_NSEQ(NS_ERROR_DOM_INVALID_MODIFICATION_ERR, rv);

    TEST_TRY_UNWRAP(bool isDeleted,
                    dm->RemoveDirectory(firstChildMeta, /* recursive */ true));
    ASSERT_TRUE(isDeleted);

    FileSystemChildMetadata thirdChildMeta(secondChild, u"Second"_ns);
    TEST_TRY_UNWRAP_ERR(
        rv, dm->GetOrCreateDirectory(thirdChildMeta, /* create */ true));
    ASSERT_NSEQ(NS_ERROR_STORAGE_CONSTRAINT, rv);  // Is this a good error?

    dm->Close();
  };

  PerformOnIOThread(std::move(ioTask));
}

TEST_F(TestFileSystemDatabaseManagerVersion001, smokeTestCreateRemoveFiles) {
  auto ioTask = []() {
    nsresult rv = NS_OK;
    // Ensure that FileSystemDataManager lives for the lifetime of the test
    RefPtr<MockFileSystemDataManager> datamanager;
    FileSystemDatabaseManagerVersion001* rdm = nullptr;
    ASSERT_NO_FATAL_FAILURE(MakeDatabaseManagerVersion001(datamanager, rdm));
    UniquePtr<FileSystemDatabaseManagerVersion001> dm(rdm);

    TEST_TRY_UNWRAP(EntryId rootId, data::GetRootHandle(GetTestOrigin()));

    FileSystemChildMetadata firstChildMeta(rootId, u"First"_ns);
    // If creating is not allowed, getting a file from empty root fails
    TEST_TRY_UNWRAP_ERR(rv, dm->GetOrCreateFile(firstChildMeta, sContentType,
                                                /* create */ false));
    ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

    // Creating a file under empty root succeeds
    TEST_TRY_UNWRAP(
        EntryId firstChild,
        dm->GetOrCreateFile(firstChildMeta, sContentType, /* create */ true));

    // Second time, the same file is returned
    TEST_TRY_UNWRAP(
        EntryId firstChildClone,
        dm->GetOrCreateFile(firstChildMeta, sContentType, /* create */ true));
    ASSERT_EQ(firstChild, firstChildClone);

    // Directory listing returns the created file
    PageNumber page = 0;
    TEST_TRY_UNWRAP(FileSystemDirectoryListing entries,
                    dm->GetDirectoryEntries(rootId, page));
    ASSERT_EQ(0u, entries.directories().Length());
    ASSERT_EQ(1u, entries.files().Length());

    auto& firstItemRef = entries.files()[0];
    ASSERT_TRUE(u"First"_ns == firstItemRef.entryName())
    << firstItemRef.entryName();
    ASSERT_EQ(firstChild, firstItemRef.entryId());

    ContentType type;
    TimeStamp lastModifiedMilliSeconds;
    Path path;
    nsCOMPtr<nsIFile> file;
    rv = dm->GetFile(firstItemRef.entryId(), type, lastModifiedMilliSeconds,
                     path, file);
    ASSERT_NSEQ(NS_OK, rv);

    ASSERT_STREQ(sContentType, type);

    const int64_t nowMilliSeconds = PR_Now() / 1000;
    ASSERT_GE(nowMilliSeconds, lastModifiedMilliSeconds);
    const int64_t expectedMaxDelayMilliSeconds = 100;
    const int64_t actualDelay = nowMilliSeconds - lastModifiedMilliSeconds;
    ASSERT_LT(actualDelay, expectedMaxDelayMilliSeconds);

    ASSERT_EQ(1u, path.Length());
    ASSERT_STREQ(u"First"_ns, path[0]);

    ASSERT_NE(nullptr, file);

    // Getting the file entry as directory fails
    TEST_TRY_UNWRAP_ERR(
        rv, dm->GetOrCreateDirectory(firstChildMeta, /* create */ false));
    ASSERT_NSEQ(NS_ERROR_DOM_TYPE_MISMATCH_ERR, rv);

    // Getting or creating the file entry as directory also fails
    TEST_TRY_UNWRAP_ERR(
        rv, dm->GetOrCreateDirectory(firstChildMeta, /* create */ true));
    ASSERT_NSEQ(NS_ERROR_DOM_TYPE_MISMATCH_ERR, rv);

    // Creating a file with non existing parent hash fails

    EntryId notAChildHash = "0123456789abcdef0123456789abcdef"_ns;
    FileSystemChildMetadata notAChildMeta(notAChildHash, u"Dummy"_ns);
    TEST_TRY_UNWRAP_ERR(rv, dm->GetOrCreateFile(notAChildMeta, sContentType,
                                                /* create */ true));
    ASSERT_NSEQ(NS_ERROR_STORAGE_CONSTRAINT, rv);  // Is this a good error?

    // We create a directory under root
    FileSystemChildMetadata secondChildMeta(rootId, u"Second"_ns);
    TEST_TRY_UNWRAP(
        EntryId secondChild,
        dm->GetOrCreateDirectory(secondChildMeta, /* create */ true));

    // The root should now contain the existing file and the new directory
    TEST_TRY_UNWRAP(FileSystemDirectoryListing fEntries,
                    dm->GetDirectoryEntries(rootId, page));
    ASSERT_EQ(1u, fEntries.directories().Length());
    ASSERT_EQ(1u, fEntries.files().Length());

    const auto& secItemRef = fEntries.directories()[0];
    ASSERT_TRUE(u"Second"_ns == secItemRef.entryName())
    << secItemRef.entryName();
    ASSERT_EQ(secondChild, secItemRef.entryId());

    // Create a file under the new directory
    FileSystemChildMetadata thirdChildMeta(secondChild, u"Third"_ns);
    TEST_TRY_UNWRAP(
        EntryId thirdChild,
        dm->GetOrCreateFile(thirdChildMeta, sContentType, /* create */ true));

    FileSystemEntryPair entryPair(rootId, thirdChild);
    TEST_TRY_UNWRAP(Path entryPath, dm->Resolve(entryPair));
    ASSERT_EQ(2u, entryPath.Length());
    ASSERT_EQ(u"Second"_ns, entryPath[0]);
    ASSERT_EQ(u"Third"_ns, entryPath[1]);

    // If recursion is not allowed, the non-empty new directory may not be
    // removed
    TEST_TRY_UNWRAP_ERR(
        rv, dm->RemoveDirectory(secondChildMeta, /* recursive */ false));
    ASSERT_NSEQ(NS_ERROR_DOM_INVALID_MODIFICATION_ERR, rv);

    // If recursion is allowed, the new directory goes away.
    TEST_TRY_UNWRAP(bool isDeleted,
                    dm->RemoveDirectory(secondChildMeta, /* recursive */ true));
    ASSERT_TRUE(isDeleted);

    // The file under the removed directory is no longer accessible.
    TEST_TRY_UNWRAP_ERR(rv, dm->GetOrCreateFile(thirdChildMeta, sContentType,
                                                /* create */ true));
    ASSERT_NSEQ(NS_ERROR_STORAGE_CONSTRAINT, rv);  // Is this a good error?

    // The deletion is reflected by the root directory listing
    TEST_TRY_UNWRAP(FileSystemDirectoryListing nEntries,
                    dm->GetDirectoryEntries(rootId, 0));
    ASSERT_EQ(0u, nEntries.directories().Length());
    ASSERT_EQ(1u, nEntries.files().Length());

    const auto& fileItemRef = nEntries.files()[0];
    ASSERT_TRUE(u"First"_ns == fileItemRef.entryName())
    << fileItemRef.entryName();
    ASSERT_EQ(firstChild, fileItemRef.entryId());

    dm->Close();
  };

  PerformOnIOThread(std::move(ioTask));
}

TEST_F(TestFileSystemDatabaseManagerVersion001,
       smokeTestCreateMoveDirectories) {
  auto ioTask = []() {
    // Ensure that FileSystemDataManager lives for the lifetime of the test
    RefPtr<MockFileSystemDataManager> datamanager;
    FileSystemDatabaseManagerVersion001* rdm = nullptr;
    ASSERT_NO_FATAL_FAILURE(MakeDatabaseManagerVersion001(datamanager, rdm));
    UniquePtr<FileSystemDatabaseManagerVersion001> dm(rdm);
    auto closeAtExit = MakeScopeExit([&dm]() { dm->Close(); });

    TEST_TRY_UNWRAP(EntryId rootId, data::GetRootHandle(GetTestOrigin()));

    FileSystemEntryMetadata rootMeta{rootId, u"root"_ns,
                                     /* is directory */ true};

    {
      // Sanity check: no existing items should be found
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(rootId, /* page */ 0u));
      ASSERT_TRUE(contents.directories().IsEmpty());
      ASSERT_TRUE(contents.files().IsEmpty());
    }

    // Create subdirectory
    FileSystemChildMetadata firstChildMeta(rootId, u"First"_ns);
    TEST_TRY_UNWRAP(
        EntryId firstChildDir,
        dm->GetOrCreateDirectory(firstChildMeta, /* create */ true));

    {
      // Check that directory listing is as expected
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(rootId, /* page */ 0u));
      ASSERT_TRUE(contents.files().IsEmpty());
      ASSERT_EQ(1u, contents.directories().Length());
      ASSERT_STREQ(firstChildMeta.childName(),
                   contents.directories()[0].entryName());
    }

    {
      // Try to move subdirectory to its current location
      FileSystemEntryMetadata src{firstChildDir, firstChildMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{rootId, src.entryName()};
      TEST_TRY_UNWRAP(bool moved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(moved);
    }

    {
      // Try to move subdirectory under itself
      FileSystemEntryMetadata src{firstChildDir, firstChildMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{src.entryId(), src.entryName()};
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->MoveEntry(src, dest));
      ASSERT_NSEQ(NS_ERROR_DOM_INVALID_MODIFICATION_ERR, rv);
    }

    {
      // Try to move root under its subdirectory
      FileSystemEntryMetadata src{rootId, rootMeta.entryName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{firstChildDir, src.entryName()};
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->MoveEntry(src, dest));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);
    }

    // Create subsubdirectory
    FileSystemChildMetadata firstChildDescendantMeta(firstChildDir,
                                                     u"Descendant"_ns);
    TEST_TRY_UNWRAP(EntryId firstChildDescendant,
                    dm->GetOrCreateDirectory(firstChildDescendantMeta,
                                             /* create */ true));

    {
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(firstChildDir, /* page */ 0u));
      ASSERT_TRUE(contents.files().IsEmpty());
      ASSERT_EQ(1u, contents.directories().Length());
      ASSERT_STREQ(firstChildDescendantMeta.childName(),
                   contents.directories()[0].entryName());

      TEST_TRY_UNWRAP(
          Path subSubDirPath,
          dm->Resolve({rootId, contents.directories()[0].entryId()}));
      ASSERT_EQ(2u, subSubDirPath.Length());
      ASSERT_STREQ(firstChildMeta.childName(), subSubDirPath[0]);
      ASSERT_STREQ(firstChildDescendantMeta.childName(), subSubDirPath[1]);
    }

    {
      // Try to move subsubdirectory to its current location
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{firstChildDir, src.entryName()};
      TEST_TRY_UNWRAP(bool moved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(moved);
    }

    {
      // Try to move subsubdirectory under itself
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{src.entryId(), src.entryName()};
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->MoveEntry(src, dest));
      ASSERT_NSEQ(NS_ERROR_DOM_INVALID_MODIFICATION_ERR, rv);
    }

    {
      // Try to move subdirectory under its descendant
      FileSystemEntryMetadata src{firstChildDir, firstChildMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{firstChildDescendant, src.entryName()};
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->MoveEntry(src, dest));
      ASSERT_NSEQ(NS_ERROR_DOM_INVALID_MODIFICATION_ERR, rv);
    }

    {
      // Try to move root under its subsubdirectory
      FileSystemEntryMetadata src{rootId, rootMeta.entryName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{firstChildDescendant, src.entryName()};
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->MoveEntry(src, dest));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);
    }

    // Create file in the subdirectory with already existing subsubdirectory
    FileSystemChildMetadata testFileMeta(firstChildDir, u"Subfile"_ns);
    TEST_TRY_UNWRAP(
        EntryId testFile,
        dm->GetOrCreateFile(testFileMeta, sContentType, /* create */ true));

    // Get handles to the original locations of the entries
    FileSystemEntryMetadata subSubDir;
    FileSystemEntryMetadata subSubFile;

    {
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(firstChildDir, /* page */ 0u));
      ASSERT_EQ(1u, contents.files().Length());
      ASSERT_EQ(1u, contents.directories().Length());

      subSubDir = contents.directories()[0];
      ASSERT_STREQ(firstChildDescendantMeta.childName(), subSubDir.entryName());

      subSubFile = contents.files()[0];
      ASSERT_STREQ(testFileMeta.childName(), subSubFile.entryName());
      ASSERT_EQ(testFile, subSubFile.entryId());
    }

    {
      TEST_TRY_UNWRAP(Path entryPath,
                      dm->Resolve({rootId, subSubFile.entryId()}));
      ASSERT_EQ(2u, entryPath.Length());
      ASSERT_STREQ(firstChildMeta.childName(), entryPath[0]);
      ASSERT_STREQ(testFileMeta.childName(), entryPath[1]);
    }

    {
      // Try to move file to its current location
      FileSystemEntryMetadata src{testFile, testFileMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{firstChildDir, src.entryName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Try to move subsubdirectory under a file
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{testFile,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->MoveEntry(src, dest));
      ASSERT_NSEQ(NS_ERROR_STORAGE_CONSTRAINT, rv);
    }

    {
      // Silently overwrite a directory with a file using rename
      FileSystemEntryMetadata src{testFile, testFileMeta.childName(),
                                  /* is directory */ false};
      const FileSystemChildMetadata& dest = firstChildDescendantMeta;
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Move file back and recreate the directory
      FileSystemEntryMetadata src{testFile,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ false};

      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, testFileMeta));
      ASSERT_TRUE(isMoved);

      TEST_TRY_UNWRAP(EntryId firstChildDescendantCheck,
                      dm->GetOrCreateDirectory(firstChildDescendantMeta,
                                               /* create */ true));
      ASSERT_EQ(firstChildDescendant, firstChildDescendantCheck);
    }

    {
      // Try to rename directory to quietly overwrite a file
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      const FileSystemChildMetadata& dest = testFileMeta;
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Move directory back and recreate the file
      FileSystemEntryMetadata src{firstChildDescendant,
                                  testFileMeta.childName(),
                                  /* is directory */ true};

      FileSystemChildMetadata dest{firstChildDir,
                                   firstChildDescendantMeta.childName()};

      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);

      TEST_TRY_UNWRAP(
          EntryId testFileCheck,
          dm->GetOrCreateFile(testFileMeta, sContentType, /* create */ true));
      ASSERT_EQ(testFile, testFileCheck);
    }

    {
      // Move file one level up
      FileSystemEntryMetadata src{testFile, testFileMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{rootId, src.entryName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Check that listings are as expected
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(firstChildDir, 0u));
      ASSERT_TRUE(contents.files().IsEmpty());
      ASSERT_EQ(1u, contents.directories().Length());
      ASSERT_STREQ(firstChildDescendantMeta.childName(),
                   contents.directories()[0].entryName());
    }

    {
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(rootId, 0u));
      ASSERT_EQ(1u, contents.files().Length());
      ASSERT_EQ(1u, contents.files().Length());
      ASSERT_STREQ(testFileMeta.childName(), contents.files()[0].entryName());
    }

    {
      TEST_TRY_UNWRAP(Path entryPath,
                      dm->Resolve({rootId, subSubFile.entryId()}));
      ASSERT_EQ(1u, entryPath.Length());
      ASSERT_STREQ(testFileMeta.childName(), entryPath[0]);
    }

    {
      // Try to get a handle to the old item
      TEST_TRY_UNWRAP_ERR(
          nsresult rv,
          dm->GetOrCreateFile(testFileMeta, sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);
    }

    {
      // Try to move + rename file one level down to collide with a
      // subSubDirectory, silently overwriting it
      FileSystemEntryMetadata src{testFile, testFileMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{firstChildDir,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Restore filename, move file to its original location and recreate
      // the overwritten directory
      FileSystemEntryMetadata src{testFile,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{rootId, testFileMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);

      FileSystemChildMetadata oldLocation{firstChildDir,
                                          firstChildDescendantMeta.childName()};

      // Is there still something out there?
      TEST_TRY_UNWRAP_ERR(
          nsresult rv,
          dm->GetOrCreateFile(oldLocation, sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP(EntryId firstChildDescendantCheck,
                      dm->GetOrCreateDirectory(oldLocation, /* create */ true));
      ASSERT_EQ(firstChildDescendant, firstChildDescendantCheck);
    }

    // Rename file first and then try to move it to collide with
    // subSubDirectory, silently overwriting it
    {
      // Rename
      FileSystemEntryMetadata src{testFile, testFileMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{rootId,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Try to move one level down
      FileSystemEntryMetadata src{testFile,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{firstChildDir,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Move the file back and recreate the directory
      FileSystemEntryMetadata src{testFile,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{rootId,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);

      FileSystemChildMetadata oldLocation{firstChildDir,
                                          firstChildDescendantMeta.childName()};

      // Is there still something out there?
      TEST_TRY_UNWRAP_ERR(
          nsresult rv,
          dm->GetOrCreateFile(oldLocation, sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP(EntryId firstChildDescendantCheck,
                      dm->GetOrCreateDirectory(oldLocation, /* create */ true));
      ASSERT_EQ(firstChildDescendant, firstChildDescendantCheck);
    }

    {
      // Try to move subSubDirectory one level up to quietly overwrite a file
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{rootId,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Move subSubDirectory back one level down and recreate the file
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{firstChildDir,
                                   firstChildDescendantMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);

      FileSystemChildMetadata oldLocation{rootId,
                                          firstChildDescendantMeta.childName()};

      // We should no longer find anything there
      TEST_TRY_UNWRAP_ERR(nsresult rv, dm->GetOrCreateDirectory(
                                           oldLocation, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP(
          EntryId testFileCheck,
          dm->GetOrCreateFile(oldLocation, sContentType, /* create */ true));
      ASSERT_NE(testFile, testFileCheck);
      testFile = testFileCheck;
    }

    // Create a new file in the subsubdirectory
    FileSystemChildMetadata newFileMeta{firstChildDescendant,
                                        testFileMeta.childName()};
    TEST_TRY_UNWRAP(
        EntryId newFile,
        dm->GetOrCreateFile(newFileMeta, sContentType, /* create */ true));

    {
      TEST_TRY_UNWRAP(Path entryPath, dm->Resolve({rootId, newFile}));
      ASSERT_EQ(3u, entryPath.Length());
      ASSERT_STREQ(firstChildMeta.childName(), entryPath[0]);
      ASSERT_STREQ(firstChildDescendantMeta.childName(), entryPath[1]);
      ASSERT_STREQ(testFileMeta.childName(), entryPath[2]);
    }

    {
      // Move subSubDirectory one level up and rename it to testFile's old name
      FileSystemEntryMetadata src{firstChildDescendant,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{rootId, testFileMeta.childName()};
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Try to get handles to the moved items
      TEST_TRY_UNWRAP_ERR(nsresult rv,
                          dm->GetOrCreateDirectory(firstChildDescendantMeta,
                                                   /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      // Still under the same parent
      TEST_TRY_UNWRAP(
          EntryId handle,
          dm->GetOrCreateFile(newFileMeta, sContentType, /* create */ false));
      ASSERT_EQ(handle, newFile);

      TEST_TRY_UNWRAP(
          handle, dm->GetOrCreateDirectory({rootId, testFileMeta.childName()},
                                           /* create */ false));
      ASSERT_EQ(handle, firstChildDescendant);
    }

    {
      // Check that new file path is as expected
      TEST_TRY_UNWRAP(Path entryPath, dm->Resolve({rootId, newFile}));
      ASSERT_EQ(2u, entryPath.Length());
      ASSERT_STREQ(testFileMeta.childName(), entryPath[0]);
      ASSERT_STREQ(testFileMeta.childName(), entryPath[1]);
    }

    // Move first file and subSubDirectory back one level down keeping the names
    {
      FileSystemEntryMetadata src{testFile,
                                  firstChildDescendantMeta.childName(),
                                  /* is directory */ false};
      FileSystemChildMetadata dest{firstChildDir,
                                   firstChildDescendantMeta.childName()};

      // Flag is ignored
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    {
      // Then move the directory
      FileSystemEntryMetadata src{firstChildDescendant,
                                  testFileMeta.childName(),
                                  /* is directory */ true};
      FileSystemChildMetadata dest{firstChildDir, testFileMeta.childName()};

      // Flag is ignored
      TEST_TRY_UNWRAP(bool isMoved, dm->MoveEntry(src, dest));
      ASSERT_TRUE(isMoved);
    }

    // Check that listings are as expected
    {
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(rootId, 0u));
      ASSERT_TRUE(contents.files().IsEmpty());
      ASSERT_EQ(1u, contents.directories().Length());
      ASSERT_STREQ(firstChildMeta.childName(),
                   contents.directories()[0].entryName());
    }

    {
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(firstChildDir, 0u));
      ASSERT_EQ(1u, contents.files().Length());
      ASSERT_EQ(1u, contents.directories().Length());
      ASSERT_STREQ(firstChildDescendantMeta.childName(),
                   contents.files()[0].entryName());
      ASSERT_STREQ(testFileMeta.childName(),
                   contents.directories()[0].entryName());
    }

    {
      TEST_TRY_UNWRAP(FileSystemDirectoryListing contents,
                      dm->GetDirectoryEntries(firstChildDescendant, 0u));
      ASSERT_EQ(1u, contents.files().Length());
      ASSERT_TRUE(contents.directories().IsEmpty());
      ASSERT_STREQ(testFileMeta.childName(), contents.files()[0].entryName());
    }

    // Names are swapped
    {
      TEST_TRY_UNWRAP(Path entryPath, dm->Resolve({rootId, testFile}));
      ASSERT_EQ(2u, entryPath.Length());
      ASSERT_STREQ(firstChildMeta.childName(), entryPath[0]);
      ASSERT_STREQ(firstChildDescendantMeta.childName(), entryPath[1]);
    }

    {
      TEST_TRY_UNWRAP(Path entryPath,
                      dm->Resolve({rootId, subSubDir.entryId()}));
      ASSERT_EQ(2u, entryPath.Length());
      ASSERT_STREQ(firstChildMeta.childName(), entryPath[0]);
      ASSERT_STREQ(testFileMeta.childName(), entryPath[1]);
    }

    {
      // Check that new file path is also as expected
      TEST_TRY_UNWRAP(Path entryPath, dm->Resolve({rootId, newFile}));
      ASSERT_EQ(3u, entryPath.Length());
      ASSERT_STREQ(firstChildMeta.childName(), entryPath[0]);
      ASSERT_STREQ(testFileMeta.childName(), entryPath[1]);
      ASSERT_STREQ(testFileMeta.childName(), entryPath[2]);
    }

    {
      // Try to get handles to the old items
      TEST_TRY_UNWRAP_ERR(
          nsresult rv, dm->GetOrCreateFile({rootId, testFileMeta.childName()},
                                           sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP_ERR(
          rv,
          dm->GetOrCreateFile({rootId, firstChildDescendantMeta.childName()},
                              sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP_ERR(
          rv, dm->GetOrCreateDirectory({rootId, testFileMeta.childName()},
                                       /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP_ERR(rv,
                          dm->GetOrCreateDirectory(
                              {rootId, firstChildDescendantMeta.childName()},
                              /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);

      TEST_TRY_UNWRAP_ERR(
          rv, dm->GetOrCreateFile({firstChildDir, testFileMeta.childName()},
                                  sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_TYPE_MISMATCH_ERR, rv);

      TEST_TRY_UNWRAP_ERR(
          rv, dm->GetOrCreateDirectory(
                  {firstChildDir, firstChildDescendantMeta.childName()},
                  /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_TYPE_MISMATCH_ERR, rv);

      TEST_TRY_UNWRAP_ERR(
          rv, dm->GetOrCreateFile({testFile, newFileMeta.childName()},
                                  sContentType, /* create */ false));
      ASSERT_NSEQ(NS_ERROR_DOM_NOT_FOUND_ERR, rv);
    }
  };

  PerformOnIOThread(std::move(ioTask));
}

}  // namespace mozilla::dom::fs::test