laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
//! `Excel::fake()`: `Maatwebsite\Excel\Fakes\ExcelFake`.

use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

use indexmap::IndexMap;

use crate::excel::Excel;
use crate::export::Export;
use crate::import::Import;

#[derive(Clone)]
struct Recorded {
    type_name: &'static str,
    snapshot: Option<Arc<dyn Any + Send + Sync>>,
}

#[derive(Default)]
struct Records {
    downloads: IndexMap<String, Recorded>,
    stored: HashMap<String, IndexMap<String, Recorded>>,
    queued: HashMap<String, IndexMap<String, Recorded>>,
    raws: IndexMap<&'static str, Recorded>,
    imported: HashMap<String, IndexMap<String, Recorded>>,
    match_by_regex: bool,
}

/// What a fake records.
#[derive(Default)]
pub(crate) struct FakeState {
    records: Mutex<Records>,
}

fn disk_key(disk: Option<&str>) -> String {
    disk.unwrap_or("default").to_owned()
}

fn export_record(export: &dyn Export) -> Recorded {
    Recorded {
        type_name: export.__type_name(),
        snapshot: export.__snapshot(),
    }
}

fn import_record(import: &dyn Import) -> Recorded {
    Recorded {
        type_name: import.__type_name(),
        snapshot: import.__snapshot(),
    }
}

impl FakeState {
    fn records(&self) -> MutexGuard<'_, Records> {
        self.records.lock().unwrap_or_else(PoisonError::into_inner)
    }

    pub(crate) fn record_download(&self, file_name: &str, export: &dyn Export) {
        self.records()
            .downloads
            .insert(file_name.to_owned(), export_record(export));
    }

    pub(crate) fn record_store(&self, disk: Option<&str>, file_path: &str, export: &dyn Export) {
        self.records()
            .stored
            .entry(disk_key(disk))
            .or_default()
            .insert(file_path.to_owned(), export_record(export));
    }

    pub(crate) fn record_queue(&self, disk: Option<&str>, file_path: &str, export: &dyn Export) {
        let mut records = self.records();
        records
            .stored
            .entry(disk_key(disk))
            .or_default()
            .insert(file_path.to_owned(), export_record(export));
        records
            .queued
            .entry(disk_key(disk))
            .or_default()
            .insert(file_path.to_owned(), export_record(export));
    }

    pub(crate) fn record_raw(&self, export: &dyn Export) {
        let record = export_record(export);
        self.records().raws.insert(record.type_name, record);
    }

    pub(crate) fn record_import(&self, disk: Option<&str>, file: &str, import: &dyn Import) {
        self.records()
            .imported
            .entry(disk_key(disk))
            .or_default()
            .insert(file.to_owned(), import_record(import));
    }

    pub(crate) fn record_queued_import(&self, disk: Option<&str>, file: &str, import: &dyn Import) {
        let mut records = self.records();
        records
            .queued
            .entry(disk_key(disk))
            .or_default()
            .insert(file.to_owned(), import_record(import));
        records
            .imported
            .entry(disk_key(disk))
            .or_default()
            .insert(file.to_owned(), import_record(import));
    }
}

/// A faked `Excel`: nothing is written or read, and every call is recorded for assertions.
///
/// Keep the handle alive while the test runs; dropping it restores the real `Excel`.
///
/// ```ignore
/// let excel = Excel::fake().await;
///
/// app.get("/users/export").await.assert_ok();
///
/// excel.assert_downloaded("users.xlsx");
/// excel.assert_downloaded_with("users.xlsx", |export: &UsersExport| export.year == 2026);
/// ```
///
/// Callbacks receive a copy of the export or import, so its type must implement `Clone`.
#[must_use = "keep the fake alive while the test runs"]
pub struct ExcelFake {
    state: Arc<FakeState>,
    slot: Arc<Mutex<Option<Arc<FakeState>>>>,
}

impl Drop for ExcelFake {
    fn drop(&mut self) {
        let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
        if slot.as_ref().is_some_and(|current| Arc::ptr_eq(current, &self.state)) {
            *slot = None;
        }
    }
}

impl Excel {
    /// `Excel::fake()`: replaces `Excel` in this application with a fake.
    pub async fn fake() -> ExcelFake {
        let slot = crate::excel::state().await.fake;
        let state = Arc::new(FakeState::default());
        *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(state.clone());
        ExcelFake { state, slot }
    }
}

impl ExcelFake {
    /// `matchByRegex()`: file names in assertions are regular expressions, such as
    /// `/\w{10}-\w{8}\.csv/`.
    pub fn match_by_regex(&self) {
        self.state.records().match_by_regex = true;
    }

    /// `doNotMatchByRegex()`: file names in assertions are exact again.
    pub fn do_not_match_by_regex(&self) {
        self.state.records().match_by_regex = false;
    }

    fn find(records: &Records, key: &str, map: &IndexMap<String, Recorded>, message: &str) -> Recorded {
        if records.match_by_regex {
            let pattern = key.trim_start_matches('/').trim_end_matches('/');
            let regex = regex::Regex::new(pattern).unwrap_or_else(|error| panic!("invalid pattern {key}: {error}"));
            let matches: Vec<&Recorded> = map
                .iter()
                .filter(|(name, _)| regex.is_match(name))
                .map(|(_, record)| record)
                .collect();
            assert!(!matches.is_empty(), "{message}");
            assert_eq!(
                matches.len(),
                1,
                "More than one result matches the file name expression '{key}'."
            );
            return matches[0].clone();
        }
        map.get(key).cloned().unwrap_or_else(|| panic!("{message}"))
    }

