reinhardt-testkit 0.1.1

Core testing infrastructure for Reinhardt framework (no functional crate dependencies)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
use reinhardt_core::security::escape_html;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

/// Debug panel information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DebugPanel {
	/// Display title of the panel.
	pub title: String,
	/// Entries displayed within this panel.
	pub content: Vec<DebugEntry>,
}

/// A single entry within a debug panel.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum DebugEntry {
	/// A key-value pair entry.
	KeyValue {
		/// The key label.
		key: String,
		/// The associated value.
		value: String,
	},
	/// A tabular data entry.
	Table {
		/// Column header names.
		headers: Vec<String>,
		/// Row data (each inner Vec corresponds to one row).
		rows: Vec<Vec<String>>,
	},
	/// A code snippet entry.
	Code {
		/// Programming language for syntax highlighting.
		language: String,
		/// The code content.
		code: String,
	},
	/// A plain text entry.
	Text {
		/// The text content.
		text: String,
	},
}

/// Request/Response timing information
#[derive(Debug, Clone, Serialize)]
pub struct TimingInfo {
	/// Total request processing time.
	pub total_time: Duration,
	/// Total time spent executing SQL queries.
	pub sql_time: Duration,
	/// Number of SQL queries executed.
	pub sql_queries: usize,
	/// Number of cache hits.
	pub cache_hits: usize,
	/// Number of cache misses.
	pub cache_misses: usize,
}

/// SQL query record
#[derive(Debug, Clone, Serialize)]
pub struct SqlQuery {
	/// The SQL query string.
	pub query: String,
	/// Time taken to execute the query.
	pub duration: Duration,
	/// Call stack at the point the query was executed.
	pub stack_trace: Vec<String>,
}

/// Debug toolbar
pub struct DebugToolbar {
	panels: Arc<RwLock<HashMap<String, DebugPanel>>>,
	timing: Arc<RwLock<TimingInfo>>,
	sql_queries: Arc<RwLock<Vec<SqlQuery>>>,
	start_time: Instant,
	enabled: bool,
}

