TestHelpers.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //
  2. // TestHelpers.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Alamofire
  25. import Foundation
  26. extension String {
  27. static let invalidURL = "invalid"
  28. static let nonexistentDomain = "https://nonexistent-domain.org"
  29. }
  30. extension URL {
  31. static let nonexistentDomain = URL(string: .nonexistentDomain)!
  32. }
  33. struct Endpoint {
  34. enum Scheme: String {
  35. case http, https
  36. var port: Int {
  37. switch self {
  38. case .http: return 80
  39. case .https: return 443
  40. }
  41. }
  42. }
  43. enum Host: String {
  44. case localhost = "127.0.0.1"
  45. case httpBin = "httpbin.org"
  46. func port(for scheme: Scheme) -> Int {
  47. switch self {
  48. case .localhost: return 8080
  49. case .httpBin: return scheme.port
  50. }
  51. }
  52. }
  53. enum Path {
  54. case basicAuth(username: String, password: String)
  55. case bytes(count: Int)
  56. case cache
  57. case chunked(count: Int)
  58. case compression(Compression)
  59. case delay(interval: Int)
  60. case digestAuth(qop: String = "auth", username: String, password: String)
  61. case download(count: Int)
  62. case hiddenBasicAuth(username: String, password: String)
  63. case image(Image)
  64. case ip
  65. case method(HTTPMethod)
  66. case payloads(count: Int)
  67. case redirect(count: Int)
  68. case redirectTo
  69. case responseHeaders
  70. case status(Int)
  71. case stream(count: Int)
  72. case upload
  73. case xml
  74. var string: String {
  75. switch self {
  76. case let .basicAuth(username: username, password: password):
  77. return "/basic-auth/\(username)/\(password)"
  78. case let .bytes(count):
  79. return "/bytes/\(count)"
  80. case .cache:
  81. return "/cache"
  82. case let .chunked(count):
  83. return "/chunked/\(count)"
  84. case let .compression(compression):
  85. return "/\(compression.rawValue)"
  86. case let .delay(interval):
  87. return "/delay/\(interval)"
  88. case let .digestAuth(qop, username, password):
  89. return "/digest-auth/\(qop)/\(username)/\(password)"
  90. case let .download(count):
  91. return "/download/\(count)"
  92. case let .hiddenBasicAuth(username, password):
  93. return "/hidden-basic-auth/\(username)/\(password)"
  94. case let .image(type):
  95. return "/image/\(type.rawValue)"
  96. case .ip:
  97. return "/ip"
  98. case let .method(method):
  99. return "/\(method.rawValue.lowercased())"
  100. case let .payloads(count):
  101. return "/payloads/\(count)"
  102. case let .redirect(count):
  103. return "/redirect/\(count)"
  104. case .redirectTo:
  105. return "/redirect-to"
  106. case .responseHeaders:
  107. return "/response-headers"
  108. case let .status(code):
  109. return "/status/\(code)"
  110. case let .stream(count):
  111. return "/stream/\(count)"
  112. case .upload:
  113. return "/upload"
  114. case .xml:
  115. return "/xml"
  116. }
  117. }
  118. }
  119. enum Image: String {
  120. case jpeg
  121. }
  122. enum Compression: String {
  123. case brotli, gzip, deflate
  124. }
  125. static var get: Endpoint { method(.get) }
  126. static func basicAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
  127. Endpoint(path: .basicAuth(username: user, password: password))
  128. }
  129. static func bytes(_ count: Int) -> Endpoint {
  130. Endpoint(path: .bytes(count: count))
  131. }
  132. static let cache: Endpoint = .init(path: .cache)
  133. static func chunked(_ count: Int) -> Endpoint {
  134. Endpoint(path: .chunked(count: count))
  135. }
  136. static func compression(_ compression: Compression) -> Endpoint {
  137. Endpoint(path: .compression(compression))
  138. }
  139. static var `default`: Endpoint { .get }
  140. static func delay(_ interval: Int) -> Endpoint {
  141. Endpoint(path: .delay(interval: interval))
  142. }
  143. static func digestAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
  144. Endpoint(path: .digestAuth(username: user, password: password))
  145. }
  146. static func download(_ count: Int = 10_000, produceError: Bool = false) -> Endpoint {
  147. Endpoint(path: .download(count: count), queryItems: [.init(name: "shouldProduceError",
  148. value: "\(produceError)")])
  149. }
  150. static func hiddenBasicAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
  151. Endpoint(path: .hiddenBasicAuth(username: user, password: password),
  152. headers: [.authorization(username: user, password: password)])
  153. }
  154. static func image(_ type: Image) -> Endpoint {
  155. Endpoint(path: .image(type))
  156. }
  157. static var ip: Endpoint {
  158. Endpoint(path: .ip)
  159. }
  160. static func method(_ method: HTTPMethod) -> Endpoint {
  161. Endpoint(path: .method(method), method: method)
  162. }
  163. static func payloads(_ count: Int) -> Endpoint {
  164. Endpoint(path: .payloads(count: count))
  165. }
  166. static func redirect(_ count: Int) -> Endpoint {
  167. Endpoint(path: .redirect(count: count))
  168. }
  169. static func redirectTo(_ url: String, code: Int? = nil) -> Endpoint {
  170. var items = [URLQueryItem(name: "url", value: url)]
  171. items = code.map { items + [.init(name: "statusCode", value: "\($0)")] } ?? items
  172. return Endpoint(path: .redirectTo, queryItems: items)
  173. }
  174. static func redirectTo(_ endpoint: Endpoint, code: Int? = nil) -> Endpoint {
  175. var items = [URLQueryItem(name: "url", value: endpoint.url.absoluteString)]
  176. items = code.map { items + [.init(name: "statusCode", value: "\($0)")] } ?? items
  177. return Endpoint(path: .redirectTo, queryItems: items)
  178. }
  179. static var responseHeaders: Endpoint {
  180. Endpoint(path: .responseHeaders)
  181. }
  182. static func status(_ code: Int) -> Endpoint {
  183. Endpoint(path: .status(code))
  184. }
  185. static func stream(_ count: Int) -> Endpoint {
  186. Endpoint(path: .stream(count: count))
  187. }
  188. static let upload: Endpoint = .init(path: .upload, method: .post, headers: [.contentType("application/octet-stream")])
  189. static var xml: Endpoint {
  190. Endpoint(path: .xml, headers: [.contentType("application/xml")])
  191. }
  192. var scheme = Scheme.http
  193. var port: Int { host.port(for: scheme) }
  194. var host = Host.localhost
  195. var path = Path.method(.get)
  196. var method: HTTPMethod = .get
  197. var headers: HTTPHeaders = .init()
  198. var timeout: TimeInterval = 60
  199. var queryItems: [URLQueryItem] = []
  200. var cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
  201. func modifying<T>(_ keyPath: WritableKeyPath<Endpoint, T>, to value: T) -> Endpoint {
  202. var copy = self
  203. copy[keyPath: keyPath] = value
  204. return copy
  205. }
  206. }
  207. extension Endpoint: URLRequestConvertible {
  208. var urlRequest: URLRequest { try! asURLRequest() }
  209. func asURLRequest() throws -> URLRequest {
  210. var request = try URLRequest(url: asURL())
  211. request.method = method
  212. request.headers = headers
  213. request.timeoutInterval = timeout
  214. request.cachePolicy = cachePolicy
  215. return request
  216. }
  217. }
  218. extension Endpoint: URLConvertible {
  219. var url: URL { try! asURL() }
  220. func asURL() throws -> URL {
  221. var components = URLComponents()
  222. components.scheme = scheme.rawValue
  223. components.port = port
  224. components.host = host.rawValue
  225. components.path = path.string
  226. if !queryItems.isEmpty {
  227. components.queryItems = queryItems
  228. }
  229. return try components.asURL()
  230. }
  231. }
  232. extension Session {
  233. func request(_ endpoint: Endpoint,
  234. parameters: Parameters? = nil,
  235. encoding: ParameterEncoding = URLEncoding.default,
  236. headers: HTTPHeaders? = nil,
  237. interceptor: RequestInterceptor? = nil,
  238. requestModifier: RequestModifier? = nil) -> DataRequest {
  239. request(endpoint as URLConvertible,
  240. method: endpoint.method,
  241. parameters: parameters,
  242. encoding: encoding,
  243. headers: headers,
  244. interceptor: interceptor,
  245. requestModifier: requestModifier)
  246. }
  247. func request<Parameters: Encodable>(_ endpoint: Endpoint,
  248. parameters: Parameters? = nil,
  249. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  250. headers: HTTPHeaders? = nil,
  251. interceptor: RequestInterceptor? = nil,
  252. requestModifier: RequestModifier? = nil) -> DataRequest {
  253. request(endpoint as URLConvertible,
  254. method: endpoint.method,
  255. parameters: parameters,
  256. encoder: encoder,
  257. headers: headers,
  258. interceptor: interceptor,
  259. requestModifier: requestModifier)
  260. }
  261. func request(_ endpoint: Endpoint, interceptor: RequestInterceptor? = nil) -> DataRequest {
  262. request(endpoint as URLRequestConvertible, interceptor: interceptor)
  263. }
  264. func streamRequest(_ endpoint: Endpoint,
  265. headers: HTTPHeaders? = nil,
  266. automaticallyCancelOnStreamError: Bool = false,
  267. interceptor: RequestInterceptor? = nil,
  268. requestModifier: RequestModifier? = nil) -> DataStreamRequest {
  269. streamRequest(endpoint as URLConvertible,
  270. method: endpoint.method,
  271. headers: headers,
  272. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  273. interceptor: interceptor,
  274. requestModifier: requestModifier)
  275. }
  276. func streamRequest(_ endpoint: Endpoint,
  277. automaticallyCancelOnStreamError: Bool = false,
  278. interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
  279. streamRequest(endpoint as URLRequestConvertible,
  280. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  281. interceptor: interceptor)
  282. }
  283. func download<Parameters: Encodable>(_ endpoint: Endpoint,
  284. parameters: Parameters? = nil,
  285. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  286. headers: HTTPHeaders? = nil,
  287. interceptor: RequestInterceptor? = nil,
  288. requestModifier: RequestModifier? = nil,
  289. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  290. download(endpoint as URLConvertible,
  291. method: endpoint.method,
  292. parameters: parameters,
  293. encoder: encoder,
  294. headers: headers,
  295. interceptor: interceptor,
  296. requestModifier: requestModifier,
  297. to: destination)
  298. }
  299. func download(_ endpoint: Endpoint,
  300. parameters: Parameters? = nil,
  301. encoding: ParameterEncoding = URLEncoding.default,
  302. headers: HTTPHeaders? = nil,
  303. interceptor: RequestInterceptor? = nil,
  304. requestModifier: RequestModifier? = nil,
  305. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  306. download(endpoint as URLConvertible,
  307. method: endpoint.method,
  308. parameters: parameters,
  309. encoding: encoding,
  310. headers: headers,
  311. interceptor: interceptor,
  312. requestModifier: requestModifier,
  313. to: destination)
  314. }
  315. func download(_ endpoint: Endpoint,
  316. interceptor: RequestInterceptor? = nil,
  317. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  318. download(endpoint as URLRequestConvertible, interceptor: interceptor, to: destination)
  319. }
  320. func upload(_ data: Data,
  321. to endpoint: Endpoint,
  322. headers: HTTPHeaders? = nil,
  323. interceptor: RequestInterceptor? = nil,
  324. fileManager: FileManager = .default,
  325. requestModifier: RequestModifier? = nil) -> UploadRequest {
  326. upload(data, to: endpoint as URLConvertible,
  327. method: endpoint.method,
  328. headers: headers,
  329. interceptor: interceptor,
  330. fileManager: fileManager,
  331. requestModifier: requestModifier)
  332. }
  333. }
  334. extension Data {
  335. var asString: String {
  336. String(decoding: self, as: UTF8.self)
  337. }
  338. func asJSONObject() throws -> Any {
  339. try JSONSerialization.jsonObject(with: self, options: .allowFragments)
  340. }
  341. }
  342. struct TestResponse: Decodable {
  343. let headers: [String: String]
  344. let origin: String
  345. let url: String?
  346. let data: String?
  347. let form: [String: String]?
  348. let args: [String: String]?
  349. }
  350. struct TestParameters: Encodable {
  351. static let `default` = TestParameters(property: "property")
  352. let property: String
  353. }
  354. struct UploadResponse: Decodable {
  355. let bytes: Int
  356. }