Skip to content

Commit c009626

Browse files
authored
Add extra capabilities for on request handling (#139)
* Add extra capabilities for on request handling * Remove unneeded fastlane logic
1 parent 295b436 commit c009626

File tree

4 files changed

+120
-14
lines changed

4 files changed

+120
-14
lines changed

Sources/Mocker/Mock.swift

+1-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ public struct Mock: Equatable {
8585
@available(*, deprecated, message: "Use `onRequestHandler` instead.")
8686
public var onRequest: OnRequest? {
8787
set {
88-
onRequestHandler = OnRequestHandler(callback: newValue)
88+
onRequestHandler = OnRequestHandler(legacyCallback: newValue)
8989
}
9090
get {
9191
onRequestHandler?.legacyCallback

Sources/Mocker/OnRequestHandler.swift

+52-4
Original file line numberDiff line numberDiff line change
@@ -37,18 +37,66 @@ public struct OnRequestHandler {
3737
legacyCallback = nil
3838
}
3939

40-
init(callback: Mock.OnRequest?) {
40+
/// Creates a new request handler using the given callback to call on request without parsing the body arguments.
41+
/// - Parameter requestCallback: The callback which will be executed just before the request executes, containing the request.
42+
public init(requestCallback: @escaping (_ request: URLRequest) -> Void) {
43+
self.internalCallback = requestCallback
44+
legacyCallback = nil
45+
}
46+
47+
/// Creates a new request handler using the given callback to call on request without parsing the body arguments and without passing the request.
48+
/// - Parameter callback: The callback which will be executed just before the request executes.
49+
public init(callback: @escaping () -> Void) {
50+
self.internalCallback = { _ in
51+
callback()
52+
}
53+
legacyCallback = nil
54+
}
55+
56+
/// Creates a new request handler using the given callback to call on request.
57+
/// - Parameter jsonDictionaryCallback: The callback that executes just before the request executes, containing the HTTP Body Arguments as a JSON Object Dictionary.
58+
public init(jsonDictionaryCallback: @escaping ((_ request: URLRequest, _ httpBodyArguments: [String: Any]?) -> Void)) {
59+
self.internalCallback = { request in
60+
guard
61+
let httpBody = request.httpBodyStreamData() ?? request.httpBody,
62+
let jsonObject = try? JSONSerialization.jsonObject(with: httpBody, options: .fragmentsAllowed) as? [String: Any]
63+
else {
64+
jsonDictionaryCallback(request, nil)
65+
return
66+
}
67+
jsonDictionaryCallback(request, jsonObject)
68+
}
69+
self.legacyCallback = nil
70+
}
71+
72+
/// Creates a new request handler using the given callback to call on request.
73+
/// - Parameter jsonDictionaryCallback: The callback that executes just before the request executes, containing the HTTP Body Arguments as a JSON Object Array.
74+
public init(jsonArrayCallback: @escaping ((_ request: URLRequest, _ httpBodyArguments: [[String: Any]]?) -> Void)) {
75+
self.internalCallback = { request in
76+
guard
77+
let httpBody = request.httpBodyStreamData() ?? request.httpBody,
78+
let jsonObject = try? JSONSerialization.jsonObject(with: httpBody, options: .fragmentsAllowed) as? [[String: Any]]
79+
else {
80+
jsonArrayCallback(request, nil)
81+
return
82+
}
83+
jsonArrayCallback(request, jsonObject)
84+
}
85+
self.legacyCallback = nil
86+
}
87+
88+
init(legacyCallback: Mock.OnRequest?) {
4189
self.internalCallback = { request in
4290
guard
4391
let httpBody = request.httpBodyStreamData() ?? request.httpBody,
4492
let jsonObject = try? JSONSerialization.jsonObject(with: httpBody, options: .fragmentsAllowed) as? [String: Any]
4593
else {
46-
callback?(request, nil)
94+
legacyCallback?(request, nil)
4795
return
4896
}
49-
callback?(request, jsonObject)
97+
legacyCallback?(request, jsonObject)
5098
}
51-
self.legacyCallback = callback
99+
self.legacyCallback = legacyCallback
52100
}
53101

54102
func handleRequest(_ request: URLRequest) {

Tests/MockerTests/MockerTests.swift

+67-4
Original file line numberDiff line numberDiff line change
@@ -311,7 +311,7 @@ final class MockerTests: XCTestCase {
311311
}
312312

313313
/// It should report post body arguments if they exist.
314-
func testOnRequestPostBodyParameters() throws {
314+
func testOnRequestLegacyPostBodyParameters() throws {
315315
let onRequestExpectation = expectation(description: "Data request should start")
316316

317317
let expectedParameters = ["test": "value"]
@@ -331,7 +331,70 @@ final class MockerTests: XCTestCase {
331331

332332
wait(for: [onRequestExpectation], timeout: 2.0)
333333
}
334-
334+
335+
func testOnRequestDecodablePostBodyParameters() throws {
336+
struct RequestParameters: Codable, Equatable {
337+
let name: String
338+
}
339+
340+
let onRequestExpectation = expectation(description: "Data request should start")
341+
342+
let expectedParameters = RequestParameters(name: UUID().uuidString)
343+
var request = URLRequest(url: URL(string: "https://www.fakeurl.com")!)
344+
request.httpMethod = Mock.HTTPMethod.post.rawValue
345+
request.httpBody = try JSONEncoder().encode(expectedParameters)
346+
347+
var mock = Mock(url: request.url!, dataType: .json, statusCode: 200, data: [.post: Data()])
348+
mock.onRequestHandler = .init(httpBodyType: RequestParameters.self, callback: { request, postBodyDecodable in
349+
XCTAssertEqual(request.url, mock.request.url)
350+
XCTAssertEqual(expectedParameters, postBodyDecodable)
351+
onRequestExpectation.fulfill()
352+
})
353+
mock.register()
354+
355+
URLSession.shared.dataTask(with: request).resume()
356+
357+
wait(for: [onRequestExpectation], timeout: 2.0)
358+
}
359+
360+
func testOnRequestJSONDictionaryPostBodyParameters() throws {
361+
let onRequestExpectation = expectation(description: "Data request should start")
362+
363+
let expectedParameters = ["test": "value"]
364+
var request = URLRequest(url: URL(string: "https://www.fakeurl.com")!)
365+
request.httpMethod = Mock.HTTPMethod.post.rawValue
366+
request.httpBody = try JSONSerialization.data(withJSONObject: expectedParameters, options: .prettyPrinted)
367+
368+
var mock = Mock(url: request.url!, dataType: .json, statusCode: 200, data: [.post: Data()])
369+
mock.onRequestHandler = .init(jsonDictionaryCallback: { request, postBodyArguments in
370+
XCTAssertEqual(request.url, mock.request.url)
371+
XCTAssertEqual(expectedParameters, postBodyArguments as? [String: String])
372+
onRequestExpectation.fulfill()
373+
})
374+
mock.register()
375+
376+
URLSession.shared.dataTask(with: request).resume()
377+
378+
wait(for: [onRequestExpectation], timeout: 2.0)
379+
}
380+
381+
func testOnRequestCallbackWithoutRequestAndParameters() throws {
382+
let onRequestExpectation = expectation(description: "Data request should start")
383+
384+
var request = URLRequest(url: URL(string: "https://www.fakeurl.com")!)
385+
request.httpMethod = Mock.HTTPMethod.post.rawValue
386+
387+
var mock = Mock(url: request.url!, dataType: .json, statusCode: 200, data: [.post: Data()])
388+
mock.onRequestHandler = .init(callback: {
389+
onRequestExpectation.fulfill()
390+
})
391+
mock.register()
392+
393+
URLSession.shared.dataTask(with: request).resume()
394+
395+
wait(for: [onRequestExpectation], timeout: 2.0)
396+
}
397+
335398
/// It should report post body arguments with top level collection type if they exist.
336399
func testOnRequestPostBodyParametersWithTopLevelCollectionType() throws {
337400
let onRequestExpectation = expectation(description: "Data request should start")
@@ -342,9 +405,9 @@ final class MockerTests: XCTestCase {
342405
request.httpBody = try JSONSerialization.data(withJSONObject: expectedParameters, options: .prettyPrinted)
343406

344407
var mock = Mock(url: request.url!, dataType: .json, statusCode: 200, data: [.post: Data()])
345-
mock.onRequestHandler = OnRequestHandler(httpBodyType: [[String:String]].self, callback: { request, postBodyArguments in
408+
mock.onRequestHandler = OnRequestHandler(jsonArrayCallback: { request, postBodyArguments in
346409
XCTAssertEqual(request.url, mock.request.url)
347-
XCTAssertEqual(expectedParameters, postBodyArguments)
410+
XCTAssertEqual(expectedParameters, postBodyArguments as? [[String: String]])
348411
onRequestExpectation.fulfill()
349412
})
350413
mock.register()

fastlane/Fastfile

-5
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,6 @@ import "./../Submodules/WeTransfer-iOS-CI/Fastlane/shared_lanes.rb"
66

77
desc "Run the tests and prepare for Danger"
88
lane :test do |options|
9-
10-
# Remove any leftover reports before running so CI won't fail due to an existing file.
11-
# This also helps for local running this workflow frequently.
12-
sh("rm -rf #{ENV['PWD']}/build/reports")
13-
149
test_package(
1510
package_name: 'Mocker',
1611
package_path: ENV['PWD'],

0 commit comments

Comments
 (0)