/
mcmare
/
RustAPI
Обзор
Документация
Войти
/
mcmare
/
RustAPI
Код
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
engine/tests/script_sqlite.rs
81 строка
3 KB
mcmare
Add Rhai scripting layer: host functions (db/hash/jwt), per-script transactions
18 июл 2026, 16:32
18 июл 2026, 16:32
4bfc229
Код
Авторство
О чём код?
use engine::config::{ConnectionDef, DbDriver}; use engine::{DbPool, ScriptEngine, ScriptRequest}; use serde_json::json; use std::{collections::HashMap, path::Path, sync::Arc}; async fn setup() -> (Arc<HashMap<String, DbPool>>, ScriptEngine) { let mut connections = HashMap::new(); connections.insert( "test_db".to_string(), ConnectionDef { driver: DbDriver::Sqlite, url: "sqlite::memory:".to_string(), }, ); let pools = Arc::new(engine::connect_all(&connections).await.expect("connect")); if let DbPool::Sqlite(p) = pools.get("test_db").unwrap() { sqlx::query("CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT, password_hash TEXT)") .execute(p) .await .expect("create users table"); } let script_engine = ScriptEngine::new(pools.clone(), "test-secret".to_string()); (pools, script_engine) } #[tokio::test] async fn register_then_login_roundtrip() { let (_pools, script_engine) = setup().await; let register_req = ScriptRequest { body: json!({ "email": "alice@example.com", "password": "hunter2" }), ..Default::default() }; let registered = script_engine .run(Path::new("tests/fixtures/scripts/register.rhai"), register_req) .await .expect("register script runs"); assert_eq!(registered.status, 200); let login_req = ScriptRequest { body: json!({ "email": "alice@example.com", "password": "hunter2" }), ..Default::default() }; let logged_in = script_engine .run(Path::new("tests/fixtures/scripts/login.rhai"), login_req) .await .expect("login script runs"); assert_eq!(logged_in.status, 200); assert!(logged_in.body["token"].as_str().is_some(), "expected a token in {:?}", logged_in.body); let wrong_password_req = ScriptRequest { body: json!({ "email": "alice@example.com", "password": "wrong" }), ..Default::default() }; let rejected = script_engine .run(Path::new("tests/fixtures/scripts/login.rhai"), wrong_password_req) .await .expect("login script runs even on bad credentials"); assert_eq!(rejected.status, 401); } #[tokio::test] async fn script_transaction_rolls_back_on_error() { let (pools, script_engine) = setup().await; let req = ScriptRequest::default(); let result = script_engine .run(Path::new("tests/fixtures/scripts/fail_after_insert.rhai"), req) .await; assert!(result.is_err(), "script calling an undefined function should error"); if let DbPool::Sqlite(p) = pools.get("test_db").unwrap() { let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users WHERE email = 'rollback@test.com'") .fetch_one(p) .await .expect("count query"); assert_eq!(count, 0, "insert should have been rolled back"); } }