impl DebugToolbar {
	/// Create a new debug toolbar
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// let toolbar = DebugToolbar::new();
	/// assert!(toolbar.is_enabled());
	/// ```
	pub fn new() -> Self {
		Self {
			panels: Arc::new(RwLock::new(HashMap::new())),
			timing: Arc::new(RwLock::new(TimingInfo {
				total_time: Duration::from_secs(0),
				sql_time: Duration::from_secs(0),
				sql_queries: 0,
				cache_hits: 0,
				cache_misses: 0,
			})),
			sql_queries: Arc::new(RwLock::new(Vec::new())),
			start_time: Instant::now(),
			enabled: true,
		}
	}
	/// Enable or disable the debug toolbar
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// let mut toolbar = DebugToolbar::new();
	/// toolbar.set_enabled(false);
	/// assert!(!toolbar.is_enabled());
	/// ```
	pub fn set_enabled(&mut self, enabled: bool) {
		self.enabled = enabled;
	}
	/// Check if the debug toolbar is enabled
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// let toolbar = DebugToolbar::new();
	/// assert!(toolbar.is_enabled());
	/// ```
	pub fn is_enabled(&self) -> bool {
		self.enabled
	}
	/// Add a debug panel
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::{DebugToolbar, DebugPanel, DebugEntry};
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// let panel = DebugPanel {
	///     title: "Test Panel".to_string(),
	///     content: vec![DebugEntry::Text { text: "Hello".to_string() }],
	/// };
	/// toolbar.add_panel("test".to_string(), panel).await;
	/// let panels = toolbar.get_panels().await;
	/// assert!(panels.contains_key("test"));
	/// # });
	/// ```
	pub async fn add_panel(&self, id: String, panel: DebugPanel) {
		if !self.enabled {
			return;
		}
		self.panels.write().await.insert(id, panel);
	}
	/// Record SQL query
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	/// use std::time::Duration;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// toolbar.record_sql_query("SELECT * FROM users".to_string(), Duration::from_millis(10)).await;
	/// let timing = toolbar.get_timing().await;
	/// assert_eq!(timing.sql_queries, 1);
	/// assert!(timing.sql_time >= Duration::from_millis(10));
	/// # });
	/// ```
	pub async fn record_sql_query(&self, query: String, duration: Duration) {
		if !self.enabled {
			return;
		}

		let sql_query = SqlQuery {
			query,
			duration,
			stack_trace: vec![],
		};

		self.sql_queries.write().await.push(sql_query);

		let mut timing = self.timing.write().await;
		timing.sql_queries += 1;
		timing.sql_time += duration;
	}
	/// Record cache hit
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// toolbar.record_cache_hit().await;
	/// let timing = toolbar.get_timing().await;
	/// assert_eq!(timing.cache_hits, 1);
	/// # });
	/// ```
	pub async fn record_cache_hit(&self) {
		if !self.enabled {
			return;
		}
		self.timing.write().await.cache_hits += 1;
	}
	/// Record cache miss
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// toolbar.record_cache_miss().await;
	/// let timing = toolbar.get_timing().await;
	/// assert_eq!(timing.cache_misses, 1);
	/// # });
	/// ```
	pub async fn record_cache_miss(&self) {
		if !self.enabled {
			return;
		}
		self.timing.write().await.cache_misses += 1;
	}
	/// Finalize timing information
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	/// use std::time::Duration;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// // Simulate some work
	/// tokio::time::sleep(Duration::from_millis(10)).await;
	/// toolbar.finalize().await;
	/// let timing = toolbar.get_timing().await;
	/// assert!(timing.total_time >= Duration::from_millis(10));
	/// # });
	/// ```
	pub async fn finalize(&self) {
		if !self.enabled {
			return;
		}
		self.timing.write().await.total_time = self.start_time.elapsed();
	}
	/// Get all panels
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::{DebugToolbar, DebugPanel, DebugEntry};
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// let panel = DebugPanel {
	///     title: "Test".to_string(),
	///     content: vec![],
	/// };
	/// toolbar.add_panel("test".to_string(), panel).await;
	/// let panels = toolbar.get_panels().await;
	/// assert_eq!(panels.len(), 1);
	/// # });
	/// ```
	pub async fn get_panels(&self) -> HashMap<String, DebugPanel> {
		self.panels.read().await.clone()
	}
	/// Get timing info
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// let timing = toolbar.get_timing().await;
	/// assert_eq!(timing.sql_queries, 0);
	/// assert_eq!(timing.cache_hits, 0);
	/// # });
	/// ```
	pub async fn get_timing(&self) -> TimingInfo {
		self.timing.read().await.clone()
	}
	/// Get SQL queries
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	/// use std::time::Duration;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// toolbar.record_sql_query("SELECT 1".to_string(), Duration::from_millis(5)).await;
	/// let queries = toolbar.get_sql_queries().await;
	/// assert_eq!(queries.len(), 1);
	/// assert_eq!(queries[0].query, "SELECT 1");
	/// # });
	/// ```
	pub async fn get_sql_queries(&self) -> Vec<SqlQuery> {
		self.sql_queries.read().await.clone()
	}
	/// Render as HTML
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_testkit::debug::DebugToolbar;
	///
	/// # tokio_test::block_on(async {
	/// let toolbar = DebugToolbar::new();
	/// toolbar.finalize().await;
	/// let html = toolbar.render_html().await;
	/// assert!(html.contains("debug-toolbar"));
	/// assert!(html.contains("Timing"));
	/// # });
	/// ```
	pub async fn render_html(&self) -> String {
		if !self.enabled {
			return String::new();
		}

		let panels = self.get_panels().await;
		let timing = self.get_timing().await;
		let queries = self.get_sql_queries().await;

		format!(
			r#"
<div class="debug-toolbar">
    <div class="timing">
        <h3>Timing</h3>
        <p>Total: {:?}</p>
        <p>SQL: {:?} ({} queries)</p>
        <p>Cache: {} hits, {} misses</p>
    </div>
    <div class="sql-queries">
        <h3>SQL Queries</h3>
        <ul>
            {}
        </ul>
    </div>
    <div class="panels">
        {}
    </div>
</div>
"#,
			timing.total_time,
			timing.sql_time,
			timing.sql_queries,
			timing.cache_hits,
			timing.cache_misses,
			queries
				.iter()
				.map(|q| format!("<li>{} ({:?})</li>", escape_html(&q.query), q.duration))
				.collect::<Vec<_>>()
				.join("\n"),
			panels
				.iter()
				.map(|(id, panel)| format!(
					"<div class='panel' id='{}'><h3>{}</h3></div>",
					escape_html(id),
					escape_html(&panel.title)
				))
				.collect::<Vec<_>>()
				.join("\n")
		)
	}
}

