Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion Sources/MicroClient/NetworkClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
var lastError: Error?

for attempt in 0...retryStrategy.count {
try Task.checkCancellation()

do {
return try await performRequest(networkRequest, attempt: attempt)
} catch {
Expand All @@ -56,7 +58,7 @@

// swiftlint:disable function_body_length

private func performRequest<ResponseModel>(

Check warning on line 61 in Sources/MicroClient/NetworkClient.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Function should have complexity 10 or less; currently complexity is 13 (cyclomatic_complexity)
_ networkRequest: NetworkRequest<some Any, ResponseModel>,
attempt: Int
) async throws -> NetworkResponse<ResponseModel> {
Expand Down Expand Up @@ -100,13 +102,18 @@
for: urlRequest,
delegate: nil
)
} catch let error as CancellationError {
throw error
} catch {
log(.error, "Transport error: \(error.localizedDescription)")
throw NetworkClientError.transportError(error)
}

if let httpResponse = response as? HTTPURLResponse {
log(.info, "Response: \(httpResponse.statusCode) \(urlRequest.httpMethod ?? "") \(urlRequest.url?.absoluteString ?? "")")
log(
.info,
"Response: \(httpResponse.statusCode) \(urlRequest.httpMethod ?? "") \(urlRequest.url?.absoluteString ?? "")"

Check warning on line 115 in Sources/MicroClient/NetworkClient.swift

View workflow job for this annotation

GitHub Actions / SwiftLint

Line should be 120 characters or less; currently it has 125 characters (line_length)
)
log(.debug, "Response headers: \(httpResponse.allHeaderFields)")

guard (200...299).contains(httpResponse.statusCode) else {
Expand Down Expand Up @@ -150,6 +157,8 @@
throw NetworkClientError.responseInterceptorError(error)
}

try Task.checkCancellation()

return networkResponse
}

Expand Down
5 changes: 5 additions & 0 deletions Tests/MicroClientTests/Doubles/URLSessionMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ final class URLSessionMock: URLSessionProtocol, @unchecked Sendable {
private var stubbedResponseToReturn = URLResponse()
private var stubbedErrorToThrow: Error?
var succeedAfter = 0
var delay: TimeInterval = 0

// MARK: - Public

Expand All @@ -22,6 +23,10 @@ final class URLSessionMock: URLSessionProtocol, @unchecked Sendable {
lastRequest = request
requestCount += 1

if delay > 0 {
try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
}

if succeedAfter > 0, requestCount > succeedAfter {
// Do not throw error, return stubbed data
} else if let error = stubbedErrorToThrow {
Expand Down
156 changes: 156 additions & 0 deletions Tests/MicroClientTests/NetworkClientCancellationTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import Foundation
import Testing

@testable import MicroClient

@Suite("NetworkClient Cancellation Tests")
struct NetworkClientCancellationTests {

@Test("It should throw CancellationError when task is cancelled before request")
func throwCancellationErrorWhenTaskIsCancelledBeforeRequest() async throws {
// Given
let mockSession = NetworkClientMother.makeMockSession()
let client = NetworkClientMother.makeNetworkClient(
session: mockSession
)

let expectedURL = try #require(URL(string: "https://api.example.com/test"))
mockSession.stubDataToReturn(
data: Data(),
response: NetworkClientMother.makeSuccessResponse(
for: expectedURL
)
)

let request = NetworkRequest<VoidRequest, VoidResponse>(
path: "/test",
method: .get
)

// When
let task = Task {
try await client.run(request)
}

task.cancel()

// Then
await #expect(throws: CancellationError.self) {
try await task.value
}
}

@Test("It should cancel ongoing request when task is cancelled mid-flight")
func cancelOngoingRequestWhenTaskIsCancelledMidFlight() async throws {
// Given
let mockSession = NetworkClientMother.makeMockSession()
mockSession.delay = 0.1

let client = NetworkClientMother.makeNetworkClient(
session: mockSession
)

let expectedURL = try #require(URL(string: "https://api.example.com/test"))
mockSession.stubDataToReturn(
data: Data(),
response: NetworkClientMother.makeSuccessResponse(
for: expectedURL
)
)

let request = NetworkRequest<VoidRequest, VoidResponse>(
path: "/test",
method: .get
)

// When
let task = Task {
try await client.run(request)
}

try await Task.sleep(nanoseconds: 10_000_000)
task.cancel()

// Then
await #expect(throws: CancellationError.self) {
try await task.value
}
}

@Test("It should cancel request during retry attempts")
func cancelRequestDuringRetryAttempts() async throws {
// Given
let mockSession = NetworkClientMother.makeMockSession()
mockSession.delay = 0.05
mockSession.stubDataToThrow(
error: URLError(.networkConnectionLost)
)

let retryStrategy = RetryStrategy.retry(count: 5)
let client = NetworkClientMother.makeNetworkClient(
session: mockSession,
retryStrategy: retryStrategy
)

let request = NetworkRequest<VoidRequest, VoidResponse>(
path: "/test",
method: .get
)

// When
let task = Task {
try await client.run(request)
}

try await Task.sleep(nanoseconds: 60_000_000)
task.cancel()

// Then
await #expect(throws: CancellationError.self) {
try await task.value
}

#expect(
mockSession.requestCount < retryStrategy.count + 1,
"It should not complete all retry attempts"
)
}

@Test("It should complete successfully if not cancelled")
func completeSuccessfullyIfNotCancelled() async throws {
// Given
let mockSession = NetworkClientMother.makeMockSession()
mockSession.delay = 0.01

let client = NetworkClientMother.makeNetworkClient(
session: mockSession
)

let expectedURL = try #require(URL(string: "https://api.example.com/test"))
mockSession.stubDataToReturn(
data: Data(),
response: NetworkClientMother.makeSuccessResponse(
for: expectedURL
)
)

let request = NetworkRequest<VoidRequest, VoidResponse>(
path: "/test",
method: .get
)

// When
let response = try await client.run(request)

// Then
#expect(
type(of: response.value) == VoidResponse.self,
"It should return VoidResponse"
)

#expect(
mockSession.requestCount == 1,
"It should make exactly one request"
)
}
}