crisol-core 1.2.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
//! The implementation-independent conformance suite for data backends (SWAP-04).
//!
//! A new backend (native Arrow, `f32` columns, a remote source) implements
//! [`Conformance`] and calls [`run`]. The suite checks schema reporting, paging,
//! bounds, slicing, and null handling without knowing how the backend stores data.
//!
//! ```
//! use crisol_core::data::conformance::run;
//! use crisol_core::data::MemorySource;
//!
//! run::<MemorySource>().expect("the in-memory backend conforms");
//! ```

use std::ops::Range;

use super::column::{CellValue, Column, ColumnType};
use super::dataset::Dataset;
use super::source::{ColumnSchema, DataSource};

/// A backend that can produce its own fixture.
///
/// The fixture must have three rows: `x = [1.0, 2.0, 3.0]`, `n = [1, 2, 3]`, and
/// `label = ["a", "b", "c"]`, with the middle `x` invalid (null).
/// # Example
///
/// ```
/// use crisol_core::data::conformance::Conformance;
/// ```
pub trait Conformance: DataSource {
    /// Build the fixture described by the trait documentation.
    fn fixture() -> Self;
}

/// One failure from the suite.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::data::conformance::ConformanceError;
/// ```
pub enum ConformanceError {
    /// The schema does not have the expected shape.
    #[error("schema: {0}")]
    Schema(String),
    /// A row count is wrong.
    #[error("row count: expected {expected}, got {actual}")]
    RowCount {
        /// Expected rows.
        expected: usize,
        /// Actual rows.
        actual: usize,
    },
    /// A page did not have the expected values.
    #[error("page: {0}")]
    Page(String),
    /// A range that should fail did not.
    #[error("range {0:?} was accepted")]
    RangeAccepted(Range<usize>),
    /// The backend could not read a valid range.
    #[error("read: {0}")]
    Read(String),
}

/// Run the full suite against a backend.
///
/// # Errors
/// With the first failed expectation.
// spec: SWAP-04
/// # Example
///
/// ```
/// use crisol_core::data::conformance::run;
/// ```
pub fn run<Impl: Conformance>() -> Result<(), ConformanceError> {
    let source = Impl::fixture();
    check_schema(source.schema())?;
    if source.row_count() != 3 {
        return Err(ConformanceError::RowCount {
            expected: 3,
            actual: source.row_count(),
        });
    }
    let all = source
        .read_range(0..3)
        .map_err(|error| ConformanceError::Read(error.to_string()))?;
    if all.row_count() != 3 {
        return Err(ConformanceError::Page(format!(
            "expected 3 rows, got {}",
            all.row_count()
        )));
    }
    if all.column(0).map(Column::kind) != Some(ColumnType::Float) {
        return Err(ConformanceError::Schema("x is not a float column".to_owned()));
    }
    if all.cell(1, 0) != CellValue::Null {
        return Err(ConformanceError::Page("the middle x is not null".to_owned()));
    }
    let page = source
        .read_range(1..3)
        .map_err(|error| ConformanceError::Read(error.to_string()))?;
    if page.row_count() != 2 || page.cell(0, 1) != CellValue::Int(2) || page.cell(1, 2) != CellValue::Text("c") {
        return Err(ConformanceError::Page("the 1..3 page is wrong".to_owned()));
    }
    for range in [2..9, 3..4] {
        if source.read_range(range.clone()).is_ok() {
            return Err(ConformanceError::RangeAccepted(range));
        }
    }
    let (start, end) = (4, 2);
    if source.read_range(start..end).is_ok() {
        return Err(ConformanceError::RangeAccepted(start..end));
    }
    Ok(())
}

fn check_schema(schema: &[ColumnSchema]) -> Result<(), ConformanceError> {
    let expected = [
        ("x", ColumnType::Float),
        ("n", ColumnType::Int),
        ("label", ColumnType::Text),
    ];
    if schema.len() != expected.len() {
        return Err(ConformanceError::Schema(format!(
            "expected {} columns, got {}",
            expected.len(),
            schema.len()
        )));
    }
    for (column, (name, kind)) in schema.iter().zip(expected) {
        if column.name != name || column.kind != kind {
            return Err(ConformanceError::Schema(format!(
                "expected {name}:{kind:?}, got {}:{:?}",
                column.name, column.kind
            )));
        }
    }
    Ok(())
}

#[cfg(feature = "polars")]
impl Conformance for super::polars::PolarsSource {
    fn fixture() -> Self {
        super::polars::conformance_fixture()
    }
}

impl Conformance for super::source::MemorySource {
    fn fixture() -> Self {
        let data = Dataset::from_columns([
            Column::floats("x", vec![1.0, 0.0, 3.0]).with_validity([true, false, true]),
            Column::ints("n", vec![1, 2, 3]),
            Column::text("label", ["a", "b", "c"]),
        ]);
        Self::new(data)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "polars")]
    #[test]
    fn the_polars_backend_conforms() {
        run::<super::super::polars::PolarsSource>().expect("Polars conforms");
    }

    #[test]
    fn the_memory_backend_conforms() {
        run::<super::super::source::MemorySource>().expect("conforms");
    }

    #[test]
    fn an_invalid_range_is_reported() {
        let error = ConformanceError::RangeAccepted(2..9);
        assert!(error.to_string().contains("2..9"));
    }

    #[test]
    fn a_bad_schema_is_reported() {
        let error = super::check_schema(&[ColumnSchema::new("x", ColumnType::Float)]).expect_err("bad");
        assert!(matches!(error, ConformanceError::Schema(_)));
    }
}