#[cfg(test)]
mod llm_model_tests {
use rstructor::{Instructor, RStructorError, Schema, SchemaType};
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct TestModel {
name: String,
age: u32,
active: bool,
}
impl SchemaType for TestModel {
fn schema() -> Schema {
Schema::new(json!({
"type": "object",
"title": "TestModel",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
},
"active": {
"type": "boolean"
}
},
"required": ["name", "age", "active"]
}))
}
fn schema_name() -> Option<String> {
Some("TestModel".to_string())
}
}
impl Instructor for TestModel {
fn validate(&self) -> rstructor::Result<()> {
self.validate()
}
}
impl TestModel {
fn validate(&self) -> rstructor::Result<()> {
if self.name.is_empty() {
return Err(RStructorError::ValidationError(
"Name cannot be empty".to_string(),
));
}
if self.age < 18 {
return Err(RStructorError::ValidationError(
"Age must be at least 18".to_string(),
));
}
Ok(())
}
}
#[test]
fn test_llm_model_default_validate() {
#[derive(Serialize, Deserialize, Debug)]
struct SimpleModel {
value: String,
}
impl SchemaType for SimpleModel {
fn schema() -> Schema {
Schema::new(json!({"type": "object"}))
}
}
impl Instructor for SimpleModel {
fn validate(&self) -> rstructor::Result<()> {
Ok(())
}
}
let model = SimpleModel {
value: "test".to_string(),
};
assert!(model.validate().is_ok());
}
#[test]
fn test_llm_model_custom_validate_success() {
let model = TestModel {
name: "Alice".to_string(),
age: 30,
active: true,
};
assert!(model.validate().is_ok());
}
#[test]
fn test_llm_model_custom_validate_empty_name() {
let model = TestModel {
name: "".to_string(), age: 30,
active: true,
};
let result = model.validate();
assert!(result.is_err());
if let Err(RStructorError::ValidationError(msg)) = result {
assert_eq!(msg, "Name cannot be empty");
} else {
panic!("Expected ValidationError, got {:?}", result);
}
}
#[test]
fn test_llm_model_custom_validate_underage() {
let model = TestModel {
name: "Bob".to_string(),
age: 17, active: true,
};
let result = model.validate();
assert!(result.is_err());
if let Err(RStructorError::ValidationError(msg)) = result {
assert_eq!(msg, "Age must be at least 18");
} else {
panic!("Expected ValidationError, got {:?}", result);
}
}
#[test]
fn test_schema_generation() {
let schema = TestModel::schema();
let json = schema.to_json();
assert_eq!(json["type"], "object");
assert_eq!(json["title"], "TestModel");
let properties = json["properties"].as_object().unwrap();
assert!(properties.contains_key("name"));
assert!(properties.contains_key("age"));
assert!(properties.contains_key("active"));
assert_eq!(properties["name"]["type"], "string");
assert_eq!(properties["age"]["type"], "integer");
assert_eq!(properties["active"]["type"], "boolean");
}
#[test]
fn test_schema_name() {
assert_eq!(TestModel::schema_name(), Some("TestModel".to_string()));
}
}