rustrails-support 0.1.1

Core utilities (ActiveSupport equivalent)
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
use chrono::{DateTime, Utc};
use once_cell::sync::Lazy;
use parking_lot::Mutex;

static FROZEN_TIME: Lazy<Mutex<Option<DateTime<Utc>>>> = Lazy::new(|| Mutex::new(None));
#[cfg(test)]
pub(crate) static TESTING_TIME_LOCK: std::sync::LazyLock<std::sync::Mutex<()>> =
    std::sync::LazyLock::new(|| std::sync::Mutex::new(()));

/// Asserts that a shared value changed to the expected state during closure execution.
///
/// This helper is intended for values with shared mutability semantics, such as
/// `Rc<Cell<T>>`, where the cloned `before` handle observes the final state.
pub fn assert_changes<T, F>(before: T, f: F, expected_after: T)
where
    T: PartialEq + std::fmt::Debug,
    F: FnOnce(),
{
    f();
    assert_eq!(
        before, expected_after,
        "expected value to change to the requested final state"
    );
}

/// Asserts that a computed value did not change during closure execution.
pub fn assert_no_changes<T, F>(get_value: impl Fn() -> T, f: F)
where
    T: PartialEq + std::fmt::Debug,
    F: FnOnce(),
{
    let before = get_value();
    f();
    let after = get_value();
    assert_eq!(before, after, "expected value to remain unchanged");
}

/// Asserts that a numeric value changed by the expected amount during closure execution.
pub fn assert_difference<F>(get_value: impl Fn() -> i64, expected_diff: i64, f: F)
where
    F: FnOnce(),
{
    let before = get_value();
    f();
    let after = get_value();
    assert_eq!(
        after - before,
        expected_diff,
        "expected numeric value to change by {expected_diff}, but changed by {}",
        after - before
    );
}

/// Asserts that a numeric value did not change during closure execution.
pub fn assert_no_difference<F>(get_value: impl Fn() -> i64, f: F)
where
    F: FnOnce(),
{
    assert_difference(get_value, 0, f);
}

/// A guard that restores the previously frozen time when dropped.
#[derive(Debug)]
pub struct TimeFreezeGuard {
    previous: Option<DateTime<Utc>>,
}

impl Drop for TimeFreezeGuard {
    fn drop(&mut self) {
        *FROZEN_TIME.lock() = self.previous;
    }
}

/// Freezes the current testing time until the returned guard is dropped.
pub fn freeze_time(at: DateTime<Utc>) -> TimeFreezeGuard {
    let mut slot = FROZEN_TIME.lock();
    let previous = slot.replace(at);
    TimeFreezeGuard { previous }
}

pub(crate) fn frozen_now() -> Option<DateTime<Utc>> {
    *FROZEN_TIME.lock()
}

#[cfg(test)]
mod tests {
    use super::{
        TESTING_TIME_LOCK, assert_changes, assert_difference, assert_no_changes,
        assert_no_difference, freeze_time, frozen_now,
    };
    use chrono::{TimeZone as _, Utc};
    use std::cell::Cell;
    use std::rc::Rc;

    #[test]
    fn testing_assert_changes_accepts_shared_mutable_values() {
        let counter = Rc::new(Cell::new(1));
        let observed = Rc::clone(&counter);

        assert_changes(observed, || counter.set(2), Rc::new(Cell::new(2)));
    }

    #[test]
    #[should_panic(expected = "expected value to change")]
    fn testing_assert_changes_panics_when_final_state_is_unexpected() {
        let counter = Rc::new(Cell::new(1));
        let observed = Rc::clone(&counter);

        assert_changes(observed, || counter.set(2), Rc::new(Cell::new(3)));
    }

    #[test]
    fn testing_assert_no_changes_passes_for_stable_values() {
        let value = Cell::new(10);

        assert_no_changes(
            || value.get(),
            || {
                let _ = value.get();
            },
        );
    }

    #[test]
    #[should_panic(expected = "expected value to remain unchanged")]
    fn testing_assert_no_changes_panics_for_changed_values() {
        let value = Cell::new(10);

        assert_no_changes(|| value.get(), || value.set(20));
    }

    #[test]
    fn testing_assert_difference_tracks_numeric_change() {
        let value = Cell::new(5);

        assert_difference(|| i64::from(value.get()), 3, || value.set(8));
    }

