fix(file-provider): Add test coverage for cancellations in small and chunked uploads through upload, create and modify
Signed-off-by: Claudio Cambra <[email protected]> Assisted-by: Codex:GPT-6 Signed-off-by: Claudio Cambra <[email protected]>
This commit is contained in:
4 files changed
+312
-13
No files matched your search
+11
-4
@@ -576,6 +576,8 @@ public class MockRemoteInterface: RemoteInterface, @unchecked Sendable {
|
||||
public var chunkPreparationError: NKError?
|
||||
public var chunkAssemblyHandler: (@Sendable () async -> Void)?
|
||||
public var uploadHandler: (@Sendable () async -> Void)?
|
||||
public var uploadRequest: UploadRequest?
|
||||
public var uploadTask: URLSessionTask?
|
||||
public private(set) var uploadOperationCount = 0
|
||||
|
||||
public var downloadHandler: (@Sendable () async -> Void)?
|
||||
@@ -829,8 +831,8 @@ public class MockRemoteInterface: RemoteInterface, @unchecked Sendable {
|
||||
modificationDate: Date? = .init(),
|
||||
account: Account,
|
||||
options: NKRequestOptions = .init(),
|
||||
requestHandler _: @escaping (Alamofire.UploadRequest) -> Void = { _ in },
|
||||
taskHandler _: @escaping (URLSessionTask) -> Void = { _ in },
|
||||
requestHandler: @escaping (Alamofire.UploadRequest) -> Void = { _ in },
|
||||
taskHandler: @escaping (URLSessionTask) -> Void = { _ in },
|
||||
progressHandler _: @escaping (Progress) -> Void = { _ in }
|
||||
) async -> (
|
||||
account: String,
|
||||
@@ -845,6 +847,12 @@ public class MockRemoteInterface: RemoteInterface, @unchecked Sendable {
|
||||
lastUploadIfMatchHeader = options.customHeader?["If-Match"]
|
||||
lastUploadIfHeader = options.customHeader?["If"]
|
||||
|
||||
if let uploadRequest {
|
||||
requestHandler(uploadRequest)
|
||||
}
|
||||
if let uploadTask {
|
||||
taskHandler(uploadTask)
|
||||
}
|
||||
if let uploadHandler {
|
||||
await uploadHandler()
|
||||
if Task.isCancelled {
|
||||
@@ -940,7 +948,7 @@ public class MockRemoteInterface: RemoteInterface, @unchecked Sendable {
|
||||
chunkCounter _: @escaping (Int) -> Void = { _ in },
|
||||
log _: any FileProviderLogging,
|
||||
chunkUploadStartHandler: @escaping ([RemoteFileChunk]) -> Void = { _ in },
|
||||
requestHandler: @escaping (UploadRequest) -> Void = { _ in },
|
||||
requestHandler _: @escaping (UploadRequest) -> Void = { _ in },
|
||||
taskHandler: @escaping (URLSessionTask) -> Void = { _ in },
|
||||
progressHandler: @escaping (Progress) -> Void = { _ in },
|
||||
chunkUploadCompleteHandler: @escaping (RemoteFileChunk) -> Void = { _ in }
|
||||
@@ -1013,7 +1021,6 @@ public class MockRemoteInterface: RemoteInterface, @unchecked Sendable {
|
||||
modificationDate: modificationDate,
|
||||
account: account,
|
||||
options: options,
|
||||
requestHandler: requestHandler,
|
||||
taskHandler: taskHandler,
|
||||
progressHandler: progressHandler
|
||||
)
|
||||
|
||||
+68
-3
@@ -1,6 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
import Alamofire
|
||||
@preconcurrency import FileProvider
|
||||
@testable import NextcloudFileProviderKit
|
||||
import NextcloudFileProviderKitMocks
|
||||
@@ -159,6 +160,69 @@ final class ItemCreateTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertNil(Self.dbManager.itemMetadata(ocId: metadata.ocId))
|
||||
}
|
||||
|
||||
func testCancellationDuringUploadDoesNotCreateFile() async throws {
|
||||
for chunkSize in [8, 3] {
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: rootItem)
|
||||
let progress = Progress()
|
||||
let data = Data(repeating: 1, count: 8)
|
||||
let isChunked = chunkSize < data.count
|
||||
let session = isChunked ? nil : Session(startRequestsImmediately: false)
|
||||
let request = session?.upload(Data(), to: "https://example.invalid/resource")
|
||||
let urlSession = URLSession(configuration: .ephemeral)
|
||||
defer { urlSession.invalidateAndCancel() }
|
||||
let (networkTask, networkCompletion) = try observedNetworkTask(
|
||||
in: urlSession,
|
||||
url: XCTUnwrap(URL(string: "https://example.invalid/resource"))
|
||||
)
|
||||
remoteInterface.uploadRequest = request
|
||||
remoteInterface.uploadTask = networkTask
|
||||
remoteInterface.uploadHandler = {
|
||||
progress.cancel()
|
||||
let cancelled = await waitForCancellation()
|
||||
XCTAssertTrue(cancelled, "Cancellation must reach the create operation")
|
||||
}
|
||||
remoteInterface.chunkUploadCompletedChunkCount = 1
|
||||
let chunkDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
remoteInterface.chunkUploadDirectory = chunkDirectory
|
||||
defer { try? FileManager.default.removeItem(at: chunkDirectory) }
|
||||
let fileUrl = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".txt")
|
||||
try data.write(to: fileUrl)
|
||||
defer { try? FileManager.default.removeItem(at: fileUrl) }
|
||||
var metadata = SendableItemMetadata(ocId: UUID().uuidString, fileName: fileUrl.lastPathComponent, account: Self.account)
|
||||
metadata.classFile = NKTypeClassFile.document.rawValue
|
||||
let template = Item(metadata: metadata, parentItemIdentifier: .rootContainer, account: Self.account, remoteInterface: remoteInterface, dbManager: Self.dbManager)
|
||||
|
||||
let (createdItem, error) = await Item.create(
|
||||
basedOn: template,
|
||||
contents: fileUrl,
|
||||
account: Self.account,
|
||||
remoteInterface: remoteInterface,
|
||||
forcedChunkSize: chunkSize,
|
||||
progress: progress,
|
||||
dbManager: Self.dbManager,
|
||||
log: FileProviderLogMock()
|
||||
)
|
||||
|
||||
XCTAssertNil(createdItem)
|
||||
XCTAssertEqual((error as? CocoaError)?.code, .userCancelled)
|
||||
let cancellationCode = try await nextTestValue(from: networkCompletion)
|
||||
XCTAssertEqual(cancellationCode, NSURLErrorCancelled)
|
||||
if !isChunked {
|
||||
XCTAssertTrue(try XCTUnwrap(request).isCancelled)
|
||||
}
|
||||
XCTAssertEqual(remoteInterface.uploadOperationCount, 1)
|
||||
XCTAssertTrue(rootItem.children.isEmpty)
|
||||
XCTAssertNil(Self.dbManager.itemMetadata(ocId: metadata.ocId))
|
||||
let remainingChunks = Self.dbManager.ncDatabase().objects(RemoteFileChunk.self)
|
||||
.where { $0.remoteChunkStoreFolderName.starts(with: chunkUploadIdentifierPrefix(forItemWithIdentifier: metadata.ocId)) }
|
||||
.toUnmanagedResults()
|
||||
XCTAssertEqual(remainingChunks.map(\.fileName).sorted(), isChunked ? ["2", "3"] : [])
|
||||
for chunk in remainingChunks {
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: chunkDirectory.appendingPathComponent(chunk.fileName).path))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCreateFile() async throws {
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: rootItem)
|
||||
var fileItemMetadata = SendableItemMetadata(
|
||||
@@ -380,8 +444,9 @@ final class ItemCreateTests: NextcloudFileProviderKitTestCase {
|
||||
.appendingPathComponent("quota-report-create")
|
||||
try Data("Hello world".utf8).write(to: tempUrl) // 11 bytes > 4 bytes available
|
||||
|
||||
let domainIdentifier = NSFileProviderDomainIdentifier(UUID().uuidString)
|
||||
let domain = NSFileProviderDomain(
|
||||
identifier: NSFileProviderDomainIdentifier("test-domain-create"),
|
||||
identifier: domainIdentifier,
|
||||
displayName: "test"
|
||||
)
|
||||
let proxy = QuotaCapturingAppProxy()
|
||||
@@ -411,10 +476,10 @@ final class ItemCreateTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertEqual(proxy.capturedItems.count, 1)
|
||||
let itemCapture = try XCTUnwrap(proxy.capturedItems.first)
|
||||
XCTAssertEqual(itemCapture.fileName, "file-quota-report")
|
||||
XCTAssertEqual(itemCapture.domainIdentifier, "test-domain-create")
|
||||
XCTAssertEqual(itemCapture.domainIdentifier, domainIdentifier.rawValue)
|
||||
XCTAssertEqual(itemCapture.fileBytes, 11)
|
||||
|
||||
XCTAssertEqual(proxy.capturedSummaryDomains, ["test-domain-create"])
|
||||
XCTAssertEqual(proxy.capturedSummaryDomains, [domainIdentifier.rawValue])
|
||||
}
|
||||
|
||||
/// Negative `quotaAvailableBytes` (the default for accounts with no quota set) must
|
||||
|
||||
+56
-6
@@ -1,6 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
|
||||
// SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
import Alamofire
|
||||
@preconcurrency import FileProvider
|
||||
@testable import NextcloudFileProviderKit
|
||||
import NextcloudFileProviderKitMocks
|
||||
@@ -31,17 +32,44 @@ final class ItemModifyTests: NextcloudFileProviderKitTestCase {
|
||||
private func assertFailedContentModificationRemainsUnuploaded(
|
||||
errorCode: Int,
|
||||
chunkSize: Int?,
|
||||
cancelDuringChunkPreparation: Bool = false
|
||||
cancelDuringChunkPreparation: Bool = false,
|
||||
cancelDuringUpload: Bool = false
|
||||
) async throws {
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: rootItem)
|
||||
let uploadError = cancelDuringChunkPreparation ? NKError.cancelled : NKError(errorCode: errorCode, errorDescription: "Upload did not complete")
|
||||
let expectCancellation = cancelDuringChunkPreparation || cancelDuringUpload
|
||||
let uploadError: NKError = if cancelDuringUpload, chunkSize == nil {
|
||||
NKError(error: URLError(.cancelled))
|
||||
} else if expectCancellation {
|
||||
.cancelled
|
||||
} else {
|
||||
NKError(errorCode: errorCode, errorDescription: "Upload did not complete")
|
||||
}
|
||||
let progress = Progress()
|
||||
let session = cancelDuringUpload && chunkSize == nil ? Session(startRequestsImmediately: false) : nil
|
||||
let request = session?.upload(Data(), to: "https://example.invalid/resource")
|
||||
let urlSession = cancelDuringUpload ? URLSession(configuration: .ephemeral) : nil
|
||||
defer { urlSession?.invalidateAndCancel() }
|
||||
let observedTask = try urlSession.map { session in
|
||||
try observedNetworkTask(in: session, url: XCTUnwrap(URL(string: "https://example.invalid/resource")))
|
||||
}
|
||||
let chunkDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: chunkDirectory) }
|
||||
if cancelDuringChunkPreparation {
|
||||
remoteInterface.chunkPreparationHandler = {
|
||||
progress.cancel()
|
||||
let cancelled = await waitForCancellation()
|
||||
XCTAssertTrue(cancelled, "Chunk preparation must receive cancellation")
|
||||
}
|
||||
} else if cancelDuringUpload {
|
||||
remoteInterface.uploadRequest = request
|
||||
remoteInterface.uploadTask = observedTask?.task
|
||||
remoteInterface.chunkUploadDirectory = chunkDirectory
|
||||
remoteInterface.chunkUploadCompletedChunkCount = 1
|
||||
remoteInterface.uploadHandler = {
|
||||
progress.cancel()
|
||||
let cancelled = await waitForCancellation()
|
||||
XCTAssertTrue(cancelled, "Cancellation must reach the modify operation")
|
||||
}
|
||||
} else {
|
||||
remoteInterface.uploadError = uploadError
|
||||
}
|
||||
@@ -86,10 +114,26 @@ final class ItemModifyTests: NextcloudFileProviderKitTestCase {
|
||||
|
||||
XCTAssertNil(modifiedItem)
|
||||
XCTAssertNotNil(error)
|
||||
if cancelDuringChunkPreparation {
|
||||
if expectCancellation {
|
||||
XCTAssertEqual((error as? CocoaError)?.code, .userCancelled)
|
||||
XCTAssertTrue(progress.isCancelled)
|
||||
XCTAssertEqual(remoteInterface.uploadOperationCount, 0)
|
||||
XCTAssertEqual(remoteInterface.uploadOperationCount, cancelDuringUpload ? 1 : 0)
|
||||
}
|
||||
if cancelDuringUpload {
|
||||
let completion = try XCTUnwrap(observedTask?.completion)
|
||||
let cancellationCode = try await nextTestValue(from: completion)
|
||||
XCTAssertEqual(cancellationCode, NSURLErrorCancelled)
|
||||
if chunkSize == nil {
|
||||
XCTAssertTrue(try XCTUnwrap(request).isCancelled)
|
||||
}
|
||||
let remainingChunks = Self.dbManager.ncDatabase().objects(RemoteFileChunk.self)
|
||||
.where { $0.remoteChunkStoreFolderName.starts(with: chunkUploadIdentifierPrefix(forItemWithIdentifier: itemMetadata.ocId)) }
|
||||
.toUnmanagedResults()
|
||||
let expectedRemainingCount = chunkSize.map { max(0, Int(ceil(Double(newContents.count) / Double($0))) - 1) } ?? 0
|
||||
XCTAssertEqual(remainingChunks.count, expectedRemainingCount)
|
||||
for chunk in remainingChunks {
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: chunkDirectory.appendingPathComponent(chunk.fileName).path))
|
||||
}
|
||||
}
|
||||
let storedMetadata = try XCTUnwrap(Self.dbManager.itemMetadata(ocId: itemMetadata.ocId))
|
||||
XCTAssertFalse(storedMetadata.uploaded)
|
||||
@@ -199,6 +243,11 @@ final class ItemModifyTests: NextcloudFileProviderKitTestCase {
|
||||
try await assertFailedContentModificationRemainsUnuploaded(errorCode: NSURLErrorCancelled, chunkSize: 2, cancelDuringChunkPreparation: true)
|
||||
}
|
||||
|
||||
func testCancellationDuringUploadRemainsUnuploaded() async throws {
|
||||
try await assertFailedContentModificationRemainsUnuploaded(errorCode: NSURLErrorCancelled, chunkSize: nil, cancelDuringUpload: true)
|
||||
try await assertFailedContentModificationRemainsUnuploaded(errorCode: NSURLErrorCancelled, chunkSize: 2, cancelDuringUpload: true)
|
||||
}
|
||||
|
||||
func testModifyFile() async throws {
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: rootItem)
|
||||
|
||||
@@ -346,8 +395,9 @@ final class ItemModifyTests: NextcloudFileProviderKitTestCase {
|
||||
var targetItemMetadata = SendableItemMetadata(value: itemMetadata)
|
||||
targetItemMetadata.size = Int64(newContents.count)
|
||||
|
||||
let domainIdentifier = NSFileProviderDomainIdentifier(UUID().uuidString)
|
||||
let domain = NSFileProviderDomain(
|
||||
identifier: NSFileProviderDomainIdentifier("test-domain-modify"),
|
||||
identifier: domainIdentifier,
|
||||
displayName: "test"
|
||||
)
|
||||
let proxy = QuotaCapturingAppProxy()
|
||||
@@ -381,7 +431,7 @@ final class ItemModifyTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertEqual(proxy.capturedItems.count, 1)
|
||||
XCTAssertEqual(proxy.capturedItems.first?.fileName, "item.txt")
|
||||
XCTAssertEqual(proxy.capturedItems.first?.fileBytes, Int64(newContents.count))
|
||||
XCTAssertEqual(proxy.capturedSummaryDomains, ["test-domain-modify"])
|
||||
XCTAssertEqual(proxy.capturedSummaryDomains, [domainIdentifier.rawValue])
|
||||
}
|
||||
|
||||
/// Pre-flight quota gate on the modify path: when the parent's `quotaAvailableBytes`
|
||||
|
||||
+177
@@ -6,6 +6,7 @@ import Alamofire
|
||||
@testable import NextcloudFileProviderKit
|
||||
import NextcloudFileProviderKitMocks
|
||||
@testable import NextcloudKit
|
||||
import RealmSwift
|
||||
import TestInterface
|
||||
import XCTest
|
||||
|
||||
@@ -193,6 +194,182 @@ final class UploadTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertTrue(try XCTUnwrap(Self.dbManager.remoteFileChunks(uploadId: uploadId)).isEmpty)
|
||||
}
|
||||
|
||||
func testCancellationDuringUploadCancelsNetworkHandlesAndAllowsRetry() async throws {
|
||||
let fileUrl = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let data = Data(repeating: 1, count: 8)
|
||||
try data.write(to: fileUrl)
|
||||
defer { try? FileManager.default.removeItem(at: fileUrl) }
|
||||
let root = MockRemoteItem.rootItem(account: Self.account)
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: root)
|
||||
let progress = Progress()
|
||||
let session = Session(startRequestsImmediately: false)
|
||||
let request = session.upload(Data(), to: "https://example.invalid/resource")
|
||||
let urlSession = URLSession(configuration: .ephemeral)
|
||||
defer { urlSession.invalidateAndCancel() }
|
||||
let (networkTask, networkCompletion) = try observedNetworkTask(
|
||||
in: urlSession,
|
||||
url: XCTUnwrap(URL(string: "https://example.invalid/resource"))
|
||||
)
|
||||
remoteInterface.uploadRequest = request
|
||||
remoteInterface.uploadTask = networkTask
|
||||
remoteInterface.uploadHandler = {
|
||||
progress.cancel()
|
||||
let cancelled = await waitForCancellation()
|
||||
XCTAssertTrue(cancelled, "Cancellation must reach the upload operation")
|
||||
}
|
||||
let itemIdentifier = UUID().uuidString
|
||||
|
||||
let result = await NextcloudFileProviderKit.upload(
|
||||
fileLocatedAt: fileUrl.path,
|
||||
toRemotePath: Self.account.davFilesUrl + "/file.txt",
|
||||
usingRemoteInterface: remoteInterface,
|
||||
withAccount: Self.account,
|
||||
inChunksSized: data.count,
|
||||
forItemWithIdentifier: itemIdentifier,
|
||||
dbManager: Self.dbManager,
|
||||
progress: progress,
|
||||
log: FileProviderLogMock()
|
||||
)
|
||||
|
||||
XCTAssertEqual(result.remoteError.errorCode, NSURLErrorCancelled)
|
||||
XCTAssertNil(result.ocId)
|
||||
let cancellationCode = try await nextTestValue(from: networkCompletion)
|
||||
XCTAssertEqual(cancellationCode, NSURLErrorCancelled)
|
||||
XCTAssertTrue(request.isCancelled)
|
||||
XCTAssertNil(progress.cancellationHandler)
|
||||
XCTAssertNil(progress.pausingHandler)
|
||||
XCTAssertNil(progress.resumingHandler)
|
||||
XCTAssertEqual(remoteInterface.uploadOperationCount, 1)
|
||||
XCTAssertTrue(root.children.isEmpty)
|
||||
|
||||
remoteInterface.uploadHandler = nil
|
||||
remoteInterface.uploadRequest = nil
|
||||
remoteInterface.uploadTask = nil
|
||||
let retry = await NextcloudFileProviderKit.upload(
|
||||
fileLocatedAt: fileUrl.path,
|
||||
toRemotePath: Self.account.davFilesUrl + "/file.txt",
|
||||
usingRemoteInterface: remoteInterface,
|
||||
withAccount: Self.account,
|
||||
inChunksSized: data.count,
|
||||
forItemWithIdentifier: itemIdentifier,
|
||||
dbManager: Self.dbManager,
|
||||
log: FileProviderLogMock()
|
||||
)
|
||||
|
||||
XCTAssertEqual(retry.remoteError, .success)
|
||||
XCTAssertEqual(remoteInterface.uploadOperationCount, 2)
|
||||
XCTAssertEqual(root.children.count, 1)
|
||||
XCTAssertEqual(root.children.first?.data, data)
|
||||
}
|
||||
|
||||
func testCancellingChunkUploadStopsInFlightPUTAndResumesRemainingChunks() async throws {
|
||||
let (account, kit, requests, stoppedRequests, cleanup) = try makeChunkUploadHTTP(observeStoppingChunk: "2")
|
||||
defer { cleanup() }
|
||||
let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
let data = Data(repeating: 1, count: 8)
|
||||
try data.write(to: fileURL)
|
||||
defer { try? FileManager.default.removeItem(at: fileURL) }
|
||||
let itemIdentifier = UUID().uuidString
|
||||
let modificationDate = Date(timeIntervalSince1970: 1_700_000_000)
|
||||
let uploadId = chunkUploadIdentifier(forItemWithIdentifier: itemIdentifier, fileSize: Int64(data.count), modificationDate: modificationDate)
|
||||
let chunksDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(uploadId, isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: chunksDirectory) }
|
||||
let progress = Progress()
|
||||
let (putTasks, taskEvents) = AsyncStream<URLSessionTask>.makeStream()
|
||||
defer { taskEvents.finish() }
|
||||
let destination = try XCTUnwrap(URL(string: account.davFilesUrl + "/file.txt"))
|
||||
let upload = startChunkUpload(
|
||||
fileURL: fileURL,
|
||||
destination: destination,
|
||||
kit: kit,
|
||||
account: account,
|
||||
itemIdentifier: itemIdentifier,
|
||||
modificationDate: modificationDate,
|
||||
progress: progress,
|
||||
taskHandler: { task in
|
||||
if task.originalRequest?.httpMethod == "PUT", task.originalRequest?.url?.lastPathComponent == "2" {
|
||||
taskEvents.yield(task)
|
||||
}
|
||||
}
|
||||
)
|
||||
defer { upload.cancel() }
|
||||
|
||||
let first = try await nextUploadRequest(from: requests, method: "PUT", name: "1")
|
||||
first.respond(status: 201)
|
||||
let interrupted = try await nextUploadRequest(from: requests, method: "PUT", name: "2")
|
||||
let reportedTask = try await nextTestValue(from: putTasks)
|
||||
XCTAssertEqual(try XCTUnwrap(reportedTask).originalRequest?.url, interrupted.request.url)
|
||||
progress.cancel()
|
||||
|
||||
let stopped = try await nextTestValue(from: stoppedRequests)
|
||||
XCTAssertEqual(try XCTUnwrap(stopped).url, interrupted.request.url)
|
||||
let result = try await testTaskValue(of: upload)
|
||||
XCTAssertEqual(result.remoteError.errorCode, NSURLErrorCancelled)
|
||||
XCTAssertNil(result.ocId)
|
||||
XCTAssertNil(progress.cancellationHandler)
|
||||
let remainingChunks = try XCTUnwrap(Self.dbManager.remoteFileChunks(uploadId: uploadId))
|
||||
XCTAssertEqual(remainingChunks.map(\.fileName).sorted(), ["2", "3"])
|
||||
for chunk in remainingChunks {
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath: chunksDirectory.appendingPathComponent(chunk.fileName).path))
|
||||
}
|
||||
|
||||
let retry = startChunkUpload(
|
||||
fileURL: fileURL,
|
||||
destination: destination,
|
||||
kit: kit,
|
||||
account: account,
|
||||
itemIdentifier: itemIdentifier,
|
||||
modificationDate: modificationDate
|
||||
)
|
||||
defer { retry.cancel() }
|
||||
|
||||
for name in ["2", "3"] {
|
||||
let chunk = try await nextUploadRequest(from: requests, method: "PUT", name: name)
|
||||
chunk.respond(status: 201)
|
||||
}
|
||||
let move = try await nextUploadRequest(from: requests, method: "MOVE", name: ".file")
|
||||
assertDestination(move.request.value(forHTTPHeaderField: "Destination").flatMap { URL(string: $0) }, matches: destination)
|
||||
move.respond(status: 201, headers: ["OC-FileID": "assembled-id", "OC-ETag": "assembled-etag"])
|
||||
|
||||
let retried = try await testTaskValue(of: retry)
|
||||
XCTAssertEqual(retried.remoteError, .success)
|
||||
XCTAssertEqual(retried.ocId, "assembled-id")
|
||||
XCTAssertEqual(retried.etag, "assembled-etag")
|
||||
XCTAssertEqual(retried.size, Int64(data.count))
|
||||
XCTAssertTrue(try XCTUnwrap(Self.dbManager.remoteFileChunks(uploadId: uploadId)).isEmpty)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: chunksDirectory.path))
|
||||
}
|
||||
|
||||
func testCancellationDuringPreflightDoesNotStartUpload() async throws {
|
||||
let fileUrl = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try Data(repeating: 1, count: 8).write(to: fileUrl)
|
||||
defer { try? FileManager.default.removeItem(at: fileUrl) }
|
||||
let root = MockRemoteItem.rootItem(account: Self.account)
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: root)
|
||||
let progress = Progress()
|
||||
remoteInterface.enumerateHandler = {
|
||||
progress.cancel()
|
||||
let cancelled = await waitForCancellation()
|
||||
XCTAssertTrue(cancelled, "Cancellation must reach the quota lookup")
|
||||
}
|
||||
|
||||
let result = await NextcloudFileProviderKit.upload(
|
||||
fileLocatedAt: fileUrl.path,
|
||||
toRemotePath: Self.account.davFilesUrl + "/file.txt",
|
||||
usingRemoteInterface: remoteInterface,
|
||||
withAccount: Self.account,
|
||||
inChunksSized: 8,
|
||||
forItemWithIdentifier: UUID().uuidString,
|
||||
dbManager: Self.dbManager,
|
||||
progress: progress,
|
||||
log: FileProviderLogMock()
|
||||
)
|
||||
|
||||
XCTAssertEqual(result.remoteError.errorCode, NSURLErrorCancelled)
|
||||
XCTAssertEqual(remoteInterface.uploadOperationCount, 0)
|
||||
XCTAssertTrue(root.children.isEmpty)
|
||||
}
|
||||
|
||||
func testCancellationErrorMappingForCollisions() async {
|
||||
let remoteInterface = MockRemoteInterface(account: Self.account, rootItem: MockRemoteItem.rootItem(account: Self.account))
|
||||
for code in [NSURLErrorCancelled, -5] {
|
||||
|
||||
Reference in new issue
Block a user