Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock Harbor requests #31

Merged
merged 8 commits into from
Nov 13, 2024
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
104 changes: 104 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Harbor is a library for making API requests in Swift in a simple way using async
- [Request Protocol](#request-protocol)
- [HJRPCRequestProtocol](#hjrpcrequestprotocol)
- [Response](#response-1)
- [Mocks](#mocks)
- [Contributing](#contributing)
- [Author](#author)
- [License](#license)
Expand All @@ -57,6 +58,7 @@ Harbor is a library for making API requests in Swift in a simple way using async
- [x] mTLS Certificate
- [x] SSL Pinning
- [x] Swift 6 Compatible
- [x] Mock Requests

## Requirements

Expand Down Expand Up @@ -301,6 +303,107 @@ case .error(let error):
}
```

## Mocks
Harbor allows you to register and manage mocks to facilitate testing your API requests.

### HMock
Use `HMock` to declare mock responses for your requests.

#### Properties:
- `request`: The request type that conforms to `HRequestBaseRequestProtocol` for which the mock is being set.
- `statusCode`: The HTTP status code to return.
- `jsonResponse`: A `String` representing the JSON response. This will be decoded as the expected model for your request.
- `error`: An optional `HRequestError` if you want to simulate an error response.
- `delay`: An optional delay (in seconds) before returning the mock response, to simulate network latency.

### Register a Mock
To register a mock, use the `register(mock:)` method. This will allow you to simulate responses instead of making actual API calls.

```swift
let mock = HMock(
///
)
await Harbor.register(mock: mock)
```

### Registering a Success Mock

```swift
let jsonResponse = """
{ "name": "John Doe" }
"""
let mock = HMock(
request: MyGetUsersRequest.self,
statusCode: 200,
jsonResponse: jsonResponse
)
await Harbor.register(mock: mock)
```

### Registering a Error Mock

```swift
let mock = HMock(
request: MyGetUsersRequest.self,
statusCode: 401,
error: .authNeeded
)
await Harbor.register(mock: mock)
```

### Using Mocks Only in Debug Mode
You can configure mocks to only be used in #DEBUG, preventing them from affecting production environments. The default value is *true*.

```swift
await Harbor.setMocksOnlyInDebug(false)
```

### Removing a Specific Mock
If you need to remove a specific mock, use the `remove(mock:)` method.

```swift
await Harbor.remove(mock: mock)
```

### Removing All Mocks
To clear all registered mocks, use the `removeAllMocks()` method.

```swift
await Harbor.removeAllMocks()
```

### Complete Example
Below is a complete example demonstrating how to set up and use mocks with Harbor:

```swift

Task {
let jsonResponse = """
{ "users": [{ "id": 1, "name": "Alice" }] }
"""
let userMock = HMock(
request: MyGetUsersRequest.self,
statusCode: 200,
jsonResponse: jsonResponse
)

// Register the mock
await Harbor.register(mock: userMock)

// Perform a request that will use the registered mock
let response = await MyGetUsersRequest().request()
switch response {
case .success(let users):
// You will receive the mocked response here
print("Users:", users)
case .error(let error):
break
case .cancelled:
break
}
}
```

## Contributing
If you run into any problems, please submit an [issue](https://github.com/javiermanzo/Harbor/issues). [Pull requests](https://github.com/javiermanzo/Harbor/pulls) are also welcome!

Expand All @@ -309,3 +412,4 @@ Harbor was created by [Javier Manzo](https://www.linkedin.com/in/javiermanzo/).

## License
Harbor is available under the MIT license. See the [LICENSE](https://github.com/javiermanzo/Harbor/blob/main/LICENSE.md) file for more info.

9 changes: 9 additions & 0 deletions Sources/Harbor/HConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,13 @@ struct HConfig: Sendable {
var sslPinningSHA256: String?
let defaultSession: URLSession = URLSession.shared
var currentSession: URLSession?
var mocksOnlyInDebug: Bool = true

var mocksEnabled: Bool {
#if DEBUG
return true
#else
return !mocksOnlyInDebug
#endif
}
}
159 changes: 96 additions & 63 deletions Sources/Harbor/HRequestManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,27 @@ import SystemConfiguration
}

@HRequestManagerActor
internal final class HRequestManager: Sendable {
internal static var config: HConfig = HConfig()
final class HRequestManager: Sendable {
static var config: HConfig = HConfig()
}

// MARK: - Request With Result
extension HRequestManager {
static func request<Model: HModel>(model: Model.Type, request: any HRequestWithResultProtocol) async -> HResponseWithResult<Model> {
if let mock = HMocker.mock(request: request), config.mocksEnabled {
if let delay = mock.delay {
let delayInNanoseconds = UInt64(delay * 1_000_000_000)
try? await Task.sleep(nanoseconds: delayInNanoseconds)
}

static func addAuthCredentialsIfNeeded(_ request: any HRequestBaseRequestProtocol) async -> (any HRequestBaseRequestProtocol)? {
if request.needsAuth {
var modifiedRequest = request
if let authCredential = await Self.config.authProvider?.getAuthorizationHeader() {
if modifiedRequest.headerParameters == nil {
modifiedRequest.headerParameters = [:]
}
modifiedRequest.headerParameters?[authCredential.key] = authCredential.value
return modifiedRequest
} else {
return nil
if let error = mock.error {
return .error(error)
}

let data = mock.jsonResponse?.data(using: .utf8) ?? Data()
return await HRequestManager.processResponse(model: model, request: request, statusCode: mock.statusCode, data: data)
}
return request
}

static func request<Model: Codable>(model: Model.Type, request: any HRequestWithResultProtocol) async -> HResponseWithResult<Model> {
if !self.isConnectedToNetwork() {
return .error(.noConnectionError)
}
Expand All @@ -48,7 +45,7 @@ extension HRequestManager {
return result
}

private static func requestHandler<Model: Codable>(model: Model.Type, request: any HRequestWithResultProtocol) async -> HResponseWithResult<Model> {
private static func requestHandler<Model: HModel>(model: Model.Type, request: any HRequestWithResultProtocol) async -> HResponseWithResult<Model> {
guard let urlRequest = self.buildUrlRequest(request: request) else {
return .error(.malformedRequestError)
}
Expand All @@ -58,7 +55,6 @@ extension HRequestManager {
}

do {

let session = getSession()

let startTime = Date()
Expand All @@ -81,30 +77,7 @@ extension HRequestManager {
request.printResponse(httpResponse: httpResponse, data: data, duration: duration)
}

switch httpResponse.statusCode {
case 200 ... 299:
do {
let parsedResponse = try request.parseData(data: data, model: model)
return .success(parsedResponse)
} catch let parseError {
return .error(.codableError(modelName: "\(model.self)", error: parseError))
}
case 401:
if await !hasNewAuthorizationHeader(request: request) {
await Self.config.authProvider?.authFailed()
return .error(.authNeeded)
} else {
return await self.request(model: model, request: request)
}
default:
if let retries = request.retries, retries > 0 {
var mutableRequest = request
mutableRequest.retries = retries - 1
return await self.request(model: model, request: mutableRequest)
} else {
return .error(.apiError(statusCode: httpResponse.statusCode, data: data))
}
}
return await processResponse(model: model, request: request, statusCode: httpResponse.statusCode, data: data)
} catch let error as URLError {
switch error.code {
case .cancelled:
Expand All @@ -122,11 +95,52 @@ extension HRequestManager {
return .error(.invalidHttpResponse)
}
}

static func processResponse<Model: HModel>(model: Model.Type, request: any HRequestWithResultProtocol, statusCode: Int, data: Data) async -> HResponseWithResult<Model> {
switch statusCode {
case 200 ... 299:
do {
let parsedResponse = try request.parseData(data: data, model: model)
return .success(parsedResponse)
} catch let parseError {
return .error(.codableError(modelName: "\(model.self)", error: parseError))
}
case 401:
if await !hasNewAuthorizationHeader(request: request) {
await Self.config.authProvider?.authFailed()
return .error(.authNeeded)
} else {
return await self.request(model: model, request: request)
}
default:
if let retries = request.retries, retries > 0 {
var mutableRequest = request
mutableRequest.retries = retries - 1
return await self.request(model: model, request: mutableRequest)
} else {
return .error(.apiError(statusCode: statusCode, data: data))
}
}
}
}

// MARK: - Request Without Result
extension HRequestManager {
static func request(request: any HRequestWithEmptyResponseProtocol) async -> HResponse {
if let mock = HMocker.mock(request: request), config.mocksEnabled {
if let delay = mock.delay {
let delayInNanoseconds = UInt64(delay * 1_000_000_000)
try? await Task.sleep(nanoseconds: delayInNanoseconds)
}

if let error = mock.error {
return .error(error)
}

let data = mock.jsonResponse?.data(using: .utf8) ?? Data()
return await HRequestManager.processResponse(request: request, statusCode: mock.statusCode, data: data)
}

if !self.isConnectedToNetwork() {
return .error(.noConnectionError)
}
Expand All @@ -147,7 +161,6 @@ extension HRequestManager {
}

do {

let session = getSession()

let startTime = Date()
Expand All @@ -170,25 +183,7 @@ extension HRequestManager {
request.printResponse(httpResponse: httpResponse, data: data, duration: duration)
}

switch httpResponse.statusCode {
case 200 ... 299:
return .success
case 401:
if await !hasNewAuthorizationHeader(request: request) {
await Self.config.authProvider?.authFailed()
return .error(.authNeeded)
} else {
return await self.request(request: request)
}
default:
if let retries = request.retries, retries > 0 {
var mutableRequest = request
mutableRequest.retries = retries - 1
return await self.request(request: mutableRequest)
} else {
return .error(.apiError(statusCode: httpResponse.statusCode, data: data))
}
}
return await processResponse(request: request, statusCode: httpResponse.statusCode, data: data)
} catch let error as URLError {
switch error.code {
case .cancelled:
Expand All @@ -206,10 +201,32 @@ extension HRequestManager {
return .error(.invalidHttpResponse)
}
}

static func processResponse(request: HRequestWithEmptyResponseProtocol, statusCode: Int, data: Data) async -> HResponse {
switch statusCode {
case 200 ... 299:
return .success
case 401:
if await !hasNewAuthorizationHeader(request: request) {
await Self.config.authProvider?.authFailed()
return .error(.authNeeded)
} else {
return await self.request(request: request)
}
default:
if let retries = request.retries, retries > 0 {
var mutableRequest = request
mutableRequest.retries = retries - 1
return await self.request(request: mutableRequest)
} else {
return .error(.apiError(statusCode: statusCode, data: data))
}
}
}
}

// MARK: - Request Builder Functions
internal extension HRequestManager {
extension HRequestManager {
static func buildUrlRequest<P: HRequestBaseRequestProtocol>(request: P) -> URLRequest? {
let url: URL?

Expand Down Expand Up @@ -327,6 +344,22 @@ internal extension HRequestManager {
}
}

static func addAuthCredentialsIfNeeded(_ request: any HRequestBaseRequestProtocol) async -> (any HRequestBaseRequestProtocol)? {
if request.needsAuth {
var modifiedRequest = request
if let authCredential = await Self.config.authProvider?.getAuthorizationHeader() {
if modifiedRequest.headerParameters == nil {
modifiedRequest.headerParameters = [:]
}
modifiedRequest.headerParameters?[authCredential.key] = authCredential.value
return modifiedRequest
} else {
return nil
}
}
return request
}

/// Session getter that handles mTLS and SSL pinning if needed
private static func getSession() -> URLSession {
if let currentSession = config.currentSession {
Expand Down
5 changes: 4 additions & 1 deletion Sources/Harbor/HRequestProtocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@

import Foundation

// MARK: - HModel
public typealias HModel = Codable & Sendable

// MARK: - Request Data Type
public enum HRequestDataType: Sendable {
case json
Expand Down Expand Up @@ -36,7 +39,7 @@ public extension HRequestWithEmptyResponseProtocol {

// MARK: - Request with Result Protocol
public protocol HRequestWithResultProtocol: HRequestBaseRequestProtocol {
associatedtype Model: Codable & Sendable
associatedtype Model: HModel
func parseData<Model: Codable> (data: Data, model: Model.Type) throws -> Model
func request() async -> HResponseWithResult<Model>
}
Expand Down
Loading