openstranded_plugin_api/
test_utils.rs1use std::cell::RefCell;
2use std::collections::HashMap;
3
4use crate::{
5 GameAPI, LogLevel, RegistryEntry, Service, ServiceError,
6};
7
8pub struct MockGameAPI {
34 registry: HashMap<String, HashMap<String, Vec<u8>>>,
36 services: Vec<(String, Box<dyn Service>)>,
38 logs: RefCell<Vec<(LogLevel, String)>>,
40}
41
42impl MockGameAPI {
43 #[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 #[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 pub fn logs(&self) -> Vec<(LogLevel, String)> {
85 self.logs.borrow().clone()
86 }
87
88 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 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#[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}