From 2a2a41ca88a5d87f3d81b7bf90d1b9a86819985d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elvis=20Nu=C3=B1ez?= <3lvis@users.noreply.github.com> Date: Sun, 1 Oct 2017 22:52:14 +0200 Subject: [PATCH] General refactor (#215) * Clean up handling fake requests * Clean up method calls * Simplify method name * Run SwiftFormat * Clean up and simplify logic --- Sources/FormDataPart.swift | 2 +- Sources/Helpers.swift | 16 +-- Sources/JSON.swift | 24 ++-- Sources/Networking+HTTPRequests.swift | 42 ++---- Sources/Networking+Private.swift | 190 +++++++++++--------------- Sources/Networking.swift | 6 +- Sources/Response.swift | 8 +- Sources/Result.swift | 2 +- Tests/DELETETests.swift | 18 +-- Tests/DownloadTests.swift | 14 +- Tests/GETTests.swift | 30 ++-- Tests/JSONTests.swift | 49 ++++--- Tests/NetworkingTests.swift | 18 +-- Tests/POSTTests.swift | 28 ++-- Tests/PUTTests.swift | 16 +-- Tests/ResponseTests.swift | 2 +- Tests/ResultTests.swift | 41 +++--- iOSDemo/FakeImageController.swift | 2 +- 18 files changed, 226 insertions(+), 282 deletions(-) diff --git a/Sources/FormDataPart.swift b/Sources/FormDataPart.swift index 7b95816..a296aa6 100644 --- a/Sources/FormDataPart.swift +++ b/Sources/FormDataPart.swift @@ -20,7 +20,7 @@ public enum FormDataPartType { return "image/png" case .jpg: return "image/jpeg" - case .custom(let value): + case let .custom(value): return value } } diff --git a/Sources/Helpers.swift b/Sources/Helpers.swift index c2107bb..bf1f42a 100644 --- a/Sources/Helpers.swift +++ b/Sources/Helpers.swift @@ -45,7 +45,7 @@ extension String { var components = self.components(separatedBy: "/") guard let lastComponent = components.popLast(), let endcodedLastComponent = lastComponent.addingPercentEncoding(withAllowedCharacters: .urlQueryParametersAllowed) else { - return nil + return nil } return (components + [endcodedLastComponent]).joined(separator: "/") @@ -69,27 +69,27 @@ extension FileManager { } extension URLRequest { - init(url: URL, requestType: Networking.RequestType, path: String, parameterType: Networking.ParameterType?, responseType: Networking.ResponseType, boundary: String, authorizationHeaderValue: String?, token: String?, authorizationHeaderKey: String, headerFields: [String: String]?) { + init(url: URL, requestType: Networking.RequestType, path _: String, parameterType: Networking.ParameterType?, responseType: Networking.ResponseType, boundary: String, authorizationHeaderValue: String?, token: String?, authorizationHeaderKey: String, headerFields: [String: String]?) { self = URLRequest(url: url) - self.httpMethod = requestType.rawValue + httpMethod = requestType.rawValue if let parameterType = parameterType, let contentType = parameterType.contentType(boundary) { - self.addValue(contentType, forHTTPHeaderField: "Content-Type") + addValue(contentType, forHTTPHeaderField: "Content-Type") } if let accept = responseType.accept { - self.addValue(accept, forHTTPHeaderField: "Accept") + addValue(accept, forHTTPHeaderField: "Accept") } if let authorizationHeader = authorizationHeaderValue { - self.setValue(authorizationHeader, forHTTPHeaderField: authorizationHeaderKey) + setValue(authorizationHeader, forHTTPHeaderField: authorizationHeaderKey) } else if let token = token { - self.setValue("Bearer \(token)", forHTTPHeaderField: authorizationHeaderKey) + setValue("Bearer \(token)", forHTTPHeaderField: authorizationHeaderKey) } if let headerFields = headerFields { for (key, value) in headerFields { - self.setValue(value, forHTTPHeaderField: key) + setValue(value, forHTTPHeaderField: key) } } } diff --git a/Sources/JSON.swift b/Sources/JSON.swift index 88166c2..243afd8 100644 --- a/Sources/JSON.swift +++ b/Sources/JSON.swift @@ -13,24 +13,20 @@ enum JSON: Equatable { case array(Data, [[String: Any]]) var dictionary: [String: Any] { - get { - switch self { - case .dictionary(_, let body): - return body - default: - return [String: Any]() - } + switch self { + case let .dictionary(_, body): + return body + default: + return [String: Any]() } } var array: [[String: Any]] { - get { - switch self { - case .array(_, let body): - return body - default: - return [[String: Any]]() - } + switch self { + case let .array(_, body): + return body + default: + return [[String: Any]]() } } diff --git a/Sources/Networking+HTTPRequests.swift b/Sources/Networking+HTTPRequests.swift index 192aa41..100dc2e 100644 --- a/Sources/Networking+HTTPRequests.swift +++ b/Sources/Networking+HTTPRequests.swift @@ -11,11 +11,9 @@ public extension Networking { /// - Returns: The request identifier. @discardableResult public func get(_ path: String, parameters: Any? = nil, completion: @escaping (_ result: JSONResult) -> Void) -> String { - let parameterType = parameters != nil ? ParameterType.formURLEncoded : ParameterType.none + let parameterType: ParameterType = parameters != nil ? .formURLEncoded : .none - return handleRequest(.get, path: path, cacheName: nil, parameterType: parameterType, parameters: parameters, parts: nil, responseType: .json) { result in - completion(result as! JSONResult) - } + return handleJSONRequest(.get, path: path, parameterType: parameterType, parameters: parameters, responseType: .json, completion: completion) } /// Registers a fake GET request for the specified path. After registering this, every GET request to the path, will return the registered response. @@ -42,7 +40,7 @@ public extension Networking { /// /// - Parameter path: The path for the cancelled GET request public func cancelGET(_ path: String) { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) cancelRequest(.data, requestType: .get, url: url) } } @@ -59,9 +57,7 @@ public extension Networking { /// - Returns: The request identifier. @discardableResult public func put(_ path: String, parameterType: ParameterType = .json, parameters: Any? = nil, completion: @escaping (_ result: JSONResult) -> Void) -> String { - return handleRequest(.put, path: path, cacheName: nil, parameterType: parameterType, parameters: parameters, parts: nil, responseType: .json) { result in - completion(result as! JSONResult) - } + return handleJSONRequest(.put, path: path, parameterType: parameterType, parameters: parameters, responseType: .json, completion: completion) } /// Registers a fake PUT request for the specified path. After registering this, every PUT request to the path, will return the registered response. @@ -88,7 +84,7 @@ public extension Networking { /// /// - Parameter path: The path for the cancelled PUT request. public func cancelPUT(_ path: String) { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) cancelRequest(.data, requestType: .put, url: url) } } @@ -105,9 +101,7 @@ public extension Networking { /// - Returns: The request identifier. @discardableResult public func post(_ path: String, parameterType: ParameterType = .json, parameters: Any? = nil, completion: @escaping (_ result: JSONResult) -> Void) -> String { - return handleRequest(.post, path: path, cacheName: nil, parameterType: parameterType, parameters: parameters, parts: nil, responseType: .json) { result in - completion(result as! JSONResult) - } + return handleJSONRequest(.post, path: path, parameterType: parameterType, parameters: parameters, responseType: .json, completion: completion) } /// POST request to the specified path, using the provided parameters. @@ -120,9 +114,7 @@ public extension Networking { /// - Returns: The request identifier. @discardableResult public func post(_ path: String, parameters: Any? = nil, parts: [FormDataPart], completion: @escaping (_ result: JSONResult) -> Void) -> String { - return handleRequest(.post, path: path, cacheName: nil, parameterType: .multipartFormData, parameters: parameters, parts: parts, responseType: .json) { result in - completion(result as! JSONResult) - } + return handleJSONRequest(.post, path: path, parameterType: .multipartFormData, parameters: parameters, parts: parts, responseType: .json, completion: completion) } /// Registers a fake POST request for the specified path. After registering this, every POST request to the path, will return the registered response. @@ -149,7 +141,7 @@ public extension Networking { /// /// - Parameter path: The path for the cancelled POST request. public func cancelPOST(_ path: String) { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) cancelRequest(.data, requestType: .post, url: url) } } @@ -165,10 +157,8 @@ public extension Networking { /// - Returns: The request identifier. @discardableResult public func delete(_ path: String, parameters: Any? = nil, completion: @escaping (_ result: JSONResult) -> Void) -> String { - let parameterType = parameters != nil ? ParameterType.formURLEncoded : ParameterType.none - return handleRequest(.delete, path: path, cacheName: nil, parameterType: parameterType, parameters: parameters, parts: nil, responseType: .json) { result in - completion(result as! JSONResult) - } + let parameterType: ParameterType = parameters != nil ? .formURLEncoded : .none + return handleJSONRequest(.delete, path: path, parameterType: parameterType, parameters: parameters, responseType: .json, completion: completion) } /// Registers a fake DELETE request for the specified path. After registering this, every DELETE request to the path, will return the registered response. @@ -195,7 +185,7 @@ public extension Networking { /// /// - Parameter path: The path for the cancelled DELETE request. public func cancelDELETE(_ path: String) { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) cancelRequest(.data, requestType: .delete, url: url) } } @@ -223,16 +213,14 @@ public extension Networking { /// - Returns: The request identifier. @discardableResult public func downloadImage(_ path: String, cacheName: String? = nil, completion: @escaping (_ result: ImageResult) -> Void) -> String { - return handleRequest(.get, path: path, cacheName: cacheName, parameterType: nil, parameters: nil, parts: nil, responseType: .image) { result in - completion(result as! ImageResult) - } + return handleImageRequest(.get, path: path, cacheName: cacheName, responseType: .image, completion: completion) } /// Cancels the image download request for the specified path. This causes the request to complete with error code URLError.cancelled. /// /// - Parameter path: The path for the cancelled image download request. public func cancelImageDownload(_ path: String) { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) cancelRequest(.data, requestType: .get, url: url) } @@ -254,9 +242,7 @@ public extension Networking { /// - completion: A closure that gets called when the download request is completed, it contains a `data` object and an `NSError`. @discardableResult public func downloadData(_ path: String, cacheName: String? = nil, completion: @escaping (_ result: DataResult) -> Void) -> String { - return handleRequest(.get, path: path, cacheName: cacheName, parameterType: nil, parameters: nil, parts: nil, responseType: .data) { result in - completion(result as! DataResult) - } + return handleDataRequest(.get, path: path, cacheName: cacheName, responseType: .data, completion: completion) } /// Retrieves data from the cache or from the filesystem. diff --git a/Sources/Networking+Private.swift b/Sources/Networking+Private.swift index ac7205e..1f83901 100644 --- a/Sources/Networking+Private.swift +++ b/Sources/Networking+Private.swift @@ -47,151 +47,117 @@ extension Networking { fakeRequests[requestType] = requests } - func handleRequest(_ requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ result: Result) -> Void) -> String { - if let fakeRequests = fakeRequests[requestType], let fakeRequest = fakeRequests[path] { - return handleFakeRequest(fakeRequest, requestType: requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType, completion: completion) + func handleFakeRequest(_ fakeRequest: FakeRequest, path: String, completion: @escaping (_ body: Any?, _ response: HTTPURLResponse, _ error: NSError?) -> Void) -> String { + var error: NSError? + let url = try! composedURL(with: path) + let response = HTTPURLResponse(url: url, statusCode: fakeRequest.statusCode) + + if let unauthorizedRequestCallback = unauthorizedRequestCallback, fakeRequest.statusCode == 403 || fakeRequest.statusCode == 401 { + TestCheck.testBlock(isSynchronous) { + unauthorizedRequestCallback() + } } else { - switch responseType { - case .json: - return handleJSONRequest(requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType, completion: completion) - case .data: - return handleDataRequest(requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType, completion: completion) - case .image: - return handleImageRequest(requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType, completion: completion) + if fakeRequest.statusCode.statusCodeType != .successful { + error = NSError(fakeRequest: fakeRequest) } + + completion(fakeRequest.response, response, error) } - } - func handleFakeRequest(_ fakeRequest: FakeRequest, requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ result: Result) -> Void) -> String { let requestID = UUID().uuidString + return requestID + } - if fakeRequest.statusCode.statusCodeType == .successful { - let url = try! self.composedURL(with: path) - let response = HTTPURLResponse(url: url, statusCode: fakeRequest.statusCode) - TestCheck.testBlock(self.isSynchronous) { - switch responseType { - case .data: - completion(DataResult(body: fakeRequest.response, response: response, error: nil)) - case .image: - completion(ImageResult(body: fakeRequest.response, response: response, error: nil)) - case .json: - completion(JSONResult(body: fakeRequest.response, response: response, error: nil)) - } + func handleJSONRequest(_ requestType: RequestType, path: String, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]? = nil, responseType: ResponseType, completion: @escaping (_ result: JSONResult) -> Void) -> String { + if let fakeRequests = fakeRequests[requestType], let fakeRequest = fakeRequests[path] { + return handleFakeRequest(fakeRequest, path: path) { _, response, error in + completion(JSONResult(body: fakeRequest.response, response: response, error: error)) } } else { - if let unauthorizedRequestCallback = unauthorizedRequestCallback, fakeRequest.statusCode == 403 || fakeRequest.statusCode == 401 { + return requestData(requestType, path: path, cacheName: nil, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType) { data, response, error in TestCheck.testBlock(self.isSynchronous) { - unauthorizedRequestCallback() - } - } else { - let url = try! self.composedURL(with: path) - let error = NSError(fakeRequest: fakeRequest) - let response = HTTPURLResponse(url: url, statusCode: fakeRequest.statusCode) - TestCheck.testBlock(self.isSynchronous) { - switch responseType { - case .data: - completion(DataResult(body: fakeRequest.response, response: response, error: error)) - case .image: - completion(ImageResult(body: fakeRequest.response, response: response, error: error)) - case .json: - completion(JSONResult(body: fakeRequest.response, response: response, error: error)) - } + completion(JSONResult(body: data, response: response, error: error)) } } } - - return requestID } - func handleJSONRequest(_ requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ result: JSONResult) -> Void) -> String { - return dataRequest(requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType) { data, response, error in - - TestCheck.testBlock(self.isSynchronous) { - completion(JSONResult(body: data, response: response, error: error)) - } - } - } - - func handleDataRequest(_ requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ result: DataResult) -> Void) -> String { - let object = objectFromCache(for: path, cacheName: cacheName, responseType: responseType) - if let object = object { - let requestID = UUID().uuidString - - TestCheck.testBlock(isSynchronous) { - let url = try! self.composedURL(with: path) - let response = HTTPURLResponse(url: url, statusCode: 200) - completion(DataResult(body: object, response: response, error: nil)) + func handleDataRequest(_ requestType: RequestType, path: String, cacheName: String?, responseType: ResponseType, completion: @escaping (_ result: DataResult) -> Void) -> String { + if let fakeRequests = fakeRequests[requestType], let fakeRequest = fakeRequests[path] { + return handleFakeRequest(fakeRequest, path: path) { _, response, error in + completion(DataResult(body: fakeRequest.response, response: response, error: error)) } - - return requestID } else { - return dataRequest(requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType) { data, response, error in - - guard let destinationURL = try? self.destinationURL(for: path, cacheName: cacheName) else { - fatalError("Couldn't get destination URL for path: \(path) and cacheName: \(String(describing: cacheName))") - + let object = objectFromCache(for: path, cacheName: cacheName, responseType: responseType) + if let object = object { + TestCheck.testBlock(isSynchronous) { + let url = try! self.composedURL(with: path) + let response = HTTPURLResponse(url: url, statusCode: 200) + completion(DataResult(body: object, response: response, error: nil)) } + let requestID = UUID().uuidString + return requestID + } else { + return requestData(requestType, path: path, cacheName: cacheName, parameterType: nil, parameters: nil, parts: nil, responseType: responseType) { data, response, error in + guard let destinationURL = try? self.destinationURL(for: path, cacheName: cacheName) else { + fatalError("Couldn't get destination URL for path: \(path) and cacheName: \(String(describing: cacheName))") + } - let returnedResponse: DataResult - if let data = data, data.count > 0 { - _ = try? data.write(to: destinationURL, options: [.atomic]) - self.cache.setObject(data as AnyObject, forKey: destinationURL.absoluteString as AnyObject) - returnedResponse = DataResult(body: data, response: response, error: error) - } else { - self.cache.removeObject(forKey: destinationURL.absoluteString as AnyObject) - returnedResponse = DataResult(body: nil, response: response, error: error) - } + if let data = data, data.count > 0 { + _ = try? data.write(to: destinationURL, options: [.atomic]) + self.cache.setObject(data as AnyObject, forKey: destinationURL.absoluteString as AnyObject) + } else { + self.cache.removeObject(forKey: destinationURL.absoluteString as AnyObject) + } - TestCheck.testBlock(self.isSynchronous) { - completion(returnedResponse) + TestCheck.testBlock(self.isSynchronous) { + completion(DataResult(body: data, response: response, error: error)) + } } } } } - func handleImageRequest(_ requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ result: ImageResult) -> Void) -> String { - let object = objectFromCache(for: path, cacheName: cacheName, responseType: responseType) - if let object = object { - let requestID = UUID().uuidString - - TestCheck.testBlock(isSynchronous) { - let url = try! self.composedURL(with: path) - let response = HTTPURLResponse(url: url, statusCode: 200) - completion(ImageResult(body: object, response: response, error: nil)) + func handleImageRequest(_ requestType: RequestType, path: String, cacheName: String?, responseType: ResponseType, completion: @escaping (_ result: ImageResult) -> Void) -> String { + if let fakeRequests = fakeRequests[requestType], let fakeRequest = fakeRequests[path] { + return handleFakeRequest(fakeRequest, path: path) { _, response, error in + completion(ImageResult(body: fakeRequest.response, response: response, error: error)) } - - return requestID } else { - return dataRequest(requestType, path: path, cacheName: cacheName, parameterType: parameterType, parameters: parameters, parts: parts, responseType: responseType) { data, response, error in - - guard let destinationURL = try? self.destinationURL(for: path, cacheName: cacheName) else { - fatalError("Couldn't get destination URL for path: \(path) and cacheName: \(String(describing: cacheName))") - + let object = objectFromCache(for: path, cacheName: cacheName, responseType: responseType) + if let object = object { + TestCheck.testBlock(isSynchronous) { + let url = try! self.composedURL(with: path) + let response = HTTPURLResponse(url: url, statusCode: 200) + completion(ImageResult(body: object, response: response, error: nil)) } - let returnedResponse: ImageResult - if let data = data, data.count > 0 { - _ = try? data.write(to: destinationURL, options: [.atomic]) - if let image = Image(data: data) { + let requestID = UUID().uuidString + return requestID + } else { + return requestData(requestType, path: path, cacheName: cacheName, parameterType: nil, parameters: nil, parts: nil, responseType: responseType) { data, response, error in + guard let destinationURL = try? self.destinationURL(for: path, cacheName: cacheName) else { + fatalError("Couldn't get destination URL for path: \(path) and cacheName: \(String(describing: cacheName))") + } + + var returnedImage: Image? + if let data = data, data.count > 0, let image = Image(data: data) { + _ = try? data.write(to: destinationURL, options: [.atomic]) + returnedImage = image self.cache.setObject(image, forKey: destinationURL.absoluteString as AnyObject) - returnedResponse = ImageResult(body: image, response: response, error: error) } else { self.cache.removeObject(forKey: destinationURL.absoluteString as AnyObject) - returnedResponse = ImageResult(body: nil, response: response, error: error) } - } else { - self.cache.removeObject(forKey: destinationURL.absoluteString as AnyObject) - returnedResponse = ImageResult(body: nil, response: response, error: error) - } - TestCheck.testBlock(self.isSynchronous) { - completion(returnedResponse) + TestCheck.testBlock(self.isSynchronous) { + completion(ImageResult(body: returnedImage, response: response, error: error)) + } } } } } - func dataRequest(_ requestType: RequestType, path: String, cacheName: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ response: Data?, _ response: HTTPURLResponse, _ error: NSError?) -> Void) -> String { + func requestData(_ requestType: RequestType, path: String, cacheName _: String?, parameterType: ParameterType?, parameters: Any?, parts: [FormDataPart]?, responseType: ResponseType, completion: @escaping (_ response: Data?, _ response: HTTPURLResponse, _ error: NSError?) -> Void) -> String { let requestID = UUID().uuidString var request = URLRequest(url: try! composedURL(with: path), requestType: requestType, path: path, parameterType: parameterType, responseType: responseType, boundary: boundary, authorizationHeaderValue: authorizationHeaderValue, token: token, authorizationHeaderKey: authorizationHeaderKey, headerFields: headerFields) @@ -263,7 +229,7 @@ extension Networking { } if let serializingError = serializingError { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) let response = HTTPURLResponse(url: url, statusCode: serializingError.code) completion(nil, response, serializingError) } else { @@ -284,10 +250,8 @@ extension Networking { } } else { var errorCode = httpResponse.statusCode - if let error = error as NSError? { - if error.code == URLError.cancelled.rawValue { - errorCode = error.code - } + if let error = error as NSError?, error.code == URLError.cancelled.rawValue { + errorCode = error.code } connectionError = NSError(domain: Networking.domain, code: errorCode, userInfo: [NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)]) @@ -329,7 +293,7 @@ extension Networking { if let response = returnedResponse as? HTTPURLResponse { completion(returnedData, response, connectionError as NSError?) } else { - let url = try! self.composedURL(with: path) + let url = try! composedURL(with: path) let errorCode = (connectionError as NSError?)?.code ?? 200 let response = HTTPURLResponse(url: url, statusCode: errorCode) completion(returnedData, response, connectionError as NSError?) diff --git a/Sources/Networking.swift b/Sources/Networking.swift index 31a75df..fa6c42b 100644 --- a/Sources/Networking.swift +++ b/Sources/Networking.swift @@ -62,7 +62,7 @@ open class Networking { return "application/x-www-form-urlencoded" case .multipartFormData: return "multipart/form-data; boundary=\(boundary)" - case .custom(let value): + case let .custom(value): return value } } @@ -114,7 +114,7 @@ open class Networking { let boundary = String(format: "net.3lvis.networking.%08x%08x", arc4random(), arc4random()) lazy var session: URLSession = { - return URLSession(configuration: self.configuration) + URLSession(configuration: self.configuration) }() /// Base initializer, it creates an instance of `Networking`. @@ -194,7 +194,7 @@ open class Networking { if let normalizedCacheName = normalizedCacheName { resourcesPath = normalizedCacheName } else { - let url = try self.composedURL(with: path) + let url = try composedURL(with: path) resourcesPath = url.absoluteString } diff --git a/Sources/Response.swift b/Sources/Response.swift index 4b2197c..e6fb827 100644 --- a/Sources/Response.swift +++ b/Sources/Response.swift @@ -12,7 +12,7 @@ public class Response { public let fullResponse: HTTPURLResponse init(response: HTTPURLResponse) { - self.fullResponse = response + fullResponse = response } } @@ -39,9 +39,9 @@ public class JSONResponse: Response { public var data: Data { switch json { - case .array(let value, _): + case let .array(value, _): return value - case .dictionary(let value, _): + case let .dictionary(value, _): return value case .none: return Data() @@ -55,7 +55,7 @@ public class JSONResponse: Response { } } -public class SuccessJSONResponse: JSONResponse { } +public class SuccessJSONResponse: JSONResponse {} public class FailureJSONResponse: JSONResponse { public let error: NSError diff --git a/Sources/Result.swift b/Sources/Result.swift index ed61f19..698e0bb 100644 --- a/Sources/Result.swift +++ b/Sources/Result.swift @@ -13,7 +13,7 @@ public enum JSONResult: Result { switch self { case .success: return nil - case .failure(let response): + case let .failure(response): return response.error } } diff --git a/Tests/DELETETests.swift b/Tests/DELETETests.swift index 4a8348e..93bb67e 100644 --- a/Tests/DELETETests.swift +++ b/Tests/DELETETests.swift @@ -18,7 +18,7 @@ class DELETETests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.delete("/delete") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let url = json["url"] as? String else { XCTFail(); return } XCTAssertEqual(url, "http://httpbin.org/delete") @@ -36,7 +36,7 @@ class DELETETests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.delete("/delete") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let url = json["url"] as? String else { XCTFail(); return } XCTAssertEqual(url, "http://httpbin.org/delete") @@ -57,7 +57,7 @@ class DELETETests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 404) } } @@ -70,7 +70,7 @@ class DELETETests: XCTestCase { networking.delete("/stories") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let value = json["name"] as? String XCTAssertEqual(value, "Elvis") @@ -89,7 +89,7 @@ class DELETETests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 401) } } @@ -102,7 +102,7 @@ class DELETETests: XCTestCase { networking.delete("/entries") { result in switch result { - case .success(let response): + case let .success(response): let json = response.arrayBody let entry = json[0] let value = entry["title"] as? String @@ -123,7 +123,7 @@ class DELETETests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertTrue(completed) XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() @@ -145,7 +145,7 @@ class DELETETests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.json, JSON.none) XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() @@ -161,7 +161,7 @@ class DELETETests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.delete("/delete", parameters: ["userId": 25]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody XCTAssertEqual(json["url"] as? String, "http://httpbin.org/delete?userId=25") case .failure: diff --git a/Tests/DownloadTests.swift b/Tests/DownloadTests.swift index 95f5fe0..f500490 100644 --- a/Tests/DownloadTests.swift +++ b/Tests/DownloadTests.swift @@ -38,7 +38,7 @@ class DownloadTests: XCTestCase { networking.downloadImage(path) { result in switch result { - case .success(let response): + case let .success(response): let pigImage = Image.find(named: "pig.png", inBundle: Bundle(for: DownloadTests.self)) let pigImageData = pigImage.pngData() let imageData = response.image.pngData() @@ -57,7 +57,7 @@ class DownloadTests: XCTestCase { networking.downloadImage(path) { result in switch result { - case .success(let response): + case let .success(response): let pigImage = Image.find(named: "døgnvillburgere.jpg", inBundle: Bundle(for: DownloadTests.self)) let pigImageData = pigImage.pngData() let imageData = response.image.pngData() @@ -157,7 +157,7 @@ class DownloadTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() } @@ -174,7 +174,7 @@ class DownloadTests: XCTestCase { networking.fakeImageDownload("/image/png", image: pigImage) networking.downloadImage("/image/png") { result in switch result { - case .success(let response): + case let .success(response): let pigImageData = pigImage.pngData() let imageData = response.image.pngData() XCTAssertEqual(pigImageData, imageData) @@ -191,7 +191,7 @@ class DownloadTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 401) } } @@ -306,7 +306,7 @@ class DownloadTests: XCTestCase { try! Helper.removeFileIfNeeded(networking, path: path) networking.downloadData(path) { result in switch result { - case .success(let response): + case let .success(response): synchronous = true XCTAssertTrue(Thread.isMainThread) XCTAssertEqual(response.data.count, 8090) @@ -324,7 +324,7 @@ class DownloadTests: XCTestCase { networking.downloadData(path) { result in switch result { - case .success(let response): + case let .success(response): let cacheData = networking.dataFromCache(path) XCTAssert(response.data == cacheData!) case .failure: diff --git a/Tests/GETTests.swift b/Tests/GETTests.swift index 4566af2..a682633 100644 --- a/Tests/GETTests.swift +++ b/Tests/GETTests.swift @@ -29,7 +29,7 @@ class GETTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.get("/get") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let url = json["url"] as? String else { XCTFail(); return } @@ -48,7 +48,7 @@ class GETTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.get("/get") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let url = json["url"] as? String else { XCTFail(); return } XCTAssertEqual(url, "http://httpbin.org/get") @@ -69,7 +69,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 404) } } @@ -86,7 +86,7 @@ class GETTests: XCTestCase { networking.get("/stories") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let value = json["name"] as? String XCTAssertEqual(value, "Elvis") @@ -105,7 +105,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 401) } } @@ -121,7 +121,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): let json = response.dictionaryBody XCTAssertEqual(json as! [String: String], expectedResponse) XCTAssertEqual(response.error.code, 401) @@ -136,7 +136,7 @@ class GETTests: XCTestCase { networking.get("/entries") { result in switch result { - case .success(let response): + case let .success(response): let json = response.arrayBody let entry = json[0] let value = entry["title"] as? String @@ -157,7 +157,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertTrue(completed) XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() @@ -179,7 +179,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() } @@ -195,7 +195,7 @@ class GETTests: XCTestCase { networking.get("/status/200") { result in switch result { - case .success(let response): + case let .success(response): XCTAssertEqual(response.statusCode, 200) case .failure: XCTFail() @@ -207,7 +207,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): let connectionError = NSError(domain: Networking.domain, code: statusCode, userInfo: [NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) XCTAssertEqual(response.error, connectionError) } @@ -218,7 +218,7 @@ class GETTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): let connectionError = NSError(domain: Networking.domain, code: statusCode, userInfo: [NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) XCTAssertEqual(response.error, connectionError) } @@ -229,7 +229,7 @@ class GETTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.get("/get", parameters: ["count": 25]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody XCTAssertEqual(json["url"] as? String, "http://httpbin.org/get?count=25") case .failure: @@ -242,7 +242,7 @@ class GETTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.get("/get?accountId=123", parameters: ["userId": 5]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody XCTAssertEqual(json["url"] as? String, "http://httpbin.org/get?accountId=123&userId=5") case .failure: @@ -255,7 +255,7 @@ class GETTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.get("/get", parameters: ["name": "Elvis Nuñez"]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody XCTAssertEqual(json["url"] as? String, "http://httpbin.org/get?name=Elvis Nuñez") case .failure: diff --git a/Tests/JSONTests.swift b/Tests/JSONTests.swift index 49dd60c..1bffd99 100644 --- a/Tests/JSONTests.swift +++ b/Tests/JSONTests.swift @@ -5,34 +5,34 @@ class JSONTests: XCTestCase { // MARK: - Equatable func testEqualDictionary() { - XCTAssertEqual(JSON(["hello":"value"]), JSON(["hello":"value"])) - XCTAssertNotEqual(JSON(["hello1":"value"]), JSON(["hello2":"value"])) + XCTAssertEqual(JSON(["hello": "value"]), JSON(["hello": "value"])) + XCTAssertNotEqual(JSON(["hello1": "value"]), JSON(["hello2": "value"])) } func testEqualArray() { - XCTAssertEqual(JSON([["hello":"value"]]), JSON([["hello":"value"]])) - XCTAssertNotEqual(JSON([["hello1":"value"]]), JSON([["hello2":"value"]])) + XCTAssertEqual(JSON([["hello": "value"]]), JSON([["hello": "value"]])) + XCTAssertNotEqual(JSON([["hello1": "value"]]), JSON([["hello2": "value"]])) - XCTAssertEqual(JSON([["hello2":"value"], ["hello1":"value"]]), JSON([["hello2":"value"], ["hello1":"value"]])) - XCTAssertNotEqual(JSON([["hello1":"value"], ["hello2":"value"]]), JSON([["hello3":"value"], ["hello4":"value"]])) + XCTAssertEqual(JSON([["hello2": "value"], ["hello1": "value"]]), JSON([["hello2": "value"], ["hello1": "value"]])) + XCTAssertNotEqual(JSON([["hello1": "value"], ["hello2": "value"]]), JSON([["hello3": "value"], ["hello4": "value"]])) } func testEqualData() { - let helloData = try! JSONSerialization.data(withJSONObject: ["a":"b"], options: []) - let byeData = try! JSONSerialization.data(withJSONObject: ["c":"d"], options: []) + let helloData = try! JSONSerialization.data(withJSONObject: ["a": "b"], options: []) + let byeData = try! JSONSerialization.data(withJSONObject: ["c": "d"], options: []) XCTAssertEqual(try! JSON(helloData), try! JSON(helloData)) XCTAssertNotEqual(try! JSON(helloData), try! JSON(byeData)) } func testEqualNone() { XCTAssertEqual(JSON.none, JSON.none) - XCTAssertNotEqual(JSON.none, JSON(["hello":"value"])) + XCTAssertNotEqual(JSON.none, JSON(["hello": "value"])) } // MARKL - Accessors func testDictionaryAccessor() { - let body = ["hello":"value"] + let body = ["hello": "value"] let json = JSON(body) XCTAssertEqual(json.dictionary.debugDescription, body.debugDescription) @@ -40,7 +40,7 @@ class JSONTests: XCTestCase { } func testArrayAccessor() { - let body = [["hello":"value"]] + let body = [["hello": "value"]] let json = JSON(body) XCTAssertEqual(json.dictionary.debugDescription, [String: Any]().debugDescription) @@ -48,12 +48,12 @@ class JSONTests: XCTestCase { } func testDataAccessor() { - let body = ["hello":"value"] + let body = ["hello": "value"] let bodyData = try! JSONSerialization.data(withJSONObject: body, options: []) let json = try! JSON(bodyData) switch json { - case .dictionary(let data, _): + case let .dictionary(data, _): XCTAssertEqual(data.hashValue, bodyData.hashValue) default: XCTFail() @@ -63,8 +63,8 @@ class JSONTests: XCTestCase { // MARK: - from func testArrayJSONFromFileNamed() { - let result = try! FileManager.json(from: "simple_array.json", bundle: Bundle(for: JSONTests.self)) as? [[String : Any]] ?? [[String : Any]]() - let compared = [["id" : 1, "name" : "Hi"]] + let result = try! FileManager.json(from: "simple_array.json", bundle: Bundle(for: JSONTests.self)) as? [[String: Any]] ?? [[String: Any]]() + let compared = [["id": 1, "name": "Hi"]] XCTAssertEqual(compared.count, result.count) // This should work but Swift is not able to compile it. @@ -76,8 +76,8 @@ class JSONTests: XCTestCase { } func testDictionaryJSONFromFileNamed() { - let result = try! FileManager.json(from: "simple_dictionary.json", bundle: Bundle(for: JSONTests.self)) as? [String : Any] ?? [String : Any]() - let compared = ["id" : 1, "name" : "Hi"] as [String : Any] + let result = try! FileManager.json(from: "simple_dictionary.json", bundle: Bundle(for: JSONTests.self)) as? [String: Any] ?? [String: Any]() + let compared = ["id": 1, "name": "Hi"] as [String: Any] XCTAssertEqual(compared.count, result.count) XCTAssertEqual(Array(compared.keys), Array(result.keys)) } @@ -85,10 +85,10 @@ class JSONTests: XCTestCase { func testFromFileNamedWithNotFoundFile() { var failed = false do { - let _ = try FileManager.json(from: "nonexistingfile.json", bundle: Bundle(for: JSONTests.self)) + _ = try FileManager.json(from: "nonexistingfile.json", bundle: Bundle(for: JSONTests.self)) } catch ParsingError.notFound { failed = true - } catch { } + } catch {} XCTAssertTrue(failed) } @@ -96,10 +96,10 @@ class JSONTests: XCTestCase { func testFromFileNamedWithInvalidJSON() { var failed = false do { - let _ = try FileManager.json(from: "invalid.json", bundle: Bundle(for: JSONTests.self)) + _ = try FileManager.json(from: "invalid.json", bundle: Bundle(for: JSONTests.self)) } catch ParsingError.failed { failed = true - } catch { } + } catch {} XCTAssertTrue(failed) } @@ -111,9 +111,9 @@ class JSONTests: XCTestCase { guard let url = URL(string: "http://httpbin.org/get") else { return } let request = URLRequest(url: url) - URLSession.shared.dataTask(with: request) { data, _, error in + URLSession.shared.dataTask(with: request) { data, _, _ in do { - let JSON = try data?.toJSON() as? [String : Any] + let JSON = try data?.toJSON() as? [String: Any] let url = JSON?["url"] as! String XCTAssertEqual(url, "http://httpbin.org/get") } catch { @@ -121,9 +121,8 @@ class JSONTests: XCTestCase { } expectation.fulfill() - }.resume() + }.resume() waitForExpectations(timeout: 10, handler: nil) } } - diff --git a/Tests/NetworkingTests.swift b/Tests/NetworkingTests.swift index 5a95e13..4bf1b27 100644 --- a/Tests/NetworkingTests.swift +++ b/Tests/NetworkingTests.swift @@ -9,7 +9,7 @@ class NetworkingTests: XCTestCase { networking.setAuthorizationHeader(username: "user", password: "passwd") networking.get("/basic-auth/user/passwd") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let user = json["user"] as? String let authenticated = json["authenticated"] as? Bool @@ -27,7 +27,7 @@ class NetworkingTests: XCTestCase { networking.setAuthorizationHeader(token: token) networking.post("/post") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let headers = json["headers"] as? [String: Any] XCTAssertEqual("Bearer \(token)", headers?["Authorization"] as? String) @@ -43,7 +43,7 @@ class NetworkingTests: XCTestCase { networking.setAuthorizationHeader(headerValue: value) networking.post("/post") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let headers = json["headers"] as? [String: Any] XCTAssertEqual(value, headers?["Authorization"] as? String) @@ -60,7 +60,7 @@ class NetworkingTests: XCTestCase { networking.setAuthorizationHeader(headerKey: key, headerValue: value) networking.post("/post") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let headers = json["headers"] as? [String: Any] XCTAssertEqual(value, headers?[key] as? String) @@ -75,7 +75,7 @@ class NetworkingTests: XCTestCase { networking.headerFields = ["HeaderKey": "HeaderValue"] networking.post("/post") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let headers = json["headers"] as? [String: Any] XCTAssertEqual("HeaderValue", headers?["Headerkey"] as? String) @@ -176,7 +176,7 @@ class NetworkingTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): cancelledGET = response.error.code == URLError.cancelled.rawValue XCTAssertTrue(cancelledGET) @@ -202,7 +202,7 @@ class NetworkingTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): cancelledGET = response.error.code == URLError.cancelled.rawValue XCTAssertTrue(cancelledGET) @@ -216,7 +216,7 @@ class NetworkingTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): cancelledPOST = response.error.code == URLError.cancelled.rawValue XCTAssertTrue(cancelledPOST) @@ -239,7 +239,7 @@ class NetworkingTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertTrue(Thread.isMainThread) XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() diff --git a/Tests/POSTTests.swift b/Tests/POSTTests.swift index be78eaf..715b61c 100644 --- a/Tests/POSTTests.swift +++ b/Tests/POSTTests.swift @@ -18,7 +18,7 @@ class POSTTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.post("/post", parameters: nil) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let headers = json["headers"] as? [String: String] else { XCTFail(); return } @@ -39,7 +39,7 @@ class POSTTests: XCTestCase { ] as [String: Any] networking.post("/post", parameters: parameters) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let JSONResponse = json["json"] as? [String: Any] else { XCTFail(); return } XCTAssertEqual(JSONResponse["string"] as? String, "valueA") @@ -60,7 +60,7 @@ class POSTTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.post("/post") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let url = json["url"] as? String else { XCTFail(); return } XCTAssertEqual(url, "http://httpbin.org/post") @@ -79,7 +79,7 @@ class POSTTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.post("/post") { result in switch result { - case .success(let response): + case let .success(response): let JSONResponse = response.dictionaryBody XCTAssertEqual("http://httpbin.org/post", JSONResponse["url"] as? String) case .failure: @@ -99,7 +99,7 @@ class POSTTests: XCTestCase { ] as [String: Any] networking.post("/post", parameterType: .formURLEncoded, parameters: parameters) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let form = json["form"] as? [String: Any] else { XCTFail(); return } XCTAssertEqual(form["string"] as? String, "B&B") @@ -128,7 +128,7 @@ class POSTTests: XCTestCase { ] as [String: Any] networking.post("/post", parameters: parameters, parts: [part1, part2]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody XCTAssertEqual(json["url"] as? String, "http://httpbin.org/post") @@ -157,7 +157,7 @@ class POSTTests: XCTestCase { let part1 = FormDataPart(data: item1.data(using: .utf8)!, parameterName: item1, filename: "\(item1).png") networking.post("/post", parameters: nil, parts: [part1]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody XCTAssertEqual(json["url"] as? String, "http://httpbin.org/post") @@ -196,7 +196,7 @@ class POSTTests: XCTestCase { networking.post("/v1_1/\(CloudinaryCloudName)/image/upload", parameters: parameters, parts: [pngPart]) { result in switch result { - case .success(let response): + case let .success(response): let JSONResponse = response.dictionaryBody XCTAssertEqual(timestamp, JSONResponse["original_filename"] as? String) @@ -213,7 +213,7 @@ class POSTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 404) } } @@ -226,7 +226,7 @@ class POSTTests: XCTestCase { networking.post("/story", parameters: ["username": "jameson", "password": "secret"]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.arrayBody let value = json[0]["name"] as? String XCTAssertEqual(value, "Elvis") @@ -245,7 +245,7 @@ class POSTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 401) } } @@ -258,7 +258,7 @@ class POSTTests: XCTestCase { networking.post("/entries") { result in switch result { - case .success(let response): + case let .success(response): let json = response.arrayBody let entry = json[0] let value = entry["title"] as? String @@ -279,7 +279,7 @@ class POSTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertTrue(completed) XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() @@ -301,7 +301,7 @@ class POSTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() } diff --git a/Tests/PUTTests.swift b/Tests/PUTTests.swift index c46fe5e..2c54a39 100644 --- a/Tests/PUTTests.swift +++ b/Tests/PUTTests.swift @@ -18,7 +18,7 @@ class PUTTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.put("/put", parameters: ["username": "jameson", "password": "secret"]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody let JSONResponse = json["json"] as? [String: String] XCTAssertEqual("jameson", JSONResponse?["username"]) @@ -36,7 +36,7 @@ class PUTTests: XCTestCase { let networking = Networking(baseURL: baseURL) networking.put("/put") { result in switch result { - case .success(let response): + case let .success(response): let json = response.dictionaryBody guard let url = json["url"] as? String else { XCTFail(); return } XCTAssertEqual(url, "http://httpbin.org/put") @@ -57,7 +57,7 @@ class PUTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 404) } } @@ -70,7 +70,7 @@ class PUTTests: XCTestCase { networking.put("/story", parameters: ["username": "jameson", "password": "secret"]) { result in switch result { - case .success(let response): + case let .success(response): let json = response.arrayBody let value = json[0]["name"] as? String XCTAssertEqual(value, "Elvis") @@ -89,7 +89,7 @@ class PUTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, 401) } } @@ -102,7 +102,7 @@ class PUTTests: XCTestCase { networking.put("/entries", parameters: nil) { result in switch result { - case .success(let response): + case let .success(response): let json = response.arrayBody let entry = json[0] let value = entry["title"] as? String @@ -123,7 +123,7 @@ class PUTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertTrue(completed) XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() @@ -145,7 +145,7 @@ class PUTTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let response): + case let .failure(response): XCTAssertEqual(response.error.code, URLError.cancelled.rawValue) expectation.fulfill() } diff --git a/Tests/ResponseTests.swift b/Tests/ResponseTests.swift index 01b5c2f..9b17eea 100644 --- a/Tests/ResponseTests.swift +++ b/Tests/ResponseTests.swift @@ -9,7 +9,7 @@ class ResponseTest: XCTestCase { networking.headerFields = expectedBody networking.get("/user-agent") { result in switch result { - case .success(let response): + case let .success(response): XCTAssertEqual(response.data.toStringStringDictionary().debugDescription, expectedBody.debugDescription) case .failure: XCTFail() diff --git a/Tests/ResultTests.swift b/Tests/ResultTests.swift index c52ea00..1985fec 100644 --- a/Tests/ResultTests.swift +++ b/Tests/ResultTests.swift @@ -13,18 +13,18 @@ class ResultTests: XCTestCase { let body = ["a": 12] let result = JSONResult(body: body, response: response, error: nil) switch result { - case .success(let value): + case let .success(value): XCTAssertEqual(value.dictionaryBody.debugDescription, body.debugDescription) XCTAssertEqual(value.arrayBody.debugDescription, [[String: Any]]().debugDescription) - //XCTAssertEqual(value.data.hashValue, body.hashValue) + // XCTAssertEqual(value.data.hashValue, body.hashValue) switch value.json { - case .dictionary(_, let valueBody): + case let .dictionary(_, valueBody): XCTAssertEqual(body.debugDescription, valueBody.debugDescription) case .array(_, _), .none: XCTFail() } - case .failure(_): + case .failure: XCTFail() } } @@ -33,19 +33,19 @@ class ResultTests: XCTestCase { let expectedBody = [["a": 12]] let result = JSONResult(body: expectedBody, response: response, error: nil) switch result { - case .success(let value): + case let .success(value): XCTAssertEqual(value.dictionaryBody.debugDescription, [String: Any]().debugDescription) XCTAssertEqual(value.arrayBody.debugDescription, expectedBody.debugDescription) - //XCTAssertEqual(value.data.hashValue, bodyData.hashValue) + // XCTAssertEqual(value.data.hashValue, bodyData.hashValue) switch value.json { - case .array(_, let valueBody): + case let .array(_, valueBody): XCTAssertEqual(expectedBody.debugDescription, valueBody.debugDescription) - //XCTAssertEqual(dataBody.hashValue, expectedBody.hashValue) + // XCTAssertEqual(dataBody.hashValue, expectedBody.hashValue) case .dictionary(_, _), .none: XCTFail() } - case .failure(_): + case .failure: XCTFail() } } @@ -55,19 +55,19 @@ class ResultTests: XCTestCase { let expectedBodyData = try! JSONSerialization.data(withJSONObject: expectedBody, options: []) let result = JSONResult(body: expectedBodyData, response: response, error: nil) switch result { - case .success(let value): + case let .success(value): XCTAssertEqual(value.dictionaryBody.debugDescription, expectedBody.debugDescription) XCTAssertEqual(value.arrayBody.debugDescription, [[String: Any]]().debugDescription) XCTAssertEqual(value.data.hashValue, expectedBodyData.hashValue) switch value.json { - case .dictionary(let dataBody, let valueBody): + case let .dictionary(dataBody, valueBody): XCTAssertEqual(dataBody.hashValue, expectedBodyData.hashValue) XCTAssertEqual(valueBody.debugDescription, expectedBody.debugDescription) case .array(_, _), .none: XCTFail() } - case .failure(_): + case .failure: XCTFail() } } @@ -77,19 +77,19 @@ class ResultTests: XCTestCase { let expectedBodyData = try! JSONSerialization.data(withJSONObject: expectedBody, options: []) let result = JSONResult(body: expectedBodyData, response: response, error: nil) switch result { - case .success(let value): + case let .success(value): XCTAssertEqual(value.dictionaryBody.debugDescription, [String: Any]().debugDescription) XCTAssertEqual(value.arrayBody.debugDescription, expectedBody.debugDescription) XCTAssertEqual(value.data.hashValue, expectedBodyData.hashValue) switch value.json { - case .array(let dataBody, let valueBody): + case let .array(dataBody, valueBody): XCTAssertEqual(dataBody.hashValue, expectedBodyData.hashValue) XCTAssertEqual(valueBody.debugDescription, expectedBody.debugDescription) case .dictionary(_, _), .none: XCTFail() } - case .failure(_): + case .failure: XCTFail() } } @@ -97,18 +97,18 @@ class ResultTests: XCTestCase { func testJSONResultNone() { let result = JSONResult(body: nil, response: response, error: nil) switch result { - case .success(let value): + case let .success(value): XCTAssertEqual(value.dictionaryBody.debugDescription, [String: Any]().debugDescription) XCTAssertEqual(value.arrayBody.debugDescription, [[String: Any]]().debugDescription) XCTAssertEqual(value.data.hashValue, Data().hashValue) switch value.json { - case .dictionary(_, _), .array(_, _): + case .dictionary(_, _), .array: XCTFail() case .none: break } - case .failure(_): + case .failure: XCTFail() } } @@ -120,7 +120,7 @@ class ResultTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let result): + case let .failure(result): XCTAssertEqual(result.error.code, URLError.cannotParseResponse.rawValue) } } @@ -132,7 +132,7 @@ class ResultTests: XCTestCase { switch result { case .success: XCTFail() - case .failure(let result): + case let .failure(result): XCTAssertEqual(result.error.code, URLError.cannotParseResponse.rawValue) } } @@ -149,4 +149,3 @@ class ResultTests: XCTestCase { XCTAssertNotNil(errorResult.error) } } - diff --git a/iOSDemo/FakeImageController.swift b/iOSDemo/FakeImageController.swift index f230d4f..c49b4c2 100644 --- a/iOSDemo/FakeImageController.swift +++ b/iOSDemo/FakeImageController.swift @@ -29,7 +29,7 @@ class FakeImageController: UIViewController { networking.downloadImage("/pig") { result in switch result { - case .success(let response): + case let .success(response): self.imageView.image = response.image case .failure: break