StubHelpers.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // StubHelpers.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/10/12.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. @discardableResult
  28. func stub(_ url: URL,
  29. data: Data,
  30. statusCode: Int = 200,
  31. length: Int? = nil,
  32. headers: [String: String] = [:]
  33. ) -> LSStubResponseDSL {
  34. var stubResult = stubRequest("GET", url.absoluteString as NSString)
  35. .andReturn(statusCode)?
  36. .withHeaders(headers)?
  37. .withBody(data as NSData)
  38. if let length = length {
  39. stubResult = stubResult?.withHeader("Content-Length", "\(length)")
  40. }
  41. return stubResult!
  42. }
  43. func delayedStub(_ url: URL,
  44. data: Data,
  45. statusCode: Int = 200,
  46. length: Int? = nil,
  47. headers: [String: String] = [:]
  48. ) -> LSStubResponseDSL {
  49. let result = stub(url, data: data, statusCode: statusCode, length: length, headers: headers)
  50. return result.delay()!
  51. }
  52. func stub(_ url: URL, errorCode: Int) {
  53. let error = NSError(domain: "stubError", code: errorCode, userInfo: nil)
  54. stub(url, error: error)
  55. }
  56. func stub(_ url: URL, error: any Error) {
  57. return stubRequest("GET", url.absoluteString as NSString).andFailWithError(error)
  58. }