Skip to content

Commit

Permalink
Merge pull request #60 from 417-72KI/stub-request-wo-ohhttpstubs
Browse files Browse the repository at this point in the history
Enable test without `OHHTTPStubs`
  • Loading branch information
417-72KI authored Apr 16, 2022
2 parents d72575c + 0c0e430 commit c7c985b
Show file tree
Hide file tree
Showing 9 changed files with 131 additions and 15 deletions.
4 changes: 2 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let testDependencies: [Package.Dependency] = isRelease
? []
: [
.package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.6.0"),
.package(url: "https://github.com/AliSoftware/OHHTTPStubs.git", from: "9.1.0"),
// .package(url: "https://github.com/AliSoftware/OHHTTPStubs.git", from: "9.1.0"),
.package(url: "https://github.com/ishkawa/APIKit.git", from: "5.3.0"),
.package(url: "https://github.com/Moya/Moya.git", from: "15.0.0"),
]
Expand All @@ -19,7 +19,7 @@ let testTargetDependencies: [Target.Dependency] = isRelease
"Alamofire",
"APIKit",
"Moya",
.product(name: "OHHTTPStubsSwift", package: "OHHTTPStubs"),
// .product(name: "OHHTTPStubsSwift", package: "OHHTTPStubs"),
]

let package = Package(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ final class MultipartFormDataParser_CocoaTests: XCTestCase {
}
#endif

#if canImport(OHHTTPStubs)
func testURLSessionDataTask() throws {
let genbaNeko = try XCTUnwrap(NSImage(data: TestResource.genbaNeko)?.jpegRepresentation)
let denwaNeko = try XCTUnwrap(NSImage(data: TestResource.denwaNeko)?.jpegRepresentation)
Expand All @@ -102,6 +101,5 @@ final class MultipartFormDataParser_CocoaTests: XCTestCase {
XCTAssertEqual(result.status, 200)
XCTAssertNil(result.error)
}
#endif
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ final class MultipartFormDataParser_UIKitTests: XCTestCase {
}
#endif

#if canImport(OHHTTPStubs)
func testURLSessionUploadTask() throws {
let genbaNeko = try XCTUnwrap(UIImage(data: TestResource.genbaNeko)?.jpegData(compressionQuality: 1))
let denwaNeko = try XCTUnwrap(UIImage(data: TestResource.denwaNeko)?.jpegData(compressionQuality: 1))
Expand All @@ -103,6 +102,5 @@ final class MultipartFormDataParser_UIKitTests: XCTestCase {
XCTAssertEqual(result.status, 200)
XCTAssertNil(result.error)
}
#endif
}
#endif
38 changes: 38 additions & 0 deletions Tests/MultipartFormDataParserTests/StubURLProtocol.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

final class StubURLProtocol: URLProtocol {
typealias RequestHandler = (URLRequest) throws -> (Data?, HTTPURLResponse)

static var requestHandler: RequestHandler?

override class func canInit(with request: URLRequest) -> Bool {
true
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
request
}

override func startLoading() {
guard let requestHandler = Self.requestHandler else { return }
do {
let (data, response) = try requestHandler(request)
client?.urlProtocol(self,
didReceive: response,
cacheStoragePolicy: .notAllowed)
if let data = data {
client?.urlProtocol(self, didLoad: data)
}
client?.urlProtocolDidFinishLoading(self)
} catch {
client?.urlProtocol(self, didFailWithError: error)
}
}

override func stopLoading() {
// no-op
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import XCTest
#if canImport(APIKit)
import APIKit

private let session: Session = {
#if canImport(OHHTTPStubs)
return .shared
#else
let configuration = URLSessionConfiguration.default
configuration.protocolClasses = [StubURLProtocol.self]
let adapter = URLSessionAdapter(configuration: configuration)
return Session(adapter: adapter)
#endif
}()

extension XCTestCase {
func requestWithAPIKit(
genbaNeko: Data,
Expand Down Expand Up @@ -37,7 +48,7 @@ extension XCTestCase {
line: line
)
var result: Result<TestRequest.Response, SessionTaskError>!
Session.shared.send(request, callbackQueue: nil) {
session.send(request, callbackQueue: nil) {
result = $0
exp.fulfill()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ import XCTest
#if canImport(Alamofire)
import Alamofire

private let session: Session = {
#if canImport(OHHTTPStubs)
return AF
#else
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
return Session(configuration: configuration)
#endif
}()

extension XCTestCase {
func uploadWithAlamoFire(
genbaNeko: Data,
Expand All @@ -14,7 +24,7 @@ extension XCTestCase {
line: UInt = #line
) throws -> TestEntity? {
let exp = expectation(description: "response")
let task = AF.upload(
let task = session.upload(
multipartFormData: { formData in
formData.append(
genbaNeko,
Expand Down Expand Up @@ -63,7 +73,7 @@ extension XCTestCase {
) async throws -> TestEntity {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return try await AF.upload(
return try await session.upload(
multipartFormData: { formData in
formData.append(
genbaNeko,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ import XCTest
#if canImport(Moya)
import Moya

private let provider: MoyaProvider<TestTarget> = {
#if canImport(OHHTTPStubs)
return MoyaProvider()
#else
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
return MoyaProvider(session: Session(configuration: configuration))
#endif
}()

extension XCTestCase {
func uploadWithMoya(
genbaNeko: Data,
Expand All @@ -23,7 +33,7 @@ extension XCTestCase {
line: line
)
var result: Result<Response, MoyaError>!
MoyaProvider().request(target) {
provider.request(target) {
result = $0
exp.fulfill()
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import Foundation
import XCTest

#if canImport(OHHTTPStubs)
private let session: URLSession = {
#if canImport(OHHTTPStubs)
return .shared
#else
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [StubURLProtocol.self]
return URLSession(configuration: configuration)
#endif
}()

extension XCTestCase {
func uploadURLSessionDataTask(
genbaNeko: Data,
Expand All @@ -15,13 +24,16 @@ extension XCTestCase {

let request = createRequest(genbaNeko: genbaNeko, denwaNeko: denwaNeko, message: message)
var responseData: Data!
URLSession.shared.dataTask(with: request) { data, _, _ in
session.dataTask(with: request) { data, _, _ in
responseData = data
exp.fulfill()
}.resume()
waitForExpectations(timeout: timeoutInterval)

guard let data = responseData else {
guard retryCount > 0 else {
throw URLError(.fileDoesNotExist)
}
return try uploadURLSessionDataTask(genbaNeko: genbaNeko,
denwaNeko: denwaNeko,
message: message,
Expand Down Expand Up @@ -52,12 +64,15 @@ extension XCTestCase {
denwaNeko: denwaNeko,
message: message)
var responseData: Data!
URLSession.shared.uploadTask(with: request, from: requestBody) { data, _, _ in
session.uploadTask(with: request, from: requestBody) { data, _, _ in
responseData = data
exp.fulfill()
}.resume()
waitForExpectations(timeout: timeoutInterval)
guard let data = responseData else {
guard retryCount > 0 else {
throw URLError(.fileDoesNotExist)
}
return try uploadURLSessionUploadTask(genbaNeko: genbaNeko,
denwaNeko: denwaNeko,
message: message,
Expand All @@ -68,7 +83,6 @@ extension XCTestCase {
return try JSONDecoder().decode(TestEntity.self, from: data)
}
}
#endif

extension XCTestCase {
func createRequest(
Expand Down
39 changes: 38 additions & 1 deletion Tests/MultipartFormDataParserTests/TestStub.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

#if canImport(Cocoa) && !targetEnvironment(macCatalyst)
import Cocoa
typealias Image = NSImage
Expand All @@ -20,6 +25,8 @@ func stubForUpload() {
let condition = isHost("localhost")
&& isPath("/upload")
stub(condition: condition, response: uploadTestStubResponse)
#else
StubURLProtocol.requestHandler = uploadTestStubResponse
#endif
}

Expand All @@ -30,7 +37,7 @@ func clearStubs() {
}

#if canImport(OHHTTPStubs)
private var uploadTestStubResponse: HTTPStubsResponseBlock = { request in
private let uploadTestStubResponse: HTTPStubsResponseBlock = { request in
let errorResponse = { (message: String) -> HTTPStubsResponse in
.init(jsonObject: ["status": 403, "error": message], statusCode: 403, headers: ["Content-Type": "application/json"])
}
Expand All @@ -51,4 +58,34 @@ private var uploadTestStubResponse: HTTPStubsResponseBlock = { request in
headers: ["Content-Type": "application/json"]
)
}
#else
private let uploadTestStubResponse: StubURLProtocol.RequestHandler = { request in
let errorResponse = { (message: String) -> (Data?, HTTPURLResponse) in
(
#"{"status": 403, "error": "\#(message)"}"#.data(using: .utf8),
HTTPURLResponse(url: request.url!,
statusCode: 403,
httpVersion: "HTTP/2",
headerFields: ["Content-Type": "application/json"])!
)
}
do {
let data = try MultipartFormData.parse(from: request)
guard let genbaNeko = data.element(forName: "genbaNeko") else { return errorResponse("genbaNeko") }
guard let denwaNeko = data.element(forName: "denwaNeko") else { return errorResponse("denwaNeko") }
guard let message = data.element(forName: "message") else { return errorResponse("message") }
guard let _ = Image(data: genbaNeko.data) else { return errorResponse("Unexpected genbaNeko") }
guard let _ = Image(data: denwaNeko.data) else { return errorResponse("Unexpected denwaNeko") }
guard message.string == "Hello world!" else { return errorResponse("Unexpected message: \(message)") }
return (
#"{"status": 200}"#.data(using: .utf8),
HTTPURLResponse(url: request.url!,
statusCode: 200,
httpVersion: "HTTP/2",
headerFields: ["Content-Type": "application/json"])!
)
} catch {
return errorResponse(error.localizedDescription)
}
}
#endif

0 comments on commit c7c985b

Please sign in to comment.