    #[test]
    #[should_panic(expected = "expected numeric value to change by 2")]
    fn testing_assert_difference_panics_for_wrong_delta() {
        let value = Cell::new(5);

        assert_difference(|| i64::from(value.get()), 2, || value.set(8));
    }

    #[test]
    fn testing_assert_no_difference_accepts_no_change() {
        let value = Cell::new(5);

        assert_no_difference(
            || i64::from(value.get()),
            || {
                let _ = value.get();
            },
        );
    }

    #[test]
    #[should_panic(expected = "expected numeric value to change by 0")]
    fn testing_assert_no_difference_panics_when_value_changes() {
        let value = Cell::new(5);

        assert_no_difference(|| i64::from(value.get()), || value.set(6));
    }

    #[test]
    fn testing_freeze_time_sets_and_restores_time() {
        let _lock = TESTING_TIME_LOCK.lock().unwrap();
        let initial = frozen_now();
        let frozen = Utc.with_ymd_and_hms(2024, 1, 1, 12, 0, 0).unwrap();

        {
            let _guard = freeze_time(frozen);
            assert_eq!(frozen_now(), Some(frozen));
        }

        assert_eq!(frozen_now(), initial);
    }

    #[test]
    fn testing_freeze_time_restores_previous_value_when_nested() {
        let _lock = TESTING_TIME_LOCK.lock().unwrap();
        let baseline = frozen_now();
        let first = Utc.with_ymd_and_hms(2024, 1, 1, 12, 0, 0).unwrap();
        let second = Utc.with_ymd_and_hms(2024, 1, 1, 13, 0, 0).unwrap();

        let outer = freeze_time(first);
        assert_eq!(frozen_now(), Some(first));
        {
            let _inner = freeze_time(second);
            assert_eq!(frozen_now(), Some(second));
        }
        assert_eq!(frozen_now(), Some(first));
        drop(outer);
        assert_eq!(frozen_now(), baseline);
    }

