-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFilesDatabaseManagerTests.swift
More file actions
1058 lines (893 loc) · 42.5 KB
/
Copy pathFilesDatabaseManagerTests.swift
File metadata and controls
1058 lines (893 loc) · 42.5 KB
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// FilesDatabaseManagerTests.swift
//
//
// Created by Claudio Cambra on 15/5/24.
//
import FileProvider
import Foundation
import RealmSwift
import XCTest
@testable import NextcloudFileProviderKit
final class FilesDatabaseManagerTests: XCTestCase {
static let account = Account(
user: "testUser", id: "testUserId", serverUrl: "https://mock.nc.com", password: "abcd"
)
static let dbManager = FilesDatabaseManager(
realmConfig: .defaultConfiguration, account: account
)
override func setUp() {
super.setUp()
Realm.Configuration.defaultConfiguration.inMemoryIdentifier = name
}
func testFilesDatabaseManagerInitialization() {
XCTAssertNotNil(Self.dbManager, "FilesDatabaseManager should be initialized")
}
func testAnyItemMetadatasForAccount() throws {
// Insert test data
let expected = true
let testAccount = "TestAccount"
let metadata = RealmItemMetadata()
metadata.account = testAccount
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(metadata)
}
// Perform test
let result = Self.dbManager.anyItemMetadatasForAccount(testAccount)
XCTAssertEqual(
result,
expected,
"anyItemMetadatasForAccount should return \(expected) for existing account"
)
}
func testItemMetadataFromOcId() throws {
let ocId = "unique-id-123"
let metadata = RealmItemMetadata()
metadata.ocId = ocId
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(metadata)
}
let fetchedMetadata = Self.dbManager.itemMetadata(ocId: ocId)
XCTAssertNotNil(fetchedMetadata, "Should fetch metadata with the specified ocId")
XCTAssertEqual(
fetchedMetadata?.ocId, ocId, "Fetched metadata ocId should match the requested ocId"
)
}
func testUpdateItemMetadatas() {
let account = Account(user: "test", id: "t", serverUrl: "https://example.com", password: "")
var metadata = SendableItemMetadata(ocId: "test", fileName: "test", account: account)
metadata.downloaded = true
metadata.uploaded = true
let result = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: account.ncKitAccount,
serverUrl: account.davFilesUrl,
updatedMetadatas: [metadata],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
XCTAssertEqual(result.newMetadatas?.isEmpty, false, "Should create new metadatas")
XCTAssertEqual(result.updatedMetadatas?.isEmpty, true, "No metadata should be updated")
// Now test we are receiving the updated basic metadatas correctly.
metadata.etag = "new and shiny"
let result2 = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: account.ncKitAccount,
serverUrl: account.davFilesUrl,
updatedMetadatas: [metadata],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
XCTAssertEqual(result2.newMetadatas?.isEmpty, true, "Should create no new metadatas")
XCTAssertEqual(result2.updatedMetadatas?.isEmpty, false, "Metadata should be updated")
// Also check the download state is correctly kept the same.
// We set it to false here to replicate the lack of a download state when converting from
// the NKFiles received during remote enumeration
metadata.downloaded = false
metadata.etag = "new and shiny, but keeping original download state"
let result3 = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: account.ncKitAccount,
serverUrl: account.davFilesUrl,
updatedMetadatas: [metadata],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
XCTAssertEqual(result3.newMetadatas?.isEmpty, true, "Should create no new metadatas")
XCTAssertEqual(result3.updatedMetadatas?.isEmpty, false, "Metadata should be updated")
XCTAssertEqual(result3.updatedMetadatas?.first?.downloaded, true)
}
func testUpdateRenamesDirectoryAndPropagatesToChildren() throws {
let account = Account(user: "test", id: "t", serverUrl: "https://example.com", password: "")
// Insert original parent directory
var parent = SendableItemMetadata(ocId: "dir1", fileName: "oldDir", account: account)
parent.directory = true
parent.serverUrl = account.davFilesUrl
parent.downloaded = true
parent.uploaded = true
Self.dbManager.addItemMetadata(parent)
// Insert a child item inside that directory
var child = SendableItemMetadata(ocId: "child1", fileName: "file.txt", account: account)
child.serverUrl = account.davFilesUrl + "/oldDir"
child.downloaded = true
Self.dbManager.addItemMetadata(child)
var newContainerFolder = SendableItemMetadata(
ocId: "ncf", fileName: "newContainerFolder", account: account
)
newContainerFolder.serverUrl = account.davFilesUrl
newContainerFolder.downloaded = true
Self.dbManager.addItemMetadata(newContainerFolder)
// Rename the directory
var renamedParent = parent
renamedParent.fileName = "newDir"
renamedParent.serverUrl = account.davFilesUrl + "/" + newContainerFolder.fileName
renamedParent.etag = "etag-changed"
let result = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: account.ncKitAccount,
serverUrl: account.davFilesUrl,
updatedMetadatas: [renamedParent],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
// Ensure rename took place
XCTAssertEqual(result.newMetadatas?.isEmpty, true)
XCTAssertEqual(result.updatedMetadatas?.isEmpty, false)
XCTAssertNotNil(result.updatedMetadatas?.first(where: { $0.fileName == "newDir" }))
// Ensure the child's serverUrl was updated accordingly
let updatedChild = Self.dbManager.itemMetadata(ocId: "child1")
XCTAssertNotNil(updatedChild)
XCTAssertEqual(updatedChild?.serverUrl, account.davFilesUrl + "/newContainerFolder/newDir")
}
func testTransitItemIsNotUpdated() throws {
let account = Account(user: "test", id: "t", serverUrl: "https://example.com", password: "")
// Simulate existing item in transit
var transit = SendableItemMetadata(ocId: "transit1", fileName: "temp", account: account)
transit.uploaded = true
transit.downloaded = false
transit.status = Status.downloading.rawValue
transit.etag = "old-etag"
Self.dbManager.addItemMetadata(transit)
// Send an updated version of the same item
var incoming = transit
incoming.uploaded = true
incoming.downloaded = false
incoming.status = Status.normal.rawValue
incoming.etag = "new-etag"
let result = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: account.ncKitAccount,
serverUrl: account.davFilesUrl,
updatedMetadatas: [incoming],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
XCTAssertEqual(result.updatedMetadatas?.isEmpty, true, "Transit items should not be updated")
XCTAssertEqual(result.newMetadatas?.isEmpty, true)
XCTAssertEqual(result.deletedMetadatas?.isEmpty, true)
let inDb = try XCTUnwrap(Self.dbManager.itemMetadata(ocId: transit.ocId))
XCTAssertEqual(inDb.etag, transit.etag)
}
func testTransitItemIsDeleted() throws {
let account = Account(user: "test", id: "t", serverUrl: "https://example.com", password: "")
// Simulate existing item in transit
var transit = SendableItemMetadata(ocId: "transit1", fileName: "temp", account: account)
transit.uploaded = true
transit.downloaded = false
transit.status = Status.downloading.rawValue
Self.dbManager.addItemMetadata(transit)
let result = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: account.ncKitAccount,
serverUrl: account.davFilesUrl,
updatedMetadatas: [],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
XCTAssertEqual(result.updatedMetadatas?.isEmpty, true)
XCTAssertEqual(result.newMetadatas?.isEmpty, true)
XCTAssertEqual(result.deletedMetadatas?.isEmpty, false)
XCTAssertEqual(result.deletedMetadatas?.first?.ocId, transit.ocId)
}
func testSetStatusForItemMetadata() throws {
// Create and add a test metadata to the database
let metadata = RealmItemMetadata()
metadata.ocId = "unique-id-123"
metadata.status = Status.normal.rawValue
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(metadata)
}
let expectedStatus = Status.uploadError
let updatedMetadata = Self.dbManager.setStatusForItemMetadata(
SendableItemMetadata(value: metadata), status: expectedStatus
)
XCTAssertEqual(
updatedMetadata?.status,
expectedStatus.rawValue,
"Status should be updated to \(expectedStatus)"
)
}
func testAddItemMetadata() {
let metadata = SendableItemMetadata(
ocId: "unique-id-123",
fileName: "b",
account: .init(user: "t", id: "t", serverUrl: "b", password: "")
)
Self.dbManager.addItemMetadata(metadata)
let fetchedMetadata = Self.dbManager.itemMetadata(ocId: "unique-id-123")
XCTAssertNotNil(fetchedMetadata, "Metadata should be added to the database")
}
func testDeleteItemMetadata() throws {
let ocId = "unique-id-123"
let metadata = RealmItemMetadata()
metadata.ocId = ocId
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(metadata)
}
let result = Self.dbManager.deleteItemMetadata(ocId: ocId)
XCTAssertTrue(result, "deleteItemMetadata should return true on successful deletion")
XCTAssertNil(
Self.dbManager.itemMetadata(ocId: ocId),
"Metadata should be deleted from the database"
)
}
func testRenameItemMetadata() throws {
let ocId = "unique-id-123"
let newFileName = "newFileName.pdf"
let newServerUrl = "https://new.example.com"
let metadata = RealmItemMetadata()
metadata.ocId = ocId
metadata.fileName = "oldFileName.pdf"
metadata.serverUrl = "https://old.example.com"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(metadata)
}
Self.dbManager.renameItemMetadata(
ocId: ocId, newServerUrl: newServerUrl, newFileName: newFileName
)
let updatedMetadata = Self.dbManager.itemMetadata(ocId: ocId)
XCTAssertEqual(updatedMetadata?.fileName, newFileName, "File name should be updated")
XCTAssertEqual(updatedMetadata?.serverUrl, newServerUrl, "Server URL should be updated")
}
func testDeleteItemMetadatasBasedOnUpdate() throws {
// Existing metadata in the database
let existingMetadata1 = RealmItemMetadata()
existingMetadata1.ocId = "id-1"
existingMetadata1.fileName = "Existing.pdf"
existingMetadata1.serverUrl = "https://example.com"
existingMetadata1.account = "TestAccount"
existingMetadata1.downloaded = true
existingMetadata1.uploaded = true
let existingMetadata2 = RealmItemMetadata()
existingMetadata2.ocId = "id-2"
existingMetadata2.fileName = "Existing2.pdf"
existingMetadata2.serverUrl = "https://example.com"
existingMetadata2.account = "TestAccount"
existingMetadata2.downloaded = true
existingMetadata2.uploaded = true
let existingMetadata3 = RealmItemMetadata()
existingMetadata3.ocId = "id-3"
existingMetadata3.fileName = "Existing3.pdf"
existingMetadata3.serverUrl = "https://example.com/folder" // Different child path
existingMetadata3.account = "TestAccount"
existingMetadata3.downloaded = true
existingMetadata3.uploaded = true
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(existingMetadata1)
realm.add(existingMetadata2)
realm.add(existingMetadata3)
}
// Simulate updated metadata that leads to a deletion
let updatedMetadatas = [existingMetadata1, existingMetadata3] // Only include 2 of the 3
let _ = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: "TestAccount",
serverUrl: "https://example.com",
updatedMetadatas: updatedMetadatas.map { SendableItemMetadata(value: $0) },
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
let remainingMetadatas = Self.dbManager.itemMetadatas(
account: "TestAccount", underServerUrl: "https://example.com"
)
XCTAssertEqual(
remainingMetadatas.count, 2, "Should have two remaining metadata after update"
)
XCTAssertNotNil(remainingMetadatas.first { $0.ocId == "id-1" })
XCTAssertNotNil(remainingMetadatas.first { $0.ocId == "id-3" })
}
func testProcessItemMetadatasToUpdate_NewAndUpdatedSeparation() throws {
let account = Account(
user: "TestAccount", id: "taid", serverUrl: "https://example.com", password: "pass"
)
// Simulate existing metadata in the database
let existingMetadata = RealmItemMetadata()
existingMetadata.ocId = "id-1"
existingMetadata.fileName = "File.pdf"
existingMetadata.account = "TestAccount"
existingMetadata.serverUrl = "https://example.com"
existingMetadata.downloaded = true
existingMetadata.uploaded = true
// Simulate updated metadata that includes changes and a new entry
let updatedMetadata =
SendableItemMetadata(ocId: "id-1", fileName: "UpdatedFile.pdf", account: account)
let newMetadata =
SendableItemMetadata(ocId: "id-2", fileName: "NewFile.pdf", account: account)
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(existingMetadata)
}
let results = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: "TestAccount",
serverUrl: "https://example.com",
updatedMetadatas: [updatedMetadata, newMetadata],
updateDirectoryEtags: true,
keepExistingDownloadState: true
)
XCTAssertEqual(results.newMetadatas?.count, 1, "Should create one new metadata")
XCTAssertEqual(results.updatedMetadatas?.count, 1, "Should update one existing metadata")
XCTAssertEqual(
results.newMetadatas?.first?.ocId, "id-2", "New metadata ocId should be 'id-2'"
)
XCTAssertEqual(
results.updatedMetadatas?.first?.fileName,
"UpdatedFile.pdf",
"Updated metadata should have the new file name"
)
}
func testUnuploadedItemsAreNotDeletedDuringUpdate() throws {
let testAccount = "TestAccount"
let testServerUrl = "https://example.com/files/"
// 1. Item that exists locally and is marked as uploaded
let uploadedItem = RealmItemMetadata()
uploadedItem.ocId = "ocid-uploaded-123"
uploadedItem.fileName = "SyncedFile.txt"
uploadedItem.account = testAccount
uploadedItem.serverUrl = testServerUrl
uploadedItem.downloaded = true
uploadedItem.uploaded = true // IMPORTANT: Marked as uploaded
// 2. Item that exists locally but is NOT marked as uploaded (e.g., new local file)
let unuploadedItem = RealmItemMetadata()
unuploadedItem.ocId = "ocid-local-456" // May or may not have ocId yet
unuploadedItem.fileName = "NewLocalFile.txt"
unuploadedItem.account = testAccount
unuploadedItem.serverUrl = testServerUrl
unuploadedItem.downloaded = true
unuploadedItem.uploaded = false // IMPORTANT: Not marked as uploaded
unuploadedItem.status = Status.normal.rawValue // Ensure it's not in a transient state if relevant
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(uploadedItem)
realm.add(unuploadedItem)
}
// Verify initial state (optional but good practice)
XCTAssertEqual(realm.objects(RealmItemMetadata.self).where { $0.account == testAccount && $0.serverUrl == testServerUrl }.count, 2)
// Simulate an update from the server that contains NEITHER of these items.
// This means the server thinks 'SyncedFile.txt' was deleted,
// and it doesn't know about 'NewLocalFile.txt' yet.
let updatedMetadatasFromServer: [SendableItemMetadata] = []
let results = Self.dbManager.depth1ReadUpdateItemMetadatas(
account: testAccount,
serverUrl: testServerUrl,
updatedMetadatas: updatedMetadatasFromServer,
updateDirectoryEtags: true, // Value doesn't strictly matter for this test logic
keepExistingDownloadState: true // Value doesn't strictly matter for this test logic
)
// --- Assertion ---
let remainingMetadatas = realm.objects(RealmItemMetadata.self)
.where { $0.account == testAccount && $0.serverUrl == testServerUrl }
// Check the returned delete list (based on the copy made before deletion)
XCTAssertEqual(results.deletedMetadatas?.count, 1, "Should identify the uploaded item as deleted.")
XCTAssertEqual(results.deletedMetadatas?.first?.ocId, "ocid-uploaded-123", "The correct uploaded item should be marked for deletion.")
XCTAssertTrue(results.deletedMetadatas?.first?.uploaded ?? false, "The item marked for deletion should have uploaded=true")
// Check the actual database state after the write transaction
XCTAssertEqual(remainingMetadatas.count, 1, "Only one item should remain in the database.")
let survivingItem = remainingMetadatas.first
XCTAssertNotNil(survivingItem, "An item should survive.")
XCTAssertEqual(survivingItem?.ocId, "ocid-local-456", "The surviving item should be the unuploaded one.")
XCTAssertEqual(survivingItem?.fileName, "NewLocalFile.txt", "Filename should match the unuploaded item.")
XCTAssertFalse(survivingItem!.uploaded, "The surviving item must be the one marked uploaded = false.")
// Check other return values are empty as expected
XCTAssertTrue(results.newMetadatas?.isEmpty ?? true, "No new items should have been created.")
XCTAssertTrue(results.updatedMetadatas?.isEmpty ?? true, "No items should have been updated.")
}
func testConcurrencyOnDatabaseWrites() {
let semaphore = DispatchSemaphore(value: 0)
let count = 100
Task {
for i in 0...count {
let metadata = SendableItemMetadata(
ocId: "concurrency-\(i)",
fileName: "name",
account: Account(user: "", id: "", serverUrl: "", password: "")
)
Self.dbManager.addItemMetadata(metadata)
}
semaphore.signal()
}
Task {
for i in 0...count {
let metadata = SendableItemMetadata(
ocId: "concurrency-\(count + 1 + i)",
fileName: "name",
account: Account(user: "", id: "", serverUrl: "", password: "")
)
Self.dbManager.addItemMetadata(metadata)
}
semaphore.signal()
}
semaphore.wait()
semaphore.wait()
for i in 0...count * 2 + 1 {
let resultsI = Self.dbManager.itemMetadata(ocId: "concurrency-\(i)")
XCTAssertNotNil(resultsI, "Metadata \(i) should be saved even under concurrency")
}
}
func testDirectoryMetadataRetrieval() throws {
let account = "TestAccount"
let serverUrl = "https://cloud.example.com/files/documents"
let directoryFileName = "documents"
let metadata = RealmItemMetadata()
metadata.ocId = "dir-1"
metadata.account = account
metadata.serverUrl = "https://cloud.example.com/files"
metadata.fileName = directoryFileName
metadata.directory = true
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(metadata)
}
let retrievedMetadata = Self.dbManager.itemMetadata(
account: account, locatedAtRemoteUrl: serverUrl
)
XCTAssertNotNil(retrievedMetadata, "Should retrieve directory metadata")
XCTAssertEqual(
retrievedMetadata?.fileName, directoryFileName, "Should match the directory file name"
)
}
func testChildItemsForDirectory() throws {
let directoryMetadata = RealmItemMetadata()
directoryMetadata.ocId = "dir-1"
directoryMetadata.account = "TestAccount"
directoryMetadata.serverUrl = "https://cloud.example.com/files"
directoryMetadata.fileName = "documents"
directoryMetadata.directory = true
let childMetadata = RealmItemMetadata()
childMetadata.ocId = "item-1"
childMetadata.account = "TestAccount"
childMetadata.serverUrl = "https://cloud.example.com/files/documents"
childMetadata.fileName = "report.pdf"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(directoryMetadata)
realm.add(childMetadata)
}
let children = Self.dbManager.childItems(
directoryMetadata: SendableItemMetadata(value: directoryMetadata)
)
XCTAssertEqual(children.count, 1, "Should return one child item")
XCTAssertEqual(
children.first?.fileName, "report.pdf", "Should match the child item's file name"
)
}
func testDeleteDirectoryAndSubdirectoriesMetadata() throws {
let directoryMetadata = RealmItemMetadata()
directoryMetadata.ocId = "dir-1"
directoryMetadata.account = "TestAccount"
directoryMetadata.serverUrl = "https://cloud.example.com/files"
directoryMetadata.fileName = "documents"
directoryMetadata.directory = true
let childMetadata = RealmItemMetadata()
childMetadata.ocId = "item-1"
childMetadata.account = "TestAccount"
childMetadata.serverUrl = "https://cloud.example.com/files/documents"
childMetadata.fileName = "report.pdf"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(directoryMetadata)
realm.add(childMetadata)
}
let deletedMetadatas = Self.dbManager.deleteDirectoryAndSubdirectoriesMetadata(
ocId: "dir-1"
)
XCTAssertNotNil(deletedMetadatas, "Should return a list of deleted metadatas")
XCTAssertEqual(deletedMetadatas?.count, 2, "Should delete the directory and its child")
}
func testRenameDirectoryAndPropagateToChildren() throws {
let directoryMetadata = RealmItemMetadata()
directoryMetadata.ocId = "dir-1"
directoryMetadata.account = "TestAccount"
directoryMetadata.serverUrl = "https://cloud.example.com/files"
directoryMetadata.fileName = "documents"
directoryMetadata.directory = true
let childMetadata = RealmItemMetadata()
childMetadata.ocId = "item-1"
childMetadata.account = "TestAccount"
childMetadata.serverUrl = "https://cloud.example.com/files/documents"
childMetadata.fileName = "report.pdf"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(directoryMetadata)
realm.add(childMetadata)
}
let updatedChildren = Self.dbManager.renameDirectoryAndPropagateToChildren(
ocId: "dir-1",
newServerUrl: "https://cloud.example.com/office",
newFileName: "files"
)
XCTAssertNotNil(updatedChildren, "Should return updated children metadatas")
XCTAssertEqual(updatedChildren?.count, 1, "Should include one child")
XCTAssertEqual(
updatedChildren?.first?.serverUrl,
"https://cloud.example.com/office/files",
"Should update serverUrl of child items"
)
}
func testErrorOnDirectoryMetadataNotFound() throws {
let nonExistentServerUrl = "https://cloud.example.com/nonexistent"
let directoryMetadata = Self.dbManager.itemMetadata(
account: "TestAccount", locatedAtRemoteUrl: nonExistentServerUrl
)
XCTAssertNil(directoryMetadata, "Should return nil when directory metadata is not found")
}
func testChildItemsForRootDirectory() throws {
var rootMetadata = SendableItemMetadata(
ocId: NSFileProviderItemIdentifier.rootContainer.rawValue,
fileName: "",
account: Account(
user: "TestAccount",
id: "ta",
serverUrl: "https://cloud.example.com/files",
password: ""
)
) // Do not write, we do not track root container
let childMetadata = RealmItemMetadata()
childMetadata.ocId = "item-1"
childMetadata.account = "TestAccount"
childMetadata.serverUrl = rootMetadata.serverUrl
childMetadata.fileName = "report.pdf"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(childMetadata)
}
let children = Self.dbManager.childItems(directoryMetadata: rootMetadata)
XCTAssertEqual(children.count, 1, "Should return one child item for the root directory")
XCTAssertEqual(
children.first?.fileName,
"report.pdf",
"Should match the child item's file name for root directory"
)
}
func testDeleteNestedDirectoriesAndSubdirectoriesMetadata() throws {
// Create nested directories and their child items
let rootDirectoryMetadata = RealmItemMetadata()
rootDirectoryMetadata.ocId = "dir-1"
rootDirectoryMetadata.account = "TestAccount"
rootDirectoryMetadata.serverUrl = "https://cloud.example.com/files"
rootDirectoryMetadata.fileName = "documents"
rootDirectoryMetadata.directory = true
let nestedDirectoryMetadata = RealmItemMetadata()
nestedDirectoryMetadata.ocId = "dir-2"
nestedDirectoryMetadata.account = "TestAccount"
nestedDirectoryMetadata.serverUrl = "https://cloud.example.com/files/documents"
nestedDirectoryMetadata.fileName = "projects"
nestedDirectoryMetadata.directory = true
let childMetadata = RealmItemMetadata()
childMetadata.ocId = "item-1"
childMetadata.account = "TestAccount"
childMetadata.serverUrl = "https://cloud.example.com/files/documents/projects"
childMetadata.fileName = "report.pdf"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(rootDirectoryMetadata)
realm.add(nestedDirectoryMetadata)
realm.add(childMetadata)
}
let deletedMetadatas = Self.dbManager.deleteDirectoryAndSubdirectoriesMetadata(
ocId: "dir-1"
)
XCTAssertNotNil(deletedMetadatas, "Should return a list of deleted metadatas")
XCTAssertEqual(
deletedMetadatas?.count,
3,
"Should delete the root directory, nested directory, and its child"
)
}
func testRecursiveRenameOfDirectoriesAndChildItems() throws {
// Setup a complex directory structure
let rootDirectoryMetadata = RealmItemMetadata()
rootDirectoryMetadata.ocId = "dir-1"
rootDirectoryMetadata.account = "TestAccount"
rootDirectoryMetadata.serverUrl = "https://cloud.example.com/files"
rootDirectoryMetadata.fileName = "documents"
rootDirectoryMetadata.directory = true
let nestedDirectoryMetadata = RealmItemMetadata()
nestedDirectoryMetadata.ocId = "dir-2"
nestedDirectoryMetadata.account = "TestAccount"
nestedDirectoryMetadata.serverUrl = "https://cloud.example.com/files/documents"
nestedDirectoryMetadata.fileName = "projects"
nestedDirectoryMetadata.directory = true
let childMetadata = RealmItemMetadata()
childMetadata.ocId = "item-1"
childMetadata.account = "TestAccount"
childMetadata.serverUrl = "https://cloud.example.com/files/documents/projects"
childMetadata.fileName = "report.pdf"
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(rootDirectoryMetadata)
realm.add(nestedDirectoryMetadata)
realm.add(childMetadata)
}
let updatedChildren = Self.dbManager.renameDirectoryAndPropagateToChildren(
ocId: "dir-1",
newServerUrl: "https://cloud.example.com/storage",
newFileName: "files"
)
XCTAssertNotNil(updatedChildren, "Should return updated children metadatas")
XCTAssertEqual(updatedChildren?.count, 2, "Should include the nested directory and child item")
XCTAssertTrue(
updatedChildren?.contains { $0.serverUrl.contains("/storage/files/") } ?? false,
"Should update serverUrl of all child items to reflect new directory path")
}
func testDeletingDirectoryWithNoChildren() throws {
let directoryMetadata = RealmItemMetadata()
directoryMetadata.ocId = "dir-1"
directoryMetadata.account = "TestAccount"
directoryMetadata.serverUrl = "https://cloud.example.com/files"
directoryMetadata.fileName = "empty"
directoryMetadata.directory = true
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(directoryMetadata)
}
let deletedMetadatas = Self.dbManager.deleteDirectoryAndSubdirectoriesMetadata(
ocId: "dir-1"
)
XCTAssertNotNil(
deletedMetadatas,
"Should return a list of deleted metadatas even if the directory has no children"
)
XCTAssertEqual(
deletedMetadatas?.count,
1,
"Should only delete the directory itself as there are no children"
)
}
func testRenamingDirectoryWithComplexNestedStructure() throws {
// Create a complex nested directory structure
let rootDirectoryMetadata = RealmItemMetadata()
rootDirectoryMetadata.ocId = "dir-1"
rootDirectoryMetadata.account = "TestAccount"
rootDirectoryMetadata.serverUrl = "https://cloud.example.com/files"
rootDirectoryMetadata.fileName = "dir-1"
rootDirectoryMetadata.directory = true
let nestedDirectoryMetadata = RealmItemMetadata()
nestedDirectoryMetadata.ocId = "dir-2"
nestedDirectoryMetadata.account = "TestAccount"
nestedDirectoryMetadata.serverUrl = "https://cloud.example.com/files/dir-1"
nestedDirectoryMetadata.fileName = "dir-2"
nestedDirectoryMetadata.directory = true
let deepNestedDirectoryMetadata = RealmItemMetadata()
deepNestedDirectoryMetadata.ocId = "dir-3"
deepNestedDirectoryMetadata.account = "TestAccount"
deepNestedDirectoryMetadata.serverUrl = "https://cloud.example.com/files/dir-1/dir-2"
deepNestedDirectoryMetadata.fileName = "dir-3"
deepNestedDirectoryMetadata.directory = true
let realm = Self.dbManager.ncDatabase()
try realm.write {
realm.add(rootDirectoryMetadata)
realm.add(nestedDirectoryMetadata)
realm.add(deepNestedDirectoryMetadata)
}
let updatedChildren = Self.dbManager.renameDirectoryAndPropagateToChildren(
ocId: "dir-1",
newServerUrl: "https://cloud.example.com/storage",
newFileName: "archives"
)
XCTAssertNotNil(updatedChildren, "Should return updated children metadatas")
XCTAssertEqual(updatedChildren?.count, 2, "Should include both nested directories")
XCTAssertTrue(
updatedChildren?.allSatisfy { $0.serverUrl.contains("/storage/archives") } ?? false,
"All children should have their serverUrl updated correctly"
)
}
func testFindingItemBasedOnRemotePath() throws {
let account = "TestAccount"
let filename = "super duper new file"
let parentUrl = "https://cloud.example.com/files/my great and incredible dir/dir-2"
let fullUrl = parentUrl + "/" + filename
let deepNestedDirectoryMetadata = RealmItemMetadata()
deepNestedDirectoryMetadata.ocId = filename
deepNestedDirectoryMetadata.account = account
deepNestedDirectoryMetadata.serverUrl = parentUrl
deepNestedDirectoryMetadata.fileName = filename
deepNestedDirectoryMetadata.directory = true
let realm = Self.dbManager.ncDatabase()
try realm.write { realm.add(deepNestedDirectoryMetadata) }
XCTAssertNotNil(Self.dbManager.itemMetadata(account: account, locatedAtRemoteUrl: fullUrl))
}
func testInitializerMigration() throws {
let account1 = Account(user: "account1", id: "account1", serverUrl: "c.nc.c", password: "a")
let account2 = Account(user: "account2", id: "account2", serverUrl: "c.nc.c", password: "b")
// 1. Create a unique temporary directory for the file provider data directory.
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
// 2. Define a custom relative database folder path.
// For example, if you normally use "Nextcloud/Realm/", here we use "Test/Realm/".
let customRelativeDatabaseFolderPath = "Test/Realm/"
// 3. Build the expected old Realm file URL using the custom relative path
// and the class’s databaseFilename.
let oldRealmURL = tempDir.appendingPathComponent(
customRelativeDatabaseFolderPath + databaseFilename
)
try FileManager.default.createDirectory(
at: oldRealmURL.deletingLastPathComponent(), withIntermediateDirectories: true
)
// 4. Create the old Realm configuration and insert test objects.
// Use stable2_0SchemaVersion and the appropriate object types.
let oldConfig = Realm.Configuration(
fileURL: oldRealmURL,
schemaVersion: stable2_0SchemaVersion,
objectTypes: [RealmItemMetadata.self, RemoteFileChunk.self]
)
let oldRealm = try Realm(configuration: oldConfig)
// Create test objects
let migratingItem = RealmItemMetadata()
migratingItem.ocId = "id1"
migratingItem.account = account1.ncKitAccount
let nonMigratingItem = RealmItemMetadata()
nonMigratingItem.ocId = "id2"
nonMigratingItem.account = account2.ncKitAccount
let remoteChunk = RemoteFileChunk()
remoteChunk.fileName = "chunk1"
try oldRealm.write {
oldRealm.add(migratingItem)
oldRealm.add(nonMigratingItem)
oldRealm.add(remoteChunk)
}
XCTAssertEqual(oldRealm.objects(RealmItemMetadata.self).count, 2)
XCTAssertEqual(oldRealm.objects(RemoteFileChunk.self).count, 1)
// 5. Prepare a new Realm configuration for the target per‑account database.
let newRealmURL = tempDir.appendingPathComponent("new.realm")
let newConfig = Realm.Configuration(
fileURL: newRealmURL,
schemaVersion: stable2_0SchemaVersion,
objectTypes: [RealmItemMetadata.self, RemoteFileChunk.self]
)
// 6. Call the initializer that performs the migration.
// It will search for the old database at:
// fileProviderDataDirUrl/appendingPathComponent(customRelativeDbFolderPath + dbFilename)
// and migrate only metadata objects with account == "account1" plus remote file chunks.
let dbManager = FilesDatabaseManager(
realmConfig: newConfig,
account: account1,
fileProviderDataDirUrl: tempDir,
relativeDatabaseFolderPath: customRelativeDatabaseFolderPath
)
// 7. Verify that the new Realm now contains the migrated objects.
let newRealm = dbManager.ncDatabase()
let newMigratedItems = newRealm.objects(RealmItemMetadata.self)
let newRemoteChunks = newRealm.objects(RemoteFileChunk.self)
XCTAssertEqual(
newMigratedItems.count, 1, "Only one metadata item for account1 should be migrated"
)
XCTAssertEqual(newMigratedItems.first?.account, account1.ncKitAccount)
XCTAssertEqual(newRemoteChunks.count, 1, "Remote file chunks should be migrated")
// 8. Verify that the old Realm has retained the migrated objects.
let oldRealmAfter = try Realm(configuration: oldConfig)
let allItems = oldRealmAfter.objects(RealmItemMetadata.self)
let allChunks = oldRealmAfter.objects(RemoteFileChunk.self)
// Expect both metadata objects still to be present.
XCTAssertEqual(
allItems.count,
2,
"The old realm should have retained both migrated and non-migrated metadata items"
)
XCTAssertTrue(
allItems.contains(where: { $0.account == account1.ncKitAccount }),
"Migrated metadata should be retained in the old realm"
)
XCTAssertEqual(
allChunks.count, 1, "The remote file chunks should be retained in the old realm"
)
// 9. Clean up by removing the temporary directory.
try FileManager.default.removeItem(at: tempDir)
}
func testMigrationIsNotPerformedTwice() throws {
let fm = FileManager.default
let tempDir = fm.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try fm.createDirectory(at: tempDir, withIntermediateDirectories: true)
let customRelativePath = "Test/Realm/"
let oldRealmURL = tempDir.appendingPathComponent(
customRelativePath + NextcloudFileProviderKit.databaseFilename
)
try fm.createDirectory(
at: oldRealmURL.deletingLastPathComponent(), withIntermediateDirectories: true
)
let account1 = Account(user: "account1", id: "account1", serverUrl: "c.nc.c", password: "a")
let account2 = Account(user: "account2", id: "account2", serverUrl: "c.nc.c", password: "b")
let accounts = (migrated: account1, nonMigrated: account2)
// Insert initial objects into the old realm
let oldConfig = Realm.Configuration(
fileURL: oldRealmURL,
schemaVersion: stable2_0SchemaVersion,
objectTypes: [RealmItemMetadata.self, RemoteFileChunk.self]
)
let oldRealm = try Realm(configuration: oldConfig)
let migratedItem = RealmItemMetadata()
migratedItem.ocId = "id1"
migratedItem.account = accounts.migrated.ncKitAccount
let nonMigratedItem = RealmItemMetadata()
nonMigratedItem.ocId = "id2"
nonMigratedItem.account = accounts.nonMigrated.ncKitAccount
let remoteChunk = RemoteFileChunk()
remoteChunk.fileName = "chunk1"
try oldRealm.write {
oldRealm.add(migratedItem)
oldRealm.add(nonMigratedItem)
oldRealm.add(remoteChunk)
}
// New realm config (target)
let newRealmURL = tempDir.appendingPathComponent("new.realm")
let newConfig = Realm.Configuration(
fileURL: newRealmURL,
schemaVersion: stable2_0SchemaVersion,
objectTypes: [RealmItemMetadata.self, RemoteFileChunk.self]
)
// First migration
let newDbManager = FilesDatabaseManager(
realmConfig: newConfig,
account: accounts.migrated,
fileProviderDataDirUrl: tempDir,
relativeDatabaseFolderPath: customRelativePath
)
let newRealm = newDbManager.ncDatabase()
let initialMigrated = newRealm.objects(RealmItemMetadata.self)
let initialChunks = newRealm.objects(RemoteFileChunk.self)