
StubTest.pudu
Pudu55 lines2.8 KB
1/** @Test.Stub.Suite — a primary handler answering from rules */2module PuduLangHttpClient.StubTest34import Std.Bytes as ByteSeq5import Std.Concurrent.Cancel as Cancel6import Std.Http as Http7import Std.Io as Io8import Std.Result as Result9import Std.Sync as Sync10import Std.Test as Test11import PuduLangHttpClient as HttpClient12import PuduLangHttpClient.Request as Request13import PuduLangHttpClient.Response as Response14import PuduLangHttpClient.Stub as Stub151617fn shape(outcome: &HttpClient.Outcome[Response.Response]) -> Result[(Int, Str), HttpClient.Failure] {18 Result.map(*outcome, |response: Response.Response| (response.status.code, Result.unwrapOr(Response.text(&response), "")))19}202122fn main() -> Int {23 let stub = Stub.create()24 Stub.respond(&stub, Http.Get, "/users", 200, "[]")25 Stub.on(&stub, Http.Post, "/users", |request: Request.Request| Ok(Response.answer(&request, 201).withText("made")))26 Stub.when(&stub, |request: Request.Request| request.uri.contains("fail"), |_request: Request.Request| Err(HttpClient.Connection("down")))27 let send = Stub.send(&stub)28 let listed = shape(&send(Request.get("http://a/users?page=1"), Cancel.token()))29 let made = shape(&send(Request.create(Http.Post, "http://a/users"), Cancel.token()))30 let failed = shape(&send(Request.get("http://a/fail"), Cancel.token()))31 let unknown = shape(&send(Request.get("http://a/none"), Cancel.token()))32 let stopped = Cancel.token()33 let _cancelled = Cancel.cancel(&stopped, "halt")34 let refused = shape(&send(Request.get("http://a/users"), stopped))35 let taken = Sync.cell(ByteSeq.empty())36 let streamed = send(Request.get("http://a/users").withReceiver(fn(piece: Bytes) -> Bool {37 let _kept = Sync.set(&taken, piece)38 true39 }), Cancel.token())40 let checks = Test.suite("Stub", &[41 Test.equals("a rule matches its method and path whatever the query", &listed, &Ok((200, "[]"))),42 Test.equals("another method on the same path has its own rule", &made, &Ok((201, "made"))),43 Test.equals("a rule may answer a failure", &failed, &Err(HttpClient.Connection("down"))),44 Test.equals("a request no rule answers is not found", &unknown, &Ok((404, ""))),45 Test.equals("a cancelled request is refused", &refused, &Err(HttpClient.Cancelled("halt"))),46 Test.equals("a receiver gets the body and the response keeps none", &(shape(&streamed), Result.unwrapOr(Sync.get(&taken), ByteSeq.empty()).toText()), &(Ok((200, "")), Some("[]"))),47 Test.equals("every request received is kept in order, cancelled ones excepted", &Stub.received(&stub).map(|request: Request.Request| request.uri), &["http://a/users?page=1", "http://a/users", "http://a/fail", "http://a/none", "http://a/users"])48 ])49 let ran = Test.run(&checks)50 for failure in Test.failuresOf(&ran) {51 let _reported = Io.writeErrorLine(failure)52 }53 Test.report(&ran)54}55