diff --git a/Cargo.lock b/Cargo.lock index 8b2c46d..6bca330 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -151,6 +151,16 @@ dependencies = [ "nom", ] +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -335,6 +345,7 @@ dependencies = [ "tracing-bunyan-formatter", "tracing-log 0.2.0", "tracing-subscriber", + "wiremock", ] [[package]] @@ -527,6 +538,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "deadpool" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b" +dependencies = [ + "deadpool-runtime", + "lazy_static", + "num_cpus", + "tokio", +] + +[[package]] +name = "deadpool-runtime" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" + [[package]] name = "der" version = "0.7.10" @@ -671,6 +700,21 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.31" @@ -744,6 +788,7 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -802,6 +847,25 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "h2" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -842,6 +906,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + [[package]] name = "hex" version = "0.4.3" @@ -940,6 +1010,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -1384,6 +1455,16 @@ dependencies = [ "libm", ] +[[package]] +name = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + [[package]] name = "once_cell" version = "1.21.3" @@ -1686,6 +1767,18 @@ dependencies = [ "bitflags", ] +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.13" @@ -2533,6 +2626,19 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + [[package]] name = "tower" version = "0.4.13" @@ -3254,6 +3360,29 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "wiremock" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031" +dependencies = [ + "assert-json-diff", + "base64 0.22.1", + "deadpool", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "once_cell", + "regex", + "serde", + "serde_json", + "tokio", + "url", +] + [[package]] name = "wit-bindgen" version = "0.46.0" diff --git a/Cargo.toml b/Cargo.toml index 6145e09..6838de5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ portpicker = "0.1" reqwest = { version = "0.12", default-features = false, features = ["blocking", "cookies", "rustls-tls"] } tempfile = "3.8" once_cell = "1.19" +wiremock = "0.6" [[test]] name = "cli" diff --git a/src/application/routes/cafes.rs b/src/application/routes/cafes.rs index 11860e8..22b355d 100644 --- a/src/application/routes/cafes.rs +++ b/src/application/routes/cafes.rs @@ -216,8 +216,14 @@ pub(crate) async fn nearby_cafes( return Err(AppError::validation("q must be at least 2 characters").into()); } - let cafes = osm::search_nearby(&state.http_client, query.lat, query.lng, q) - .await - .map_err(ApiError::from)?; + let cafes = osm::search_nearby( + &state.http_client, + &state.nominatim_url, + query.lat, + query.lng, + q, + ) + .await + .map_err(ApiError::from)?; Ok(Json(cafes)) } diff --git a/src/application/server.rs b/src/application/server.rs index c4dc51f..504a415 100644 --- a/src/application/server.rs +++ b/src/application/server.rs @@ -46,6 +46,7 @@ pub struct AppState { pub token_repo: Arc, pub session_repo: Arc, pub http_client: reqwest::Client, + pub nominatim_url: String, } impl AppState { @@ -62,6 +63,7 @@ impl AppState { token_repo: Arc, session_repo: Arc, http_client: reqwest::Client, + nominatim_url: String, ) -> Self { Self { roaster_repo, @@ -75,6 +77,7 @@ impl AppState { token_repo, session_repo, http_client, + nominatim_url, } } } @@ -114,6 +117,7 @@ pub async fn serve(config: ServerConfig) -> anyhow::Result<()> { token_repo, session_repo, reqwest::Client::new(), + crate::infrastructure::osm::NOMINATIM_SEARCH_URL.to_string(), ); let listener = TcpListener::bind(config.bind_address) diff --git a/src/infrastructure/osm.rs b/src/infrastructure/osm.rs index 6246c63..09ef490 100644 --- a/src/infrastructure/osm.rs +++ b/src/infrastructure/osm.rs @@ -4,14 +4,14 @@ use serde::{Deserialize, Serialize}; use crate::application::errors::AppError; -const NOMINATIM_SEARCH_URL: &str = "https://nominatim.openstreetmap.org/search"; +pub const NOMINATIM_SEARCH_URL: &str = "https://nominatim.openstreetmap.org/search"; const USER_AGENT: &str = "Brewlog/1.0"; const MAX_RESULTS: &str = "8"; const REQUEST_TIMEOUT: Duration = Duration::from_secs(10); /// Viewbox half-size in degrees (~11 km at equator, tighter at higher latitudes). const VIEWBOX_DELTA: f64 = 0.1; -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct NearbyCafe { pub name: String, pub latitude: f64, @@ -26,6 +26,7 @@ pub struct NearbyCafe { /// Results are biased towards (but not restricted to) the user's location. pub async fn search_nearby( client: &reqwest::Client, + base_url: &str, lat: f64, lng: f64, query: &str, @@ -39,7 +40,7 @@ pub async fn search_nearby( ); let response = client - .get(NOMINATIM_SEARCH_URL) + .get(base_url) .header("User-Agent", USER_AGENT) .timeout(REQUEST_TIMEOUT) .query(&[ diff --git a/tests/server/helpers.rs b/tests/server/helpers.rs index 02d3017..0f001e0 100644 --- a/tests/server/helpers.rs +++ b/tests/server/helpers.rs @@ -37,6 +37,8 @@ pub struct TestApp { #[allow(dead_code)] pub token_repo: Option>, pub auth_token: Option, + #[allow(dead_code)] + pub mock_server: Option, } impl TestApp { @@ -72,6 +74,40 @@ pub async fn spawn_app() -> TestApp { let session_repo: Arc = Arc::new(SqlSessionRepository::new(database.clone_pool())); + spawn_app_inner( + database, + roaster_repo, + roast_repo, + bag_repo, + gear_repo, + brew_repo, + cafe_repo, + timeline_repo, + user_repo, + token_repo, + session_repo, + brewlog::infrastructure::osm::NOMINATIM_SEARCH_URL.to_string(), + None, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn spawn_app_inner( + _database: Database, + roaster_repo: Arc, + roast_repo: Arc, + bag_repo: Arc, + gear_repo: Arc, + brew_repo: Arc, + cafe_repo: Arc, + timeline_repo: Arc, + user_repo: Arc, + token_repo: Arc, + session_repo: Arc, + nominatim_url: String, + mock_server: Option, +) -> TestApp { // Create application state let state = AppState::new( roaster_repo.clone(), @@ -85,6 +121,7 @@ pub async fn spawn_app() -> TestApp { token_repo.clone(), session_repo, reqwest::Client::new(), + nominatim_url, ); // Create router @@ -114,12 +151,63 @@ pub async fn spawn_app() -> TestApp { user_repo: Some(user_repo), token_repo: Some(token_repo), auth_token: None, + mock_server, } } pub async fn spawn_app_with_auth() -> TestApp { - let mut app = spawn_app().await; + let app = spawn_app().await; + add_auth_to_app(app).await +} +pub async fn spawn_app_with_nominatim_mock() -> TestApp { + let mock_server = wiremock::MockServer::start().await; + let nominatim_url = format!("{}/search", mock_server.uri()); + + let database = Database::connect("sqlite::memory:") + .await + .expect("Failed to connect to in-memory database"); + + database + .migrate() + .await + .expect("Failed to migrate database"); + + let roaster_repo = Arc::new(SqlRoasterRepository::new(database.clone_pool())); + let roast_repo = Arc::new(SqlRoastRepository::new(database.clone_pool())); + let bag_repo = Arc::new(SqlBagRepository::new(database.clone_pool())); + let gear_repo = Arc::new(SqlGearRepository::new(database.clone_pool())); + let brew_repo = Arc::new(SqlBrewRepository::new(database.clone_pool())); + let cafe_repo = Arc::new(SqlCafeRepository::new(database.clone_pool())); + let timeline_repo = Arc::new(SqlTimelineEventRepository::new(database.clone_pool())); + let user_repo: Arc = + Arc::new(SqlUserRepository::new(database.clone_pool())); + let token_repo: Arc = + Arc::new(SqlTokenRepository::new(database.clone_pool())); + let session_repo: Arc = + Arc::new(SqlSessionRepository::new(database.clone_pool())); + + let app = spawn_app_inner( + database, + roaster_repo, + roast_repo, + bag_repo, + gear_repo, + brew_repo, + cafe_repo, + timeline_repo, + user_repo, + token_repo, + session_repo, + nominatim_url, + Some(mock_server), + ) + .await; + + add_auth_to_app(app).await +} + +async fn add_auth_to_app(mut app: TestApp) -> TestApp { // Create admin user with known password let password_hash = hash_password("test_password").expect("Failed to hash password"); let admin_user = NewUser::new("admin".to_string(), password_hash); diff --git a/tests/server/main.rs b/tests/server/main.rs index 7ec9d25..9b79988 100644 --- a/tests/server/main.rs +++ b/tests/server/main.rs @@ -6,6 +6,7 @@ pub mod cafes_api; pub mod datastar; pub mod gear_api; pub mod helpers; +pub mod nearby_api; pub mod roasters_api; pub mod roasts_api; pub mod timeline; diff --git a/tests/server/nearby_api.rs b/tests/server/nearby_api.rs new file mode 100644 index 0000000..77b8d28 --- /dev/null +++ b/tests/server/nearby_api.rs @@ -0,0 +1,177 @@ +use brewlog::infrastructure::osm::NearbyCafe; +use wiremock::matchers::{method, path, query_param}; +use wiremock::{Mock, ResponseTemplate}; + +use crate::helpers::spawn_app_with_nominatim_mock; + +/// Canned Nominatim JSON for two results near London (51.5, -0.1). +fn nominatim_two_results() -> serde_json::Value { + serde_json::json!([ + { + "place_id": 123, + "lat": "51.5246", + "lon": "-0.1098", + "display_name": "Prufrock Coffee, Leather Lane, London, England, United Kingdom", + "namedetails": { "name": "Prufrock Coffee" }, + "address": { + "cafe": "Prufrock Coffee", + "road": "Leather Lane", + "city": "London", + "country": "United Kingdom" + }, + "extratags": { + "website": "https://www.prufrockcoffee.com" + } + }, + { + "place_id": 456, + "lat": "51.5200", + "lon": "-0.1050", + "display_name": "Department of Coffee, Leather Lane, London, England, United Kingdom", + "namedetails": { "name": "Department of Coffee" }, + "address": { + "city": "London", + "country": "United Kingdom" + } + } + ]) +} + +#[tokio::test] +async fn nearby_search_returns_results() { + let app = spawn_app_with_nominatim_mock().await; + let mock_server = app.mock_server.as_ref().unwrap(); + + Mock::given(method("GET")) + .and(path("/search")) + .and(query_param("q", "coffee")) + .and(query_param("format", "json")) + .respond_with(ResponseTemplate::new(200).set_body_json(nominatim_two_results())) + .expect(1) + .mount(mock_server) + .await; + + let client = reqwest::Client::new(); + let response = client + .get(app.api_url("/nearby-cafes")) + .bearer_auth(app.auth_token.as_ref().unwrap()) + .query(&[("lat", "51.5"), ("lng", "-0.1"), ("q", "coffee")]) + .send() + .await + .expect("Failed to execute request"); + + assert_eq!(response.status(), 200); + + let cafes: Vec = response.json().await.expect("Failed to parse response"); + assert_eq!(cafes.len(), 2); + + assert_eq!(cafes[0].name, "Prufrock Coffee"); + assert_eq!(cafes[0].city, "London"); + assert_eq!(cafes[0].country, "United Kingdom"); + assert_eq!( + cafes[0].website.as_deref(), + Some("https://www.prufrockcoffee.com") + ); + assert!(cafes[0].distance_meters > 0); + + assert_eq!(cafes[1].name, "Department of Coffee"); + assert!(cafes[1].website.is_none()); +} + +#[tokio::test] +async fn nearby_search_returns_empty_for_no_matches() { + let app = spawn_app_with_nominatim_mock().await; + let mock_server = app.mock_server.as_ref().unwrap(); + + Mock::given(method("GET")) + .and(path("/search")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([]))) + .expect(1) + .mount(mock_server) + .await; + + let client = reqwest::Client::new(); + let response = client + .get(app.api_url("/nearby-cafes")) + .bearer_auth(app.auth_token.as_ref().unwrap()) + .query(&[("lat", "51.5"), ("lng", "-0.1"), ("q", "nonexistent")]) + .send() + .await + .expect("Failed to execute request"); + + assert_eq!(response.status(), 200); + + let cafes: Vec = response.json().await.expect("Failed to parse response"); + assert!(cafes.is_empty()); +} + +#[tokio::test] +async fn nearby_search_requires_authentication() { + let app = spawn_app_with_nominatim_mock().await; + + let client = reqwest::Client::new(); + let response = client + .get(app.api_url("/nearby-cafes")) + .query(&[("lat", "51.5"), ("lng", "-0.1"), ("q", "coffee")]) + .send() + .await + .expect("Failed to execute request"); + + assert_eq!(response.status(), 401); +} + +#[tokio::test] +async fn nearby_search_rejects_short_query() { + let app = spawn_app_with_nominatim_mock().await; + + let client = reqwest::Client::new(); + let response = client + .get(app.api_url("/nearby-cafes")) + .bearer_auth(app.auth_token.as_ref().unwrap()) + .query(&[("lat", "51.5"), ("lng", "-0.1"), ("q", "a")]) + .send() + .await + .expect("Failed to execute request"); + + assert_eq!(response.status(), 400); +} + +#[tokio::test] +async fn nearby_search_rejects_invalid_coordinates() { + let app = spawn_app_with_nominatim_mock().await; + + let client = reqwest::Client::new(); + let response = client + .get(app.api_url("/nearby-cafes")) + .bearer_auth(app.auth_token.as_ref().unwrap()) + .query(&[("lat", "999"), ("lng", "-0.1"), ("q", "coffee")]) + .send() + .await + .expect("Failed to execute request"); + + assert_eq!(response.status(), 400); +} + +#[tokio::test] +async fn nearby_search_returns_500_on_upstream_failure() { + let app = spawn_app_with_nominatim_mock().await; + let mock_server = app.mock_server.as_ref().unwrap(); + + Mock::given(method("GET")) + .and(path("/search")) + .respond_with(ResponseTemplate::new(503)) + .expect(1) + .mount(mock_server) + .await; + + let client = reqwest::Client::new(); + let response = client + .get(app.api_url("/nearby-cafes")) + .bearer_auth(app.auth_token.as_ref().unwrap()) + .query(&[("lat", "51.5"), ("lng", "-0.1"), ("q", "coffee")]) + .send() + .await + .expect("Failed to execute request"); + + assert_eq!(response.status(), 500); +}