use std::sync::Arc;
use mln_style::StyleLoadError;
use crate::exec::queue::Queue;
use crate::map::{Map, MapEvent, MapOptions};
use crate::storage::response::{Reason, ResourceError};
use crate::storage::stub_file_source::{ResponseType, StubFileSource};
use crate::storage::{Kind, Resource, Response};
fn testdata(relative: &str) -> String {
std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
.join("testdata")
.join(relative)
.to_string_lossy()
.into_owned()
}
fn map_over(file_source: Arc<StubFileSource>, options: MapOptions) -> Map {
super::test_map(file_source, options)
}
fn map_with_style_response(
responder: impl Fn(&Resource) -> Option<Response> + Send + Sync + 'static,
) -> (Map, Queue<()>) {
let run_loop = Queue::<()>::new();
let file_source = StubFileSource::on_queue(&run_loop, ResponseType::Asynchronous);
file_source.set_response(Kind::Style, responder);
(map_over(file_source, MapOptions::default()), run_loop)
}
fn style_response(json: &str) -> Response {
let mut response = Response::new();
response.data = Some(Arc::new(json.as_bytes().to_vec()));
response
}
fn load_failures(events: &[MapEvent]) -> Vec<StyleLoadError> {
events
.iter()
.filter_map(|event| match event {
MapEvent::LoadingFailed(error) => Some(error.clone()),
_ => None,
})
.collect()
}
const REMOTE: &str = r#"{"version": 8, "name": "Remote", "sources": {}, "layers": []}"#;
#[test]
fn a_url_loads_the_style_it_answers_with() {
let (mut map, run_loop) = map_with_style_response(|resource| {
assert_eq!(resource.url, "http://some-url");
Some(style_response(REMOTE))
});
map.load_style_url("http://some-url");
assert!(!map.style_document_loaded());
assert_eq!(Some("http://some-url"), map.style_url());
run_loop.run_once(&mut ());
assert!(map.has_reports());
map.process_events();
assert!(map.style_document_loaded());
assert_eq!("Remote", map.style().name());
assert_eq!(Some("http://some-url"), map.style_url());
}
#[test]
fn a_url_answered_without_a_style_fails_the_load() {
let error: fn() -> Response = || {
let mut response = Response::new();
response.error = Some(Box::new(ResourceError::new(Reason::NotFound, "HTTP status code 404")));
response
};
let no_content = || Response { no_content: true, ..Response::new() };
let not_modified = || Response { not_modified: true, ..Response::new() };
let cases = [
(error, "HTTP status code 404"),
(no_content, "the style request returned no content"),
(not_modified, "the style request returned not modified, but no earlier response delivered the style"),
];
for (response, message) in cases {
let (mut map, run_loop) = map_with_style_response(move |_| Some(response()));
map.load_style_url("http://some-url");
run_loop.run_once(&mut ());
let events = map.drain_events();
assert_eq!(vec![StyleLoadError::Load(format!("loading style failed: {message}"))], load_failures(&events));
assert!(!map.style_document_loaded());
}
}
#[test]
fn load_url_ignores_no_content_and_not_modified_after_a_style() {
let (mut map, run_loop) = map_with_style_response(|_| Some(style_response(REMOTE)));
map.load_style_url("http://some-url");
run_loop.run_once(&mut ());
map.drain_events();
assert!(map.style_document_loaded());
for (no_content, not_modified) in [(true, false), (false, true)] {
let mut response = Response::new();
response.no_content = no_content;
response.not_modified = not_modified;
map.style_loader().push_style_response(response);
let events = map.drain_events();
assert!(load_failures(&events).is_empty(), "{events:?}");
}
assert!(map.style_document_loaded());
assert_eq!("Remote", map.style().name());
}
fn connection_error() -> Response {
let mut response = Response::new();
response.error = Some(Box::new(ResourceError::new(Reason::Connection, "offline")));
response
}
#[test]
fn a_streak_of_errors_fails_the_load_once() {
let (mut map, run_loop) = map_with_style_response(|_| Some(connection_error()));
map.load_style_url("http://some-url");
run_loop.run_once(&mut ());
let mut events = map.drain_events();
for _ in 0..2 {
map.style_loader().push_style_response(connection_error());
events.extend(map.drain_events());
}
assert_eq!(1, load_failures(&events).len());
map.style_loader().push_style_response(style_response(REMOTE));
map.drain_events();
assert!(map.style_document_loaded());
}
#[test]
fn failed_revalidations_keep_the_style() {
let (mut map, run_loop) = map_with_style_response(|_| Some(style_response(REMOTE)));
map.load_style_url("http://some-url");
run_loop.run_once(&mut ());
map.drain_events();
for _ in 0..3 {
map.style_loader().push_style_response(connection_error());
let events = map.drain_events();
assert!(load_failures(&events).is_empty(), "{events:?}");
}
assert!(map.style_document_loaded());
assert_eq!("Remote", map.style().name());
}
#[test]
fn json_that_is_no_style_fails_the_load() {
let (mut map, _run_loop) = map_with_style_response(|_| None);
map.load_style_json("[]");
let events = map.drain_events();
assert_eq!(
vec![StyleLoadError::Parse("Failed to parse style: style must be an object".to_owned())],
load_failures(&events)
);
assert!(!map.style_document_loaded());
}
#[test]
fn json_loaded_during_a_url_load_wins_over_the_url() {
let run_loop = Queue::<()>::new();
let file_source = Arc::new(StubFileSource::new(ResponseType::Manual));
file_source.set_response(Kind::Style, |_| Some(style_response(r#"{"version": 8, "name": "Streets"}"#)));
let mut map = super::test_map(Arc::<StubFileSource>::clone(&file_source), MapOptions::default());
map.load_style_url("http://some-url");
map.load_style_json(r#"{"version": 8, "name": "Test Style", "sources": {}, "layers": []}"#);
assert_eq!("Test Style", map.style().name());
assert_eq!(None, map.style_url());
assert!(map.style().json().contains("Test Style"));
file_source.respond_to_all();
run_loop.run_once(&mut ());
map.process_events();
assert_eq!("Test Style", map.style().name());
}
#[test]
fn the_document_is_loaded_before_its_sources() {
let mut map = map_over(Arc::new(StubFileSource::new(ResponseType::Manual)), MapOptions::default());
assert!(!map.style_document_loaded());
map.load_style_json(
r#"{
"version": 8,
"sources": {
"pending": {
"type": "geojson",
"data": { "type": "FeatureCollection", "features": [] }
}
},
"layers": []
}"#,
);
assert!(map.style_document_loaded());
map.load_style_url("http://some-url");
assert!(!map.style_document_loaded());
}
fn default_sprite_path() -> String {
testdata("test/fixtures/resources/sprite")
}
fn sprite_style(sprite_path: &str) -> String {
serde_json::json!({"version": 8, "sprite": sprite_path, "sources": {}, "layers": []}).to_string()
}
fn successful_response(
extension: &'static str,
sprite_path: String,
pixel_ratio: f32,
) -> impl Fn(&Resource) -> Option<Response> {
move |resource: &Resource| {
assert_eq!(format!("{sprite_path}{}{extension}", if pixel_ratio == 2.0 { "@2x" } else { "" }), resource.url);
let mut response = Response::new();
response.data = Some(Arc::new(std::fs::read(&resource.url).unwrap()));
Some(response)
}
}
fn failed_sprite_response() -> Response {
let mut response = Response::new();
response.error = Some(Box::new(ResourceError::new(Reason::Other, "Failed by the test case")));
response
}
fn corrupt_sprite_response() -> Response {
let mut response = Response::new();
response.data = Some(Arc::new(b"CORRUPT".to_vec()));
response
}
fn load_sprite(
file_source: Arc<StubFileSource>,
sprite_path: &str,
pixel_ratio: f32,
run_loop: &Queue<()>,
) -> (Map, MapEvent) {
let options = MapOptions { pixel_ratio, ..Default::default() };
let mut map = map_over(file_source, options);
let handle = run_loop.clone();
map.set_reports_waker(Some(Arc::new(move || handle.stop())));
map.load_style_json(&sprite_style(sprite_path));
loop {
for event in map.drain_events() {
if matches!(event, MapEvent::SpriteLoaded(_) | MapEvent::SpriteError(..)) {
return (map, event);
}
}
run_loop.run(&mut ());
}
}
#[test]
fn a_sprite_loads_its_images() {
let versatiles = testdata("test/fixtures/resources/versatiles-sprite/sprite");
for (sprite_path, pixel_ratio, images) in
[(default_sprite_path(), 1.0, 418), (versatiles.clone(), 1.0, 112), (versatiles, 2.0, 112)]
{
let run_loop = Queue::<()>::new();
let file_source = StubFileSource::on_queue(&run_loop, ResponseType::Asynchronous);
file_source.set_response(Kind::SpriteImage, successful_response(".png", sprite_path.clone(), pixel_ratio));
file_source.set_response(Kind::SpriteJSON, successful_response(".json", sprite_path.clone(), pixel_ratio));
let (map, event) = load_sprite(file_source, &sprite_path, pixel_ratio, &run_loop);
assert!(matches!(event, MapEvent::SpriteLoaded(Some(_))), "{event:?}");
assert_eq!(images, map.style().images().len(), "{sprite_path} at {pixel_ratio}");
assert!(map.style_loaded());
}
}
fn sprite_error(
image: impl Fn(&Resource) -> Option<Response> + Send + Sync + 'static,
json: impl Fn(&Resource) -> Option<Response> + Send + Sync + 'static,
) -> String {
let run_loop = Queue::<()>::new();
let file_source = StubFileSource::on_queue(&run_loop, ResponseType::Asynchronous);
file_source.set_response(Kind::SpriteImage, image);
file_source.set_response(Kind::SpriteJSON, json);
let (map, event) = load_sprite(file_source, &default_sprite_path(), 1.0, &run_loop);
let MapEvent::SpriteError(Some(_), error) = event else { panic!("{event:?}") };
assert_eq!(Some(&error), map.last_style_error());
error.to_string()
}
#[test]
fn a_sprite_that_fails_to_load_or_parse_reports_why() {
let image = || successful_response(".png", default_sprite_path(), 1.0);
let json = || successful_response(".json", default_sprite_path(), 1.0);
let failed = |_: &Resource| Some(failed_sprite_response());
let corrupt = |_: &Resource| Some(corrupt_sprite_response());
assert_eq!("Failed by the test case", sprite_error(image(), failed));
assert_eq!("Failed by the test case", sprite_error(failed, json()));
let error = sprite_error(image(), corrupt);
assert!(error.starts_with("Failed to parse JSON: "), "{error}");
sprite_error(corrupt, json());
}
#[test]
fn a_sprite_without_answers_keeps_the_style_loading() {
let run_loop = Queue::<()>::new();
let file_source = StubFileSource::on_queue(&run_loop, ResponseType::Asynchronous);
let stop = run_loop.clone();
let end = move |_: &Resource| -> Option<Response> {
stop.stop();
None
};
file_source.set_response(Kind::SpriteImage, end.clone());
file_source.set_response(Kind::SpriteJSON, end);
let mut map = map_over(file_source, MapOptions::default());
map.load_style_json(&sprite_style(&default_sprite_path()));
run_loop.run(&mut ());
let events = map.drain_events();
assert!(events.iter().any(|event| matches!(event, MapEvent::SpriteRequested(Some(_)))), "{events:?}");
assert!(!events.iter().any(|event| matches!(event, MapEvent::SpriteLoaded(_))), "Should never be called");
assert!(!map.style_loaded());
}
#[test]
fn a_style_without_a_sprite_loads_an_empty_one() {
let (mut map, _run_loop) = map_with_style_response(|_| None);
map.load_style_json(REMOTE);
let events = map.drain_events();
assert!(events.iter().any(|event| matches!(event, MapEvent::SpriteLoaded(None))), "{events:?}");
assert!(map.style_loaded());
}
const DOTS: &str = r#"{"id":"dots","type":"circle","source":"points"}"#;
#[test]
fn edits_fail_while_the_style_is_not_loaded() {
let (mut map, _run_loop) = map_with_style_response(|_| None);
assert!(!map.style_document_loaded());
let not_loaded = |result: Result<(), mln_style::error::Error>| {
let error = result.expect_err("the edit should fail");
assert_eq!(
(mln_style::error::ErrorKind::InvalidState, "style is not loaded"),
(error.kind, error.message.as_str())
);
};
not_loaded(map.edit_loaded_style(|style| style.add_layer_json(DOTS, None)));
not_loaded(map.edit_loaded_style(|style| style.set_layer_property_json("dots", "circle-radius", "4")));
not_loaded(map.edit_loaded_style(|style| style.set_root_property_json("light", r#"{"intensity":0.5}"#)));
not_loaded(map.edit_loaded_style(|style| style.set_global_state_property_json("theme", "true")));
assert!(map.style().sources().is_empty() && map.style().layers().len() == 0);
}
#[test]
fn edits_fail_during_a_url_load_and_the_old_version_stays_published() {
let run_loop = Queue::<()>::new();
let file_source = Arc::new(StubFileSource::new(ResponseType::Manual));
file_source.set_response(Kind::Style, |_| Some(style_response(REMOTE)));
let options = MapOptions { map_mode: crate::map::MapMode::Continuous, ..MapOptions::default() };
let mut map = super::test_map(Arc::<StubFileSource>::clone(&file_source), options);
let reader = map.update_reader();
map.load_style_json(r#"{"version": 8, "name": "Local", "sources": {}, "layers": []}"#);
let published = Arc::clone(&reader.latest().expect("an update").parameters.style);
let local = Arc::clone(map.style());
map.load_style_url("http://some-url");
assert!(!map.style_document_loaded());
let error = map.edit_loaded_style(|style| style.add_layer_json(r#"{"id":"paper","type":"background"}"#, None));
assert_eq!(mln_style::error::ErrorKind::InvalidState, error.unwrap_err().kind);
assert!(Arc::ptr_eq(&local, map.style()));
assert!(Arc::ptr_eq(&local, &published));
assert!(Arc::ptr_eq(&published, &reader.latest().expect("an update").parameters.style));
file_source.respond_to_all();
run_loop.run_once(&mut ());
map.process_events();
assert!(map.style_document_loaded());
assert_eq!("Remote", map.style().name());
map.edit_loaded_style(|style| style.add_layer_json(r#"{"id":"paper","type":"background"}"#, None)).unwrap();
}