mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! Test helpers: the C++ `FixtureLog`, over `tracing` and per thread,
//! and `convertJSON`.

use std::borrow::Cow;
use std::fmt::{self, Write as _};
use std::sync::Arc;

use parking_lot::Mutex;
use tracing::Level;
use tracing::subscriber::DefaultGuard;
use tracing_subscriber::layer::{Context, SubscriberExt};
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::{Layer, Registry};

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct LogMessage {
    pub(crate) level: Level,
    pub(crate) target: String,
    /// The message followed by each other field as ` name=value`.
    pub(crate) msg: String,
    /// The `error` field, which carries the text a style's parser reports.
    pub(crate) error: Option<String>,
}

type Messages = Arc<Mutex<Vec<(LogMessage, bool)>>>;

/// An event's line: its message, then each other field as ` name=value`.
#[derive(Default)]
struct Message {
    message: String,
    fields: String,
    error: Option<String>,
}

impl Message {
    fn line(&self) -> String {
        format!("{}{}", self.message, self.fields)
    }
}

impl tracing::field::Visit for Message {
    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        if field.name() == "message" {
            self.message = value.to_owned();
        } else {
            let _ = write!(self.fields, " {}={value}", field.name());
            if field.name() == "error" {
                self.error = Some(value.to_owned());
            }
        }
    }

    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
        if field.name() == "message" {
            self.message = format!("{value:?}");
        } else {
            let _ = write!(self.fields, " {}={value:?}", field.name());
            if field.name() == "error" {
                self.error = Some(format!("{value:?}"));
            }
        }
    }
}

/// Collects the library's events.
struct Catcher(Messages);

impl<S: tracing::Subscriber + for<'a> LookupSpan<'a>> Layer<S> for Catcher {
    fn on_event(&self, event: &tracing::Event<'_>, _cx: Context<'_, S>) {
        let metadata = event.metadata();
        if !metadata.target().starts_with("mln_") || *metadata.level() > Level::INFO {
            return;
        }
        let mut message = Message::default();
        event.record(&mut message);
        let message = LogMessage {
            level: *metadata.level(),
            target: metadata.target().to_owned(),
            msg: message.line(),
            error: message.error,
        };
        self.0.lock().push((message, false));
    }
}

/// Records this thread's log messages while alive.
pub(crate) struct FixtureLog {
    messages: Messages,
    _guard: DefaultGuard,
}

impl FixtureLog {
    pub(crate) fn new() -> Self {
        let messages = Messages::default();
        let guard = tracing::subscriber::set_default(Registry::default().with(Catcher(Arc::clone(&messages))));
        FixtureLog { messages, _guard: guard }
    }

    /// `count(message)`: the number of matching messages, which are then
    /// checked.
    pub(crate) fn count(&self, level: Level, target: &str, msg: &str) -> usize {
        let mut messages = self.messages.lock();
        let mut count = 0;
        for (m, checked) in messages.iter_mut() {
            if m.level == level && m.target == target && m.msg == msg {
                *checked = true;
                count += 1;
            }
        }
        count
    }

    /// `count`, for a message whose `error` field is `error`.
    pub(crate) fn count_error(&self, level: Level, target: &str, error: &str) -> usize {
        let mut messages = self.messages.lock();
        let mut count = 0;
        for (m, checked) in messages.iter_mut() {
            if m.level == level && m.target == target && m.error.as_deref() == Some(error) {
                *checked = true;
                count += 1;
            }
        }
        count
    }

    /// The messages no `count` call has matched.
    pub(crate) fn unchecked(&self) -> Vec<LogMessage> {
        self.messages.lock().iter().filter(|(_, checked)| !checked).map(|(m, _)| m.clone()).collect()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.messages.lock().is_empty()
    }

    pub(crate) fn messages(&self) -> Vec<LogMessage> {
        self.messages.lock().iter().map(|(m, _)| m.clone()).collect()
    }
}

/// Reads a file of testdata/, the copy of the C++ repository's files that
/// these tests read, by its path relative to the repository.
pub(crate) fn read_file(relative: &str) -> String {
    let path = std::path::Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("testdata").join(relative);
    std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
}

