AliSoftware / AliSoftware/OHHTTPStubs

Fluent API for stubbing

Abierto
#349 0 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
Objective-C
Estrellas
5.1k
Forks
597
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

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):
```swift
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.

```swift
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.

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.