before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
/// Encodes `true` as `1`, `false` as `0`. case numeric /// Encodes `true` as "true", `false` as "false". case literal /// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// - Returns: The encoded `String`...
Probably clearer to say: "Encodes dates according to the ISO 8601 and RFC3339 standards.", similar to the `JSONEncoder` documentation.
/// Encodes `true` as `1`, `false` as `0`. case numeric /// Encodes `true` as "true", `false` as "false". case literal /// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// - Returns: The encoded `String`...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp. + case se...
Source/ParameterEncoder.swift
26
Swift
0.5
suggestion
134
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
serializationQueue: serializationQueue, interceptor: interceptor, serverTrustManager: serverTrustManager, redirectHandler: redirectHandler, cachedResponseHandler: cachedResponseHandler, eventMonitors: eventMonito...
Should we hop back off `rootQueue` here to avoid clients hanging it up? If yes, should we provide a `queue` parameter that defaults maybe to `.main`?
serializationQueue: serializationQueue, interceptor: interceptor, serverTrustManager: serverTrustManager, redirectHandler: redirectHandler, cachedResponseHandler: cachedResponseHandler, eventMonitors: eventMonito...
@@ -192,6 +194,22 @@ open class Session { session.invalidateAndCancel() } + // MARK: - Cancellation + + /// Cancel all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: This is an asynchronous operation and does not block the creation of future `Re...
Source/Session.swift
26
Swift
0.571
question
149
51
51
false
Add cancelAllRequests API
2,890
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?) -> UploadRequest { let request = UploadRequest(convertible: upload, underlyingQueue: rootQueue, serializationQueue: serializationQueue, ...
Do we actually need `self.` now?
} func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?) -> UploadRequest { let request = UploadRequest(convertible: upload, underlyingQueue: rootQueue, serializationQueue: serializationQueue, ...
@@ -750,11 +768,17 @@ open class Session { // MARK: Perform + + /// Perform `Request`. + /// + /// - Note: Called during retry. + /// + /// - Parameter request: The `Request` to perform. func perform(_ request: Request) { switch request { - case let r as DataRequest: perform...
Source/Session.swift
26
Swift
0.214
question
32
51
51
false
Add cancelAllRequests API
2,890
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substan...
These property names should not be changed. In fact, they were changed *to* `success` / `failure` to get away from our previous names in order to prevent [a confusing error](https://stackoverflow.com/questions/55484714/value-is-inaccessible-due-to-internal-protection-level/55485139#55485139) seen when using `value` / `...
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substan...
@@ -0,0 +1,106 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Softwar...
Source/Result+Alamofire.swift
26
Swift
0.786
bug
358
51
51
false
Rename internal `flatMap` to `tryMap`
2,892
Alamofire/Alamofire
41,690
Swift
jshier
philtre
import Foundation // MARK: - Internal APIs extension Result { /// Returns the associated value if the result is a success, `nil` otherwise. var value: Success? { guard case .success(let value) = self else { return nil } return value } /// Returns the associated error value if the resu...
What was the purpose of this change? I can't find a use site in the current diff that shows improvement with the use of autoclosures..
import Foundation /// `Result` that always has an `Error` `Failure` type. public typealias AFResult<T> = Result<T, Error> // MARK: - Internal APIs extension Result { /// Returns the associated value if the result is a success, `nil` otherwise. var success: Success? { guard case .success(let value) = ...
@@ -0,0 +1,106 @@ +// +// Result+Alamofire.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Softwar...
Source/Result+Alamofire.swift
26
Swift
0.429
question
134
51
51
false
Rename internal `flatMap` to `tryMap`
2,892
Alamofire/Alamofire
41,690
Swift
jshier
philtre
/// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Success, Failure: Error> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse...
Shouldn't `error` now be `Failure` instead of `Error` so that transforms can move to other `Error` types?
/// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The final metrics of the response. public let metrics: URLSession...
@@ -42,10 +45,10 @@ public struct DataResponse<Value> { public let serializationDuration: TimeInterval /// The result of response serialization. - public let result: Result<Value, Error> + public let result: Result<Success, Failure> /// Returns the associated value of the result if it is a succ...
Source/Response.swift
26
Swift
0.714
bug
105
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
/// Event called when a `Request` receives a `suspend` call. func requestDidSuspend(_ request: Request) /// Event called when a `Request`'s associated `URLSessionTask` is suspended. func request(_ request: Request, didSuspendTask task: URLSessionTask) /// Event called when a `Request` receives a `...
Even though there will only be one error type here, it's probably a good idea to make this (and the corresponding download method) generic for `Failure: Error` as well, just to ensure we're compatible with future changes.
/// Event called when a `Request` receives a `suspend` call. func requestDidSuspend(_ request: Request) /// Event called when a `Request`'s associated `URLSessionTask` is suspended. func request(_ request: Request, didSuspendTask task: URLSessionTask) /// Event called when a `Request` receives a `...
@@ -159,10 +159,10 @@ public protocol EventMonitor { withResult result: Request.ValidationResult) /// Event called when a `DataRequest` creates a `DataResponse<Data?>` value without calling a `ResponseSerializer`. - func request(_ request: DataRequest, didParseResponse response: DataResponse...
Source/EventMonitor.swift
26
Swift
0.786
bug
221
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
/// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if /// the `InputStream` does not wrap a `Data` value or file `URL`. func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) // MARK: DownloadRequest Events ...
Should probably make this doubly generic as well.
/// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if /// the `InputStream` does not wrap a `Data` value or file `URL`. func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) // MARK: DownloadRequest Events ...
@@ -193,10 +193,10 @@ public protocol EventMonitor { withResult result: Request.ValidationResult) /// Event called when a `DownloadRequest` creates a `DownloadResponse<URL?>` without calling a `ResponseSerializer`. - func request(_ request: DownloadRequest, didParseResponse response: Downloa...
Source/EventMonitor.swift
26
Swift
0.143
suggestion
49
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
// // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation...
I think we need a better name here. The `AF` prefix doesn't buy us anything, as it's not differentiating from Swift itself this time. Perhaps `SimpleDataResponse`?
// // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation...
@@ -24,8 +24,11 @@ import Foundation +/// `DataResponse` that always has an `Error` `Failure` type. +public typealias AFDataResponse<Success> = DataResponse<Success, Error>
Source/Response.swift
26
Swift
0.571
question
163
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
func alwaysFails() throws -> TestError { throw TransformationError.error } } class ResponseMapErrorTestCase: BaseTestCase { func testThatMapErrorTransformsFailureValue() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.exp...
Please do not change the structure of tests as part of this PR.
func alwaysFails() throws -> TestError { throw TransformationError.error } } class ResponseMapErrorTestCase: BaseTestCase { func testThatMapErrorTransformsFailureValue() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.exp...
@@ -543,23 +543,25 @@ class ResponseMapErrorTestCase: BaseTestCase { } waitForExpectations(timeout: timeout, handler: nil) + + if response == nil { XCTFail(); return }
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
63
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
// Then XCTAssertNotNil(response.request) XCTAssertNil(response.response) XCTAssertNil(response.data) XCTAssertEqual(response.result.isFailure, true) XCTAssertNil(response.value) XCTAssertNotNil(response.error) XCTAssertNotNil(response.metrics) } ...
Please do not change the structure of tests as part of this PR.
XCTAssertNil(response?.response) XCTAssertNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) guard let error = response?.error, case .error = error else { XCTFail(); return } XCTAssertNotNil(response?.metrics) } func testThatMapErrorPreservesSuccessVal...
@@ -568,95 +570,105 @@ class ResponseMapErrorTestCase: BaseTestCase { } waitForExpectations(timeout: timeout, handler: nil) + + if response == nil { XCTFail(); return }
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
63
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
XCTAssertEqual(response.result.isSuccess, true) XCTAssertNotNil(response.value) XCTAssertNil(response.error) XCTAssertNotNil(response.metrics) } } // MARK: - class ResponseTryMapErrorTestCase: BaseTestCase { func testThatTryMapErrorPreservesSuccessValue() { // Given ...
Please do not change the structure of tests as part of this PR.
// MARK: - class ResponseTryMapErrorTestCase: BaseTestCase { func testThatTryMapErrorPreservesSuccessValue() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Data, Error>? ...
@@ -568,95 +570,105 @@ class ResponseMapErrorTestCase: BaseTestCase { } waitForExpectations(timeout: timeout, handler: nil) + + if response == nil { XCTFail(); return } // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - ...
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
63
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
if response == nil { XCTFail(); return } // Then XCTAssertNotNil(response.request) XCTAssertNotNil(response.response) XCTAssertNotNil(response.data) XCTAssertEqual(response.result.isSuccess, true) XCTAssertNotNil(response.metrics) } func testThat...
Please do not change the structure of tests as part of this PR.
} func testThatTryMapErrorCatchesTransformationError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail") var response: DataResponse<Data, Error>? // When AF.reque...
@@ -568,95 +570,105 @@ class ResponseMapErrorTestCase: BaseTestCase { } waitForExpectations(timeout: timeout, handler: nil) + + if response == nil { XCTFail(); return } // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - ...
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
63
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
if let error = response.result.error { XCTAssertTrue(error is TransformationError) } else { XCTFail("flatMapError should catch the transformation error") } XCTAssertNotNil(response.metrics) } func testThatTryMapErrorTransformsError() { // Given ...
Please do not change the structure of tests as part of this PR.
func testThatTryMapErrorTransformsError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail") var response: DataResponse<Data, Error>? // When AF.request(urlString).resp...
@@ -568,95 +570,105 @@ class ResponseMapErrorTestCase: BaseTestCase { } waitForExpectations(timeout: timeout, handler: nil) + + if response == nil { XCTFail(); return } // Then - XCTAssertNotNil(response?.request) - XCTAssertNotNil(response?.response) - ...
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
63
39
27
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
XCTAssertEqual(response?.result.isFailure, true) XCTAssertNotNil(response?.metrics) } } // MARK: - enum TestError: Error { case error(error: Error) } enum TransformationError: Error { case error func alwaysFails() throws -> TestError { throw TransformationError.error } } ...
This should just be a normal optional, as you're using optionally below.
XCTAssertEqual(response?.result.isFailure, true) XCTAssertNotNil(response?.metrics) } } // MARK: - enum TestError: Error { case error(error: Error) } enum TransformationError: Error { case error func alwaysFails() throws -> TestError { throw TransformationError.error } } ...
@@ -531,7 +531,7 @@ class ResponseMapErrorTestCase: BaseTestCase { let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should not succeed") - var response: DataResponse<Any>? + var response: DataResponse<Any, TestE...
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
72
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
AF.request(urlString).responseJSON { resp in response = resp.mapError { error in return TestError.error(error: error) } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(respo...
This should also just be a normal optional.
AF.request(urlString).responseJSON { resp in response = resp.mapError { error in return TestError.error(error: error) } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(respo...
@@ -559,7 +559,7 @@ class ResponseMapErrorTestCase: BaseTestCase { let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") - var response: DataResponse<Data>? + var response: DataResponse<Data, TestError>!
Tests/ResponseTests.swift
26
Swift
0.143
suggestion
43
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
// When AF.request(urlString).responseData { resp in response = resp.mapError { TestError.error(error: $0) } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertN...
This should also be a normal optional.
// When AF.request(urlString).responseData { resp in response = resp.mapError { TestError.error(error: $0) } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertN...
@@ -580,13 +580,13 @@ class ResponseMapErrorTestCase: BaseTestCase { // MARK: - -class ResponseFlatMapErrorTestCase: BaseTestCase { - func testThatFlatMapErrorPreservesSuccessValue() { +class ResponseTryMapErrorTestCase: BaseTestCase { + func testThatTryMapErrorPreservesSuccessValue() { // Given ...
Tests/ResponseTests.swift
26
Swift
0.143
suggestion
38
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Data, Error>! // When AF.request(urlString).responseData { resp in response = resp.tryMapError { TestError.error(error: $0) } expectation.fulfill() } ...
This should be a normal optional.
let expectation = self.expectation(description: "request should succeed") var response: DataResponse<Data, Error>? // When AF.request(urlString).responseData { resp in response = resp.tryMapError { TestError.error(error: $0) } expectation.fulfill() } ...
@@ -604,12 +604,12 @@ class ResponseFlatMapErrorTestCase: BaseTestCase { XCTAssertNotNil(response?.metrics) } - func testThatFlatMapErrorCatchesTransformationError() { + func testThatTryMapErrorCatchesTransformationError() { // Given let urlString = "https://invalid-url-here.org/...
Tests/ResponseTests.swift
26
Swift
0.143
suggestion
33
51
51
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if let erro...
This should be a normal optional.
expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) if let erro...
@@ -628,18 +628,18 @@ class ResponseFlatMapErrorTestCase: BaseTestCase { if let error = response?.result.error { XCTAssertTrue(error is TransformationError) } else { - XCTFail("flatMapError should catch the transformation error") + XCTFail("tryMapError should catch t...
Tests/ResponseTests.swift
26
Swift
0.143
suggestion
33
47
47
false
Add failure constraint to *Response
2,893
Alamofire/Alamofire
41,690
Swift
jshier
philtre
/// `CONNECT` method. public static let connect = HTTPMethod(rawValue: "CONNECT") /// `DELETE` method. public static let delete = HTTPMethod(rawValue: "DELETE") /// `GET` method. public static let get = HTTPMethod(rawValue: "GET") /// `HEAD` method. public static let head = HTTPMethod(ra...
Is there any reason @jshier that we'd not want to uppercase the `rawValue`?
public struct HTTPMethod: RawRepresentable, Equatable, Hashable { /// `CONNECT` method. public static let connect = HTTPMethod(rawValue: "CONNECT") /// `DELETE` method. public static let delete = HTTPMethod(rawValue: "DELETE") /// `GET` method. public static let get = HTTPMethod(rawValue: "GET")...
@@ -25,23 +25,32 @@ /// HTTP method definitions. /// /// See https://tools.ietf.org/html/rfc7231#section-4.3 -public enum HTTPMethod: String { +public struct HTTPMethod: RawRepresentable, Equatable, Hashable { /// `CONNECT` method. - case connect = "CONNECT" + public static let connect = HTTPMethod(rawVal...
Source/HTTPMethod.swift
26
Swift
0.357
question
75
29
27
false
Unfreeze HTTPMethod
2,901
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// - Throws: Any `Error` produced during serialization. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject } /// The type to which all download response serializers must conform in order to serialize a response. public protocol DownloadR...
I really like this change overall. It really gives you a lot of flexibility if you need it. I think for users that actually need this functionality though might be better served by this being a protocol rather than a closure. I think most people would want to define an explicit type to very easily test rather than havi...
/// - Throws: Any `Error` produced during serialization. func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject } /// The type to which all download response serializers must conform in order to serialize a response. public protocol DownloadR...
@@ -64,18 +64,25 @@ public protocol DownloadResponseSerializerProtocol { /// A serializer that can handle both data and download responses. public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// Closure type used to prepare `Data` for serialization. + t...
Source/ResponseSerialization.swift
26
Swift
0.786
security
850
51
51
false
Add DataPreprocessor API
2,903
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// A `ResponseSerializer` that performs minimal response checking and returns any response data as-is. By default, a /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for /// empty responses (`204`, `205`), then an empty `Data` value is returned. public ...
Does `dataPreprocessor` have a place in the top-level response chainable APIs, or is it such an advanced feature that it only warrants customization at the response serializer initializers? Also, would you expect people to create their own chainable extensions when using these? > Not that this matters so much for...
extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - Parameters: /// - queue: The queue on which the completion handler is dispatched. `.main` by default. /// - completionHandler: The code to be executed once the request has finished. ...
@@ -398,33 +405,37 @@ extension DataRequest { /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for /// empty responses (`204`, `205`), then an empty `Data` value is returned. public final class DataResponseSerializer: ResponseSerializer { - /// HTT...
Source/ResponseSerialization.swift
26
Swift
0.571
suggestion
358
51
51
false
Add DataPreprocessor API
2,903
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// HTTP response codes for which empty response bodies are considered appropriate. var emptyResponseCodes: Set<Int> { get } } /// Type used to preprocess `Data` before it handled by a serializer. public protocol DataPreprocessor { /// Process `Data` before it's handled by a serializer. /// -...
I'm not sure this `XSSI` type is actually being used at all right now. Also, would it make sense to expose `Passthrough` as a `public` type? Would it be convenient for clients, or would you just expect those building custom response serializers to use `ResponseSerializer.defaultDataPreprocessor`?
/// HTTP response codes for which empty response bodies are considered appropriate. var emptyResponseCodes: Set<Int> { get } } /// Type used to preprocess `Data` before it handled by a serializer. public protocol DataPreprocessor { /// Process `Data` before it's handled by a serializer. /// -...
@@ -64,18 +64,42 @@ public protocol DownloadResponseSerializerProtocol { /// A serializer that can handle both data and download responses. public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol { + /// `DataPreprocessor` closure used to prepare incoming `Data` fo...
Source/ResponseSerialization.swift
26
Swift
0.786
security
297
51
51
false
Add DataPreprocessor API
2,903
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
} /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = (NetworkReachabilityStatus) -> Void /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `....
Does the `label` become an issue if you create more than 1 manager? I'm sure I've done this before without realizing. Would two separate DispatchQueues created with the same label actually be two different instances that just happened to share the same label? Would that only affect the queue visualization in Xcode? Or ...
} /// A closure executed when the network reachability status changes. The closure takes a single argument: the /// network reachability status. public typealias Listener = (NetworkReachabilityStatus) -> Void /// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `....
@@ -42,65 +42,86 @@ open class NetworkReachabilityManager { case notReachable /// The network is reachable on the associated `ConnectionType`. case reachable(ConnectionType) - } - /// Defines the various connection types detected by reachability flags. - public enum ConnectionType ...
Source/NetworkReachabilityManager.swift
26
Swift
0.571
question
349
51
51
false
Refactor Reachability
2,915
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
if let currentFlags = flags { reachabilityQueue.async { self.notifyListener(currentFlags) } } return callbackAdded && queueAdded } /// Stops listening for changes in network reachability status. open func stopListening() { SCNetworkRe...
Do we also need to lock status read access inside the reachability queue to be fully thread-safe?
if let currentFlags = flags { reachabilityQueue.async { self.notifyListener(currentFlags) } } return callbackAdded && queueAdded } /// Stops listening for changes in network reachability status. open func stopListening() { SCNetworkRe...
@@ -137,86 +151,100 @@ open class NetworkReachabilityManager { /// Starts listening for changes in network reachability status. /// + /// - Note: Stops and removes any existing listener. + /// + /// - Parameters: + /// - queue: `DispatchQueue` on which to call the `listener` closure. `.main...
Source/NetworkReachabilityManager.swift
26
Swift
0.357
question
97
51
51
false
Refactor Reachability
2,915
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// Whether or not to sort the encoded key value pairs. /// /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to /// ` D...
```suggestion /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default. ```
/// Whether or not to sort the encoded key value pairs. /// /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`, /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to /// ` D...
@@ -317,20 +324,24 @@ public final class URLEncodedFormEncoder { /// Creates an instance from the supplied parameters. /// /// - Parameters: - /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default. - /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default...
Source/URLEncodedFormEncoder.swift
26
Swift
0.714
suggestion
128
51
51
false
Stable encoded parameter order for URLEncodedFormEncoder
2,961
Alamofire/Alamofire
41,690
Swift
jshier
jshier
func encode(_ string: String) -> String { switch self { case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") } } } /// `URLEncodedFormEncoder` err...
I think this `Note` is a bit outdated since you've switched over to a tuple array. Isn't it now going to be either the order the parameters were provided or alphabetically sorted?
func encode(_ string: String) -> String { switch self { case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20") case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+") } } } /// `URLEncodedFormEncoder` err...
@@ -294,11 +294,18 @@ public final class URLEncodedFormEncoder { var localizedDescription: String { switch self { - case let .invalidRootObject(object): return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead." + case let .invalidRootObject(obje...
Source/URLEncodedFormEncoder.swift
26
Swift
0.5
question
179
51
51
false
Stable encoded parameter order for URLEncodedFormEncoder
2,961
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
// Start response handlers processNextResponseSerializer() eventMonitor?.requestDidFinish(self) } /// Appends the response serialization closure to the instance. /// /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. /// ...
Genius! Too bad we didn't think of this months ago. Great work!
// Start response handlers processNextResponseSerializer() eventMonitor?.requestDidFinish(self) } /// Appends the response serialization closure to the instance. /// /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`. /// ...
@@ -478,6 +480,10 @@ public class Request { if mutableState.responseSerializerProcessingFinished { underlyingQueue.async { self.processNextResponseSerializer() } } + + if mutableState.state.canTransitionTo(.resumed) { + underlyingQueue.asy...
Source/Request.swift
26
Swift
0.214
suggestion
63
51
51
false
Move Automatic Resume Behavior to After the First Response Handler is Added
2,965
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
else { return (.performDefaultHandling, nil, nil) } do { guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { return (.performDefaultHandling, nil, nil) } try evaluator.evaluate(t...
Please adjust the whitespace here to align with the line above. You can do it manually or run `swiftformat .` at the root of the project.
else { return (.performDefaultHandling, nil, nil) } do { guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { return (.performDefaultHandling, nil, nil) } try evaluator.evaluate(t...
@@ -121,14 +121,14 @@ extension SessionDelegate: URLSessionTaskDelegate { } } - /// Evaluates the HTTP authentication `URLAuthenticationChallenge` received for `task`. + /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. /// /// - Paramete...
Source/SessionDelegate.swift
26
Swift
0.5
suggestion
137
51
51
false
Accept NTLM and Negotiate as valid authentication methods
2,975
Alamofire/Alamofire
41,690
Swift
jshier
akashivskyy
} } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription ...
`[Data]` is no longer necessary, as you're already printing it as a `String`. It can be removed.
} } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription ...
@@ -131,15 +131,20 @@ extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. publ...
Source/Response.swift
26
Swift
0.429
suggestion
96
51
51
false
feat (Response) : update debugDescription
2,976
Alamofire/Alamofire
41,690
Swift
jshier
rain2540
self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertibl...
You've misspelled `Description` here. Please correct it.
self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible...
@@ -383,18 +388,21 @@ extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertibl /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serializati...
Source/Response.swift
26
Swift
0.357
suggestion
56
51
51
false
feat (Response) : update debugDescription
2,976
Alamofire/Alamofire
41,690
Swift
jshier
rain2540
result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConv...
Sorry, didn't notice it before, but `Description` is misspelled here too.
result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConv...
@@ -131,15 +131,19 @@ extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. publ...
Source/Response.swift
26
Swift
0.357
suggestion
73
51
51
false
feat (Response) : update debugDescription
2,976
Alamofire/Alamofire
41,690
Swift
jshier
rain2540
// When AF.request(urlString).responseData { resp in response = resp.tryMapError { TestError.error(error: $0) } expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAss...
We prefer extensions on the `AFError` type itself, not the response type, otherwise we need separate extensions for every response.
// // ResponseTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -672,8 +672,27 @@ final class ResponseTryMapErrorTestCase: BaseTestCase { else { XCTFail(); return } XCTAssertEqual(underlyingError.asAFError?.isSessionTaskError, true) - XCTAssertEqual((underlyingError.asAFError?.underlyingError as? URLError)?.code, .cannotFindHost) - + XCTAssertEq...
Tests/ResponseTests.swift
26
Swift
0.714
suggestion
131
45
679
false
Response test host error fix
3,003
Alamofire/Alamofire
41,690
Swift
jshier
tronthomas
waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNil(response?.response) XCTAssertNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) guard let error = response?.error as? TestError, ...
You can put this in the `AFError+AlamofireTests.swift` file alongside our other `is*` convenience properties. Additionally, you can simplify the property down to: ```swift return [.cannotConnectToHost, .cannotFindHost].contains((underlyingError as? URLError)?.code) ```
// // ResponseTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -672,8 +672,27 @@ final class ResponseTryMapErrorTestCase: BaseTestCase { else { XCTFail(); return } XCTAssertEqual(underlyingError.asAFError?.isSessionTaskError, true) - XCTAssertEqual((underlyingError.asAFError?.underlyingError as? URLError)?.code, .cannotFindHost) - + XCTAssertEq...
Tests/ResponseTests.swift
26
Swift
1
refactor
276
39
679
false
Response test host error fix
3,003
Alamofire/Alamofire
41,690
Swift
jshier
tronthomas
XCTAssertNil(response?.response) XCTAssertNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) guard let error = response?.error as? TestError, case let .error(underlyingError) = error else { XCTFail(); return } XCTAssertEqual(underlyingError...
I don't think a separate property is necessary here, and it's not really appropriate to fall back to the `.unknown` case rather than using `nil`.
// // ResponseTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -672,8 +672,27 @@ final class ResponseTryMapErrorTestCase: BaseTestCase { else { XCTFail(); return } XCTAssertEqual(underlyingError.asAFError?.isSessionTaskError, true) - XCTAssertEqual((underlyingError.asAFError?.underlyingError as? URLError)?.code, .cannotFindHost) - + XCTAssertEq...
Tests/ResponseTests.swift
26
Swift
0.5
suggestion
145
34
679
false
Response test host error fix
3,003
Alamofire/Alamofire
41,690
Swift
jshier
tronthomas
case let .error(underlyingError) = error else { XCTFail(); return } XCTAssertEqual(underlyingError.asAFError?.isSessionTaskError, true) XCTAssertEqual(underlyingError.asAFError?.isHostURLError, true) XCTAssertNotNil(response?.metrics) } } private extension DataResponse ...
You can inline this check pretty easily, so no need to have a separate declaration.
// // ResponseTests.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -672,8 +672,27 @@ final class ResponseTryMapErrorTestCase: BaseTestCase { else { XCTFail(); return } XCTAssertEqual(underlyingError.asAFError?.isSessionTaskError, true) - XCTAssertEqual((underlyingError.asAFError?.underlyingError as? URLError)?.code, .cannotFindHost) - + XCTAssertEq...
Tests/ResponseTests.swift
26
Swift
0.214
suggestion
83
29
679
false
Response test host error fix
3,003
Alamofire/Alamofire
41,690
Swift
jshier
tronthomas
XCTAssertNotNil(response?.metrics) } func testThatTryMapPreservesFailureError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<Stri...
This should be structured similar to the previous line, where we compare the value optionally.
XCTAssertNotNil(response?.metrics) } func testThatTryMapPreservesFailureError() { // Given let urlString = "https://invalid-url-here.org/this/does/not/exist" let expectation = self.expectation(description: "request should fail with 404") var response: DataResponse<Stri...
@@ -518,7 +518,7 @@ final class ResponseTryMapTestCase: BaseTestCase { XCTAssertNil(response?.data) XCTAssertEqual(response?.result.isFailure, true) XCTAssertEqual(response?.error?.asAFError?.isSessionTaskError, true) - XCTAssertEqual((response?.error?.asAFError?.underlyingError as? UR...
Tests/ResponseTests.swift
26
Swift
0.286
suggestion
94
51
51
false
Response test host error fix
3,003
Alamofire/Alamofire
41,690
Swift
jshier
tronthomas
init() { mutex = .allocate(capacity: 1) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK)) let err = pthread_mutex_init(mutex, &attr) precondition(err == 0, "Failed to create pthread_mute...
This might be better specified as a positive check for Apple platforms to better support arbitrary future platforms. ```suggestion #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) ```
init() { mutex = .allocate(capacity: 1) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK)) let error = pthread_mutex_init(mutex, &attr) precondition(error == 0, "Failed to create pthread_...
@@ -24,10 +24,64 @@ import Foundation -// MARK: - +private protocol Lock { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value t...
Source/Protected.swift
26
Swift
0.786
suggestion
189
51
51
false
Linux Preparation
3,115
Alamofire/Alamofire
41,690
Swift
SlaunchaMan
jshier
deinit { unfairLock.deinitialize(count: 1) unfairLock.deallocate() } fileprivate func lock() { os_unfair_lock_lock(unfairLock) } fileprivate func unlock() { os_unfair_lock_unlock(unfairLock) } } #endif /// A thread-safe wrapper around a value. @propertyWrappe...
As before, doing this without calling out Linux specifically would look like this: ```suggestion #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) private let lock = UnfairLock() #elseif os(Linux) private let lock = MutexLock() #endif ```
unfairLock = .allocate(capacity: 1) unfairLock.initialize(to: os_unfair_lock()) } deinit { unfairLock.deinitialize(count: 1) unfairLock.deallocate() } fileprivate func lock() { os_unfair_lock_lock(unfairLock) } fileprivate func unlock() { os_unf...
@@ -40,38 +94,26 @@ final class UnfairLock { unfairLock.deallocate() } - private func lock() { + fileprivate func lock() { os_unfair_lock_lock(unfairLock) } - private func unlock() { + fileprivate func unlock() { os_unfair_lock_unlock(unfairLock) } - - /// Ex...
Source/Protected.swift
26
Swift
0.786
suggestion
267
51
51
false
Linux Preparation
3,115
Alamofire/Alamofire
41,690
Swift
SlaunchaMan
jshier
private var mutex: UnsafeMutablePointer<pthread_mutex_t> init() { mutex = .allocate(capacity: 1) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK)) let err = pthread_mutex_init(mutex, &attr) ...
```suggestion #if os(Linux) final class MutexLock: Lock { private var mutex: UnsafeMutablePointer<pthread_mutex_t> init() { mutex = .allocate(capacity: 1) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, .init(PTHREAD_MUT...
final class MutexLock: Lock { private var mutex: UnsafeMutablePointer<pthread_mutex_t> init() { mutex = .allocate(capacity: 1) var attr = pthread_mutexattr_t() pthread_mutexattr_init(&attr) pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK)) let error = p...
@@ -24,10 +24,64 @@ import Foundation -// MARK: - +private protocol Lock { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value t...
Source/Protected.swift
26
Swift
0.929
bug
695
51
51
false
Linux Preparation
3,115
Alamofire/Alamofire
41,690
Swift
SlaunchaMan
jshier
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation private protocol Lock { func lock() func unlock() } extension Lock { /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to ...
Is there a reason to include this version? The project builds and the tests pass without it; I’m assuming the compiler can infer `T` as `Void` if it needs to.
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation private protocol Lock { func lock() func unlock() } extension Lock { /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to ...
@@ -24,10 +24,65 @@ import Foundation -// MARK: - +private protocol Lock { + func lock() + func unlock() +} + +extension Lock { + /// Executes a closure returning a value while acquiring the lock. + /// + /// - Parameter closure: The closure to run. + /// + /// - Returns: The value t...
Source/Protected.swift
26
Swift
0.5
suggestion
158
51
51
false
Linux Preparation
3,115
Alamofire/Alamofire
41,690
Swift
SlaunchaMan
jshier
uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) } } /// Perform a closure on the current `state` while locked. /// /// - Parameter perform: The closure to perform. func withState(perform: (State) -> Void) { protectedMutableState.withStat...
This is definitely key for retry to work correctly. 👍🏻
serializationQueue.async { responseSerializer() } } /// Notifies the `Request` that the response serializer is complete. /// /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers /// are complete. f...
@@ -556,7 +564,10 @@ public class Request { downloadProgress.totalUnitCount = 0 downloadProgress.completedUnitCount = 0 - protectedMutableState.write { $0.responseSerializerCompletions = [] } + protectedMutableState.write { state in + state.isFinishing = false + s...
Source/Request.swift
26
Swift
0.214
suggestion
54
51
51
false
Prevent Multiple finish() Calls
3,116
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
serverKeys: trust.af.publicKeys)) } } } /// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the /// evaluators consider it valid. public final class CompositeTrustEv...
This should also include the `renamed` parameter, and should be rephrased. ```suggestion @available(*, deprecated, renamed: "DisabledTrustEvaluator", message: "DisabledEvaluator has been renamed DisabledTrustEvaluator.") ```
serverKeys: trust.af.publicKeys)) } } } /// Uses the provided evaluators to validate the server trust. The trust is only considered valid if all of the /// evaluators consider it valid. public final class CompositeTrustEv...
@@ -335,7 +335,10 @@ public final class CompositeTrustEvaluator: ServerTrustEvaluating { /// Disables all evaluation which in turn will always consider any server trust as valid. /// /// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** -public final class DisabledEvaluator: ServerTrustEvaluating { +@available(...
Source/ServerTrustEvaluation.swift
26
Swift
0.857
suggestion
229
51
51
false
Changed DisabledEvaluator to DisabledTrustEvaluator
3,162
Alamofire/Alamofire
41,690
Swift
jshier
MrCloud
/// evaluators consider it valid. public final class CompositeTrustEvaluator: ServerTrustEvaluating { private let evaluators: [ServerTrustEvaluating] /// Creates a `CompositeTrustEvaluator`. /// /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. public...
Please copy the previous doc comment to this type, in addition to the `typealias`.
/// evaluators consider it valid. public final class CompositeTrustEvaluator: ServerTrustEvaluating { private let evaluators: [ServerTrustEvaluating] /// Creates a `CompositeTrustEvaluator`. /// /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. public...
@@ -335,7 +335,10 @@ public final class CompositeTrustEvaluator: ServerTrustEvaluating { /// Disables all evaluation which in turn will always consider any server trust as valid. /// /// **THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION!** -public final class DisabledEvaluator: ServerTrustEvaluating { +@available(...
Source/ServerTrustEvaluation.swift
26
Swift
0.5
suggestion
82
51
51
false
Changed DisabledEvaluator to DisabledTrustEvaluator
3,162
Alamofire/Alamofire
41,690
Swift
jshier
MrCloud
/// - request: `Request` that failed due to the provided `Error`. /// - error: `Error` encountered while executing the `Request`. /// - Returns: `true` if `request` HTTP method is contained in the retryable HTTP methods and `request` response or `error` contain any of the retryable statuses and c...
It doesn't make sense to allow overriding of the delay calculation, as `RetryPolicy` was designed around geometric backoff and doesn't really make sense without it.
open func shouldRetry(request: Request, dueTo error: Error) -> Bool { guard let httpMethod = request.request?.method, retryableHTTPMethods.contains(httpMethod) else { return false } if let statusCode = request.response?.statusCode, retryableHTTPStatusCodes.contains(statusCode) { ...
@@ -309,31 +309,49 @@ open class RetryPolicy: RequestInterceptor { for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { - if - request.retryCount < retryLimit, - let httpMethod = request.reque...
Source/RetryPolicy.swift
26
Swift
0.5
suggestion
164
51
46
false
adding more flexibility in reusing RetryPolicy
3,181
Alamofire/Alamofire
41,690
Swift
jshier
Skoti
serverTrustManager: serverTrustManager, redirectHandler: redirectHandler, cachedResponseHandler: cachedResponseHandler, eventMonitors: eventMonitors) } deinit { finishRequestsForDeinit() session.invalidateAndCancel() } ...
This API doesn't really match our other APIs conventions with `completion` closures. Would the following make more sense? ```swift public func withAllRequests( perform action: @escaping (Request) -> Void, queue: DispatchQueue = .main, completion: (() -> Void)? = nil) ``` This would also put the p...
serverTrustManager: serverTrustManager, redirectHandler: redirectHandler, cachedResponseHandler: cachedResponseHandler, eventMonitors: eventMonitors) } deinit { finishRequestsForDeinit() session.invalidateAndCancel() } ...
@@ -204,7 +204,29 @@ open class Session { session.invalidateAndCancel() } - // MARK: - Cancellation + // MARK: - All Requests API + + /// Perform an action on all active `Request`s, optionally calling a completion handler when complete. + /// + /// - Note: The provided `action` closure is...
Source/Session.swift
26
Swift
0.786
question
454
51
51
false
On Hold: Add withAllRequests API
3,200
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// - Parameter handler: The `CachedResponseHandler`. /// /// - Returns: The instance. @discardableResult public func cacheResponse(using handler: CachedResponseHandler) -> Self { $mutableState.write { mutableState in precondition(mutableState.cachedResponseHandler == n...
As a note, this is not truly an API compatible change, so needs to change.
/// - Parameter handler: The `CachedResponseHandler`. /// /// - Returns: The instance. @discardableResult public func cacheResponse(using handler: CachedResponseHandler) -> Self { $mutableState.write { mutableState in precondition(mutableState.cachedResponseHandler == n...
@@ -816,17 +831,65 @@ public class Request { /// /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called. /// - /// - Parameter handler: Closure to be called when the cURL description is available. + /// - Parameters: + /// - queue: `Disp...
Source/Request.swift
26
Swift
0.286
suggestion
74
51
51
false
Lifetime Event APIs
3,219
Alamofire/Alamofire
41,690
Swift
jshier
jshier
usingThreshold: 0).response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFai...
```suggestion func testThatUploadingMultipartFormDataWithNonexistentFileThrowsAnError() { ``` This can be made a bit easier to read.
usingThreshold: 0).response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFai...
@@ -518,6 +518,32 @@ class UploadMultipartFormDataTestCase: BaseTestCase { XCTFail("Content-Type header value should not be nil") } } + + func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() {
Tests/UploadTests.swift
26
Swift
0.857
suggestion
141
51
51
false
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
jshier
sudopark
expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFail("Uploadable is not .file") return } XCTAssertTrue(response?.result....
```suggestion let urlString = URL.makeHTTPBinURL(path: "post") ``` We have APIs for generating our URLs which should be used instead of raw `String`s.
expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFail("Uploadable is not .file") return } XCTAssertTrue(response?.result....
@@ -518,6 +518,32 @@ class UploadMultipartFormDataTestCase: BaseTestCase { XCTFail("Content-Type header value should not be nil") } } + + func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() { + // Given + let urlString = "https://httpbin.org/post"
Tests/UploadTests.swift
26
Swift
0.786
suggestion
163
51
51
false
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
jshier
sudopark
waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFail("Uploadable is not .file") return } XCTAssertTrue(response?.result.isSuccess == true) if le...
```suggestion let expectation = self.expectation(description: "multipart form data upload from nonexistent file should fail") ``` Again, this can be made a bit easier to read.
waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFail("Uploadable is not .file") return } XCTAssertTrue(response?.result.isSuccess == true) if le...
@@ -518,6 +518,32 @@ class UploadMultipartFormDataTestCase: BaseTestCase { XCTFail("Content-Type header value should not be nil") } } + + func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() { + // Given + let urlString = "https://httpbin.org/post" + ...
Tests/UploadTests.swift
26
Swift
0.786
bug
188
51
51
false
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
jshier
sudopark
} waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFail("Uploadable is not .file") return } XCTAssertTrue(response?.result.isSuccess == true) if ...
```suggestion let imageURL = URL(fileURLWithPath: "does_not_exist.jpg") ``` This makes it a bit safer.
} waitForExpectations(timeout: timeout, handler: nil) // Then guard let uploadable = request.uploadable, case .file = uploadable else { XCTFail("Uploadable is not .file") return } XCTAssertTrue(response?.result.isSuccess == true) if ...
@@ -518,6 +518,32 @@ class UploadMultipartFormDataTestCase: BaseTestCase { XCTFail("Content-Type header value should not be nil") } } + + func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() { + // Given + let urlString = "https://httpbin.org/post" + ...
Tests/UploadTests.swift
26
Swift
0.714
suggestion
115
51
51
false
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
jshier
sudopark
let contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUpl...
```suggestion waitForExpectations(timeout: timeout) ``` `handler` is unnecessary when `nil`.
let contentType = request.value(forHTTPHeaderField: "Content-Type") { XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match") } else { XCTFail("Content-Type header value should not be nil") } } func testThatUploadi...
@@ -518,6 +518,32 @@ class UploadMultipartFormDataTestCase: BaseTestCase { XCTFail("Content-Type header value should not be nil") } } + + func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() { + // Given + let urlString = "https://httpbin.org/post" + ...
Tests/UploadTests.swift
26
Swift
0.857
suggestion
105
51
51
false
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
jshier
sudopark
} } func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() { // Given let urlString = "https://httpbin.org/post" let imageURL = URL(string: "file://not_exists_file.jpg")! let expectation = self.expectation(description: "multipart form data upload with w...
```suggestion XCTAssertNil(request.uploadable) ``` Since the `uploadable` value isn't being used it can just be checked inline.
} } func testThatUploadingMultipartFormDataWithNonexistentFileThrowsAnError() { // Given let urlString = URL.makeHTTPBinURL(path: "post") let imageURL = URL(fileURLWithPath: "does_not_exist.jpg") let expectation = self.expectation(description: "multipart form data uploa...
@@ -518,6 +518,32 @@ class UploadMultipartFormDataTestCase: BaseTestCase { XCTFail("Content-Type header value should not be nil") } } + + func testThatUploadingMultipartFormDataWithNotExistFileShouldFail() { + // Given + let urlString = "https://httpbin.org/post" + ...
Tests/UploadTests.swift
26
Swift
0.786
suggestion
140
51
51
false
Fix to throw an error in MultipartUpload when copying a file to a temporary path fails.
3,306
Alamofire/Alamofire
41,690
Swift
jshier
sudopark
let expect = expectation(description: "request should complete") var response: AFDataResponse<Data?>? // When let request = session.request(urlRequest, interceptor: compositeInterceptor).validate().response { response = $0 expect.fulfill() } wai...
This test case could likely use some simplification.
let expect = expectation(description: "request should complete") var response: AFDataResponse<Data?>? // When let request = session.request(urlRequest, interceptor: compositeInterceptor).validate().response { response = $0 expect.fulfill() } wai...
@@ -447,10 +455,57 @@ class AuthenticationInterceptorTestCase: BaseTestCase { XCTAssertEqual(request.retryCount, 1) } + // Produces double lock reported in https://github.com/Alamofire/Alamofire/issues/3294#issuecomment-703241558 + func testThatInterceptorNeedingImmediateRefreshWithSynchronouslyRe...
Tests/AuthenticationInterceptorTests.swift
26
Swift
0.286
suggestion
52
51
51
false
Fix Double Lock in AuthenticationInterceptor
3,322
Alamofire/Alamofire
41,690
Swift
jshier
jshier
/// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. case bodyPartFilenameInvalid(in: URL) /// The file at the `fileURL` provided was not reachable. case bodyPartFileNotReachable(at: URL) /// Attempting to check the reachability of...
Adding cases to `AFError` unfortunately requires a major version bump. In the mean time, a custom `Error` type that can fit into `inputStreamReadFailed` could serve the same purpose.
/// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension. case bodyPartFilenameInvalid(in: URL) /// The file at the `fileURL` provided was not reachable. case bodyPartFileNotReachable(at: URL) /// Attempting to check the reachability of...
@@ -55,6 +55,8 @@ public enum AFError: Error { case outputStreamWriteFailed(error: Error) /// The attempt to read an encoded body part `InputStream` failed with underlying system error. case inputStreamReadFailed(error: Error) + /// The data read from an body part `InputStream` has une...
Source/AFError.swift
26
Swift
0.714
bug
182
51
51
false
Ensure that the encoded body stream data has expected length
3,380
Alamofire/Alamofire
41,690
Swift
jshier
YuAo
return Data(headerText.utf8) } private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } var encoded = Data() while inputStream.hasBytesAvailable { v...
This would be better expressed as a `guard`.
return Data(headerText.utf8) } private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { let inputStream = bodyPart.bodyStream inputStream.open() defer { inputStream.close() } var encoded = Data() while inputStream.hasBytesAvailable { v...
@@ -418,6 +418,10 @@ open class MultipartFormData { break } } + + if UInt64(encoded.count) != bodyPart.bodyContentLength {
Source/MultipartFormData.swift
26
Swift
0.286
suggestion
44
51
51
false
Ensure that the encoded body stream data has expected length
3,380
Alamofire/Alamofire
41,690
Swift
jshier
YuAo
// Then XCTAssertNotNil(encodingError, "encoding error should not be nil") XCTAssertEqual(encodingError?.asAFError?.isOutputStreamURLInvalid, true) } func testThatStreamBodyPartHasUnexpectedLength() { // Given let multipartFormData = MultipartFormData() let d...
This comment is unnecessary, unless you'd like to explain why we'd expect an error now.
// Then XCTAssertNotNil(encodingError, "encoding error should not be nil") XCTAssertEqual(encodingError?.asAFError?.isOutputStreamURLInvalid, true) } func testThatStreamBodyPartHasUnexpectedLength() { // Given let multipartFormData = MultipartFormData() let d...
@@ -918,4 +918,33 @@ class MultipartFormDataFailureTestCase: BaseTestCase { XCTAssertNotNil(encodingError, "encoding error should not be nil") XCTAssertEqual(encodingError?.asAFError?.isOutputStreamURLInvalid, true) } + + func testThatStreamBodyPartHasUnexpectedLength() { + // Given...
Tests/MultipartFormDataTests.swift
26
Swift
0.357
suggestion
87
35
35
false
Ensure that the encoded body stream data has expected length
3,380
Alamofire/Alamofire
41,690
Swift
jshier
YuAo
let fileURL = URL(string: "/this/is/not/a/valid/url")! let multipartFormData = MultipartFormData() let data = Data("Lorem ipsum dolor sit amet.".utf8) multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multip...
This error belongs to the `Given` section.
let fileURL = URL(string: "/this/is/not/a/valid/url")! let multipartFormData = MultipartFormData() let data = Data("Lorem ipsum dolor sit amet.".utf8) multipartFormData.append(data, withName: "data") var encodingError: Error? // When do { try multip...
@@ -918,4 +918,33 @@ class MultipartFormDataFailureTestCase: BaseTestCase { XCTAssertNotNil(encodingError, "encoding error should not be nil") XCTAssertEqual(encodingError?.asAFError?.isOutputStreamURLInvalid, true) } + + func testThatStreamBodyPartHasUnexpectedLength() { + // Given...
Tests/MultipartFormDataTests.swift
26
Swift
0.357
suggestion
42
50
50
false
Ensure that the encoded body stream data has expected length
3,380
Alamofire/Alamofire
41,690
Swift
jshier
YuAo
public enum Downloadable { /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. case request(URLRequestConvertible) /// Download should be started from the associated resume `Data` value. case resumeData(Data) } // MA...
Return the `error?.downloadResumeData` in computed property may not be a good solution. It will still get wrong data when other developers use `mutableDownloadState` internally. In my view, a better solution is to assign `error?.downloadResumeData` directly to `mutableDownloadState`.
public enum Downloadable { /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value. case request(URLRequestConvertible) /// Download should be started from the associated resume `Data` value. case resumeData(Data) } // MA...
@@ -1528,11 +1528,11 @@ public class DownloadRequest: Request { @Protected private var mutableDownloadState = DownloadRequestMutableState() - /// If the download is resumable and eventually cancelled, this value may be used to resume the download using the - /// `download(resumingWith data:)` API. + ...
Source/Request.swift
26
Swift
0.786
bug
287
51
51
false
Add Support for Resume Data on Error
3,419
Alamofire/Alamofire
41,690
Swift
LucasXu0
jshier
multipartFormData.append(japaneseData, withName: "japanese") } } let request = MultipartFormDataRequest() let expectation = self.expectation(description: "multipart form data upload should succeed") var response: DataResponse<Data?, AFError>? // Whe...
Our usual style is `case let`, so make sure to run the formatter and it'll fix it.
multipartFormData.append(japaneseData, withName: "japanese") } } let request = MultipartFormDataRequest() let expectation = self.expectation(description: "multipart form data upload should succeed") var response: DataResponse<Data?, AFError>? // Whe...
@@ -580,6 +580,54 @@ final class UploadMultipartFormDataTestCase: BaseTestCase { XCTAssertTrue(response?.result.isSuccess == false) } + func testThatUploadingMultipartFormDataWorksWhenAppendingBodyPartsInURLRequestConvertible() { + // Given + struct MultipartFormDataRequest: URLRequestC...
Tests/UploadTests.swift
26
Swift
0.357
style
82
51
51
false
Multipart Form Data Encoding Fix
3,438
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
deinit { let error = pthread_mutex_destroy(mutex) precondition(error == 0, "Failed to destroy pthread_mutex") } fileprivate func lock() { let error = pthread_mutex_lock(mutex) precondition(error == 0, "Failed to lock pthread_mutex") } fileprivate func unlock() { ...
I may be better, at least for this initial version, to wrap `NSLock` on Windows. I don't understand the Windows locking primitives at all, so it would probably be better to use an implementation that has already been proven.
deinit { unfairLock.deinitialize(count: 1) unfairLock.deallocate() } fileprivate func lock() { os_unfair_lock_lock(unfairLock) } fileprivate func unlock() { os_unfair_lock_unlock(unfairLock) } } #endif /// A thread-safe wrapper around a value. @propertyWrapper ...
@@ -82,6 +82,45 @@ final class MutexLock: Lock { } #endif +#if os(Windows) +import WinSDK +private func randomString(length: Int) -> String { + let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + return String((0..<length).map{ _ in letters.randomElement()! }) +} + +/// A `CreateM...
Source/Protected.swift
26
Swift
0.643
suggestion
225
51
51
false
Initial Windows Support
3,462
Alamofire/Alamofire
41,690
Swift
jshier
alex-taffe
extension Lock { /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to run. /// /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure()...
Do we need this at all? Shouldn't `NSLock` check this itself?
extension Lock { /// Executes a closure returning a value while acquiring the lock. /// /// - Parameter closure: The closure to run. /// /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure()...
@@ -49,35 +49,27 @@ extension Lock { } } -#if os(Linux) -/// A `pthread_mutex_t` wrapper. -final class MutexLock: Lock { - private var mutex: UnsafeMutablePointer<pthread_mutex_t> - - init() { - mutex = .allocate(capacity: 1) - - var attr = pthread_mutexattr_t() - pthread_mutexattr_in...
Source/Protected.swift
26
Swift
0.429
question
61
51
51
false
Initial Windows Support
3,462
Alamofire/Alamofire
41,690
Swift
jshier
alex-taffe
// // Combine.swift // // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
this check must be broader to check for windows and linux that doesn't support Combine framework
// // Combine.swift // // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including wi...
@@ -22,7 +22,7 @@ // THE SOFTWARE. // -#if canImport(Combine) +#if !(os(iOS) && (arch(i386) || arch(arm)))
Source/Combine.swift
25
Swift
0.214
suggestion
96
50
50
false
Xcode 13 Support
3,486
Alamofire/Alamofire
41,690
Swift
jlcvp
jshier
adapted = true completion(.success(request)) } var result: Result<URLRequest, Error>! // When adapter.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(adapted) XCTAssertTrue(result.isSuccess) } func testThat...
I would suggest capturing the `UUID` separately and then comparing the values returned from the adaptation to those provided in the `RequestAdapterState`, just to ensure they're round tripping appropriately.
adapted = true completion(.success(request)) } var result: Result<URLRequest, Error>! // When adapter.adapt(urlRequest, for: session) { result = $0 } // Then XCTAssertTrue(adapted) XCTAssertTrue(result.isSuccess) } func testThat...
@@ -99,6 +99,29 @@ final class AdapterTestCase: BaseTestCase { XCTAssertTrue(result.isSuccess) } + func testThatAdapterCallsAdaptHandlerWithStateAPI() { + // Given + let urlRequest = Endpoint().urlRequest + let session = Session() + var adapted = false + + let adapt...
Tests/RequestInterceptorTests.swift
26
Swift
0.571
suggestion
207
51
51
false
Request Adapter State
3,504
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
let contentTypes: () -> [String] = { [unowned self] in self.acceptableContentTypes } return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } } // MARK: - extension DownloadRequest { /// A closure used to validate a request that takes a URL...
Please keep the extra line between the parameter and return.
@discardableResult public func validate() -> Self { let contentTypes: () -> [String] = { [unowned self] in self.acceptableContentTypes } return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) } } // MARK: - extension DownloadRequest { ...
@@ -253,9 +251,8 @@ extension DownloadRequest { /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// - /// - Parameter statusCode: `Sequence` of acceptable response status codes. - /// - /// - Returns: The instance. + /// - Paramet...
Source/Validation.swift
26
Swift
0.214
suggestion
60
51
51
false
Fixes for parameters in doc comments throughout the project
3,511
Alamofire/Alamofire
41,690
Swift
jshier
evnik
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - returns...
Please keep the extra line between the parameter and return.
/// Validates that the response has a status code in the default acceptable range of 200...299, and that the content /// type matches any specified in the Accept HTTP header field. /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// /// - return...
@@ -200,9 +199,8 @@ extension DataStreamRequest { /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// - /// - Parameter statusCode: `Sequence` of acceptable response status codes. - /// - /// - Returns: The instance. + /// - Param...
Source/Validation.swift
26
Swift
0.214
suggestion
60
51
51
false
Fixes for parameters in doc comments throughout the project
3,511
Alamofire/Alamofire
41,690
Swift
jshier
evnik
} } let error: AFError = { let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType) return AFError.responseValid...
Please keep the extra line between the parameter and return.
} } let error: AFError = { let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType) return AFError.responseValid...
@@ -152,9 +152,8 @@ extension DataRequest { /// /// If validation fails, subsequent calls to response handlers will have an associated error. /// - /// - Parameter statusCode: `Sequence` of acceptable response status codes. - /// - /// - Returns: The instance. + /// - Parameter a...
Source/Validation.swift
26
Swift
0.214
suggestion
60
51
51
false
Fixes for parameters in doc comments throughout the project
3,511
Alamofire/Alamofire
41,690
Swift
jshier
evnik
/// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public func publishString(queue: DispatchQueue = .main, preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, ...
This should actually be `emptyRequestMethods` to match the underlying function call. We can leave it for now or you can create a properly named method and deprecate this one, copying the docs from this method and then removing them. The deprecated method could then call through to the proper method.
/// - Returns: The `DownloadResponsePublisher`. @available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) public func publishString(queue: DispatchQueue = .main, preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor, ...
@@ -571,17 +571,17 @@ extension DownloadRequest { /// response. /// /// - Parameters: - /// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default. - /// - queue: `DispatchQueue` on which the `DataResponse` will be publishe...
Source/Combine.swift
26
Swift
0.643
suggestion
300
51
51
false
Fixes for parameters in doc comments throughout the project
3,511
Alamofire/Alamofire
41,690
Swift
jshier
evnik
/// resulting URL request. public enum Destination { /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and /// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded qu...
```suggestion /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. ```
/// resulting URL request. public enum Destination { /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and /// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded qu...
@@ -85,13 +85,17 @@ public struct URLEncoding: ParameterEncoding { case brackets /// No brackets are appended. The key is encoded as is. case noBrackets + /// Brackets containing the item index appended. This matches the jQuery and Node.js behavior.
Source/ParameterEncoding.swift
26
Swift
0.714
suggestion
126
51
51
false
Add .indexInBrackets array serialization option for URL parameters
3,516
Alamofire/Alamofire
41,690
Swift
jshier
TiagoMaiaL
/// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded query string result to existing query string. case queryString /// Sets encoded query string result as the HTTP body of the URL request. case httpBody ...
I'd suggest something like `encode(key: String, atIndex index: Int)` to better match Swift's naming guidelines to make the usage a bit more fluent.
/// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded query string result to existing query string. case queryString /// Sets encoded query string result as the HTTP body of the URL request. case httpBody ...
@@ -85,13 +85,17 @@ public struct URLEncoding: ParameterEncoding { case brackets /// No brackets are appended. The key is encoded as is. case noBrackets + /// Brackets containing the item index appended. This matches the jQuery and Node.js behavior. + case indexInBrackets - ...
Source/ParameterEncoding.swift
26
Swift
0.571
suggestion
147
51
51
false
Add .indexInBrackets array serialization option for URL parameters
3,516
Alamofire/Alamofire
41,690
Swift
jshier
TiagoMaiaL
/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the /// square brackets appended to array keys. /// /// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. /// /// `DateEncoding`...
Now that there are multiple parameters, you can regenerate these docs using `Command - Option - /` and get a `Parameters` section instead. Also, though it was missing before, our general style is to put an empty line between the parameters and the return.
/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the /// square brackets appended to array keys. /// /// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. /// /// `DateEncoding`...
@@ -48,15 +48,19 @@ public final class URLEncodedFormEncoder { case brackets /// No brackets are appended to the key and the key is encoded as is. case noBrackets + /// Brackets containing the item index appended. This matches the jQuery and Node.js behavior. + case indexInBrack...
Source/URLEncodedFormEncoder.swift
26
Swift
0.643
suggestion
256
51
51
false
Add .indexInBrackets array serialization option for URL parameters
3,516
Alamofire/Alamofire
41,690
Swift
jshier
TiagoMaiaL
/// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. /// /// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` /// strategy is used, which formats dates from their structure. ...
Like the other `encode`, `index` would be more fluently expressed as `atIndex`.
/// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. /// /// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate` /// strategy is used, which formats dates from their structure. ...
@@ -48,15 +48,19 @@ public final class URLEncodedFormEncoder { case brackets /// No brackets are appended to the key and the key is encoded as is. case noBrackets + /// Brackets containing the item index appended. This matches the jQuery and Node.js behavior. + case indexInBrack...
Source/URLEncodedFormEncoder.swift
26
Swift
0.357
suggestion
79
51
51
false
Add .indexInBrackets array serialization option for URL parameters
3,516
Alamofire/Alamofire
41,690
Swift
jshier
TiagoMaiaL
output = alphabetizeKeyValuePairs ? output.sorted() : output return output.joinedWithAmpersands() } func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { switch component { case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(esc...
Seems you've missed the use site for the updated name.
output = alphabetizeKeyValuePairs ? output.sorted() : output return output.joinedWithAmpersands() } func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String { switch component { case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(esc...
@@ -930,8 +936,8 @@ final class URLEncodedFormSerializer { } func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String { - var segments: [String] = array.map { component in - let keyPath = arrayEncoding.encode(key) + var segments: [String] = array.enumerated()...
Source/URLEncodedFormEncoder.swift
26
Swift
0.286
suggestion
54
51
51
false
Add .indexInBrackets array serialization option for URL parameters
3,516
Alamofire/Alamofire
41,690
Swift
jshier
TiagoMaiaL
fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, !data.is...
Rather than materializing and sorting an `Array`, you can just call `sorted()` on the `acceptableContentTypes` directly: `acceptableContentTypes.sorted()`.
fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S, response: HTTPURLResponse, data: Data?) -> ValidationResult where S.Iterator.Element == String { guard let data = data, !data.is...
@@ -117,7 +117,7 @@ extension Request { } let error: AFError = { - let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableConten...
Source/Validation.swift
26
Swift
0.643
suggestion
155
51
51
false
Sort acceptable content-types in error messages
3,518
Alamofire/Alamofire
41,690
Swift
jshier
Usipov
guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .succes...
Same as the other use site, you can sort the types directly.
guard let responseContentType = response.mimeType, let responseMIMEType = MIMEType(responseContentType) else { for contentType in acceptableContentTypes { if let mimeType = MIMEType(contentType), mimeType.isWildcard { return .succes...
@@ -131,7 +131,7 @@ extension Request { } let error: AFError = { - let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), + let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes...
Source/Validation.swift
26
Swift
0.429
suggestion
60
51
51
false
Sort acceptable content-types in error messages
3,518
Alamofire/Alamofire
41,690
Swift
jshier
Usipov
.validate(contentType: ["*/json"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } ...
A single test with two items is too likely to succeed randomly. Can you add a specific test, or update this test, to use many content types, like the image content types you mentioned? That should ensure the whole list is being alphabetized.
.validate(contentType: ["*/json"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNil(requestError) XCTAssertNil(downloadError) } ...
@@ -221,14 +221,14 @@ final class ContentTypeValidationTestCase: BaseTestCase { // When AF.request(endpoint) - .validate(contentType: ["application/octet-stream"]) + .validate(contentType: ["application/octet-stream", "application/json"])
Tests/ValidationTests.swift
26
Swift
0.643
suggestion
241
51
51
false
Sort acceptable content-types in error messages
3,518
Alamofire/Alamofire
41,690
Swift
jshier
Usipov
.response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: ["application/octet-stream"]) .response { resp in downloadError = resp.error expect...
This test title doesn't really make sense, since this test is about ensuring the possible content types are sorted, not that the failure happens in the first place. I'd suggest `testThatContentTypeValidationFailureSortsPossibleContentTypes()`.
.response { resp in requestError = resp.error expectation1.fulfill() } AF.download(endpoint) .validate(contentType: ["application/octet-stream"]) .response { resp in downloadError = resp.error expect...
@@ -247,6 +247,78 @@ final class ContentTypeValidationTestCase: BaseTestCase { } } + func testThatValidationForRequestWithUnacceptableContentTypeResponseFailsWhenMultipleContentTypesAreAcceptable() {
Tests/ValidationTests.swift
26
Swift
0.714
bug
243
51
51
false
Sort acceptable content-types in error messages
3,518
Alamofire/Alamofire
41,690
Swift
jshier
Usipov
AF.download(endpoint) .validate(contentType: ["application/octet-stream"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestE...
These can be given better names. Perhaps `request1DidComplete` and `request2DidComplete`? And update the `description`s to indicate which request it's talking about.
AF.download(endpoint) .validate(contentType: ["application/octet-stream"]) .response { resp in downloadError = resp.error expectation2.fulfill() } waitForExpectations(timeout: timeout) // Then XCTAssertNotNil(requestE...
@@ -247,6 +247,78 @@ final class ContentTypeValidationTestCase: BaseTestCase { } } + func testThatValidationForRequestWithUnacceptableContentTypeResponseFailsWhenMultipleContentTypesAreAcceptable() { + // Given + let endpoint = Endpoint.xml + + let expectation1 = expectation(desc...
Tests/ValidationTests.swift
26
Swift
0.571
suggestion
165
51
51
false
Sort acceptable content-types in error messages
3,518
Alamofire/Alamofire
41,690
Swift
jshier
Usipov
/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. /// /// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, /// which encodes the keys directly from the `Encodable` implementation. /// /// `KeyPathEncoding` can be u...
```suggestion case custom((_ key: String, _ index: Int) -> String) ``` Internal labels make this a bit nicer to read.
/// encoding is used, which encodes `Date`s using their default `Encodable` implementation. /// /// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used, /// which encodes the keys directly from the `Encodable` implementation. /// /// `KeyPathEncoding` can be u...
@@ -60,6 +60,8 @@ public final class URLEncodedFormEncoder { case noBrackets /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custom((S...
Source/URLEncodedFormEncoder.swift
26
Swift
0.714
suggestion
130
51
51
false
Add ArrayEncoding.custom to URLEncodedFormEncoder and ParameterEncoding
3,699
Alamofire/Alamofire
41,690
Swift
jshier
naquin
/// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded query string result to existing query string. case queryString /// Sets encoded query string result as the HTTP body of the URL request. case httpBody ...
```suggestion case custom((_ key: String, _ index: Int) -> String) ``` Internal labels make this a bit nicer to read.
/// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded query string result to existing query string. case queryString /// Sets encoded query string result as the HTTP body of the URL request. case httpBody ...
@@ -87,6 +87,8 @@ public struct URLEncoding: ParameterEncoding { case noBrackets /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior. case indexInBrackets + /// Provide a custom array key encoding with the given closure. + case custo...
Source/ParameterEncoding.swift
26
Swift
0.714
suggestion
130
51
51
false
Add ArrayEncoding.custom to URLEncodedFormEncoder and ParameterEncoding
3,699
Alamofire/Alamofire
41,690
Swift
jshier
naquin
case .queryString: return true case .httpBody: return false } } } /// Configures how `Array` parameters are encoded. public enum ArrayEncoding { /// An empty set of square brackets is appended to the key for every value. This is the default behavior. ...
```suggestion case let .custom(encoding): return encoding(key, index) ``` Follow the existing indentation.
case .queryString: return true case .httpBody: return false } } } /// Configures how `Array` parameters are encoded. public enum ArrayEncoding { /// An empty set of square brackets is appended to the key for every value. This is the default behavior. ...
@@ -96,6 +98,7 @@ public struct URLEncoding: ParameterEncoding { return key case .indexInBrackets: return "\(key)[\(index)]" + case let .custom(encoding): return encoding(key, index)
Source/ParameterEncoding.swift
26
Swift
0.714
suggestion
139
51
51
false
Add ArrayEncoding.custom to URLEncodedFormEncoder and ParameterEncoding
3,699
Alamofire/Alamofire
41,690
Swift
jshier
naquin
let encoder = URLEncodedFormEncoder(arrayEncoding: .indexInBrackets) let parameters = ["foo": [["bar": true], ["qux": false], ["quy": true]]] // When let result = Result<String, Error> { try encoder.encode(parameters) } // Then XCTAssertEqual(result.success, "foo%5B0%5D...
```suggestion "\(key).\(index + 1)" ``` A little spacing for the index.
let encoder = URLEncodedFormEncoder(arrayEncoding: .indexInBrackets) let parameters = ["foo": [["bar": true], ["qux": false], ["quy": true]]] // When let result = Result<String, Error> { try encoder.encode(parameters) } // Then XCTAssertEqual(result.success, "foo%5B0%5D...
@@ -624,6 +624,20 @@ final class URLEncodedFormEncoderTests: BaseTestCase { XCTAssertEqual(result.success, "array=1&array=2") } + func testThatArraysCanBeEncodedWithCustomClosure() { + // Given + let encoder = URLEncodedFormEncoder(arrayEncoding: .custom({ key, index in + "\(ke...
Tests/ParameterEncoderTests.swift
26
Swift
0.571
suggestion
84
51
51
false
Add ArrayEncoding.custom to URLEncodedFormEncoder and ParameterEncoding
3,699
Alamofire/Alamofire
41,690
Swift
jshier
naquin
responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(responseRequest...
No issues found.
responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil) // Then XCTAssertNotNil(responseRequest...
@@ -27,27 +27,27 @@ import XCTest class RequestInitializationTestCase: BaseTestCase { func testRequestClassMethodWithMethodAndURL() { // Given - let URL = "http://httpbin.org/" + let URLString = "http://httpbin.org/" // When - let request = Alamofire.request(.GET, URL) + ...
Tests/RequestTests.swift
0
Swift
1
none
16
51
51
true
Created more robust data, upload and download progress tests
494
Alamofire/Alamofire
41,690
Swift
cnoon
func testURLParameterEncodeStringWithQuestionMarkKeyStringWithQuestionMarkValueParameter() { // Given let parameters = ["?foo?": "?bar?"] // When let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLReques...
No issues found.
func testURLParameterEncodeStringWithQuestionMarkKeyStringWithQuestionMarkValueParameter() { // Given let parameters = ["?foo?": "?bar?"] // When let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters) // Then XCTAssertEqual(URLReques...
@@ -35,7 +35,7 @@ class URLParameterEncodingTestCase: ParameterEncodingTestCase { let encoding: ParameterEncoding = .URL - // MARK: Tests + // MARK: Tests - Parameter Types func testURLParameterEncodeNilParameters() { // Given @@ -161,6 +161,78 @@ class URLParameterEncodingTestCase: Param...
Tests/ParameterEncodingTests.swift
0
Swift
1
none
16
51
51
true
Added parameter encoding characters along with additional documentation
504
Alamofire/Alamofire
41,690
Swift
cnoon
subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } }...
No issues found.
subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } }...
@@ -208,8 +208,8 @@ public class Manager { } public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) { - if sessionDidReceiveChallenge != nil { - ...
Source/Manager.swift
0
Swift
1
none
16
51
51
true
[Refactoring] Replace many of force unwrapping usages with optional binding and where clause
557
Alamofire/Alamofire
41,690
Swift
ikesyo
// MARK: Override Closures var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCreden...
No issues found.
// MARK: Override Closures var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCreden...
@@ -134,56 +134,6 @@ public class Request { return self } - // MARK: - Response - - /** - A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process. - */ - public typealias Serializer = (NSURL...
Source/Request.swift
0
Swift
1
none
16
51
51
true
Feature - Response Serializer Generics
593
Alamofire/Alamofire
41,690
Swift
cnoon
self.progress = NSProgress(totalUnitCount: 0) self.queue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.suspended = true if operationQueue.respondsToSelector("qualityOfServ...
No issues found.
self.progress = NSProgress(totalUnitCount: 0) self.queue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.suspended = true if operationQueue.respondsToSelector("qualityOfServ...
@@ -305,8 +305,16 @@ public class Request { if let taskDidCompleteWithError = self.taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { - if error != nil { + if let error = error { self.error = er...
Source/Request.swift
0
Swift
1
none
16
51
51
true
Feature - Download Resume Data
595
Alamofire/Alamofire
41,690
Swift
cnoon
If validation fails, subsequent calls to response handlers will have an associated error. - parameter range: The range of acceptable status codes. - returns: The request. */ public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Se...
No issues found.
If validation fails, subsequent calls to response handlers will have an associated error. - parameter range: The range of acceptable status codes. - returns: The request. */ public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Se...
@@ -130,6 +130,8 @@ extension Request { */ public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self { return validate { _, response in + guard let validData = self.delegate.data where validData.length > 0 else { return .Succe...
Source/Validation.swift
0
Swift
1
none
16
51
51
true
Feature - Content Type Validation on Empty Data
890
Alamofire/Alamofire
41,690
Swift
cnoon
guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSData()) } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." le...
No issues found.
guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSData()) } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." le...
@@ -119,16 +119,25 @@ extension Request { self.delegate.error ) - dispatch_async(queue ?? dispatch_get_main_queue()) { - let response = Response<T.SerializedObject, T.ErrorObject>( - request: self.request, - response: self.r...
Source/ResponseSerialization.swift
0
Swift
1
none
16
51
51
true
Feature - Request Timelines
1,054
Alamofire/Alamofire
41,690
Swift
cnoon
/// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completi...
No issues found.
/// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completi...
@@ -123,19 +123,18 @@ public class SessionDelegate: NSObject { // MARK: Properties - private var subdelegates: [Int: TaskDelegate] = [:] - private let subdelegateQueue = DispatchQueue(label: "Alamofire Sub Delegate Queue", attributes: .concurrent) + private var requests: [Int: Request] = [:] + priv...
Source/SessionDelegate.swift
0
Swift
1
none
16
51
51
true
Feature - Moving SessionDelegate to Store Requests
1,391
Alamofire/Alamofire
41,690
Swift
cnoon
} } // MARK: - class ResponseStringTestCase: BaseTestCase { func testThatResponseStringReturnsSuccessResultWithValidString() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataRespons...
No issues found.
} } // MARK: - class ResponseStringTestCase: BaseTestCase { func testThatResponseStringReturnsSuccessResultWithValidString() { // Given let urlString = "https://httpbin.org/get" let expectation = self.expectation(description: "request should succeed") var response: DataRespons...
@@ -26,6 +26,62 @@ import Alamofire import Foundation import XCTest +class ResponseTestCase: BaseTestCase { + func testThatResponseReturnsSuccessResultWithValidData() { + // Given + let urlString = "https://httpbin.org/get" + let expectation = self.expectation(description: "request should su...
Tests/ResponseTests.swift
0
Swift
1
none
16
51
51
true
Feature - Task Metrics
1,492
Alamofire/Alamofire
41,690
Swift
cnoon
XCTAssertNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.data?.count, 0) XCTAssertNotNil(response?.error) if let error = response?.error as? AFError { XCTAssertTrue(error.isInvalidURLError) ...
No issues found.
XCTAssertNil(response?.request) XCTAssertNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertEqual(response?.data?.count, 0) XCTAssertNotNil(response?.error) if let error = response?.error as? AFError { XCTAssertTrue(error.isInvalidURLError) ...
@@ -52,11 +52,15 @@ class SessionManagerTestCase: BaseTestCase { private class RequestHandler: RequestAdapter, RequestRetrier { var adaptedCount = 0 var retryCount = 0 + var shouldApplyAuthorizationHeader = false var throwsErrorOnSecondAdapt = false func adapt(_ urlRe...
Tests/SessionManagerTests.swift
0
Swift
1
none
16
51
51
true
Feature - Throwing Adapt Error Calls Retrier
1,682
Alamofire/Alamofire
41,690
Swift
cnoon
do { self = try .success(value()) } catch { self = .failure(error) } } /// Returns the success value, or throws the failure error. /// /// let possibleString: Result<String> = .success("success") /// try print(possibleString.unwrap()) /// ...
No issues found.
do { self = try .success(value()) } catch { self = .failure(error) } } /// Returns the success value, or throws the failure error. /// /// let possibleString: Result<String> = .success("success") /// try print(possibleString.unwrap()) /// ...
@@ -162,7 +162,7 @@ extension Result { /// try print(noInt.unwrap()) /// // Throws error /// - /// - parameter transform: A closure that takes the success value of the result instance. + /// - parameter transform: A closure that takes the success value of the `Result` instance. /// ...
Source/Result.swift
0
Swift
1
none
16
51
51
true
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
jshier
return try URLEncoding.default.encode(request, with: headers) } catch { return request } } return request } override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { return false } // MARK:...
No issues found.
return try URLEncoding.default.encode(request, with: headers) } catch { return request } } return request } override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { return false } // MARK:...
@@ -92,15 +92,15 @@ class ProxyURLProtocol: URLProtocol { // MARK: - -extension ProxyURLProtocol: URLSessionDelegate { +extension ProxyURLProtocol: URLSessionDataDelegate { // MARK: NSURLSessionDelegate - func URLSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: Data) { ...
Tests/URLProtocolTests.swift
0
Swift
1
none
16
51
51
true
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
jshier
/// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'...
No issues found.
/// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. public func escape(_ string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'...
@@ -223,9 +223,9 @@ public struct URLEncoding: ParameterEncoding { let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex - let substring = string.substring(with: range) + ...
Source/ParameterEncoding.swift
0
Swift
1
none
16
51
51
true
Fixed `substring` API warnings for Swift 3.2 and up
2,240
Alamofire/Alamofire
41,690
Swift
htinlinn
if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value)...
No issues found.
if session.configuration.httpShouldSetCookies { if let cookieStorage = session.configuration.httpCookieStorage, let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value)...
@@ -88,14 +88,8 @@ open class Request { /// The delegate for the underlying task. open internal(set) var delegate: TaskDelegate { - get { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - return taskDelegate - } - set { - taskDelegateLock...
Source/Request.swift
0
Swift
1
none
16
51
51
true
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
jshier
let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo%26bar=baz%26qux&foobar=bazqux") } catch { XCTFa...
No issues found.
let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"] // When let urlRequest = try encoding.encode(self.urlRequest, with: parameters) // Then XCTAssertEqual(urlRequest.url?.query, "foo%26bar=baz%26qux&foobar=bazqux") } catch { XCTFa...
@@ -207,6 +207,22 @@ class URLParameterEncodingTestCase: ParameterEncodingTestCase { } } + func testURLParameterEncodeStringKeyArrayValueParameterWithoutBrackets() { + do { + // Given + let encoding = URLEncoding(arrayEncoding: .noBrackets) + let parameters = [...
Tests/ParameterEncodingTests.swift
0
Swift
1
none
16
51
51
true
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
heiberg
func testThatJSONDecodableResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = JSONDecodableResponseSerializer<DecodableValue>() // When let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: error) } // Then ...
No issues found.
func testThatJSONDecodableResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = JSONDecodableResponseSerializer<DecodableValue>() // When let result = Result { try serializer.serialize(request: nil, response: nil, data: nil, error: error) } // Then ...
@@ -30,7 +30,7 @@ class DataResponseSerializationTestCase: BaseTestCase { // MARK: Properties - private let error = AFError.responseSerializationFailed(reason: .inputDataNil) + private let error = AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) // MARK: DataResponseSerialize...
Tests/ResponseSerializationTests.swift
0
Swift
1
none
16
51
51
true
Alamofire 5: Customizable Empty Response Handling
2,639
Alamofire/Alamofire
41,690
Swift
jshier
return false } var isUnacceptableStatusCode: Bool { if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true } return false } } // MARK: - extension AFError.ParameterEncodingFailureReason { var isMissingURL: Bool { if case .mi...
No issues found.
return false } var isUnacceptableStatusCode: Bool { if case let .responseValidationFailed(reason) = self, reason.isUnacceptableStatusCode { return true } return false } } // MARK: - extension AFError.ParameterEncodingFailureReason { var isMissingURL: Bool { if case .mi...
@@ -137,6 +137,11 @@ extension AFError { return false } + var isInvalidEmptyResponse: Bool { + if case let .responseSerializationFailed(reason) = self, reason.isInvalidEmptyResponse { return true } + return false + } + // ResponseValidationFailureReason var isDataFileNil:...
Tests/AFError+AlamofireTests.swift
0
Swift
1
none
16
51
51
true
Implementing protocol EmptyResponse so that an empty response value can be returned when an empty http status code is encountered
2,664
Alamofire/Alamofire
41,690
Swift
jvannoord
func testThatRequestRedirectHandlerCanModifyRedirects() { // Given let session = Session() let redirectURLString = "https://www.nike.com" let redirectURLRequest = URLRequest(url: URL(string: redirectURLString)!) var response: DataResponse<Data?>? let expectation = se...
No issues found.
func testThatRequestRedirectHandlerCanModifyRedirects() { // Given let session = Session() let redirectURLString = "https://www.nike.com" let redirectURLRequest = URLRequest(url: URL(string: redirectURLString)!) var response: DataResponse<Data?>? let expectation = se...
@@ -0,0 +1,224 @@ +// +// RedirectHandlerTests.swift +// +// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Tests/RedirectHandlerTests.swift
0
Swift
1
none
16
51
51
true
Feature - Redirect Handlers
2,699
Alamofire/Alamofire
41,690
Swift
cnoon