    fn check<T: 'static>(record: &Recorded, callback: impl FnOnce(&T) -> bool, failure: &str) {
        let snapshot = record.snapshot.as_ref().unwrap_or_else(|| {
            panic!(
                "{} must implement Clone for an assertion callback to inspect it.",
                record.type_name
            )
        });
        let value = snapshot.downcast_ref::<T>().unwrap_or_else(|| {
            panic!(
                "The recorded {} isn't a {}.",
                record.type_name,
                std::any::type_name::<T>()
            )
        });
        assert!(callback(value), "{failure}");
    }

    /// `assertDownloaded()`.
    #[track_caller]
    pub fn assert_downloaded(&self, file_name: &str) {
        let records = self.state.records();
        Self::find(
            &records,
            file_name,
            &records.downloads,
            &format!("{file_name} is not downloaded"),
        );
    }

    /// `assertDownloaded()` with a callback.
    #[track_caller]
    pub fn assert_downloaded_with<E: 'static>(&self, file_name: &str, callback: impl FnOnce(&E) -> bool) {
        let records = self.state.records();
        let record = Self::find(
            &records,
            file_name,
            &records.downloads,
            &format!("{file_name} is not downloaded"),
        );
        drop(records);
        Self::check(
            &record,
            callback,
            &format!("The file [{file_name}] was not downloaded with the expected data."),
        );
    }

    fn stored_record(&self, file_path: &str, disk: Option<&str>) -> Recorded {
        let disk = disk_key(disk);
        let records = self.state.records();
        let empty = IndexMap::new();
        let map = records.stored.get(&disk).unwrap_or(&empty);
        Self::find(
            &records,
            file_path,
            map,
            &format!("{file_path} is not stored on disk {disk}"),
        )
    }

    /// `assertStored()` on the default disk (`None`) or the named disk.
    #[track_caller]
    pub fn assert_stored(&self, file_path: &str, disk: Option<&str>) {
        self.stored_record(file_path, disk);
    }

    /// `assertStored()` with a callback.
    #[track_caller]
    pub fn assert_stored_with<E: 'static>(
        &self,
        file_path: &str,
        disk: Option<&str>,
        callback: impl FnOnce(&E) -> bool,
    ) {
        let record = self.stored_record(file_path, disk);
        Self::check(
            &record,
            callback,
            &format!("The file [{file_path}] was not stored with the expected data."),
        );
    }

    fn queued_record(&self, file_path: &str, disk: Option<&str>) -> Recorded {
        let disk = disk_key(disk);
        let records = self.state.records();
        let empty = IndexMap::new();
        let map = records.queued.get(&disk).unwrap_or(&empty);
        Self::find(
            &records,
            file_path,
            map,
            &format!("{file_path} is not queued for export on disk {disk}"),
        )
    }

    /// `assertQueued()`: an export (or import) was queued for `file_path`.
    #[track_caller]
    pub fn assert_queued(&self, file_path: &str, disk: Option<&str>) {
        self.queued_record(file_path, disk);
    }

    /// `assertQueued()` with a callback.
    #[track_caller]
    pub fn assert_queued_with<E: 'static>(
        &self,
        file_path: &str,
        disk: Option<&str>,
        callback: impl FnOnce(&E) -> bool,
    ) {
        let record = self.queued_record(file_path, disk);
        Self::check(
            &record,
            callback,
            &format!("The file [{file_path}] was not stored with the expected data."),
        );
    }

    /// `assertExportedInRaw()`: an export of type `E` was written with `raw()`.
    #[track_caller]
    pub fn assert_exported_in_raw<E: 'static>(&self) {
        let name = std::any::type_name::<E>();
        assert!(
            self.state.records().raws.contains_key(name),
            "{name} is not exported in raw"
        );
    }

    /// `assertExportedInRaw()` with a callback.
    #[track_caller]
    pub fn assert_exported_in_raw_with<E: 'static>(&self, callback: impl FnOnce(&E) -> bool) {
        let name = std::any::type_name::<E>();
        let record = self
            .state
            .records()
            .raws
            .get(name)
            .cloned()
            .unwrap_or_else(|| panic!("{name} is not exported in raw"));
        Self::check(
            &record,
            callback,
            &format!("The [{name}] export was not exported in raw with the expected data."),
        );
    }

    fn imported_record(&self, file_path: &str, disk: Option<&str>) -> Recorded {
        let disk = disk_key(disk);
        let records = self.state.records();
        let empty = IndexMap::new();
        let map = records.imported.get(&disk).unwrap_or(&empty);
        Self::find(
            &records,
            file_path,
            map,
            &format!("{file_path} is not stored on disk {disk}"),
        )
    }

    /// `assertImported()`.
    #[track_caller]
    pub fn assert_imported(&self, file_path: &str, disk: Option<&str>) {
        self.imported_record(file_path, disk);
    }

    /// `assertImported()` with a callback.
    #[track_caller]
    pub fn assert_imported_with<I: 'static>(
        &self,
        file_path: &str,
        disk: Option<&str>,
        callback: impl FnOnce(&I) -> bool,
    ) {
        let record = self.imported_record(file_path, disk);
        Self::check(
            &record,
            callback,
            &format!("The file [{file_path}] was not imported with the expected data."),
        );
    }
}