TestHelpers.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 xml
  73. var string: String {
  74. switch self {
  75. case let .basicAuth(username: username, password: password):
  76. return "/basic-auth/\(username)/\(password)"
  77. case let .bytes(count):
  78. return "/bytes/\(count)"
  79. case .cache:
  80. return "/cache"
  81. case let .chunked(count):
  82. return "/chunked/\(count)"
  83. case let .compression(compression):
  84. return "/\(compression.rawValue)"
  85. case let .delay(interval):
  86. return "/delay/\(interval)"
  87. case let .digestAuth(qop, username, password):
  88. return "/digest-auth/\(qop)/\(username)/\(password)"
  89. case let .download(count):
  90. return "/download/\(count)"
  91. case let .hiddenBasicAuth(username, password):
  92. return "/hidden-basic-auth/\(username)/\(password)"
  93. case let .image(type):
  94. return "/image/\(type.rawValue)"
  95. case .ip:
  96. return "/ip"
  97. case let .method(method):
  98. return "/\(method.rawValue.lowercased())"
  99. case let .payloads(count):
  100. return "/payloads/\(count)"
  101. case let .redirect(count):
  102. return "/redirect/\(count)"
  103. case .redirectTo:
  104. return "/redirect-to"
  105. case .responseHeaders:
  106. return "/response-headers"
  107. case let .status(code):
  108. return "/status/\(code)"
  109. case let .stream(count):
  110. return "/stream/\(count)"
  111. case .xml:
  112. return "/xml"
  113. }
  114. }
  115. }
  116. enum Image: String {
  117. case jpeg
  118. }
  119. enum Compression: String {
  120. case brotli, gzip, deflate
  121. }
  122. static var get: Endpoint { method(.get) }
  123. static func basicAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
  124. Endpoint(path: .basicAuth(username: user, password: password))
  125. }
  126. static func bytes(_ count: Int) -> Endpoint {
  127. Endpoint(path: .bytes(count: count))
  128. }
  129. static let cache: Endpoint = .init(path: .cache)
  130. static func chunked(_ count: Int) -> Endpoint {
  131. Endpoint(path: .chunked(count: count))
  132. }
  133. static func compression(_ compression: Compression) -> Endpoint {
  134. Endpoint(path: .compression(compression))
  135. }
  136. static var `default`: Endpoint { .get }
  137. static func delay(_ interval: Int) -> Endpoint {
  138. Endpoint(path: .delay(interval: interval))
  139. }
  140. static func digestAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
  141. Endpoint(path: .digestAuth(username: user, password: password))
  142. }
  143. static func download(_ count: Int = 10_000, produceError: Bool = false) -> Endpoint {
  144. Endpoint(path: .download(count: count), queryItems: [.init(name: "shouldProduceError",
  145. value: "\(produceError)")])
  146. }
  147. static func hiddenBasicAuth(forUser user: String = "user", password: String = "password") -> Endpoint {
  148. Endpoint(path: .hiddenBasicAuth(username: user, password: password),
  149. headers: [.authorization(username: user, password: password)])
  150. }
  151. static func image(_ type: Image) -> Endpoint {
  152. Endpoint(path: .image(type))
  153. }
  154. static var ip: Endpoint {
  155. Endpoint(path: .ip)
  156. }
  157. static func method(_ method: HTTPMethod) -> Endpoint {
  158. Endpoint(path: .method(method), method: method)
  159. }
  160. static func payloads(_ count: Int) -> Endpoint {
  161. Endpoint(path: .payloads(count: count))
  162. }
  163. static func redirect(_ count: Int) -> Endpoint {
  164. Endpoint(path: .redirect(count: count))
  165. }
  166. static func redirectTo(_ url: String, code: Int? = nil) -> Endpoint {
  167. var items = [URLQueryItem(name: "url", value: url)]
  168. items = code.map { items + [.init(name: "statusCode", value: "\($0)")] } ?? items
  169. return Endpoint(path: .redirectTo, queryItems: items)
  170. }
  171. static func redirectTo(_ endpoint: Endpoint, code: Int? = nil) -> Endpoint {
  172. var items = [URLQueryItem(name: "url", value: endpoint.url.absoluteString)]
  173. items = code.map { items + [.init(name: "statusCode", value: "\($0)")] } ?? items
  174. return Endpoint(path: .redirectTo, queryItems: items)
  175. }
  176. static var responseHeaders: Endpoint {
  177. Endpoint(path: .responseHeaders)
  178. }
  179. static func status(_ code: Int) -> Endpoint {
  180. Endpoint(path: .status(code))
  181. }
  182. static func stream(_ count: Int) -> Endpoint {
  183. Endpoint(path: .stream(count: count))
  184. }
  185. static var xml: Endpoint {
  186. Endpoint(path: .xml, headers: [.contentType("application/xml")])
  187. }
  188. var scheme = Scheme.http
  189. var port: Int { host.port(for: scheme) }
  190. var host = Host.localhost
  191. var path = Path.method(.get)
  192. var method: HTTPMethod = .get
  193. var headers: HTTPHeaders = .init()
  194. var timeout: TimeInterval = 60
  195. var queryItems: [URLQueryItem] = []
  196. var cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy
  197. func modifying<T>(_ keyPath: WritableKeyPath<Endpoint, T>, to value: T) -> Endpoint {
  198. var copy = self
  199. copy[keyPath: keyPath] = value
  200. return copy
  201. }
  202. }
  203. extension Endpoint: URLRequestConvertible {
  204. var urlRequest: URLRequest { try! asURLRequest() }
  205. func asURLRequest() throws -> URLRequest {
  206. var request = try URLRequest(url: asURL())
  207. request.method = method
  208. request.headers = headers
  209. request.timeoutInterval = timeout
  210. request.cachePolicy = cachePolicy
  211. return request
  212. }
  213. }
  214. extension Endpoint: URLConvertible {
  215. var url: URL { try! asURL() }
  216. func asURL() throws -> URL {
  217. var components = URLComponents()
  218. components.scheme = scheme.rawValue
  219. components.port = port
  220. components.host = host.rawValue
  221. components.path = path.string
  222. if !queryItems.isEmpty {
  223. components.queryItems = queryItems
  224. }
  225. return try components.asURL()
  226. }
  227. }
  228. extension Session {
  229. func request(_ endpoint: Endpoint,
  230. parameters: Parameters? = nil,
  231. encoding: ParameterEncoding = URLEncoding.default,
  232. headers: HTTPHeaders? = nil,
  233. interceptor: RequestInterceptor? = nil,
  234. requestModifier: RequestModifier? = nil) -> DataRequest {
  235. request(endpoint as URLConvertible,
  236. method: endpoint.method,
  237. parameters: parameters,
  238. encoding: encoding,
  239. headers: headers,
  240. interceptor: interceptor,
  241. requestModifier: requestModifier)
  242. }
  243. func request<Parameters: Encodable>(_ endpoint: Endpoint,
  244. parameters: Parameters? = nil,
  245. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  246. headers: HTTPHeaders? = nil,
  247. interceptor: RequestInterceptor? = nil,
  248. requestModifier: RequestModifier? = nil) -> DataRequest {
  249. request(endpoint as URLConvertible,
  250. method: endpoint.method,
  251. parameters: parameters,
  252. encoder: encoder,
  253. headers: headers,
  254. interceptor: interceptor,
  255. requestModifier: requestModifier)
  256. }
  257. func request(_ endpoint: Endpoint, interceptor: RequestInterceptor? = nil) -> DataRequest {
  258. request(endpoint as URLRequestConvertible, interceptor: interceptor)
  259. }
  260. func streamRequest(_ endpoint: Endpoint,
  261. headers: HTTPHeaders? = nil,
  262. automaticallyCancelOnStreamError: Bool = false,
  263. interceptor: RequestInterceptor? = nil,
  264. requestModifier: RequestModifier? = nil) -> DataStreamRequest {
  265. streamRequest(endpoint as URLConvertible,
  266. method: endpoint.method,
  267. headers: headers,
  268. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  269. interceptor: interceptor,
  270. requestModifier: requestModifier)
  271. }
  272. func streamRequest(_ endpoint: Endpoint,
  273. automaticallyCancelOnStreamError: Bool = false,
  274. interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
  275. streamRequest(endpoint as URLRequestConvertible,
  276. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  277. interceptor: interceptor)
  278. }
  279. func download<Parameters: Encodable>(_ endpoint: Endpoint,
  280. parameters: Parameters? = nil,
  281. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  282. headers: HTTPHeaders? = nil,
  283. interceptor: RequestInterceptor? = nil,
  284. requestModifier: RequestModifier? = nil,
  285. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  286. download(endpoint as URLConvertible,
  287. method: endpoint.method,
  288. parameters: parameters,
  289. encoder: encoder,
  290. headers: headers,
  291. interceptor: interceptor,
  292. requestModifier: requestModifier,
  293. to: destination)
  294. }
  295. func download(_ endpoint: Endpoint,
  296. parameters: Parameters? = nil,
  297. encoding: ParameterEncoding = URLEncoding.default,
  298. headers: HTTPHeaders? = nil,
  299. interceptor: RequestInterceptor? = nil,
  300. requestModifier: RequestModifier? = nil,
  301. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  302. download(endpoint as URLConvertible,
  303. method: endpoint.method,
  304. parameters: parameters,
  305. encoding: encoding,
  306. headers: headers,
  307. interceptor: interceptor,
  308. requestModifier: requestModifier,
  309. to: destination)
  310. }
  311. func download(_ endpoint: Endpoint,
  312. interceptor: RequestInterceptor? = nil,
  313. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  314. download(endpoint as URLRequestConvertible, interceptor: interceptor, to: destination)
  315. }
  316. func upload(_ data: Data,
  317. to endpoint: Endpoint,
  318. headers: HTTPHeaders? = nil,
  319. interceptor: RequestInterceptor? = nil,
  320. fileManager: FileManager = .default,
  321. requestModifier: RequestModifier? = nil) -> UploadRequest {
  322. upload(data, to: endpoint as URLConvertible,
  323. method: endpoint.method,
  324. headers: headers,
  325. interceptor: interceptor,
  326. fileManager: fileManager,
  327. requestModifier: requestModifier)
  328. }
  329. }
  330. extension Data {
  331. var asString: String {
  332. String(decoding: self, as: UTF8.self)
  333. }
  334. func asJSONObject() throws -> Any {
  335. try JSONSerialization.jsonObject(with: self, options: .allowFragments)
  336. }
  337. }
  338. struct TestResponse: Decodable {
  339. let headers: [String: String]
  340. let origin: String
  341. let url: String?
  342. let data: String?
  343. let form: [String: String]?
  344. let args: [String: String]?
  345. }
  346. struct TestParameters: Encodable {
  347. static let `default` = TestParameters(property: "property")
  348. let property: String
  349. }