salsa/tests/singleton.rs

68 lines
1.3 KiB
Rust
Raw Normal View History

//! Basic Singleton struct test:
2022-09-02 01:54:21 +00:00
//!
//! Singleton structs are created only once. Subsequent `get`s and `new`s after creation return the same `Id`.
2022-09-02 01:54:21 +00:00
use expect_test::expect;
2024-06-18 07:40:21 +00:00
mod common;
use common::{HasLogger, Logger};
2022-09-02 01:54:21 +00:00
2024-07-17 10:41:56 +00:00
use salsa::Database as _;
2022-09-02 01:54:21 +00:00
use test_log::test;
#[salsa::input(singleton)]
struct MyInput {
field: u32,
id_field: u16,
2022-09-02 01:54:21 +00:00
}
2024-07-17 10:41:56 +00:00
#[salsa::db]
2022-09-02 01:54:21 +00:00
#[derive(Default)]
struct Database {
storage: salsa::Storage<Self>,
logger: Logger,
}
2024-07-17 10:41:56 +00:00
#[salsa::db]
2022-09-02 01:54:21 +00:00
impl salsa::Database for Database {}
impl HasLogger for Database {
fn logger(&self) -> &Logger {
&self.logger
}
}
#[test]
fn basic() {
let db = Database::default();
let input1 = MyInput::new(&db, 3, 4);
2022-09-02 01:54:21 +00:00
let input2 = MyInput::get(&db);
assert_eq!(input1, input2);
let input3 = MyInput::try_get(&db);
assert_eq!(Some(input1), input3);
}
#[test]
#[should_panic]
fn twice() {
let db = Database::default();
let input1 = MyInput::new(&db, 3, 4);
let input2 = MyInput::get(&db);
2022-09-02 01:54:21 +00:00
assert_eq!(input1, input2);
// should panic here
_ = MyInput::new(&db, 3, 5);
}
2022-09-02 01:54:21 +00:00
#[test]
fn debug() {
2024-07-17 10:41:56 +00:00
Database::default().attach(|db| {
let input = MyInput::new(db, 3, 4);
let actual = format!("{:?}", input);
let expected = expect!["MyInput { [salsa id]: 0, field: 3, id_field: 4 }"];
expected.assert_eq(&actual);
});
2022-09-02 01:54:21 +00:00
}