-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdefault_role_integration_test.rs
More file actions
346 lines (291 loc) Β· 11.5 KB
/
Copy pathdefault_role_integration_test.rs
File metadata and controls
346 lines (291 loc) Β· 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::path::PathBuf;
use std::time::Duration;
use serial_test::serial;
use tokio::time::sleep;
mod common;
use common::wait_for_health;
use terraphim_config::{Config, ConfigState};
use terraphim_server::{ConfigResponse, SearchResponse, axum_server};
/// Integration test for Default role configuration with Ripgrep haystack
///
/// This test validates:
/// 1. Server starts with Default role configuration
/// 2. Ripgrep haystack is configured for local docs
/// 3. Search functionality works with basic text queries
/// 4. Results are returned from local documentation
#[tokio::test]
#[serial]
async fn test_default_role_ripgrep_integration() {
// Set up logging
let _ = env_logger::builder()
.filter_level(log::LevelFilter::Info)
.try_init();
let current_dir = std::env::current_dir().unwrap();
log::info!("Test running from directory: {:?}", current_dir);
// Check if documentation exists
let docs_src_path = if current_dir.ends_with("terraphim_server") {
PathBuf::from("../docs/src")
} else {
PathBuf::from("docs/src")
};
if !docs_src_path.exists() {
log::warn!(
"Documentation not found at {:?}. Skipping test.",
docs_src_path
);
return;
}
// Load the combined roles configuration
let config_path = if current_dir.ends_with("terraphim_server") {
PathBuf::from("default/combined_roles_config.json")
} else {
PathBuf::from("terraphim_server/default/combined_roles_config.json")
};
if !config_path.exists() {
log::warn!(
"Combined roles config not found at {:?}. Skipping test.",
config_path
);
return;
}
let config_content = tokio::fs::read_to_string(&config_path)
.await
.expect("Failed to read config file");
let config_content = config_content.trim();
log::info!("Config file content length: {} bytes", config_content.len());
let mut config: Config = serde_json::from_str(config_content)
.map_err(|e| {
log::error!("JSON parsing error: {}", e);
e
})
.expect("Failed to parse config JSON");
// Fix paths in configuration for test environment
if current_dir.ends_with("terraphim_server") {
for (_role_name, role) in &mut config.roles {
for haystack in &mut role.haystacks {
if haystack.location == "docs/src" {
haystack.location = "../docs/src".to_string();
}
}
}
log::info!("β
Adjusted config paths for test environment");
}
// Create config state
let config_state = ConfigState::new(&mut config)
.await
.expect("Failed to create config state");
log::info!("β
Configuration loaded with {} roles", config.roles.len());
// Verify Default role exists and is configured correctly
let default_role = config
.roles
.get(&"Default".into())
.expect("Default role should exist");
assert_eq!(
default_role.name,
"Default".into(),
"Role name should be Default"
);
assert!(
!default_role.haystacks.is_empty(),
"Default role should have at least one haystack"
);
// Verify Ripgrep haystack
let ripgrep_haystack = default_role
.haystacks
.iter()
.find(|h| h.service == terraphim_config::ServiceType::Ripgrep)
.expect("Should have Ripgrep haystack");
log::info!("β
Default role configuration validated");
log::info!(" - Ripgrep haystack: {}", ripgrep_haystack.location);
// Start server on an ephemeral port (held by the listener until axum binds,
// eliminating the port-race that caused the #2947/#2998 flake).
let listener =
std::net::TcpListener::bind("127.0.0.1:0").expect("Failed to bind ephemeral port");
let server_addr = listener.local_addr().expect("Failed to read bound port");
drop(listener); // axum_server rebinds; held long enough to avoid TOCTOU on busy CI
let server_handle = tokio::spawn(async move {
if let Err(e) = axum_server(server_addr, config_state).await {
log::error!("Server error: {:?}", e);
}
});
// Deterministic readiness: poll /health instead of a fixed sleep.
// AC #2998: harness waits for /health success before issuing search requests.
log::info!("β³ Waiting for server startup via /health...");
wait_for_health(server_addr, 60).await;
let client = terraphim_service::http_client::create_default_client()
.expect("Failed to create HTTP client");
let base_url = format!("http://{server_addr}");
// Test 1: Health check (body contract: {"status":"ok"})
log::info!("π Testing server health...");
let health_response = client
.get(format!("{base_url}/health"))
.send()
.await
.expect("Health check failed");
assert!(
health_response.status().is_success(),
"Health check should succeed"
);
// Lock the JSON body contract added in #2998 (was free-form "OK" text).
let health_json: serde_json::Value = health_response
.json()
.await
.expect("/health body must be valid JSON");
assert_eq!(
health_json.get("status").and_then(|v| v.as_str()),
Some("ok"),
"/health body must be {{\"status\":\"ok\"}}, got: {health_json}"
);
log::info!("β
Server health check passed");
// Test 2: Get configuration
log::info!("π Testing configuration endpoint...");
let config_response = client
.get(format!("{}/config", base_url))
.send()
.await
.expect("Config request failed");
assert!(
config_response.status().is_success(),
"Config request should succeed"
);
let config_json: ConfigResponse = config_response
.json()
.await
.expect("Failed to parse config response");
assert!(config_json.config.roles.contains_key(&"Default".into()));
log::info!("β
Configuration endpoint validated");
// Test 3: Search with Default role for common documentation terms
log::info!("π Testing search with Default role...");
let doc_terms = [
"installation",
"configuration",
"quickstart",
"api",
"usage",
];
for term in &doc_terms {
log::info!("π Testing search for documentation term: {}", term);
let search_params = [("q", *term), ("role", "Default"), ("limit", "5")];
let search_response = client
.get(format!("{}/documents/search", base_url))
.query(&search_params)
.send()
.await;
match search_response {
Ok(response) => {
if response.status().is_success() {
let search_json: SearchResponse = response.json().await.unwrap_or_else(|_| {
panic!("Failed to parse search response for '{}'", term)
});
log::info!(
"β
Found {} results for '{}'",
search_json.results.len(),
term
);
// Log some sample results
for (i, doc) in search_json.results.iter().take(2).enumerate() {
log::info!(" {}. {}", i + 1, doc.title);
if let Some(ref source) = doc.source_haystack {
log::info!(" Source: {}", source);
}
}
// Verify results are from Ripgrep haystack
if !search_json.results.is_empty() {
let all_from_ripgrep = search_json.results.iter().all(|doc| {
doc.source_haystack
.as_ref()
.map(|s| s.contains("docs/src"))
.unwrap_or(true)
});
if !all_from_ripgrep {
log::warn!("β οΈ Some results not from expected Ripgrep source");
}
}
} else {
log::info!(
"βΉοΈ Search for '{}' returned status: {} (may not exist in docs)",
term,
response.status()
);
}
}
Err(e) => {
log::warn!("β οΈ Search for '{}' failed: {}", term, e);
}
}
// Small delay between requests
sleep(Duration::from_millis(100)).await;
}
// Test 4: Search for specific content that should exist in docs
log::info!("π Testing search for specific documentation content...");
let specific_terms = ["terraphim", "rust", "search"];
for term in &specific_terms {
log::info!("π Testing search for specific term: {}", term);
let search_params = [("q", *term), ("role", "Default"), ("limit", "3")];
let search_response = client
.get(format!("{}/documents/search", base_url))
.query(&search_params)
.send()
.await
.unwrap_or_else(|_| panic!("Search for '{}' failed", term));
if search_response.status().is_success() {
let search_json: SearchResponse = search_response
.json()
.await
.unwrap_or_else(|_| panic!("Failed to parse search response for '{}'", term));
log::info!(
"β
Found {} results for '{}'",
search_json.results.len(),
term
);
}
}
// Cleanup
server_handle.abort();
log::info!("β
Default role integration test completed");
}
/// Test Default role configuration structure without making searches
#[tokio::test]
async fn test_default_role_config_structure() {
let current_dir = std::env::current_dir().unwrap();
let config_path = if current_dir.ends_with("terraphim_server") {
PathBuf::from("default/combined_roles_config.json")
} else {
PathBuf::from("terraphim_server/default/combined_roles_config.json")
};
if !config_path.exists() {
log::warn!("Combined roles config not found. Skipping test.");
return;
}
let config_content = tokio::fs::read_to_string(&config_path)
.await
.expect("Failed to read config file");
let config: Config =
serde_json::from_str(&config_content).expect("Failed to parse config JSON");
// Verify role exists
let default_role = config
.roles
.get(&"Default".into())
.expect("Default role should exist in config");
// Verify basic properties
assert_eq!(default_role.name, "Default".into());
assert!(!default_role.haystacks.is_empty());
// Verify Ripgrep haystack
let has_ripgrep = default_role
.haystacks
.iter()
.any(|h| h.service == terraphim_config::ServiceType::Ripgrep);
assert!(has_ripgrep, "Default role should have Ripgrep haystack");
// Verify relevance function
assert_eq!(
default_role.relevance_function,
terraphim_types::RelevanceFunction::TitleScorer,
"Default role should use TitleScorer relevance function"
);
println!("β
Default role config structure validated");
println!(" - Haystacks: {}", default_role.haystacks.len());
println!(
" - Relevance function: {:?}",
default_role.relevance_function
);
}