focus/crates/focus-tools/tests/write_tests.rs

46 lines
1.3 KiB
Rust

//! `write` 工具的单元测试。
//! Unit tests for the `write` tool.
use focus_core::tool::Tool;
use focus_json::JsonValue;
use focus_tools::WriteTool;
use std::fs;
use std::path::PathBuf;
fn temp_dir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("focus-tools-write-{}-{}", tag, std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn writes_and_overwrites() {
let dir = temp_dir("overwrite");
fs::write(dir.join("a.txt"), "old").unwrap();
let tool = WriteTool::new(&dir);
let mut args = JsonValue::obj();
args.insert("path", "a.txt".into()).ok();
args.insert("content", "new content".into()).ok();
let r = tool.execute("id", &args, None).unwrap();
assert!(r.content[0].as_text().unwrap().text.contains("11 bytes"));
assert_eq!(
fs::read_to_string(dir.join("a.txt")).unwrap(),
"new content"
);
}
#[test]
fn creates_parent_directories() {
let dir = temp_dir("nested");
let tool = WriteTool::new(&dir);
let mut args = JsonValue::obj();
args.insert("path", "deep/nested/file.txt".into()).ok();
args.insert("content", "hi".into()).ok();
tool.execute("id", &args, None).unwrap();
assert_eq!(
fs::read_to_string(dir.join("deep/nested/file.txt")).unwrap(),
"hi"
);
}