impl Default for DebugToolbar {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[tokio::test]
	async fn test_debug_toolbar() {
		let toolbar = DebugToolbar::new();

		toolbar
			.record_sql_query("SELECT * FROM users".to_string(), Duration::from_millis(10))
			.await;
		toolbar.record_cache_hit().await;
		toolbar.finalize().await;

		let timing = toolbar.get_timing().await;
		assert_eq!(timing.sql_queries, 1);
		assert_eq!(timing.cache_hits, 1);

		let queries = toolbar.get_sql_queries().await;
		assert_eq!(queries.len(), 1);
	}

	#[tokio::test]
	async fn test_debug_panel() {
		let toolbar = DebugToolbar::new();

		let panel = DebugPanel {
			title: "Test Panel".to_string(),
			content: vec![DebugEntry::KeyValue {
				key: "key".to_string(),
				value: "value".to_string(),
			}],
		};

		toolbar.add_panel("test".to_string(), panel).await;

		let panels = toolbar.get_panels().await;
		assert_eq!(panels.len(), 1);
		assert!(panels.contains_key("test"));
	}

	#[test]
	fn test_escape_html() {
		assert_eq!(escape_html("hello"), "hello");
		assert_eq!(
			escape_html("<script>alert('xss')</script>"),
			"&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;"
		);
		assert_eq!(escape_html("a & b"), "a &amp; b");
		assert_eq!(escape_html(r#"key="value""#), "key=&quot;value&quot;");
	}

	#[tokio::test]
	async fn test_render_html_escapes_sql_queries() {
		let toolbar = DebugToolbar::new();
		toolbar
			.record_sql_query(
				"SELECT * FROM users WHERE name = '<script>alert(1)</script>'".to_string(),
				Duration::from_millis(1),
			)
			.await;
		toolbar.finalize().await;

		let html = toolbar.render_html().await;
		assert!(!html.contains("<script>"));
		assert!(html.contains("&lt;script&gt;"));
	}

	#[tokio::test]
	async fn test_render_html_escapes_panel_content() {
		let toolbar = DebugToolbar::new();
		let panel = DebugPanel {
			title: "<img src=x onerror=alert(1)>".to_string(),
			content: vec![],
		};
		toolbar.add_panel("<script>".to_string(), panel).await;
		toolbar.finalize().await;

		let html = toolbar.render_html().await;
		assert!(!html.contains("<script>"));
		assert!(!html.contains("<img src=x"));
		assert!(html.contains("&lt;script&gt;"));
		assert!(html.contains("&lt;img src=x onerror=alert(1)&gt;"));
	}

	#[tokio::test]
	async fn test_disabled_toolbar() {
		let mut toolbar = DebugToolbar::new();
		toolbar.set_enabled(false);

		toolbar
			.record_sql_query("SELECT 1".to_string(), Duration::from_millis(1))
			.await;

		let timing = toolbar.get_timing().await;
		assert_eq!(timing.sql_queries, 0);
	}
}