Repository navigation
Expand file tree
/
Copy pathtesting.rs
More file actions
641 lines (552 loc) · 16.3 KB
/
Copy pathtesting.rs
File metadata and controls
641 lines (552 loc) · 16.3 KB
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! Testing utilities.
//!
//! Provides utilities for testing including mocking,
//! test fixtures, and assertions.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use cortex_common::timestamp_now;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
/// Test result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestResult {
/// Test name.
pub name: String,
/// Passed.
pub passed: bool,
/// Duration in milliseconds.
pub duration_ms: u64,
/// Error message if failed.
pub error: Option<String>,
/// Output.
pub output: Option<String>,
/// Skipped.
pub skipped: bool,
/// Skip reason.
pub skip_reason: Option<String>,
}
impl TestResult {
/// Create a passing result.
pub fn pass(name: impl Into<String>, duration_ms: u64) -> Self {
Self {
name: name.into(),
passed: true,
duration_ms,
error: None,
output: None,
skipped: false,
skip_reason: None,
}
}
/// Create a failing result.
pub fn fail(name: impl Into<String>, error: impl Into<String>, duration_ms: u64) -> Self {
Self {
name: name.into(),
passed: false,
duration_ms,
error: Some(error.into()),
output: None,
skipped: false,
skip_reason: None,
}
}
/// Create a skipped result.
pub fn skip(name: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
name: name.into(),
passed: true,
duration_ms: 0,
error: None,
output: None,
skipped: true,
skip_reason: Some(reason.into()),
}
}
/// Set output.
pub fn with_output(mut self, output: impl Into<String>) -> Self {
self.output = Some(output.into());
self
}
}
/// Test suite result.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TestSuiteResult {
/// Suite name.
pub name: String,
/// Test results.
pub tests: Vec<TestResult>,
/// Total duration.
pub duration_ms: u64,
/// Passed count.
pub passed: u32,
/// Failed count.
pub failed: u32,
/// Skipped count.
pub skipped: u32,
}
impl TestSuiteResult {
/// Create a new suite result.
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
/// Add a test result.
pub fn add(&mut self, result: TestResult) {
self.duration_ms += result.duration_ms;
if result.skipped {
self.skipped += 1;
} else if result.passed {
self.passed += 1;
} else {
self.failed += 1;
}
self.tests.push(result);
}
/// Get total count.
pub fn total(&self) -> u32 {
self.passed + self.failed + self.skipped
}
/// Get pass rate.
pub fn pass_rate(&self) -> f32 {
let total = self.passed + self.failed;
if total == 0 {
1.0
} else {
self.passed as f32 / total as f32
}
}
/// Check if all passed.
pub fn all_passed(&self) -> bool {
self.failed == 0
}
/// Format summary.
pub fn summary(&self) -> String {
format!(
"{}: {} passed, {} failed, {} skipped ({}ms)",
self.name, self.passed, self.failed, self.skipped, self.duration_ms
)
}
}
/// Mock value.
#[derive(Debug, Clone)]
pub struct MockValue {
/// The value.
value: serde_json::Value,
/// Call count.
calls: u32,
}
impl MockValue {
/// Create a new mock value.
pub fn new<T: Serialize>(value: T) -> Self {
Self {
value: serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
calls: 0,
}
}
/// Get the value.
pub fn get<T: for<'de> Deserialize<'de>>(&mut self) -> Option<T> {
self.calls += 1;
serde_json::from_value(self.value.clone()).ok()
}
/// Get call count.
pub fn call_count(&self) -> u32 {
self.calls
}
}
/// Mock store.
pub struct MockStore {
/// Values.
values: RwLock<HashMap<String, MockValue>>,
/// Call history.
history: RwLock<Vec<MockCall>>,
}
impl MockStore {
/// Create a new store.
pub fn new() -> Self {
Self {
values: RwLock::new(HashMap::new()),
history: RwLock::new(Vec::new()),
}
}
/// Register a mock value.
pub async fn register<T: Serialize>(&self, key: impl Into<String>, value: T) {
self.values
.write()
.await
.insert(key.into(), MockValue::new(value));
}
/// Get a mock value.
pub async fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Option<T> {
let mut values = self.values.write().await;
values.get_mut(key).and_then(MockValue::get)
}
/// Record a call.
pub async fn record_call(&self, name: impl Into<String>, args: Vec<serde_json::Value>) {
self.history.write().await.push(MockCall {
name: name.into(),
args,
timestamp: timestamp_now(),
});
}
/// Get call history.
pub async fn call_history(&self, name: &str) -> Vec<MockCall> {
self.history
.read()
.await
.iter()
.filter(|c| c.name == name)
.cloned()
.collect()
}
/// Get call count.
pub async fn call_count(&self, name: &str) -> usize {
self.history
.read()
.await
.iter()
.filter(|c| c.name == name)
.count()
}
/// Clear history.
pub async fn clear(&self) {
self.values.write().await.clear();
self.history.write().await.clear();
}
}
impl Default for MockStore {
fn default() -> Self {
Self::new()
}
}
/// Mock call.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MockCall {
/// Function name.
pub name: String,
/// Arguments.
pub args: Vec<serde_json::Value>,
/// Timestamp.
pub timestamp: u64,
}
/// Test fixture.
pub struct TestFixture {
/// Temp directory.
temp_dir: Option<tempfile::TempDir>,
/// Mock store.
mocks: MockStore,
/// Environment overrides.
env_overrides: HashMap<String, String>,
/// Original env values.
original_env: HashMap<String, Option<String>>,
}
impl TestFixture {
/// Create a new fixture.
pub fn new() -> Self {
Self {
temp_dir: None,
mocks: MockStore::new(),
env_overrides: HashMap::new(),
original_env: HashMap::new(),
}
}
/// Create with temp directory.
pub fn with_temp_dir() -> std::io::Result<Self> {
let temp = tempfile::tempdir()?;
Ok(Self {
temp_dir: Some(temp),
mocks: MockStore::new(),
env_overrides: HashMap::new(),
original_env: HashMap::new(),
})
}
/// Get temp directory path.
pub fn temp_path(&self) -> Option<&Path> {
self.temp_dir.as_ref().map(tempfile::TempDir::path)
}
/// Create a temp file.
pub fn create_file(&self, name: &str, content: &str) -> std::io::Result<PathBuf> {
let path = self
.temp_path()
.ok_or_else(|| std::io::Error::other("No temp directory"))?
.join(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, content)?;
Ok(path)
}
/// Get mock store.
pub fn mocks(&self) -> &MockStore {
&self.mocks
}
/// Set environment variable.
pub fn set_env(&mut self, key: impl Into<String>, value: impl Into<String>) {
let key = key.into();
let value = value.into();
// Save original
if !self.original_env.contains_key(&key) {
self.original_env
.insert(key.clone(), std::env::var(&key).ok());
}
// SAFETY: We restore the original values in Drop
unsafe {
std::env::set_var(&key, &value);
}
self.env_overrides.insert(key, value);
}
/// Unset environment variable.
pub fn unset_env(&mut self, key: impl Into<String>) {
let key = key.into();
// Save original
if !self.original_env.contains_key(&key) {
self.original_env
.insert(key.clone(), std::env::var(&key).ok());
}
// SAFETY: We restore the original values in Drop
unsafe {
std::env::remove_var(&key);
}
}
}
impl Drop for TestFixture {
fn drop(&mut self) {
// Restore environment
// SAFETY: Restoring original environment values
unsafe {
for (key, original) in &self.original_env {
match original {
Some(value) => std::env::set_var(key, value),
None => std::env::remove_var(key),
}
}
}
}
}
impl Default for TestFixture {
fn default() -> Self {
Self::new()
}
}
/// Assertion helpers.
pub mod assert {
use super::*;
/// Assert that a value is Some.
pub fn is_some<T>(option: &Option<T>, message: &str) {
if option.is_none() {
panic!("Expected Some, got None: {message}");
}
}
/// Assert that a value is None.
pub fn is_none<T>(option: &Option<T>, message: &str) {
if option.is_some() {
panic!("Expected None, got Some: {message}");
}
}
/// Assert that a result is Ok.
pub fn is_ok<T, E: std::fmt::Debug>(result: &Result<T, E>, message: &str) {
if let Err(e) = result {
panic!("Expected Ok, got Err({e:?}): {message}");
}
}
/// Assert that a result is Err.
pub fn is_err<T: std::fmt::Debug, E>(result: &Result<T, E>, message: &str) {
if let Ok(v) = result {
panic!("Expected Err, got Ok({v:?}): {message}");
}
}
/// Assert that a string contains a substring.
pub fn contains(haystack: &str, needle: &str, message: &str) {
if !haystack.contains(needle) {
panic!("Expected '{haystack}' to contain '{needle}': {message}");
}
}
/// Assert that a string does not contain a substring.
pub fn not_contains(haystack: &str, needle: &str, message: &str) {
if haystack.contains(needle) {
panic!("Expected '{haystack}' to not contain '{needle}': {message}");
}
}
/// Assert that a collection is empty.
pub fn is_empty<T>(collection: &[T], message: &str) {
if !collection.is_empty() {
panic!(
"Expected empty collection, got {} items: {}",
collection.len(),
message
);
}
}
/// Assert that a collection is not empty.
pub fn not_empty<T>(collection: &[T], message: &str) {
if collection.is_empty() {
panic!("Expected non-empty collection: {message}");
}
}
/// Assert that a path exists.
pub fn path_exists(path: &Path, message: &str) {
if !path.exists() {
panic!("Expected path to exist: {path:?}: {message}");
}
}
/// Assert that a path does not exist.
pub fn path_not_exists(path: &Path, message: &str) {
if path.exists() {
panic!("Expected path to not exist: {path:?}: {message}");
}
}
/// Assert approximate equality for floats.
pub fn approx_eq(a: f64, b: f64, epsilon: f64, message: &str) {
if (a - b).abs() > epsilon {
panic!("Expected {a} ≈ {b} (ε={epsilon}): {message}");
}
}
}
/// Test runner.
pub struct TestRunner {
/// Test cases.
cases: Vec<TestCase>,
/// Setup function.
setup: Option<Box<dyn Fn() -> TestFixture + Send + Sync>>,
}
impl TestRunner {
/// Create a new runner.
pub fn new() -> Self {
Self {
cases: Vec::new(),
setup: None,
}
}
/// Set setup function.
pub fn setup<F>(mut self, f: F) -> Self
where
F: Fn() -> TestFixture + Send + Sync + 'static,
{
self.setup = Some(Box::new(f));
self
}
/// Add a test case.
pub fn test<F>(mut self, name: impl Into<String>, f: F) -> Self
where
F: Fn(&TestFixture) -> Result<(), String> + Send + Sync + 'static,
{
self.cases.push(TestCase {
name: name.into(),
test_fn: Box::new(f),
skip: false,
skip_reason: None,
});
self
}
/// Run all tests.
pub fn run(&self) -> TestSuiteResult {
let mut results = TestSuiteResult::new("Test Suite");
for case in &self.cases {
let fixture = if let Some(ref setup) = self.setup {
setup()
} else {
TestFixture::new()
};
if case.skip {
results.add(TestResult::skip(
&case.name,
case.skip_reason.as_deref().unwrap_or("Skipped"),
));
continue;
}
let start = std::time::Instant::now();
let result = (case.test_fn)(&fixture);
let duration = start.elapsed().as_millis() as u64;
match result {
Ok(()) => results.add(TestResult::pass(&case.name, duration)),
Err(e) => results.add(TestResult::fail(&case.name, e, duration)),
}
}
results
}
}
impl Default for TestRunner {
fn default() -> Self {
Self::new()
}
}
/// Test case.
struct TestCase {
name: String,
test_fn: Box<dyn Fn(&TestFixture) -> Result<(), String> + Send + Sync>,
skip: bool,
skip_reason: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_test_result() {
let pass = TestResult::pass("test1", 100);
assert!(pass.passed);
assert!(!pass.skipped);
let fail = TestResult::fail("test2", "error", 50);
assert!(!fail.passed);
assert_eq!(fail.error, Some("error".to_string()));
let skip = TestResult::skip("test3", "not implemented");
assert!(skip.skipped);
}
#[test]
fn test_suite_result() {
let mut suite = TestSuiteResult::new("suite");
suite.add(TestResult::pass("test1", 100));
suite.add(TestResult::pass("test2", 50));
suite.add(TestResult::fail("test3", "err", 25));
assert_eq!(suite.passed, 2);
assert_eq!(suite.failed, 1);
assert_eq!(suite.total(), 3);
assert!(!suite.all_passed());
}
#[tokio::test]
async fn test_mock_store() {
let store = MockStore::new();
store.register("key1", "value1").await;
let value: Option<String> = store.get("key1").await;
assert_eq!(value, Some("value1".to_string()));
store
.record_call("func1", vec![serde_json::json!(42)])
.await;
assert_eq!(store.call_count("func1").await, 1);
}
#[test]
fn test_fixture() {
let mut fixture = TestFixture::new();
fixture.set_env("TEST_VAR_123", "test_value");
assert_eq!(
std::env::var("TEST_VAR_123").ok(),
Some("test_value".to_string())
);
drop(fixture);
// Env should be restored
}
#[test]
fn test_fixture_with_temp() {
let fixture = TestFixture::with_temp_dir().unwrap();
let path = fixture.create_file("test.txt", "content").unwrap();
assert!(path.exists());
assert_eq!(std::fs::read_to_string(&path).unwrap(), "content");
}
#[test]
fn test_assertions() {
assert::is_some(&Some(42), "should be some");
assert::is_none::<i32>(&None, "should be none");
assert::contains("hello world", "world", "should contain");
assert::not_empty(&[1, 2, 3], "should not be empty");
assert::approx_eq(1.0, 1.001, 0.01, "should be approximately equal");
}
#[test]
fn test_runner() {
let results = TestRunner::new()
.test("passing", |_| Ok(()))
.test("failing", |_| Err("intentional".to_string()))
.run();
assert_eq!(results.passed, 1);
assert_eq!(results.failed, 1);
}
}