    #[test]
    fn testing_freeze_time_restores_baseline_after_panic() {
        let _lock = TESTING_TIME_LOCK.lock().unwrap();
        let baseline = frozen_now();
        let frozen = Utc.with_ymd_and_hms(2024, 2, 1, 9, 30, 0).unwrap();

        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = freeze_time(frozen);
            assert_eq!(frozen_now(), Some(frozen));
            panic!("boom");
        }));

        assert!(panic.is_err());
        assert_eq!(frozen_now(), baseline);
    }

    #[test]
    fn testing_nested_freeze_time_restores_outer_value_after_inner_panic() {
        let _lock = TESTING_TIME_LOCK.lock().unwrap();
        let baseline = frozen_now();
        let first = Utc.with_ymd_and_hms(2024, 2, 1, 9, 30, 0).unwrap();
        let second = Utc.with_ymd_and_hms(2024, 2, 1, 10, 30, 0).unwrap();

        let outer = freeze_time(first);
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _inner = freeze_time(second);
            assert_eq!(frozen_now(), Some(second));
            panic!("boom");
        }));

        assert!(panic.is_err());
        assert_eq!(frozen_now(), Some(first));
        drop(outer);
        assert_eq!(frozen_now(), baseline);
    }

    #[test]
    fn testing_assert_changes_accepts_multiple_mutations_before_final_state() {
        let value = Rc::new(Cell::new(1));
        let observed = Rc::clone(&value);

        assert_changes(
            observed,
            || {
                value.set(2);
                value.set(3);
            },
            Rc::new(Cell::new(3)),
        );
    }

    #[test]
    fn testing_assert_changes_panic_message_is_stable() {
        use std::panic::{AssertUnwindSafe, catch_unwind};

        let value = Rc::new(Cell::new(1));
        let observed = Rc::clone(&value);

        let panic = catch_unwind(AssertUnwindSafe(|| {
            assert_changes(observed, || value.set(2), Rc::new(Cell::new(3)));
        }))
        .unwrap_err();

        let message = panic
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| {
                panic
                    .downcast_ref::<&str>()
                    .map(|message| (*message).to_owned())
            })
            .unwrap();

        assert!(message.contains("expected value to change to the requested final state"));
    }

    #[test]
    fn testing_assert_no_changes_panic_message_is_stable() {
        use std::panic::{AssertUnwindSafe, catch_unwind};

        let value = Cell::new(10);

        let panic = catch_unwind(AssertUnwindSafe(|| {
            assert_no_changes(|| value.get(), || value.set(20));
        }))
        .unwrap_err();

        let message = panic
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| {
                panic
                    .downcast_ref::<&str>()
                    .map(|message| (*message).to_owned())
            })
            .unwrap();

        assert!(message.contains("expected value to remain unchanged"));
    }

    #[test]
    fn testing_assert_difference_supports_negative_deltas() {
        let value = Cell::new(5);

        assert_difference(|| i64::from(value.get()), -2, || value.set(3));
    }

    #[test]
    fn testing_assert_difference_supports_explicit_zero_delta() {
        let value = Cell::new(5);

        assert_difference(
            || i64::from(value.get()),
            0,
            || {
                let _ = value.get();
            },
        );
    }

    #[test]
    fn testing_assert_difference_panic_reports_actual_delta() {
        use std::panic::{AssertUnwindSafe, catch_unwind};

        let value = Cell::new(5);

        let panic = catch_unwind(AssertUnwindSafe(|| {
            assert_difference(|| i64::from(value.get()), 2, || value.set(8));
        }))
        .unwrap_err();

        let message = panic
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| {
                panic
                    .downcast_ref::<&str>()
                    .map(|message| (*message).to_owned())
            })
            .unwrap();

        assert!(message.contains("expected numeric value to change by 2"));
        assert!(message.contains("changed by 3"));
    }

    #[test]
    fn testing_assert_no_difference_panic_mentions_zero_delta() {
        use std::panic::{AssertUnwindSafe, catch_unwind};

        let value = Cell::new(5);

        let panic = catch_unwind(AssertUnwindSafe(|| {
            assert_no_difference(|| i64::from(value.get()), || value.set(6));
        }))
        .unwrap_err();

        let message = panic
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| {
                panic
                    .downcast_ref::<&str>()
                    .map(|message| (*message).to_owned())
            })
            .unwrap();

        assert!(message.contains("expected numeric value to change by 0"));
    }

    #[test]
    fn testing_nested_assert_difference_tracks_both_scopes() {
        let outer = Cell::new(1);
        let inner = Cell::new(10);

        assert_difference(
            || i64::from(outer.get()),
            2,
            || {
                assert_difference(|| i64::from(inner.get()), -3, || inner.set(7));
                outer.set(3);
            },
        );
    }

    #[test]
    fn testing_assert_difference_can_wrap_assert_no_difference() {
        let changed = Cell::new(1);
        let stable = Cell::new(10);

        assert_difference(
            || i64::from(changed.get()),
            4,
            || {
                assert_no_changes(
                    || stable.get(),
                    || {
                        let _ = stable.get();
                    },
                );
                changed.set(5);
            },
        );
    }

    #[test]
    fn testing_assert_no_difference_can_wrap_assert_difference_on_other_value() {
        let stable = Cell::new(10);
        let changed = Cell::new(1);

        assert_no_difference(
            || i64::from(stable.get()),
            || {
                assert_difference(|| i64::from(changed.get()), 2, || changed.set(3));
            },
        );
    }

    #[test]
    fn testing_assert_changes_supports_refcell_backed_values() {
        use std::cell::RefCell;

        let value = Rc::new(RefCell::new(String::from("draft")));
        let observed = Rc::clone(&value);

        assert_changes(
            observed,
            || *value.borrow_mut() = String::from("published"),
            Rc::new(RefCell::new(String::from("published"))),
        );
    }

    #[test]
    fn testing_assert_no_changes_allows_nested_reads() {
        let value = Cell::new(10);

        assert_no_changes(
            || value.get(),
            || {
                let before = value.get();
                let after = value.get();
                assert_eq!(before, after);
            },
        );
    }

    #[test]
    fn testing_assert_difference_observes_multiple_updates() {
        let value = Cell::new(1);

        assert_difference(
            || i64::from(value.get()),
            4,
            || {
                value.set(3);
                value.set(5);
            },
        );
    }

    #[test]
    fn testing_assert_difference_handles_negative_start_values() {
        let value = Cell::new(-3);

        assert_difference(|| i64::from(value.get()), 5, || value.set(2));
    }

    #[test]
    fn testing_frozen_now_matches_baseline_without_guard() {
        let _lock = TESTING_TIME_LOCK.lock().unwrap();
        let baseline = frozen_now();

        assert_eq!(frozen_now(), baseline);
    }
}