openstranded_plugin_api/
test_utils.rs1use std::cell::RefCell;
2
3use crate::{
4 GameAPI, LogLevel, Registry, RegistryEntry, Service, ServiceError,
5};
6
7pub struct MockGameAPI {
33 pub registry: Registry,
35 services: Vec<(String, Box<dyn Service>)>,
37 logs: RefCell<Vec<(LogLevel, String)>>,
39}
40
41impl MockGameAPI {
42 #[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 #[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 pub fn logs(&self) -> Vec<(LogLevel, String)> {
82 self.logs.borrow().clone()
83 }
84
85 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 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#[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}