Skip to main content

eov_plugin_api/
testing.rs

1//! Unit-test support for plugins: run a [`Plugin`] against an in-memory
2//! mock host.
3//!
4//! ```
5//! use eov_plugin_api::prelude::*;
6//! use eov_plugin_api::testing::TestHarness;
7//!
8//! struct Counter {
9//!     host: Host,
10//! }
11//!
12//! impl Plugin for Counter {
13//!     fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
14//!         Ok(Self { host })
15//!     }
16//!
17//!     fn on_event(&self, event: HostEvent) -> Result<(), String> {
18//!         if let HostEvent::FileOpened { file } = event {
19//!             self.host.info(format!("opened {}", file.filename));
20//!         }
21//!         Ok(())
22//!     }
23//! }
24//!
25//! let harness = TestHarness::<Counter>::new().unwrap();
26//! harness
27//!     .send(HostEvent::FileOpened {
28//!         file: FileInfo {
29//!             file_id: 1,
30//!             filename: "a.svs".into(),
31//!             ..Default::default()
32//!         },
33//!     })
34//!     .unwrap();
35//! assert_eq!(harness.calls_to("log").len(), 1);
36//! ```
37//!
38//! The mock answers every method the real host knows with a plausible
39//! result, keeps layers, surfaces, settings and contributions in memory so
40//! tests can inspect them, and records every call. Unlike eov, it does not
41//! turn `host.warn`/`host.error` into notifications: find those among the
42//! recorded `log` calls by their `level`.
43//!
44//! # Languages in tests
45//!
46//! The language and catalog [`tr!`](crate::tr!) translates with belong to
47//! the whole plugin library, not to one harness: every
48//! [`TestHarness::new`] or [`TestHarness::with_init`] sets them from
49//! [`PluginInit::language`] ([`test_init`] gives English), and
50//! [`HostEvent::LanguageChanged`] switches them for every test of the
51//! binary. Tests run in parallel, so a test that changes the language can
52//! change the texts another test compares, and creating a harness can put
53//! it back to English in the middle of that test. Run the tests that
54//! change languages in an integration-test binary of their own
55//! (`tests/language.rs`), one at a time behind a lock, as eov's own plugins
56//! do; or hold the same lock while every harness is created and used.
57//!
58//! The `thread-local-language` feature of this crate, on its
59//! dev-dependency (`eov-plugin-api = { version = "1.1", features =
60//! ["thread-local-language"] }` under `[dev-dependencies]`), gives each
61//! thread its own language and catalog instead. A harness then sets them
62//! for the thread that creates it, and `LanguageChanged` for the thread
63//! that sends it; texts a plugin makes on threads of its own are in
64//! English, since new threads start in English. It suits plugins that make
65//! their texts on the thread that delivers events.
66//!
67//! A harness finds the plugin's catalogs as eov does: through the `[i18n]`
68//! table of `plugin.toml` in [`PluginInit::plugin_root`]. [`test_init`]'s
69//! root is an empty temporary folder, so a language set on it changes only
70//! [`i18n::current`](crate::i18n::current) (the decimal separator,
71//! isolation), and `tr!` stays English without a word. To test
72//! translations, put `plugin.toml` and
73//! `<catalogs>/<tag>/LC_MESSAGES/<domain>.po` into `plugin_root` before
74//! creating the harness, as the example plugin's
75//! `texts_follow_the_language_of_the_interface` test does, or set a catalog
76//! with [`i18n::set_catalog`](crate::i18n::set_catalog) after creating it
77//! (creating another harness sets the language and catalog again).
78
79use crate::abi::{
80    FfiError, FfiErrorKind, FfiResult, FilterFrame, FilterView, HostFfi, HostFfi_TO, Pixels,
81    PluginBox, RasterUpload, RegionRequest,
82};
83use crate::protocol::{methods, *};
84use crate::sdk::{Image, Plugin, create_plugin, slide_source_of};
85use abi_stable::{
86    sabi_trait::TD_Opaque,
87    std_types::{RErr, ROk, RSliceMut, RStr, RString},
88};
89use serde::de::DeserializeOwned;
90use serde_json::{Map, Value, json};
91use std::collections::BTreeMap;
92use std::marker::PhantomData;
93use std::sync::atomic::{AtomicU64, Ordering};
94use std::sync::{Arc, Mutex, MutexGuard};
95
96/// One recorded host call.
97#[derive(Debug, Clone, PartialEq)]
98pub struct RecordedCall {
99    pub method: String,
100    pub args: Value,
101}
102
103/// A layer as the mock host stores it.
104#[derive(Debug, Clone, PartialEq)]
105pub struct MockLayer {
106    pub spec: LayerSpec,
107    pub objects: BTreeMap<String, OverlayObject>,
108    pub rasters: BTreeMap<String, RasterUpload>,
109    pub selection: Vec<String>,
110    /// Panes the plugin hid the layer in (`layer.set_pane_visibility`).
111    pub hidden_panes: std::collections::BTreeSet<PaneId>,
112    /// Objects drawn highlighted (`layer.highlight`).
113    pub highlighted: Vec<String>,
114    /// The only panes showing the layer (`layer.set_panes`).
115    pub only_panes: Option<Vec<PaneId>>,
116}
117
118/// A surface as the mock host stores it.
119#[derive(Debug, Clone, PartialEq)]
120pub struct MockSurface {
121    pub spec: SurfaceSpec,
122    pub properties: Map<String, Value>,
123    pub open: bool,
124}
125
126type RegionReader = dyn Fn(&RegionRequest) -> Result<Image, String> + Send + Sync;
127
128/// Everything the mock host knows. Tests may read and modify it freely.
129#[derive(Default)]
130pub struct MockState {
131    pub calls: Vec<RecordedCall>,
132    pub snapshot: HostSnapshot,
133    pub properties: BTreeMap<FileId, PropertyMap>,
134    pub settings: Map<String, Value>,
135    pub layers: BTreeMap<String, MockLayer>,
136    pub surfaces: BTreeMap<String, MockSurface>,
137    pub toolbar_buttons: BTreeMap<String, ToolbarButtonSpec>,
138    pub hud_buttons: BTreeMap<String, HudButtonSpec>,
139    pub tools: BTreeMap<String, ToolSpec>,
140    pub hotkeys: BTreeMap<String, HotkeySpec>,
141    /// Badges by id: (slide, text).
142    pub badges: BTreeMap<String, (Option<FileId>, String)>,
143    /// Batch commands registered, by id.
144    pub batch_commands: BTreeMap<String, BatchCommandSpec>,
145    /// `batch.progress` calls, in order.
146    pub batch_progress: Vec<BatchProgressArgs>,
147    /// `batch.finish` calls, in order.
148    pub batch_finished: Vec<BatchFinishArgs>,
149    pub active_tool: Option<String>,
150    pub filters: BTreeMap<String, FilterSpec>,
151    pub undo: Vec<UndoPushArgs>,
152    pub notifications: Vec<NotifyArgs>,
153    pub status: Option<String>,
154    pub clipboard: Option<String>,
155    pub roi: BTreeMap<FileId, Rect>,
156    pub measurements: Vec<MeasurementInfo>,
157    /// What `view.display` answers.
158    pub display: DisplayAdjustments,
159    pub posted: Vec<String>,
160    /// The model store: what `model.resolve` and `model.list` answer, by
161    /// the SHA-256 of the main file (lower case). See
162    /// [`MockState::add_model`].
163    pub models: BTreeMap<String, ModelRecord>,
164    /// `model.fetch` requests, in order, with the request id each was
165    /// answered with. Answer them with [`TestHarness::finish_model_fetch`]
166    /// or [`TestHarness::cancel_model_fetch`].
167    pub model_fetches: Vec<(String, ModelFetchArgs)>,
168    /// Serves `read_region`; without one a mid-grey opaque image is returned.
169    pub region_reader: Option<Box<RegionReader>>,
170    /// Methods that fail with [`FfiErrorKind::Unsupported`], to emulate an
171    /// older host.
172    pub unsupported: Vec<String>,
173}
174
175impl MockState {
176    /// Puts a model in the mock's model store.
177    pub fn add_model(&mut self, record: ModelRecord) {
178        self.models
179            .insert(record.sha256.to_ascii_lowercase(), record);
180    }
181
182    /// The arguments of every recorded call to `method`.
183    pub fn calls_to(&self, method: &str) -> Vec<Value> {
184        self.calls
185            .iter()
186            .filter(|call| call.method == method)
187            .map(|call| call.args.clone())
188            .collect()
189    }
190
191    /// Objects of a layer, in id order.
192    pub fn objects(&self, layer_id: &str) -> Vec<OverlayObject> {
193        self.layers
194            .get(layer_id)
195            .map(|layer| layer.objects.values().cloned().collect())
196            .unwrap_or_default()
197    }
198}
199
200/// The mock host object handed to the plugin.
201#[derive(Clone)]
202pub struct MockHost {
203    state: Arc<Mutex<MockState>>,
204    next_id: Arc<AtomicU64>,
205}
206
207impl Default for MockHost {
208    fn default() -> Self {
209        Self::new()
210    }
211}
212
213impl MockHost {
214    pub fn new() -> Self {
215        Self {
216            state: Arc::new(Mutex::new(MockState::default())),
217            next_id: Arc::new(AtomicU64::new(1)),
218        }
219    }
220
221    /// The shared state (poison-tolerant).
222    pub fn state(&self) -> MutexGuard<'_, MockState> {
223        self.state.lock().unwrap_or_else(|e| e.into_inner())
224    }
225
226    /// The FFI object to pass to a plugin.
227    pub fn to_ffi(&self) -> crate::abi::HostBox {
228        HostFfi_TO::from_value(self.clone(), TD_Opaque)
229    }
230
231    fn fresh_id(&self, prefix: &str) -> String {
232        format!("{prefix}-{}", self.next_id.fetch_add(1, Ordering::Relaxed))
233    }
234
235    fn handle(&self, method: &str, args: Value) -> Result<Value, FfiError> {
236        let mut state = self.state();
237        state.calls.push(RecordedCall {
238            method: method.to_string(),
239            args: args.clone(),
240        });
241        if state.unsupported.iter().any(|m| m == method) {
242            return Err(FfiError::new(
243                FfiErrorKind::Unsupported,
244                format!("unknown method '{method}'"),
245            ));
246        }
247        fn parse<T: DeserializeOwned>(args: Value) -> Result<T, FfiError> {
248            serde_json::from_value(args)
249                .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, e.to_string()))
250        }
251        let null = Value::Null;
252        Ok(match method {
253            methods::LOG | methods::RENDER_REQUEST | methods::EVENTS_SUBSCRIBE => null,
254            methods::NOTIFY => {
255                let args: NotifyArgs = parse(args)?;
256                state.notifications.push(args);
257                null
258            }
259            methods::STATUS => {
260                let args: StatusArgs = parse(args)?;
261                state.status = args.text;
262                null
263            }
264            methods::SNAPSHOT => json!(state.snapshot),
265            methods::FILE_INFO => {
266                let args: FileArgs = parse(args)?;
267                let file =
268                    state.snapshot.file(args.file_id).cloned().ok_or_else(|| {
269                        FfiError::failed(format!("no open file {}", args.file_id))
270                    })?;
271                json!(file)
272            }
273            methods::FILE_PROPERTIES => {
274                let args: FileArgs = parse(args)?;
275                json!(
276                    state
277                        .properties
278                        .get(&args.file_id)
279                        .cloned()
280                        .unwrap_or_default()
281                )
282            }
283            methods::FILE_OPEN => null,
284            methods::TOOLBAR_ADD => {
285                let spec: ToolbarButtonSpec = parse(args)?;
286                state.toolbar_buttons.insert(spec.button_id.clone(), spec);
287                null
288            }
289            methods::TOOLBAR_UPDATE => {
290                let update: ButtonUpdate = parse(args)?;
291                let button = state
292                    .toolbar_buttons
293                    .get_mut(&update.button_id)
294                    .ok_or_else(|| FfiError::failed("unknown toolbar button"))?;
295                if let Some(active) = update.active {
296                    button.active = active;
297                }
298                if let Some(enabled) = update.enabled {
299                    button.enabled = enabled;
300                }
301                if let Some(tooltip) = update.tooltip {
302                    button.tooltip = tooltip;
303                }
304                if let Some(icon) = update.icon_svg {
305                    button.icon_svg = icon;
306                }
307                null
308            }
309            methods::TOOLBAR_REMOVE => {
310                let args: IdArgs = parse(args)?;
311                state.toolbar_buttons.remove(&args.id);
312                null
313            }
314            methods::HUD_ADD => {
315                let spec: HudButtonSpec = parse(args)?;
316                state.hud_buttons.insert(spec.button_id.clone(), spec);
317                null
318            }
319            methods::HUD_UPDATE => {
320                let update: ButtonUpdate = parse(args)?;
321                let button = state
322                    .hud_buttons
323                    .get_mut(&update.button_id)
324                    .ok_or_else(|| FfiError::failed("unknown HUD button"))?;
325                if let Some(active) = update.active {
326                    button.active = active;
327                }
328                if let Some(menu) = update.menu {
329                    button.menu = menu;
330                }
331                // As eov does (plugins re-send tooltips when the language
332                // changes).
333                if let Some(tooltip) = update.tooltip {
334                    button.tooltip = tooltip;
335                }
336                if let Some(icon) = update.icon_svg {
337                    button.icon_svg = icon;
338                }
339                null
340            }
341            methods::HUD_REMOVE => {
342                let args: IdArgs = parse(args)?;
343                state.hud_buttons.remove(&args.id);
344                null
345            }
346            methods::BATCH_REGISTER => {
347                let spec: BatchCommandSpec = parse(args)?;
348                state.batch_commands.insert(spec.command_id.clone(), spec);
349                null
350            }
351            methods::BATCH_PROGRESS => {
352                state.batch_progress.push(parse(args)?);
353                null
354            }
355            methods::BATCH_FINISH => {
356                state.batch_finished.push(parse(args)?);
357                null
358            }
359            methods::BADGE_SET => {
360                let args: BadgeArgs = parse(args)?;
361                match args.text {
362                    Some(text) => {
363                        state.badges.insert(args.badge_id, (args.file_id, text));
364                    }
365                    None => {
366                        state.badges.remove(&args.badge_id);
367                    }
368                }
369                null
370            }
371            methods::HOTKEY_REGISTER => {
372                let spec: HotkeySpec = parse(args)?;
373                state.hotkeys.insert(spec.hotkey_id.clone(), spec);
374                null
375            }
376            methods::HOTKEY_UNREGISTER => {
377                let args: IdArgs = parse(args)?;
378                state.hotkeys.remove(&args.id);
379                null
380            }
381            methods::TOOL_REGISTER => {
382                let spec: ToolSpec = parse(args)?;
383                state.tools.insert(spec.tool_id.clone(), spec);
384                null
385            }
386            methods::TOOL_UNREGISTER => {
387                let args: IdArgs = parse(args)?;
388                state.tools.remove(&args.id);
389                if state.active_tool.as_deref() == Some(args.id.as_str()) {
390                    state.active_tool = None;
391                }
392                null
393            }
394            methods::TOOL_ACTIVATE => {
395                let args: IdArgs = parse(args)?;
396                if !state.tools.contains_key(&args.id) {
397                    return Err(FfiError::failed(format!("unknown tool '{}'", args.id)));
398                }
399                state.active_tool = Some(args.id);
400                null
401            }
402            methods::TOOL_DEACTIVATE => {
403                state.active_tool = None;
404                null
405            }
406            methods::LAYER_CREATE => {
407                let spec: LayerSpec = parse(args)?;
408                state.layers.insert(
409                    spec.layer_id.clone(),
410                    MockLayer {
411                        spec,
412                        objects: BTreeMap::new(),
413                        rasters: BTreeMap::new(),
414                        selection: Vec::new(),
415                        hidden_panes: Default::default(),
416                        highlighted: Vec::new(),
417                        only_panes: None,
418                    },
419                );
420                null
421            }
422            methods::LAYER_UPDATE => {
423                let update: LayerUpdate = parse(args)?;
424                let layer = layer_mut(&mut state, &update.layer_id)?;
425                if let Some(visible) = update.visible {
426                    layer.spec.visible = visible;
427                }
428                if let Some(opacity) = update.opacity {
429                    layer.spec.opacity = opacity;
430                }
431                if let Some(name) = update.name {
432                    layer.spec.name = name;
433                }
434                if let Some(z) = update.z {
435                    layer.spec.z = z;
436                }
437                if let Some(style) = update.style {
438                    layer.spec.style = style;
439                }
440                null
441            }
442            methods::LAYER_REMOVE => {
443                let args: IdArgs = parse(args)?;
444                state.layers.remove(&args.id);
445                null
446            }
447            methods::LAYER_HIGHLIGHT => {
448                let args: SelectArgs = parse(args)?;
449                layer_mut(&mut state, &args.layer_id)?.highlighted = args.object_ids;
450                null
451            }
452            methods::LAYER_SET_MIN_ZOOM => {
453                let args: MinZoomArgs = parse(args)?;
454                layer_mut(&mut state, &args.layer_id)?.spec.min_zoom = args.min_zoom;
455                null
456            }
457            methods::LAYER_SET_PANES => {
458                let args: PaneFilterArgs = parse(args)?;
459                layer_mut(&mut state, &args.layer_id)?.only_panes = args.panes;
460                null
461            }
462            methods::LAYER_SET_PANE_VISIBILITY => {
463                let args: PaneVisibilityArgs = parse(args)?;
464                let layer = layer_mut(&mut state, &args.layer_id)?;
465                if args.visible {
466                    layer.hidden_panes.remove(&args.pane);
467                } else {
468                    layer.hidden_panes.insert(args.pane);
469                }
470                null
471            }
472            methods::VIEW_DISPLAY => json!(state.display),
473            methods::LAYER_SELECT => {
474                let args: SelectArgs = parse(args)?;
475                layer_mut(&mut state, &args.layer_id)?.selection = args.object_ids;
476                null
477            }
478            methods::LAYER_UPSERT => {
479                let args: UpsertObjectsArgs = parse(args)?;
480                if let Some(bad) = args.objects.iter().find(|o| !o.shape.is_valid()) {
481                    return Err(FfiError::new(
482                        FfiErrorKind::InvalidArguments,
483                        format!("object '{}' has an invalid shape", bad.object_id),
484                    ));
485                }
486                let layer = layer_mut(&mut state, &args.layer_id)?;
487                if args.replace_all {
488                    layer.objects.clear();
489                    layer.rasters.clear();
490                }
491                for object in args.objects {
492                    layer.objects.insert(object.object_id.clone(), object);
493                }
494                null
495            }
496            methods::LAYER_REMOVE_OBJECTS => {
497                let args: RemoveObjectsArgs = parse(args)?;
498                let layer = layer_mut(&mut state, &args.layer_id)?;
499                for id in &args.object_ids {
500                    layer.objects.remove(id);
501                    layer.rasters.remove(id);
502                }
503                layer.selection.retain(|id| !args.object_ids.contains(id));
504                null
505            }
506            methods::LAYER_CLEAR => {
507                let args: IdArgs = parse(args)?;
508                let layer = layer_mut(&mut state, &args.id)?;
509                layer.objects.clear();
510                layer.rasters.clear();
511                layer.selection.clear();
512                null
513            }
514            methods::SURFACE_OPEN => {
515                let spec: SurfaceSpec = parse(args)?;
516                drop(state);
517                let surface_id = self.fresh_id("surface");
518                let mut state = self.state();
519                if spec.kind == SurfaceKind::Sidebar {
520                    // One sidebar at a time, as in the real host.
521                    for surface in state.surfaces.values_mut() {
522                        if surface.spec.kind == SurfaceKind::Sidebar {
523                            surface.open = false;
524                        }
525                    }
526                }
527                state.surfaces.insert(
528                    surface_id.clone(),
529                    MockSurface {
530                        properties: spec.properties.clone(),
531                        spec,
532                        open: true,
533                    },
534                );
535                json!(SurfaceOpened { surface_id })
536            }
537            methods::SURFACE_SET => {
538                let args: SurfaceProperties = parse(args)?;
539                let surface = state
540                    .surfaces
541                    .get_mut(&args.surface_id)
542                    .filter(|s| s.open)
543                    .ok_or_else(|| FfiError::failed("surface is not open"))?;
544                surface.properties.extend(args.properties);
545                null
546            }
547            methods::SURFACE_CLOSE => {
548                let args: IdArgs = parse(args)?;
549                if let Some(surface) = state.surfaces.get_mut(&args.id) {
550                    surface.open = false;
551                }
552                null
553            }
554            methods::SURFACE_IS_OPEN => {
555                let args: IdArgs = parse(args)?;
556                json!(state.surfaces.get(&args.id).is_some_and(|s| s.open))
557            }
558            methods::DIALOG_CONFIRM | methods::DIALOG_OPEN_FILE | methods::DIALOG_SAVE_FILE => {
559                drop(state);
560                json!(RequestId {
561                    request_id: self.fresh_id("request"),
562                })
563            }
564            methods::VIEW_SET
565            | methods::VIEW_PAN
566            | methods::VIEW_ZOOM
567            | methods::VIEW_FIT
568            | methods::VIEW_FRAME
569            | methods::VIEW_ORIENTATION
570            | methods::APP_CYCLE_PANE
571            | methods::APP_CYCLE_TAB
572            | methods::APP_SERIES => null,
573            methods::UNDO_PUSH => {
574                let args: UndoPushArgs = parse(args)?;
575                state.undo.push(args);
576                null
577            }
578            methods::UNDO_CLEAR => {
579                let args: UndoClearArgs = parse(args)?;
580                match args.file_id {
581                    Some(file_id) => state.undo.retain(|e| e.file_id != Some(file_id)),
582                    None => state.undo.clear(),
583                }
584                null
585            }
586            methods::FILTER_REGISTER => {
587                let spec: FilterSpec = parse(args)?;
588                state.filters.insert(spec.filter_id.clone(), spec);
589                null
590            }
591            methods::FILTER_SET_ENABLED => {
592                let args: FilterEnableArgs = parse(args)?;
593                state
594                    .filters
595                    .get_mut(&args.filter_id)
596                    .ok_or_else(|| FfiError::failed("unknown filter"))?
597                    .enabled = args.enabled;
598                null
599            }
600            methods::FILTER_UNREGISTER => {
601                let args: IdArgs = parse(args)?;
602                state.filters.remove(&args.id);
603                null
604            }
605            methods::SETTINGS_GET => {
606                let args: KeyArgs = parse(args)?;
607                state
608                    .settings
609                    .get(&args.key)
610                    .cloned()
611                    .unwrap_or(Value::Null)
612            }
613            methods::SETTINGS_SET => {
614                let args: SettingsSetArgs = parse(args)?;
615                if args.value.is_null() {
616                    state.settings.remove(&args.key);
617                } else {
618                    state.settings.insert(args.key, args.value);
619                }
620                null
621            }
622            methods::JOB_START => {
623                drop(state);
624                json!(JobStarted {
625                    job_id: self.fresh_id("job"),
626                })
627            }
628            methods::JOB_UPDATE | methods::JOB_FINISH => null,
629            methods::CLIPBOARD_SET_TEXT => {
630                let args: TextArgs = parse(args)?;
631                state.clipboard = Some(args.text);
632                null
633            }
634            methods::ROI_GET => {
635                let args: FileArgs = parse(args)?;
636                json!(state.roi.get(&args.file_id))
637            }
638            methods::MEASUREMENTS_LIST => {
639                let args: FileArgs = parse(args)?;
640                json!(
641                    state
642                        .measurements
643                        .iter()
644                        .filter(|m| m.file_id == args.file_id)
645                        .collect::<Vec<_>>()
646                )
647            }
648            methods::POST => {
649                let args: PostArgs = parse(args)?;
650                state.posted.push(args.token);
651                null
652            }
653            methods::MODEL_FETCH => {
654                let args: ModelFetchArgs = parse(args)?;
655                args.validate()
656                    .map_err(|e| FfiError::new(FfiErrorKind::InvalidArguments, e))?;
657                drop(state);
658                let request_id = self.fresh_id("model");
659                self.state().model_fetches.push((request_id.clone(), args));
660                json!(RequestId { request_id })
661            }
662            methods::MODEL_RESOLVE => {
663                let args: ModelResolveArgs = parse(args)?;
664                if !is_sha256_hex(&args.sha256) {
665                    return Err(FfiError::new(
666                        FfiErrorKind::InvalidArguments,
667                        "sha256 must be 64 hex digits",
668                    ));
669                }
670                json!(state.models.get(&args.sha256.to_ascii_lowercase()))
671            }
672            methods::MODEL_LIST => json!(state.models.values().collect::<Vec<_>>()),
673            other => {
674                return Err(FfiError::new(
675                    FfiErrorKind::Unsupported,
676                    format!("unknown method '{other}'"),
677                ));
678            }
679        })
680    }
681}
682
683fn layer_mut<'a>(state: &'a mut MockState, layer_id: &str) -> Result<&'a mut MockLayer, FfiError> {
684    state
685        .layers
686        .get_mut(layer_id)
687        .ok_or_else(|| FfiError::failed(format!("unknown layer '{layer_id}'")))
688}
689
690impl HostFfi for MockHost {
691    fn call(&self, method: RStr<'_>, args_json: RStr<'_>) -> FfiResult<RString> {
692        let args: Value = match serde_json::from_str(args_json.as_str()) {
693            Ok(args) => args,
694            Err(e) => {
695                return RErr(FfiError::new(FfiErrorKind::InvalidArguments, e.to_string()));
696            }
697        };
698        match self.handle(method.as_str(), args) {
699            Ok(value) => ROk(RString::from(value.to_string())),
700            Err(error) => RErr(error),
701        }
702    }
703
704    fn read_region(&self, request: RegionRequest) -> FfiResult<Pixels> {
705        let pixels = u64::from(request.width) * u64::from(request.height);
706        if pixels > crate::abi::MAX_REGION_PIXELS {
707            return RErr(FfiError::new(
708                FfiErrorKind::InvalidArguments,
709                "region too large",
710            ));
711        }
712        let state = self.state();
713        let image = match &state.region_reader {
714            Some(reader) => match reader(&request) {
715                Ok(image) => image,
716                Err(e) => return RErr(FfiError::failed(e)),
717            },
718            None => Image {
719                width: request.width,
720                height: request.height,
721                data: [128, 128, 128, 255].repeat(pixels as usize),
722            },
723        };
724        ROk(Pixels {
725            width: image.width,
726            height: image.height,
727            data: image.data.into(),
728        })
729    }
730
731    fn read_associated_image(&self, _file_id: i64, name: RStr<'_>) -> FfiResult<Pixels> {
732        RErr(FfiError::failed(format!(
733            "no associated image '{}'",
734            name.as_str()
735        )))
736    }
737
738    fn put_raster(&self, raster: RasterUpload) -> FfiResult<()> {
739        if !raster.pixels.is_well_formed() {
740            return RErr(FfiError::new(
741                FfiErrorKind::InvalidArguments,
742                "raster size does not match its data",
743            ));
744        }
745        let mut state = self.state();
746        let layer_id = raster.layer_id.to_string();
747        match layer_mut(&mut state, &layer_id) {
748            Ok(layer) => {
749                layer.rasters.insert(raster.object_id.to_string(), raster);
750                ROk(())
751            }
752            Err(e) => RErr(e),
753        }
754    }
755}
756
757/// Default init for tests: unique, writable temporary directories, and no
758/// language, so the plugin's texts are in English (see the
759/// [module documentation](self#languages-in-tests) on tests that switch
760/// languages). Its `plugin_root` holds no `plugin.toml` and no catalogs.
761pub fn test_init(plugin_id: &str) -> PluginInit {
762    static COUNTER: AtomicU64 = AtomicU64::new(0);
763    let root = std::env::temp_dir().join(format!(
764        "eov-plugin-test-{}-{}",
765        std::process::id(),
766        COUNTER.fetch_add(1, Ordering::Relaxed)
767    ));
768    let data_dir = root.join("data");
769    let cache_dir = root.join("cache");
770    let _ = std::fs::create_dir_all(&data_dir);
771    let _ = std::fs::create_dir_all(&cache_dir);
772    PluginInit {
773        plugin_id: plugin_id.to_string(),
774        plugin_version: "0.0.0".to_string(),
775        host_name: "eov".to_string(),
776        host_version: crate::abi::API_VERSION.to_string(),
777        api_version: crate::abi::API_VERSION.to_string(),
778        plugin_root: root.to_string_lossy().into_owned(),
779        data_dir: data_dir.to_string_lossy().into_owned(),
780        cache_dir: cache_dir.to_string_lossy().into_owned(),
781        settings: Map::new(),
782        legacy_config_dir: None,
783        headless: false,
784        language: None,
785    }
786}
787
788/// Drives a plugin through the same FFI adapter the host uses.
789pub struct TestHarness<P: Plugin> {
790    host: MockHost,
791    instance: PluginBox,
792    _plugin: PhantomData<fn() -> P>,
793}
794
795impl<P: Plugin> TestHarness<P> {
796    /// Creates the plugin with [`test_init`]. Like eov, this sets the
797    /// language `tr!` translates with, here English, for the whole plugin
798    /// library (see the [module documentation](self#languages-in-tests)).
799    pub fn new() -> Result<Self, String> {
800        Self::with_init(test_init("test_plugin"))
801    }
802
803    /// Creates the plugin with `init`, switching `tr!` to `init.language`
804    /// (English when `None`) for the whole plugin library, or for this
805    /// thread with the `thread-local-language` feature, and loading the
806    /// catalog that `plugin.toml` in `init.plugin_root` declares for it.
807    pub fn with_init(init: PluginInit) -> Result<Self, String> {
808        Self::with_host(MockHost::new(), init)
809    }
810
811    /// Uses a prepared mock (e.g. with a snapshot or region reader set).
812    /// Sets the language as [`Self::with_init`] does.
813    pub fn with_host(host: MockHost, init: PluginInit) -> Result<Self, String> {
814        let init_json = serde_json::to_string(&init).map_err(|e| e.to_string())?;
815        let instance =
816            create_plugin::<P>(host.to_ffi(), &init_json).map_err(|e| e.message.into_string())?;
817        Ok(Self {
818            host,
819            instance,
820            _plugin: PhantomData,
821        })
822    }
823
824    pub fn host(&self) -> &MockHost {
825        &self.host
826    }
827
828    pub fn state(&self) -> MutexGuard<'_, MockState> {
829        self.host.state()
830    }
831
832    /// The arguments of every call to `method` so far.
833    pub fn calls_to(&self, method: &str) -> Vec<Value> {
834        self.state().calls_to(method)
835    }
836
837    /// Delivers an event; returns the plugin's JSON response.
838    pub fn send(&self, event: HostEvent) -> Result<Value, FfiError> {
839        let json = serde_json::to_string(&event).map_err(|e| FfiError::failed(e.to_string()))?;
840        let reply = self
841            .instance
842            .handle_event(RStr::from_str(&json))
843            .into_result()?;
844        serde_json::from_str(reply.as_str()).map_err(|e| FfiError::failed(e.to_string()))
845    }
846
847    /// Requests context-menu items.
848    pub fn context_menu(&self, context: MenuContext) -> Result<Vec<MenuItem>, FfiError> {
849        let reply = self.send(HostEvent::ContextMenuRequested(context))?;
850        let response: ContextMenuResponse =
851            serde_json::from_value(reply).map_err(|e| FfiError::failed(e.to_string()))?;
852        Ok(response.items)
853    }
854
855    /// Invokes a surface callback.
856    /// Opens a slide through the plugin's slide source as eov does, through
857    /// the FFI: what [`TestSlide`] returns is what eov would get.
858    pub fn open_slide(&self, request: &SlideOpenRequest) -> Result<TestSlide, FfiError> {
859        let source = slide_source_of::<P>(&self.instance).into_result()?;
860        let json = serde_json::to_string(request).map_err(|e| FfiError::failed(e.to_string()))?;
861        let slide = source.open(RStr::from_str(&json)).into_result()?;
862        Ok(TestSlide { slide })
863    }
864
865    pub fn ui_callback(
866        &self,
867        surface_id: &str,
868        name: &str,
869        args: Vec<Value>,
870    ) -> Result<Value, FfiError> {
871        self.send(HostEvent::UiCallback {
872            surface_id: surface_id.to_string(),
873            name: name.to_string(),
874            args,
875        })
876    }
877
878    /// The last `model.fetch` request: the request id it was answered with
879    /// and its arguments.
880    pub fn last_model_fetch(&self) -> Option<(String, ModelFetchArgs)> {
881        self.state().model_fetches.last().cloned()
882    }
883
884    /// Answers the `model.fetch` request `request_id` as eov does: with the
885    /// stored model (which then also goes into the mock's model store, so
886    /// `model.resolve` finds it) or with the error eov reported.
887    pub fn finish_model_fetch(
888        &self,
889        request_id: &str,
890        outcome: Result<ModelRecord, String>,
891    ) -> Result<Value, FfiError> {
892        let event = match outcome {
893            Ok(record) => {
894                self.state().add_model(record.clone());
895                HostEvent::ModelFetched {
896                    request_id: request_id.to_string(),
897                    path: Some(record.path.clone()),
898                    model: Some(record),
899                    error: None,
900                    cancelled: false,
901                }
902            }
903            Err(error) => HostEvent::ModelFetched {
904                request_id: request_id.to_string(),
905                path: None,
906                model: None,
907                error: Some(error),
908                cancelled: false,
909            },
910        };
911        self.send(event)
912    }
913
914    /// Answers `request_id` as eov does when the user declines or cancels
915    /// the download.
916    pub fn cancel_model_fetch(&self, request_id: &str) -> Result<Value, FfiError> {
917        self.send(HostEvent::ModelFetched {
918            request_id: request_id.to_string(),
919            path: None,
920            model: None,
921            error: Some("The download was cancelled.".to_string()),
922            cancelled: true,
923        })
924    }
925
926    /// Runs a filter over a tightly packed RGBA buffer.
927    pub fn apply_filter(
928        &self,
929        filter_id: &str,
930        pixels: &mut [u8],
931        width: u32,
932        height: u32,
933        view: FilterView,
934    ) -> Result<(), FfiError> {
935        self.instance
936            .apply_filter(
937                RStr::from_str(filter_id),
938                FilterFrame {
939                    pixels: RSliceMut::from_mut_slice(pixels),
940                    width,
941                    height,
942                    stride: width * 4,
943                    view,
944                },
945            )
946            .into_result()
947    }
948}
949
950impl<P: Plugin> Drop for TestHarness<P> {
951    fn drop(&mut self) {
952        self.instance.shutdown();
953    }
954}
955
956/// A slide opened with [`TestHarness::open_slide`].
957pub struct TestSlide {
958    slide: crate::abi::SlideBox,
959}
960
961impl TestSlide {
962    /// The slide's metadata, checked as eov checks it.
963    pub fn info(&self) -> Result<SlideInfo, String> {
964        let json = self
965            .slide
966            .info()
967            .into_result()
968            .map_err(|e| e.message.into_string())?;
969        let info: SlideInfo = serde_json::from_str(json.as_str()).map_err(|e| e.to_string())?;
970        info.validate()?;
971        Ok(info)
972    }
973
974    /// The RGBA pixels of `region`, read into a zeroed buffer as eov reads
975    /// them.
976    pub fn read_region(&self, region: crate::abi::SlideRegion) -> Result<Vec<u8>, FfiError> {
977        let mut out = vec![0u8; region.width as usize * region.height as usize * 4];
978        self.slide
979            .read_region(
980                region,
981                abi_stable::std_types::RSliceMut::from_mut_slice(&mut out),
982            )
983            .into_result()?;
984        Ok(out)
985    }
986}
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991    use crate::sdk::{Frame, Host};
992
993    struct Probe {
994        host: Host,
995    }
996
997    impl Plugin for Probe {
998        fn create(host: Host, init: PluginInit) -> Result<Self, String> {
999            if init.plugin_id == "refuse" {
1000                return Err("refused".into());
1001            }
1002            host.add_toolbar_button(ToolbarButtonSpec {
1003                button_id: "go".into(),
1004                tooltip: "Go".into(),
1005                icon_svg: "<svg/>".into(),
1006                ..Default::default()
1007            })
1008            .map_err(String::from)?;
1009            Ok(Self { host })
1010        }
1011
1012        fn on_event(&self, event: HostEvent) -> Result<(), String> {
1013            match event {
1014                HostEvent::ToolbarButtonClicked { button_id } if button_id == "panic" => {
1015                    panic!("boom")
1016                }
1017                HostEvent::ToolbarButtonClicked { .. } => {
1018                    let layer = self
1019                        .host
1020                        .create_layer(LayerSpec::new("cells", 1).named("Cells").interactive(true))
1021                        .map_err(String::from)?;
1022                    layer
1023                        .upsert(vec![OverlayObject::new(
1024                            "c1",
1025                            Shape::Point { x: 1.0, y: 2.0 },
1026                        )])
1027                        .map_err(String::from)?;
1028                    Ok(())
1029                }
1030                HostEvent::FileClosed { .. } => Err("cannot close".into()),
1031                _ => Ok(()),
1032            }
1033        }
1034
1035        fn context_menu(&self, context: &MenuContext) -> Vec<MenuItem> {
1036            vec![MenuItem {
1037                item_id: format!("at-{}", context.image_x),
1038                label: "Here".into(),
1039                ..Default::default()
1040            }]
1041        }
1042
1043        fn ui_callback(&self, _surface: &str, name: &str, args: &[Value]) -> Result<Value, String> {
1044            Ok(json!({ "name": name, "argc": args.len() }))
1045        }
1046
1047        fn apply_filter(&self, _filter_id: &str, frame: &mut Frame<'_>) -> Result<(), String> {
1048            frame.for_each_pixel(|_, _, px| px[0] = 255 - px[0]);
1049            Ok(())
1050        }
1051    }
1052
1053    fn view() -> ViewInfo {
1054        ViewInfo {
1055            pane: 1,
1056            file_id: 1,
1057            zoom: 1.0,
1058            ..Default::default()
1059        }
1060    }
1061
1062    #[test]
1063    fn layers_take_min_zoom_and_pane_visibility() {
1064        use crate::sdk::{Host, Image};
1065        let mock = MockHost::new();
1066        let host = Host::from_ffi(mock.to_ffi());
1067        host.create_layer(LayerSpec::new("heat", 1)).unwrap();
1068        let layer = host.layer("heat");
1069        layer.set_min_zoom(Some(0.25)).unwrap();
1070        layer.set_visible_in_pane(3, false).unwrap();
1071        let rect = Rect {
1072            x: 0.0,
1073            y: 0.0,
1074            width: 10.0,
1075            height: 10.0,
1076        };
1077        let blank = Image {
1078            width: 2,
1079            height: 2,
1080            data: vec![0; 16],
1081        };
1082        layer.put_raster("map", rect, blank, false).unwrap();
1083        let state = mock.state();
1084        let mock_layer = &state.layers["heat"];
1085        assert_eq!(mock_layer.spec.min_zoom, Some(0.25));
1086        assert!(mock_layer.hidden_panes.contains(&3));
1087        assert!(mock_layer.rasters.contains_key("map"));
1088        drop(state);
1089        assert_eq!(host.display_adjustments(None).unwrap().gamma, 1.0);
1090    }
1091
1092    #[test]
1093    fn hotkeys_badges_and_highlights_reach_the_host() {
1094        use crate::sdk::Host;
1095        let mock = MockHost::new();
1096        let host = Host::from_ffi(mock.to_ffi());
1097        host.register_hotkey(HotkeySpec {
1098            hotkey_id: "next".into(),
1099            hotkey: Hotkey::key("j"),
1100            description: "Next object".into(),
1101        })
1102        .unwrap();
1103        host.set_badge("predicted", Some(1), Some("Predicted"))
1104            .unwrap();
1105        host.create_layer(LayerSpec::new("cells", 1)).unwrap();
1106        host.layer("cells").highlight(vec!["a".into()]).unwrap();
1107        {
1108            let state = mock.state();
1109            assert!(state.hotkeys.contains_key("next"));
1110            assert_eq!(
1111                state.badges["predicted"],
1112                (Some(1), "Predicted".to_string())
1113            );
1114            assert_eq!(state.layers["cells"].highlighted, ["a"]);
1115        }
1116        host.set_badge("predicted", None, None).unwrap();
1117        host.unregister_hotkey("next").unwrap();
1118        let state = mock.state();
1119        assert!(state.badges.is_empty() && state.hotkeys.is_empty());
1120    }
1121
1122    #[test]
1123    fn create_registers_contributions() {
1124        let harness = TestHarness::<Probe>::new().unwrap();
1125        // Built with `..Default::default()`, it arrives enabled.
1126        assert!(harness.state().toolbar_buttons["go"].enabled);
1127    }
1128
1129    #[test]
1130    fn create_errors_are_reported() {
1131        let error = TestHarness::<Probe>::with_init(test_init("refuse"))
1132            .err()
1133            .unwrap();
1134        assert_eq!(error, "refused");
1135    }
1136
1137    #[test]
1138    fn events_reach_the_plugin_and_overlays_are_stored() {
1139        let harness = TestHarness::<Probe>::new().unwrap();
1140        harness
1141            .send(HostEvent::ToolbarButtonClicked {
1142                button_id: "go".into(),
1143            })
1144            .unwrap();
1145        let objects = harness.state().objects("cells");
1146        assert_eq!(objects.len(), 1);
1147        assert_eq!(objects[0].shape, Shape::Point { x: 1.0, y: 2.0 });
1148    }
1149
1150    #[test]
1151    fn panics_become_errors() {
1152        let harness = TestHarness::<Probe>::new().unwrap();
1153        let error = harness
1154            .send(HostEvent::ToolbarButtonClicked {
1155                button_id: "panic".into(),
1156            })
1157            .unwrap_err();
1158        assert_eq!(error.kind(), FfiErrorKind::Panicked);
1159        assert!(error.message.contains("boom"));
1160        // The instance is still usable afterwards.
1161        harness
1162            .send(HostEvent::Ready {
1163                restore_sidebar: false,
1164            })
1165            .unwrap();
1166    }
1167
1168    #[test]
1169    fn handler_errors_are_failures() {
1170        let harness = TestHarness::<Probe>::new().unwrap();
1171        let error = harness
1172            .send(HostEvent::FileClosed { file_id: 1 })
1173            .unwrap_err();
1174        assert_eq!(error.kind(), FfiErrorKind::Failed);
1175        assert_eq!(error.message.as_str(), "cannot close");
1176    }
1177
1178    #[test]
1179    fn context_menus_and_callbacks_return_values() {
1180        let harness = TestHarness::<Probe>::new().unwrap();
1181        let items = harness
1182            .context_menu(MenuContext {
1183                pane: 1,
1184                view: view(),
1185                image_x: 5.0,
1186                image_y: 6.0,
1187                hit: None,
1188                selection: Vec::new(),
1189            })
1190            .unwrap();
1191        assert_eq!(items[0].item_id, "at-5");
1192        assert!(items[0].enabled, "built with `..Default::default()`");
1193        let reply = harness
1194            .ui_callback("surface-1", "clicked", vec![json!(1), json!("x")])
1195            .unwrap();
1196        assert_eq!(reply, json!({ "name": "clicked", "argc": 2 }));
1197    }
1198
1199    #[test]
1200    fn filters_modify_frames_in_place() {
1201        let harness = TestHarness::<Probe>::new().unwrap();
1202        let mut pixels = vec![10, 20, 30, 255, 40, 50, 60, 255];
1203        harness
1204            .apply_filter("invert", &mut pixels, 2, 1, FilterView::default())
1205            .unwrap();
1206        assert_eq!(pixels, vec![245, 20, 30, 255, 215, 50, 60, 255]);
1207    }
1208
1209    #[test]
1210    fn short_frames_are_rejected() {
1211        let harness = TestHarness::<Probe>::new().unwrap();
1212        let mut pixels = vec![0u8; 7];
1213        let error = harness
1214            .apply_filter("invert", &mut pixels, 2, 1, FilterView::default())
1215            .unwrap_err();
1216        assert_eq!(error.kind(), FfiErrorKind::InvalidArguments);
1217    }
1218
1219    #[test]
1220    fn unknown_methods_are_unsupported() {
1221        let host = MockHost::new();
1222        let sdk_host = Host::from_ffi(host.to_ffi());
1223        let error = sdk_host
1224            .call::<_, Value>("does.not.exist", &json!({}))
1225            .unwrap_err();
1226        assert!(error.is_unsupported());
1227    }
1228
1229    #[test]
1230    fn invalid_shapes_are_rejected() {
1231        let host = MockHost::new();
1232        let sdk_host = Host::from_ffi(host.to_ffi());
1233        let layer = sdk_host.create_layer(LayerSpec::new("l", 1)).unwrap();
1234        let error = layer
1235            .upsert(vec![OverlayObject::new(
1236                "bad",
1237                Shape::Polyline {
1238                    points: vec![[0.0, f64::NAN]],
1239                },
1240            )])
1241            .unwrap_err();
1242        assert_eq!(error.kind, FfiErrorKind::InvalidArguments);
1243    }
1244
1245    #[test]
1246    fn settings_round_trip() {
1247        let host = MockHost::new();
1248        let sdk_host = Host::from_ffi(host.to_ffi());
1249        sdk_host.set_setting("threshold", &0.5).unwrap();
1250        assert_eq!(sdk_host.setting::<f64>("threshold").unwrap(), Some(0.5));
1251        sdk_host.remove_setting("threshold").unwrap();
1252        assert_eq!(sdk_host.setting::<f64>("threshold").unwrap(), None);
1253    }
1254
1255    const MODEL_SHA: &str = "70a8deef1f01716efbc87feb181ea398425d08b5e4984ad9d4ab2b83fd354f92";
1256
1257    /// Uses a stored model, or asks eov for it, on a toolbar click.
1258    struct ModelUser {
1259        host: Host,
1260        request: std::sync::Mutex<Option<String>>,
1261    }
1262
1263    impl Plugin for ModelUser {
1264        fn create(host: Host, _init: PluginInit) -> Result<Self, String> {
1265            Ok(Self {
1266                host,
1267                request: std::sync::Mutex::new(None),
1268            })
1269        }
1270
1271        fn on_event(&self, event: HostEvent) -> Result<(), String> {
1272            match event {
1273                HostEvent::ToolbarButtonClicked { .. } => {
1274                    if let Some(model) = self.host.resolve_model(MODEL_SHA).map_err(String::from)? {
1275                        self.host.info(format!("using {}", model.path));
1276                        return Ok(());
1277                    }
1278                    let request = self
1279                        .host
1280                        .fetch_model(ModelFetchArgs {
1281                            url: Some("https://models.example.org/m.onnx".into()),
1282                            sha256: MODEL_SHA.into(),
1283                            name: Some("Reference".into()),
1284                            companions: vec![ModelFileSpec {
1285                                sha256: "cd2735866bd69648eb17df97f196f266e6e2569f8c21fa1e9779fb7e3a233ef8"
1286                                    .into(),
1287                                file_name: Some("m.onnx.data".into()),
1288                                ..Default::default()
1289                            }],
1290                            ..Default::default()
1291                        })
1292                        .map_err(String::from)?;
1293                    *self.request.lock().unwrap() = Some(request);
1294                }
1295                HostEvent::ModelFetched {
1296                    request_id,
1297                    path,
1298                    error,
1299                    cancelled,
1300                    ..
1301                } if self.request.lock().unwrap().as_deref() == Some(request_id.as_str()) => {
1302                    match (path, error) {
1303                        (Some(path), _) => self.host.info(format!("using {path}")),
1304                        (None, _) if cancelled => self.host.info("not now"),
1305                        (None, error) => self.host.info(format!("failed: {error:?}")),
1306                    }
1307                }
1308                _ => {}
1309            }
1310            Ok(())
1311        }
1312    }
1313
1314    fn logged(harness: &TestHarness<ModelUser>) -> Vec<String> {
1315        harness
1316            .calls_to("log")
1317            .iter()
1318            .map(|args| args["message"].as_str().unwrap_or_default().to_string())
1319            .collect()
1320    }
1321
1322    #[test]
1323    fn models_are_fetched_once_and_then_resolved() {
1324        let harness = TestHarness::<ModelUser>::new().unwrap();
1325        let click = || {
1326            harness
1327                .send(HostEvent::ToolbarButtonClicked {
1328                    button_id: "x".into(),
1329                })
1330                .unwrap()
1331        };
1332        click();
1333        let (request, args) = harness.last_model_fetch().expect("the plugin asked");
1334        assert_eq!(args.sha256, MODEL_SHA);
1335        assert_eq!(args.companions.len(), 1);
1336        harness
1337            .finish_model_fetch(
1338                &request,
1339                Ok(ModelRecord {
1340                    sha256: MODEL_SHA.into(),
1341                    path: "/models/70a8/m.onnx".into(),
1342                    file_name: "m.onnx".into(),
1343                    size: 10,
1344                    ..Default::default()
1345                }),
1346            )
1347            .unwrap();
1348        assert_eq!(logged(&harness), ["using /models/70a8/m.onnx"]);
1349        // Stored now: the next click resolves it without a download.
1350        click();
1351        assert_eq!(harness.state().model_fetches.len(), 1);
1352        assert_eq!(logged(&harness).len(), 2);
1353        let listed = Host::from_ffi(harness.host().to_ffi()).models().unwrap();
1354        assert_eq!(listed.len(), 1);
1355    }
1356
1357    #[test]
1358    fn declined_and_failed_fetches_reach_the_plugin() {
1359        let harness = TestHarness::<ModelUser>::new().unwrap();
1360        let click = || {
1361            harness
1362                .send(HostEvent::ToolbarButtonClicked {
1363                    button_id: "x".into(),
1364                })
1365                .unwrap()
1366        };
1367        click();
1368        let (request, _) = harness.last_model_fetch().unwrap();
1369        harness.cancel_model_fetch(&request).unwrap();
1370        click();
1371        let (request, _) = harness.last_model_fetch().unwrap();
1372        harness
1373            .finish_model_fetch(&request, Err("SHA-256 mismatch".into()))
1374            .unwrap();
1375        assert_eq!(
1376            logged(&harness),
1377            ["not now", "failed: Some(\"SHA-256 mismatch\")"]
1378        );
1379        assert!(harness.state().models.is_empty());
1380    }
1381
1382    #[test]
1383    fn model_requests_are_checked_and_old_hosts_refuse_them() {
1384        let mock = MockHost::new();
1385        let host = Host::from_ffi(mock.to_ffi());
1386        let bad = host
1387            .fetch_model(ModelFetchArgs {
1388                sha256: "abc".into(),
1389                ..Default::default()
1390            })
1391            .unwrap_err();
1392        assert_eq!(bad.kind, FfiErrorKind::InvalidArguments);
1393        let nameless = host
1394            .fetch_model(ModelFetchArgs {
1395                sha256: MODEL_SHA.into(),
1396                companions: vec![ModelFileSpec {
1397                    sha256: MODEL_SHA.into(),
1398                    ..Default::default()
1399                }],
1400                ..Default::default()
1401            })
1402            .unwrap_err();
1403        assert!(nameless.message.contains("file_name"), "{nameless}");
1404        assert_eq!(host.resolve_model(MODEL_SHA).unwrap(), None);
1405        mock.state()
1406            .unsupported
1407            .push(methods::MODEL_FETCH.to_string());
1408        assert!(
1409            host.fetch_model(ModelFetchArgs {
1410                sha256: MODEL_SHA.into(),
1411                ..Default::default()
1412            })
1413            .unwrap_err()
1414            .is_unsupported()
1415        );
1416    }
1417}