AliSoftware / OHHTTPStubs

Stub your network requests easily! Test your apps with fake network data and custom response time, response code and headers!
MIT License
5.03k stars 602 forks source link

Fluent API for stubbing #349

Open Tyler-Keith-Thompson opened 2 years ago

Tyler-Keith-Thompson commented 2 years ago

It'd be really nice if there was a fluent API for stubbing. I personally feel this drastically helps readability and has the added benefit of making it very simple to return different responses for the same condition.

Ideal API (in my head):

    func testExample() async throws {
        let expectedData = try XCTUnwrap(UUID().uuidString.data(using: .utf8))
        let secondData = try XCTUnwrap(UUID().uuidString.data(using: .utf8))
        StubResponse(on: isHost("www.someapi.com") && isMethodGET() ) { req in
            HTTPStubsResponse(data: expectedData, statusCode: 500, headers: nil)
        }.thenRespond(on: isHost("www.someapi.com") && isMethodGET() ) { req in
            HTTPStubsResponse(data: secondData, statusCode: 400, headers: nil)
        }

        let (data, response) = try await URLSession.shared.data(from: URL(string: "https://www.someapi.com")!)
        XCTAssertEqual((response as? HTTPURLResponse)?.statusCode, 500) // first respond with a 500
        XCTAssertEqual(data, expectedData)

        let (data2, response2) = try await URLSession.shared.data(from: URL(string: "https://www.someapi.com")!)
        XCTAssertEqual((response2 as? HTTPURLResponse)?.statusCode, 400) // then respond with a 400
        XCTAssertEqual(data2, secondData)

        let (data3, response3) = try await URLSession.shared.data(from: URL(string: "https://www.someapi.com")!)
        XCTAssertEqual((response3 as? HTTPURLResponse)?.statusCode, 400) // 400 response stays stubbed, cause that was the last one
        XCTAssertEqual(data3, secondData)
    }

WIP - (The thing I usually rebuild)

I thought I'd share code I often rewrite when I pull in this library so that others might benefit. It has some drawbacks, it's not particularly efficient, and it's a little questionable how it removes stubs, but I think it's a useful copy/paste if you also like this sort of thing.

import OHHTTPStubs
import OHHTTPStubsSwift

final class StubResponse {
    var stubs: [(condition: HTTPStubsTestBlock, response: HTTPStubsResponseBlock)] = []
    @discardableResult convenience init(on condition: @escaping HTTPStubsTestBlock, with response: @escaping HTTPStubsResponseBlock) {
        self.init(stubs: [(condition, response)])
    }

    private init(stubs: [(condition: HTTPStubsTestBlock, response: HTTPStubsResponseBlock)]) {
        self.stubs = stubs
        stub { req in
            let filtered = self.stubs.enumerated().filter { $0.element.condition(req) }
            return !filtered.isEmpty
        } response: { req in
            let filtered = self.stubs.enumerated().filter { $0.element.condition(req) }
            guard let first = filtered.first else { fatalError("No stub response found, something bad happened") }
            defer {
                if filtered.count > 1, let first = filtered.first {
                    self.stubs.remove(at: first.offset)
                }
            }
            return first.element.response(req)
        }
    }

    @discardableResult func thenRespond(on condition: @escaping HTTPStubsTestBlock, with response: @escaping HTTPStubsResponseBlock) -> Self {
        Self(stubs: stubs.appending((condition, response)))
    }
}

extension Array {
    fileprivate func appending(_ element: Element) -> Self {
        var copy = self
        copy.append(element)
        return copy
    }
}

I would submit a PR but I'm not sure if others would find this useful and didn't want to spend time resolving the issues mentioned unless this is useful to anybody other than me.