pub(crate) fn parse_json(json: &str) -> serde_json::Value {
    serde_json::from_str(json).expect("test JSON must parse")
}

pub(super) use crate::conversion::value_to_json;

pub(crate) struct StubGeometryTileFeature {
    pub(crate) properties: crate::feature::PropertyMap,
    pub(crate) id: crate::feature::Identifier,
    pub(crate) type_: crate::geometry::FeatureType,
    pub(crate) geometry: crate::feature::GeometryCollection,
}

impl StubGeometryTileFeature {
    pub(crate) fn new(properties: crate::feature::PropertyMap) -> Self {
        StubGeometryTileFeature {
            properties,
            id: crate::feature::Identifier::Null,
            type_: crate::geometry::FeatureType::Point,
            geometry: crate::feature::GeometryCollection::default(),
        }
    }

    pub(crate) fn with_geometry(
        type_: crate::geometry::FeatureType,
        geometry: crate::feature::GeometryCollection,
    ) -> Self {
        StubGeometryTileFeature {
            properties: crate::feature::PropertyMap::default(),
            id: crate::feature::Identifier::Null,
            type_,
            geometry,
        }
    }

    /// A feature with an id, a type and properties, and no geometry.
    pub(crate) fn with_id_type(
        id: crate::feature::Identifier,
        type_: crate::geometry::FeatureType,
        properties: crate::feature::PropertyMap,
    ) -> Self {
        StubGeometryTileFeature { properties, id, type_, geometry: crate::feature::GeometryCollection::default() }
    }
}

impl crate::feature::GeometryTileFeature for StubGeometryTileFeature {
    fn feature_type(&self) -> crate::geometry::FeatureType {
        self.type_
    }

    fn value(&self, key: &str) -> Option<crate::feature::Value> {
        self.properties.get(key).cloned()
    }

    fn properties(&self) -> Cow<'_, crate::feature::PropertyMap> {
        Cow::Borrowed(&self.properties)
    }

    fn id(&self) -> crate::feature::Identifier {
        self.id.clone()
    }

    fn geometries(&self) -> Result<Cow<'_, crate::feature::GeometryCollection>, crate::error::Error> {
        Ok(Cow::Borrowed(&self.geometry))
    }
}

pub(crate) fn property_map(entries: &[(&str, crate::feature::Value)]) -> crate::feature::PropertyMap {
    entries.iter().map(|(k, v)| ((*k).to_owned(), v.clone())).collect()
}

/// A layer of the built-in type `type_`.
pub(crate) fn new_layer(type_: &str, id: &str, source: &str) -> crate::layer::Layer {
    crate::layer::Layer::new(&crate::StyleRegistry::with_builtins(), type_, id, source).unwrap()
}

/// The style data of `layer`, a `T` layer.
pub(crate) fn style_of<T: crate::layer::StyleLayerType>(layer: &crate::layer::Layer) -> &crate::layer::LayerStyle<T> {
    crate::layer::LayerStyle::recover_ref(&**layer.style()).unwrap()
}

impl crate::Style {
    /// Replaces the style with the one `json` describes, as a map's loader
    /// does; a document that doesn't parse leaves the style as it was.
    pub(crate) fn load_json(&mut self, json: &str) {
        if let Ok(parsed) = Self::from_json(&Arc::clone(self.registry()), json) {
            *self = parsed;
        }
    }
}

impl crate::Style {
    /// Records the source that `json` describes, as the map does when it
    /// adds one.
    pub(crate) fn add_source_json(&mut self, id: &str, json: &str) {
        let value: serde_json::Value = serde_json::from_str(json).expect("JSON");
        let mut error = crate::conversion::Error::default();
        let registry = Arc::clone(self.registry());
        let source =
            crate::source::convert_source(&crate::conversion::Convertible::from(&value), &mut error, id, &registry)
                .expect("a source");
        let _ = self.apply(crate::style::edit::Edit::AddSource(source));
    }
}