Skip to main content

openstranded_plugin_api/
test_utils.rs

1use std::cell::RefCell;
2use std::collections::HashMap;
3
4use crate::{
5    GameAPI, LogLevel, RegistryEntry, Service, ServiceError, Value,
6};
7
8/// A mock implementation of `GameAPI` for unit-testing plugins natively.
9///
10/// Stores all state in-memory (no WASM, no ECS). Useful for testing
11/// plugin logic without spinning up the full engine.
12///
13/// # Example
14///
15/// ```rust
16/// use openstranded_plugin_api::test_utils::MockGameAPI;
17/// use openstranded_plugin_api::{GameAPI, Value, Service, ServiceError};
18///
19/// struct MyService;
20/// impl Service for MyService {
21///     fn call(&self, _method: &str, _args: &[Value]) -> Result<Value, ServiceError> {
22///         Ok(Value::String("ok".into()))
23///     }
24/// }
25///
26/// let mut api = MockGameAPI::new();
27/// api.register_service("my", Box::new(MyService)).unwrap();
28/// assert!(api.has_service("my"));
29/// assert!(api.logs().is_empty());
30/// ```
31pub struct MockGameAPI {
32    /// In-memory registry: domain → { filename → raw bytes }.
33    registry: HashMap<String, HashMap<String, Vec<u8>>>,
34    /// Registered services (domain → service).
35    services: Vec<(String, Box<dyn Service>)>,
36    /// Accumulated log messages (interior mutability for &self log access).
37    logs: RefCell<Vec<(LogLevel, String)>>,
38    /// Simulated config values (dotted key → Value).
39    config: HashMap<String, Value>,
40    /// Simulated keybinds.
41    keybinds: HashMap<String, String>,
42    /// In-memory save data store.
43    save_data: HashMap<String, Vec<u8>>,
44    /// Content files by path.
45    content_files: HashMap<String, Vec<u8>>,
46    /// Next entity ID for spawn_entity.
47    next_entity: u64,
48    /// Emitted events (for test assertions).
49    events: RefCell<Vec<(String, Value)>>,
50}
51
52impl MockGameAPI {
53    /// Create an empty mock API.
54    #[must_use]
55    pub fn new() -> Self {
56        Self {
57            registry: HashMap::new(),
58            services: Vec::new(),
59            logs: RefCell::new(Vec::new()),
60            config: HashMap::new(),
61            keybinds: HashMap::new(),
62            save_data: HashMap::new(),
63            content_files: HashMap::new(),
64            next_entity: 1,
65            events: RefCell::new(Vec::new()),
66        }
67    }
68
69    /// Create a mock API pre-populated with a single registry file.
70    #[must_use]
71    pub fn with_registry_file(domain: &str, filename: &str, data: &[u8]) -> Self {
72        let mut reg: HashMap<String, HashMap<String, Vec<u8>>> = HashMap::new();
73        reg.entry(domain.to_owned())
74            .or_default()
75            .insert(filename.to_owned(), data.to_vec());
76        Self {
77            registry: reg,
78            services: Vec::new(),
79            logs: RefCell::new(Vec::new()),
80            config: HashMap::new(),
81            keybinds: HashMap::new(),
82            save_data: HashMap::new(),
83            content_files: HashMap::new(),
84            next_entity: 1,
85            events: RefCell::new(Vec::new()),
86        }
87    }
88
89    /// Set a config value for testing (dotted key path).
90    pub fn set_config(&mut self, key: &str, value: Value) {
91        self.config.insert(key.to_owned(), value);
92    }
93
94    /// Set a keybinding for testing.
95    pub fn set_keybind(&mut self, action: &str, key: &str) {
96        self.keybinds.insert(action.to_owned(), key.to_owned());
97    }
98
99    /// Add a content file by path.
100    pub fn add_content_file(&mut self, path: &str, data: Vec<u8>) {
101        self.content_files.insert(path.to_owned(), data);
102    }
103
104    /// Get all accumulated log messages (for assertions in tests).
105    pub fn logs(&self) -> Vec<(LogLevel, String)> {
106        self.logs.borrow().clone()
107    }
108
109    /// Check whether a specific log message exists.
110    pub fn has_log(&self, level: LogLevel, msg_substring: &str) -> bool {
111        self.logs
112            .borrow()
113            .iter()
114            .any(|(l, m)| *l == level && m.contains(msg_substring))
115    }
116
117    /// Get all registered service domains.
118    pub fn service_domains(&self) -> Vec<&str> {
119        self.services.iter().map(|(d, _)| d.as_str()).collect()
120    }
121
122    /// Get all emitted events (for test assertions).
123    pub fn events(&self) -> Vec<(String, Value)> {
124        self.events.borrow().clone()
125    }
126
127    /// Check whether a specific event was emitted.
128    pub fn has_event(&self, name: &str) -> bool {
129        self.events.borrow().iter().any(|(n, _)| n == name)
130    }
131}
132
133impl Default for MockGameAPI {
134    fn default() -> Self {
135        Self::new()
136    }
137}
138
139impl GameAPI for MockGameAPI {
140    // ── Registry ──────────────────────────────────────────────────
141
142    fn registry_domain(&self, name: &str) -> Result<Vec<RegistryEntry>, ServiceError> {
143        let files = self.registry.get(name).ok_or_else(|| {
144            ServiceError::RegistryDomainNotFound(name.into())
145        })?;
146        Ok(files
147            .iter()
148            .map(|(filename, data)| RegistryEntry {
149                filename: filename.clone(),
150                data: data.clone(),
151            })
152            .collect())
153    }
154
155    fn registry_file(&self, domain: &str, filename: &str) -> Result<Vec<u8>, ServiceError> {
156        self.registry
157            .get(domain)
158            .and_then(|files| files.get(filename))
159            .cloned()
160            .ok_or_else(|| ServiceError::FileNotFound {
161                domain: domain.into(),
162                filename: filename.into(),
163            })
164    }
165
166    // ── Content file access ──────────────────────────────────────
167
168    fn read_content_file(&self, path: &str) -> Result<Vec<u8>, ServiceError> {
169        self.content_files
170            .get(path)
171            .cloned()
172            .ok_or_else(|| ServiceError::ContentFileNotFound(path.into()))
173    }
174
175    // ── Services ─────────────────────────────────────────────────
176
177    fn register_service(
178        &mut self,
179        domain: &str,
180        service: Box<dyn Service>,
181    ) -> Result<(), ServiceError> {
182        if self.services.iter().any(|(d, _)| d == domain) {
183            return Err(ServiceError::Internal(format!(
184                "service domain '{domain}' is already registered"
185            )));
186        }
187        self.services.push((domain.to_owned(), service));
188        Ok(())
189    }
190
191    fn get_service(&self, domain: &str) -> Result<&dyn Service, ServiceError> {
192        self.services
193            .iter()
194            .find(|(d, _)| d == domain)
195            .map(|(_, s)| s.as_ref())
196            .ok_or_else(|| ServiceError::DomainNotFound(domain.into()))
197    }
198
199    fn call_service(
200        &self,
201        domain: &str,
202        method: &str,
203        args: &[Value],
204    ) -> Result<Value, ServiceError> {
205        let service = self.get_service(domain)?;
206        service.call(method, args)
207    }
208
209    fn has_service(&self, domain: &str) -> bool {
210        self.services.iter().any(|(d, _)| d == domain)
211    }
212
213    // ── ECS bridge (mock — minimal) ──────────────────────────────
214
215    fn get_component(&self, _entity: u64, _type_name: &str) -> Result<Vec<u8>, ServiceError> {
216        Err(ServiceError::Internal(
217            "MockGameAPI does not support ECS operations".into(),
218        ))
219    }
220
221    fn set_component(
222        &mut self,
223        _entity: u64,
224        _type_name: &str,
225        _data: &[u8],
226    ) -> Result<(), ServiceError> {
227        // Mock accepts silently (no-op).
228        Ok(())
229    }
230
231    fn query_entities(&self, _component_name: &str) -> Result<Vec<u64>, ServiceError> {
232        Ok(Vec::new()) // No entities in mock.
233    }
234
235    fn spawn_entity(&mut self, _archetype: &str) -> Result<u64, ServiceError> {
236        let id = self.next_entity;
237        self.next_entity += 1;
238        Ok(id)
239    }
240
241    fn despawn_entity(&mut self, _entity: u64) -> Result<(), ServiceError> {
242        Ok(())
243    }
244
245    // ── Configuration ────────────────────────────────────────────
246
247    fn read_config(&self, key: &str) -> Result<Value, ServiceError> {
248        Ok(self.config.get(key).cloned().unwrap_or(Value::Null))
249    }
250
251    fn read_keybinds(&self) -> Result<Value, ServiceError> {
252        let map: HashMap<String, Value> = self
253            .keybinds
254            .iter()
255            .map(|(k, v)| (k.clone(), Value::String(v.clone())))
256            .collect();
257        Ok(Value::Map(map))
258    }
259
260    // ── Save / Load ──────────────────────────────────────────────
261
262    fn register_save_data(
263        &mut self,
264        domain: &str,
265        data: Vec<u8>,
266    ) -> Result<(), ServiceError> {
267        self.save_data.insert(domain.to_owned(), data);
268        Ok(())
269    }
270
271    fn load_save_data(&self, domain: &str) -> Result<Option<Vec<u8>>, ServiceError> {
272        Ok(self.save_data.get(domain).cloned())
273    }
274
275    // ── Events ───────────────────────────────────────────────────
276
277    fn emit_event(&self, name: &str, data: &Value) -> Result<(), ServiceError> {
278        self.events.borrow_mut().push((name.to_owned(), data.clone()));
279        Ok(())
280    }
281
282    // ── Logging ──────────────────────────────────────────────────
283
284    fn log(&self, level: LogLevel, message: &str) {
285        self.logs.borrow_mut().push((level, message.to_owned()));
286    }
287}
288
289// ── Tests ──────────────────────────────────────────────────────────
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use crate::Value;
295
296    struct PingService;
297
298    impl Service for PingService {
299        fn call(&self, _method: &str, _args: &[Value]) -> Result<Value, ServiceError> {
300            Ok(Value::String("pong".into()))
301        }
302    }
303
304    #[test]
305    fn test_mock_register_and_get_service() {
306        let mut api = MockGameAPI::new();
307        api.register_service("ping", Box::new(PingService)).unwrap();
308        assert!(api.has_service("ping"));
309
310        let svc = api.get_service("ping").unwrap();
311        let result = svc.call("ping", &[]).unwrap();
312        assert_eq!(result, Value::String("pong".into()));
313    }
314
315    #[test]
316    fn test_mock_register_duplicate() {
317        let mut api = MockGameAPI::new();
318        api.register_service("x", Box::new(PingService)).unwrap();
319        let err = api.register_service("x", Box::new(PingService)).unwrap_err();
320        assert!(matches!(err, ServiceError::Internal(..)));
321    }
322
323    #[test]
324    fn test_mock_get_service_not_found() {
325        let api = MockGameAPI::new();
326        let result = api.get_service("nonexistent");
327        assert!(result.is_err());
328    }
329
330    #[test]
331    fn test_mock_registry_domain() {
332        let api = MockGameAPI::with_registry_file("test", "file.ron", b"hello");
333        let entries = api.registry_domain("test").unwrap();
334        assert_eq!(entries.len(), 1);
335        assert_eq!(entries[0].filename, "file.ron");
336        assert_eq!(entries[0].data, b"hello");
337    }
338
339    #[test]
340    fn test_mock_registry_file() {
341        let api = MockGameAPI::with_registry_file("test", "file.ron", b"hello");
342        let data = api.registry_file("test", "file.ron").unwrap();
343        assert_eq!(data, b"hello");
344    }
345
346    #[test]
347    fn test_mock_registry_domain_not_found() {
348        let api = MockGameAPI::new();
349        let result = api.registry_domain("nonexistent");
350        assert!(result.is_err());
351    }
352
353    #[test]
354    fn test_mock_service_domains() {
355        let mut api = MockGameAPI::new();
356        api.register_service("a", Box::new(PingService)).unwrap();
357        api.register_service("b", Box::new(PingService)).unwrap();
358        let mut domains = api.service_domains();
359        domains.sort();
360        assert_eq!(domains, vec!["a", "b"]);
361    }
362
363    #[test]
364    fn test_mock_log() {
365        let api = MockGameAPI::new();
366        api.log(LogLevel::Info, "hello world");
367        api.log(LogLevel::Warn, "warning: something");
368
369        let logs = api.logs();
370        assert_eq!(logs.len(), 2);
371        assert_eq!(logs[0].0, LogLevel::Info);
372        assert_eq!(logs[0].1, "hello world");
373
374        assert!(api.has_log(LogLevel::Warn, "warning"));
375    }
376}