107 lines
2.4 KiB
Rust
107 lines
2.4 KiB
Rust
use heromodels_derive::model;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
// Define the necessary structs and traits for testing
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct BaseModelData {
|
|
pub id: u32,
|
|
pub created_at: i64,
|
|
pub modified_at: i64,
|
|
pub comments: Vec<u32>,
|
|
}
|
|
|
|
impl BaseModelData {
|
|
pub fn new(id: u32) -> Self {
|
|
let now = 1000; // Mock timestamp
|
|
Self {
|
|
id,
|
|
created_at: now,
|
|
modified_at: now,
|
|
comments: Vec::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct IndexKey {
|
|
pub name: &'static str,
|
|
pub value: String,
|
|
}
|
|
|
|
pub trait Model: std::fmt::Debug + Clone {
|
|
fn db_prefix() -> &'static str;
|
|
fn get_id(&self) -> u32;
|
|
fn base_data_mut(&mut self) -> &mut BaseModelData;
|
|
fn db_keys(&self) -> Vec<IndexKey>;
|
|
}
|
|
|
|
pub trait Index {
|
|
type Model: Model;
|
|
type Key: ?Sized;
|
|
fn key() -> &'static str;
|
|
}
|
|
|
|
// Test struct using the model macro
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
#[model]
|
|
struct TestUser {
|
|
base_data: BaseModelData,
|
|
|
|
#[index]
|
|
username: String,
|
|
|
|
#[index]
|
|
is_active: bool,
|
|
}
|
|
|
|
// Test struct with custom index name
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
#[model]
|
|
struct TestUserWithCustomIndex {
|
|
base_data: BaseModelData,
|
|
|
|
#[index(name = "custom_username")]
|
|
username: String,
|
|
|
|
#[index]
|
|
is_active: bool,
|
|
}
|
|
|
|
#[test]
|
|
fn test_basic_model() {
|
|
assert_eq!(TestUser::db_prefix(), "test_user");
|
|
|
|
let user = TestUser {
|
|
base_data: BaseModelData::new(1),
|
|
username: "test".to_string(),
|
|
is_active: true,
|
|
};
|
|
|
|
let keys = user.db_keys();
|
|
assert_eq!(keys.len(), 2);
|
|
assert_eq!(keys[0].name, "username");
|
|
assert_eq!(keys[0].value, "test");
|
|
assert_eq!(keys[1].name, "is_active");
|
|
assert_eq!(keys[1].value, "true");
|
|
}
|
|
|
|
#[test]
|
|
fn test_custom_index_name() {
|
|
let user = TestUserWithCustomIndex {
|
|
base_data: BaseModelData::new(1),
|
|
username: "test".to_string(),
|
|
is_active: true,
|
|
};
|
|
|
|
// Check that the Username struct uses the custom index name
|
|
assert_eq!(Username::key(), "custom_username");
|
|
|
|
// Check that the db_keys method returns the correct keys
|
|
let keys = user.db_keys();
|
|
assert_eq!(keys.len(), 2);
|
|
assert_eq!(keys[0].name, "custom_username");
|
|
assert_eq!(keys[0].value, "test");
|
|
assert_eq!(keys[1].name, "is_active");
|
|
assert_eq!(keys[1].value, "true");
|
|
}
|