Files
biggus-dickus/crates/api/tests/admin_catalog.rs
T
logaritmisk d15afda9b2 feat(api): on-write search reindex after catalogue writes (#17)
Wire best-effort Meilisearch index sync into the admin write paths
(create/update/delete/set_fields/set_visibility). Adds
SearchClient::sync_object (reindex if the object exists, remove if gone —
one uniform path), an optional AppState.search client, and a reindex
helper that logs failures via tracing without failing the committed
write. Server gains MEILI_URL/MEILI_MASTER_KEY/MEILI_INDEX config;
search stays disabled (no-op) when unset. reindex_all remains the
recovery path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 23:25:43 +02:00

266 lines
7.8 KiB
Rust

use api::{AppState, build_app, migrate_sessions};
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use db::users;
use domain::{AuditActor, Email, NewUser, Role};
use http_body_util::BodyExt;
use sqlx::PgPool;
use tower::ServiceExt;
fn state(pool: PgPool) -> AppState {
AppState {
db: db::Db::from_pool(pool),
app_name: "Test".into(),
cookie_secure: false,
search: None,
}
}
async fn seed_user(pool: &PgPool, email: &str, password: &str, role: Role) {
let db = db::Db::from_pool(pool.clone());
let mut tx = db.pool().begin().await.unwrap();
users::create_user(
&mut tx,
AuditActor::System,
&NewUser {
email: Email::parse(email).unwrap(),
password_hash: auth::hash_password(password).unwrap(),
role,
},
)
.await
.unwrap();
tx.commit().await.unwrap();
}
fn login_request(email: &str, password: &str) -> Request<Body> {
Request::builder()
.method("POST")
.uri("/api/admin/login")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(format!(
r#"{{"email":"{email}","password":"{password}"}}"#
)))
.unwrap()
}
fn session_cookie(resp: &axum::http::Response<Body>) -> String {
resp.headers()
.get(header::SET_COOKIE)
.unwrap()
.to_str()
.unwrap()
.split(';')
.next()
.unwrap()
.to_owned()
}
async fn login(app: &axum::Router, email: &str, pw: &str) -> String {
let resp = app.clone().oneshot(login_request(email, pw)).await.unwrap();
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
session_cookie(&resp)
}
#[sqlx::test(migrations = "../db/migrations")]
async fn create_list_vocabulary_and_terms(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone()))
.await
.unwrap();
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
let app = build_app(state(pool));
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
// create a vocabulary
let created = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/vocabularies")
.header(header::COOKIE, &cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"key":"colour"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(created.status(), StatusCode::CREATED);
let vocab: serde_json::Value =
serde_json::from_slice(&created.into_body().collect().await.unwrap().to_bytes()).unwrap();
let vocab_id = vocab["id"].as_str().unwrap().to_owned();
// list vocabularies includes it
let list = app
.clone()
.oneshot(
Request::builder()
.uri("/api/admin/vocabularies")
.header(header::COOKIE, &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let list_json: serde_json::Value =
serde_json::from_slice(&list.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert!(
list_json
.as_array()
.unwrap()
.iter()
.any(|item| item["key"] == "colour")
);
// add a term with labels
let term = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri(format!("/api/admin/vocabularies/{vocab_id}/terms"))
.header(header::COOKIE, &cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
r#"{"external_uri":null,"labels":[{"lang":"en","label":"red"},{"lang":"sv","label":"röd"}]}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(term.status(), StatusCode::CREATED);
// list terms shows it (with both labels)
let terms = app
.oneshot(
Request::builder()
.uri(format!("/api/admin/vocabularies/{vocab_id}/terms"))
.header(header::COOKIE, &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let terms_json: serde_json::Value =
serde_json::from_slice(&terms.into_body().collect().await.unwrap().to_bytes()).unwrap();
let arr = terms_json.as_array().unwrap();
assert_eq!(arr.len(), 1);
assert_eq!(arr[0]["labels"].as_array().unwrap().len(), 2);
}
#[sqlx::test(migrations = "../db/migrations")]
async fn vocabulary_create_requires_auth(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone()))
.await
.unwrap();
let app = build_app(state(pool));
let resp = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/vocabularies")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"key":"x"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
async fn app2_get(app: &axum::Router, cookie: &str, uri: &str) -> StatusCode {
app.clone()
.oneshot(
Request::builder()
.uri(uri)
.header(header::COOKIE, cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
.status()
}
#[sqlx::test(migrations = "../db/migrations")]
async fn create_and_list_authorities_by_kind(pool: PgPool) {
migrate_sessions(&db::Db::from_pool(pool.clone()))
.await
.unwrap();
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
let app = build_app(state(pool));
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
let created = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/authorities")
.header(header::COOKIE, &cookie)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
r#"{"kind":"person","external_uri":null,"labels":[{"lang":"en","label":"Ada Lovelace"}]}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(created.status(), StatusCode::CREATED);
// list by kind
let list = app
.clone()
.oneshot(
Request::builder()
.uri("/api/admin/authorities?kind=person")
.header(header::COOKIE, &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(list.status(), StatusCode::OK);
let json: serde_json::Value =
serde_json::from_slice(&list.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert_eq!(json.as_array().unwrap().len(), 1);
assert_eq!(json[0]["kind"], "person");
// a different kind is empty
let places = app
.clone()
.oneshot(
Request::builder()
.uri("/api/admin/authorities?kind=place")
.header(header::COOKIE, &cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(places.status(), StatusCode::OK);
let places_json: serde_json::Value =
serde_json::from_slice(&places.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert!(places_json.as_array().unwrap().is_empty());
// bad kind → 422
let bad = app2_get(&app, &cookie, "/api/admin/authorities?kind=alien").await;
assert_eq!(bad, StatusCode::UNPROCESSABLE_ENTITY);
}