Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fluent API for stubbing #349

Open
Tyler-Keith-Thompson opened this issue Jan 28, 2022 · 0 comments
Open

Fluent API for stubbing #349

Tyler-Keith-Thompson opened this issue Jan 28, 2022 · 0 comments

Comments

@Tyler-Keith-Thompson
Copy link

Tyler-Keith-Thompson commented Jan 28, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant