use amethystate::store::StorePath;
use amethystate::store::builder::{Backend, StoreBuilder};
use amethystate::{StateScope, amethystate};
use amethystate_test_macros::backends;
#[amethystate(prefix = "ui.window")]
pub struct WindowState {
#[amestate(default = 1280)]
pub width: u32,
}
#[amethystate(prefix = "net")]
pub struct NetState {
#[amestate(path = "listen_port", default = 8080u16)]
pub port: u16,
}
#[amethystate(as_root)]
pub struct RootState {
#[amestate(default = 1280)]
pub width: u32,
}
#[test]
fn a_prefix_builds_the_path_its_levels_build() {
let cases = [
(
<WindowState as StateScope>::PATH,
<WindowState as StateScope>::KEY,
vec!["ui", "window"],
),
(
<NetState as StateScope>::PATH,
<NetState as StateScope>::KEY,
vec!["net"],
),
(
<RootState as StateScope>::PATH,
<RootState as StateScope>::KEY,
vec![],
),
];
for (path, key, levels) in cases {
let built = StorePath::from_segments(&levels);
assert_eq!(path, built, "levels: {levels:?}");
assert_eq!(path.to_string(), built.to_string(), "levels: {levels:?}");
assert_eq!(key, built.to_string(), "levels: {levels:?}");
assert_eq!(
path.segments()
.map(|l| l.as_str().to_string())
.collect::<Vec<_>>(),
levels,
"levels: {levels:?}"
);
}
}
#[test]
fn a_written_prefix_keeps_the_levels_it_names() {
assert_eq!(<WindowState as StateScope>::PATH.len(), 2);
assert_eq!(<WindowState as StateScope>::KEY, "ui.window");
assert_ne!(
<WindowState as StateScope>::KEY,
StorePath::from_segments(["ui.window"]).to_string(),
"one level called `ui.window` is a different path"
);
}
#[backends(all)]
fn a_field_key_names_a_level_under_the_prefix(backend: Backend) {
let at = amethystate_core::test_utils::TempPath::new("prefix_path_key");
let store = StoreBuilder::new(&at).backend(backend).build().unwrap();
let net = NetState::new_with(&store).unwrap();
net.port().set(9090).unwrap();
assert_eq!(
store.get::<u16>(["net", "listen_port"]).unwrap(),
Some(9090),
"the key names the level, and the field's own name does not"
);
assert_eq!(store.get::<u16>(["net", "port"]).unwrap(), None);
}