Skip to main content

openstranded_plugin_api/
test_utils.rs

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