Cotton code
41 lines · 2.3 KB · RustRaw
use super::*;use std::sync::Mutex;/// The server, as a test hears it: every ask it was handed, and one answer.#[derive(Default)]struct Server {    asked: Mutex<Vec<(String, String, String, Ask)>>,    answer: Option<Result<Answer, Unread>>,}impl Reader for Server {    fn read(&self, publisher: &str, name: &str, table: &str, ask: &Ask) -> Result<Answer, Unread> {        self.asked.lock().unwrap().push((publisher.into(), name.into(), table.into(), ask.clone()));        self.answer.clone().unwrap_or_else(|| Ok(Answer { version: "v1".into(), rows: vec![] }))    }}fn search(q: &str, prefer: Option<&str>) -> Ask {    Ask::Search { q: q.into(), prefer: prefer.map(str::to_string), limit: 8 }}/// RULE: The server's published database answers every read, no app bundles a copy; signed out there is no answer, said as signed out, never an empty list.#[test]fn the_server_answers_and_signed_out_is_said() {    let server = Server { answer: Some(Ok(Answer { version: "2026-10-14-ab".into(), rows: vec![json!({"id": "geonames:1269843", "name": "Hyderabad"})] })), ..Server::default() };    let answer = read_with(Some(&server), "places", "places", &search("hyd", Some("IN"))).unwrap();    assert_eq!(answer.version, "2026-10-14-ab");    assert_eq!(server.asked.lock().unwrap().as_slice(), [("cotton".to_string(), "places".to_string(), "places".to_string(), search("hyd", Some("IN")))]);    assert_eq!(read_with(None, "places", "places", &search("hyd", None)), Err(Unread::SignedOut));    let offline = Server { answer: Some(Err(Unread::Offline("no route to host".into()))), ..Server::default() };    let unread = read_with(Some(&offline), "places", "places", &search("hyd", None)).unwrap_err();    assert_eq!((unread.code(), unread.line(), unread.said()), ("published_offline", "published.offline", "no route to host"));}/// RULE: The ask goes to the server as the route's body: words never in a URL, a near point as {lat, lng}, ids with the version they were picked at.#[test]fn an_ask_is_the_routes_body() {    assert_eq!(search("hyd", Some("IN")).body(), json!({"q": "hyd", "prefer": "IN", "limit": 8}));    assert_eq!(Ask::Near { lat: 1.5, lng: -2.0, limit: 1 }.body(), json!({"near": {"lat": 1.5, "lng": -2.0}, "limit": 1}));    assert_eq!(Ask::Ids { ids: vec!["IN".into()], version: Some("v1".into()) }.body(), json!({"ids": ["IN"], "version": "v1"}));}