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,
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///
30/// // Check emitted logs
31/// assert!(api.logs().is_empty());
32/// ```
33pub struct MockGameAPI {
34    /// In-memory registry: domain → { filename → raw bytes }.
35    registry: HashMap<String, HashMap<String, Vec<u8>>>,
36    /// Registered services (domain → service).
37    services: Vec<(String, Box<dyn Service>)>,
38    /// Accumulated log messages (interior mutability for &self log access).
39    logs: RefCell<Vec<(LogLevel, String)>>,
40}
41
42impl MockGameAPI {
43    /// Create an empty mock API.
44    #[must_use]
45    pub fn new() -> Self {
46        Self {
47            registry: HashMap::new(),
48            services: Vec::new(),
49            logs: RefCell::new(Vec::new()),
50        }
51    }
52
53    /// Create a mock API pre-populated with a single registry file.
54    ///
55    /// Convenience for tests that need registry data.
56    ///
57    /// # Example
58    ///
59    /// ```rust
60    /// use openstranded_plugin_api::test_utils::MockGameAPI;
61    /// use openstranded_plugin_api::GameAPI;
62    ///
63    /// let api = MockGameAPI::with_registry_file(
64    ///     "items", "items_edible.ron",
65    ///     b"[{ \"id\": 1, \"name\": \"Wood\" }]"
66    /// );
67    /// let entries = api.registry_domain("items").unwrap();
68    /// assert_eq!(entries.len(), 1);
69    /// ```
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        }
81    }
82
83    /// Get all accumulated log messages (for assertions in tests).
84    pub fn logs(&self) -> Vec<(LogLevel, String)> {
85        self.logs.borrow().clone()
86    }
87
88    /// Check whether a specific log message exists.
89    pub fn has_log(&self, level: LogLevel, msg_substring: &str) -> bool {
90        self.logs
91            .borrow()
92            .iter()
93            .any(|(l, m)| *l == level && m.contains(msg_substring))
94    }
95
96    /// Get all registered service domains.
97    pub fn service_domains(&self) -> Vec<&str> {
98        self.services.iter().map(|(d, _)| d.as_str()).collect()
99    }
100}
101
102impl Default for MockGameAPI {
103    fn default() -> Self {
104        Self::new()
105    }
106}
107
108impl GameAPI for MockGameAPI {
109    fn registry_domain(&self, name: &str) -> Result<Vec<RegistryEntry>, ServiceError> {
110        let files = self.registry.get(name).ok_or_else(|| {
111            ServiceError::RegistryDomainNotFound(name.into())
112        })?;
113        Ok(files
114            .iter()
115            .map(|(filename, data)| RegistryEntry {
116                filename: filename.clone(),
117                data: data.clone(),
118            })
119            .collect())
120    }
121
122    fn registry_file(&self, domain: &str, filename: &str) -> Result<Vec<u8>, ServiceError> {
123        self.registry
124            .get(domain)
125            .and_then(|files| files.get(filename))
126            .cloned()
127            .ok_or_else(|| ServiceError::FileNotFound {
128                domain: domain.into(),
129                filename: filename.into(),
130            })
131    }
132
133    fn register_service(
134        &mut self,
135        domain: &str,
136        service: Box<dyn Service>,
137    ) -> Result<(), ServiceError> {
138        if self.services.iter().any(|(d, _)| d == domain) {
139            return Err(ServiceError::Internal(format!(
140                "service domain '{domain}' is already registered"
141            )));
142        }
143        self.services.push((domain.to_owned(), service));
144        Ok(())
145    }
146
147    fn get_service(&self, domain: &str) -> Result<&dyn Service, ServiceError> {
148        self.services
149            .iter()
150            .find(|(d, _)| d == domain)
151            .map(|(_, s)| s.as_ref())
152            .ok_or_else(|| ServiceError::DomainNotFound(domain.into()))
153    }
154
155    fn has_service(&self, domain: &str) -> bool {
156        self.services.iter().any(|(d, _)| d == domain)
157    }
158
159    fn log(&self, level: LogLevel, message: &str) {
160        self.logs.borrow_mut().push((level, message.to_owned()));
161    }
162}
163
164// ── Tests ──────────────────────────────────────────────────────────
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::Value;
170
171    struct PingService;
172
173    impl Service for PingService {
174        fn call(&self, _method: &str, _args: &[Value]) -> Result<Value, ServiceError> {
175            Ok(Value::String("pong".into()))
176        }
177    }
178
179    #[test]
180    fn test_mock_register_and_get_service() {
181        let mut api = MockGameAPI::new();
182        api.register_service("ping", Box::new(PingService)).unwrap();
183        assert!(api.has_service("ping"));
184
185        let svc = api.get_service("ping").unwrap();
186        let result = svc.call("ping", &[]).unwrap();
187        assert_eq!(result, Value::String("pong".into()));
188    }
189
190    #[test]
191    fn test_mock_register_duplicate() {
192        let mut api = MockGameAPI::new();
193        api.register_service("x", Box::new(PingService)).unwrap();
194        let err = api.register_service("x", Box::new(PingService)).unwrap_err();
195        assert!(matches!(err, ServiceError::Internal(..)));
196    }
197
198    #[test]
199    fn test_mock_get_service_not_found() {
200        let api = MockGameAPI::new();
201        let result = api.get_service("nonexistent");
202        assert!(result.is_err());
203    }
204
205    #[test]
206    fn test_mock_registry_domain() {
207        let api = MockGameAPI::with_registry_file("test", "file.ron", b"hello");
208        let entries = api.registry_domain("test").unwrap();
209        assert_eq!(entries.len(), 1);
210        assert_eq!(entries[0].filename, "file.ron");
211        assert_eq!(entries[0].data, b"hello");
212    }
213
214    #[test]
215    fn test_mock_registry_file() {
216        let api = MockGameAPI::with_registry_file("test", "file.ron", b"hello");
217        let data = api.registry_file("test", "file.ron").unwrap();
218        assert_eq!(data, b"hello");
219    }
220
221    #[test]
222    fn test_mock_registry_domain_not_found() {
223        let api = MockGameAPI::new();
224        let result = api.registry_domain("nonexistent");
225        assert!(result.is_err());
226    }
227
228    #[test]
229    fn test_mock_service_domains() {
230        let mut api = MockGameAPI::new();
231        api.register_service("a", Box::new(PingService)).unwrap();
232        api.register_service("b", Box::new(PingService)).unwrap();
233        let mut domains = api.service_domains();
234        domains.sort();
235        assert_eq!(domains, vec!["a", "b"]);
236    }
237
238    #[test]
239    fn test_mock_log() {
240        let api = MockGameAPI::new();
241        api.log(LogLevel::Info, "hello world");
242        api.log(LogLevel::Warn, "warning: something");
243
244        let logs = api.logs();
245        assert_eq!(logs.len(), 2);
246        assert_eq!(logs[0].0, LogLevel::Info);
247        assert_eq!(logs[0].1, "hello world");
248
249        assert!(api.has_log(LogLevel::Warn, "warning"));
250    }
251}