62 lines
1.7 KiB
Rust
62 lines
1.7 KiB
Rust
use std::env;
|
|
|
|
use chrono::Utc;
|
|
// tests/db_test.rs
|
|
use dotenv::dotenv;
|
|
use rust_logger::model::{LogLevel, LogRecord};
|
|
use rust_logger::outputs::LogOutput;
|
|
use rust_logger::outputs::postgres::PostgresOutput;
|
|
use sqlx::postgres::PgPoolOptions;
|
|
|
|
#[sqlx::test] // sqlx 提供的强大宏,自动为每个测试创建一个临时数据库
|
|
async fn test_postgres_write() {
|
|
dotenv().ok();
|
|
let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
|
let pool = PgPoolOptions::new()
|
|
.max_connections(5)
|
|
.connect(&db_url)
|
|
.await
|
|
.unwrap();
|
|
// 1. 准备表结构 (需要在测试库里建表)
|
|
sqlx::query(
|
|
r#"
|
|
CREATE TABLE IF NOT EXISTS app_logs (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
service_name VARCHAR(50),
|
|
log_level VARCHAR(10),
|
|
message TEXT,
|
|
module VARCHAR(100),
|
|
created_at TIMESTAMPTZ,
|
|
trace_id VARCHAR(64)
|
|
)
|
|
"#,
|
|
)
|
|
.execute(&pool)
|
|
.await
|
|
.unwrap();
|
|
|
|
// 2. 初始化 Output
|
|
let output = PostgresOutput::new(pool.clone());
|
|
|
|
// 3. 写入日志
|
|
// ... 构造 record ...
|
|
let record = LogRecord {
|
|
service_name: "db_test".into(),
|
|
timestamp: Utc::now(),
|
|
level: LogLevel::INFO,
|
|
message: "Hello Integration Test Db".into(),
|
|
module: "tests".into(),
|
|
trace_id: Some("123-abc".into()),
|
|
};
|
|
output.write(&record).await;
|
|
|
|
// 4. 验证是否写入
|
|
let count: i64 =
|
|
sqlx::query_scalar("SELECT count(*) FROM app_logs WHERE service_name = 'db_test'")
|
|
.fetch_one(&pool)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert!(count > 1);
|
|
}
|