返回 CodeWhale
tests.rs
根目录 / crates / engine / src / tools / fetch_url / tests.rs
1 use super::*;
2 use crate::tools::spec::ToolContext;
3 use std::path::PathBuf;
4
5 struct ArtifactRootRestore(Option<PathBuf>);
6
7 impl Drop for ArtifactRootRestore {
8 fn drop(&mut self) {
9 codewhale_runtime::artifacts::set_test_artifact_sessions_root(self.0.take());
10 }
11 }
12
13 fn runtime() -> tokio::runtime::Runtime {
14 tokio::runtime::Builder::new_current_thread()
15 .enable_all()
16 .build()
17 .expect("test runtime")
18 }
19
20 #[test]
21 fn raw_pdf_production_path_preserves_exact_bytes_without_extractor() {
22 let _lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
23 .lock()
24 .unwrap_or_else(|error| error.into_inner());
25 let temporary = tempfile::tempdir().expect("artifact root");
26 let prior = codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(
27 temporary.path().join("sessions"),
28 ));
29 let _restore = ArtifactRootRestore(prior);
30 let bytes = b"%PDF-1.7\nraw fixture that is intentionally not parseable\n%%EOF";
31 let missing = temporary.path().join("definitely-not-pdftotext");
32 let document = runtime()
33 .block_on(extract_fetched_document(
34 Format::Raw,
35 "https://example.com/raw.pdf",
36 "application/pdf",
37 bytes,
38 false,
39 true,
40 None,
41 PdfTextCommand::test(missing.as_os_str(), Duration::from_millis(50), None),
42 ))
43 .expect("signed raw PDF must bypass the missing extractor");
44 let (content, artifact) = render_extracted(
45 "https://example.com/raw.pdf",
46 "application/pdf",
47 Format::Raw,
48 document,
49 bytes,
50 &ToolContext::new("."),
51 )
52 .expect("raw PDF preservation must not require pdftotext");
53 let artifact = artifact.expect("raw PDF artifact");
54 assert!(content.contains("PDF response saved"), "{content}");
55 assert_eq!(std::fs::read(artifact.absolute_path).unwrap(), bytes);
56 }
57
58 #[test]
59 fn raw_pdf_spoofs_and_contradictory_media_mime_create_no_artifact() {
60 let _lock = codewhale_runtime::artifacts::TEST_ARTIFACT_SESSIONS_GUARD
61 .lock()
62 .unwrap_or_else(|error| error.into_inner());
63 let temporary = tempfile::tempdir().expect("artifact root");
64 let sessions = temporary.path().join("sessions");
65 let prior =
66 codewhale_runtime::artifacts::set_test_artifact_sessions_root(Some(sessions.clone()));
67 let _restore = ArtifactRootRestore(prior);
68 let missing = temporary.path().join("definitely-not-pdftotext");
69 let request = PdfTextCommand::test(missing.as_os_str(), Duration::from_millis(50), None);
70 let runtime = runtime();
71
72 for (url, content_type, bytes, expected) in [
73 (
74 "https://example.com/download",
75 "application/pdf",
76 b"plain text pretending to be a PDF".as_slice(),
77 "PDF signature",
78 ),
79 (
80 "https://example.com/spoof.pdf",
81 "text/plain",
82 b"plain text pretending to be a PDF".as_slice(),
83 "PDF signature",
84 ),
85 (
86 "https://example.com/signed",
87 "image/png",
88 b"%PDF-1.7\n%%EOF".as_slice(),
89 "did not match its PDF bytes",
90 ),
91 ] {
92 let error = runtime
93 .block_on(extract_fetched_document(
94 Format::Raw,
95 url,
96 content_type,
97 bytes,
98 false,
99 true,
100 None,
101 request,
102 ))
103 .expect_err("invalid PDF response must fail before raw preservation");
104 assert!(error.to_string().contains(expected), "{error}");
105 }
106 assert!(
107 !sessions.exists(),
108 "rejected bytes must not create artifacts"
109 );
110 }
111
112 #[tokio::test]
113 async fn fetched_pdf_missing_helper_is_a_failed_typed_outcome() {
114 let temporary = tempfile::tempdir().expect("tempdir");
115 let missing = temporary.path().join("definitely-not-pdftotext");
116 let error = extract_fetched_document(
117 Format::Text,
118 "https://example.com/document.pdf",
119 "application/pdf",
120 b"%PDF-1.7\n%%EOF",
121 false,
122 true,
123 None,
124 PdfTextCommand::test(missing.as_os_str(), Duration::from_secs(1), None),
125 )
126 .await
127 .expect_err("missing helper must fail the fetched PDF call");
128 let payload = match &error.error {
129 ToolError::NotAvailable { message } => {
130 serde_json::from_str::<Value>(message).expect("structured unavailable payload")
131 }
132 other => panic!("unexpected error: {other:?}"),
133 };
134 assert_eq!(payload["type"], "binary_unavailable");
135 assert_eq!(
136 crate::tools::spec::ToolExecutionOutcome::from_legacy(Err(error.into())).status,
137 crate::tools::spec::ToolTerminalStatus::Failed
138 );
139 }
140
141 #[cfg(unix)]
142 #[tokio::test(flavor = "current_thread")]
143 async fn fetched_pdf_host_text_matches_default_and_raw_bypasses_host() {
144 use crate::extension_host::{ExtensionHostManager, ExtensionHostOptions, TestManagerGuard};
145 use codewhale_runtime::features::{Feature, Features};
146 use std::os::unix::fs::PermissionsExt;
147 use std::sync::Arc;
148 let _home = crate::test_support::SealedHome::new();
149 let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(false);
150 let Some(node) = crate::extension_host::test_support::node_for_tests("fetched_pdf_host") else {
151 return;
152 };
153 let root = tempfile::tempdir().unwrap();
154 let binary = root.path().join("fake-pdftotext");
155 std::fs::write(&binary, "#!/bin/sh\nprintf 'page one\\fpage two\\n'\n").unwrap();
156 std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap();
157 let manager = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
158 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node,
159 node_override: Some(node),
160 root: Some(root.path().join("host")),
161 ..ExtensionHostOptions::default()
162 }));
163 let _manager = TestManagerGuard::install(Arc::clone(&manager));
164 let rust = ToolContext::new(root.path());
165 let mut flags = Features::with_defaults();
166 flags.enable(Feature::PdfHost);
167 let host = ToolContext::new(root.path()).with_features(flags);
168 let bytes = b"%PDF-1.7\nfixture\n%%EOF";
169 for format in [Format::Text, Format::Markdown] {
170 let expected = extract_fetched_document(
171 format,
172 "https://example.com/fixture.pdf",
173 "application/pdf",
174 bytes,
175 false,
176 true,
177 None,
178 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), None)
179 .with_context(&rust),
180 )
181 .await
182 .unwrap();
183 let actual = extract_fetched_document(
184 format,
185 "https://example.com/fixture.pdf",
186 "application/pdf",
187 bytes,
188 false,
189 true,
190 None,
191 PdfTextCommand::test(binary.as_os_str(), Duration::from_secs(10), None)
192 .with_context(&host),
193 )
194 .await
195 .unwrap();
196 assert_eq!(actual.text, expected.text);
197 assert_eq!(actual.markdown, expected.markdown);
198 assert_eq!(actual.pdf_pages, expected.pdf_pages);
199 }
200 manager.shutdown().await;
201 drop(_manager);
202 // A signed raw response deliberately has no extraction consumer, even with
203 // the Host flag selected and an unusable runtime/parser.
204 let unavailable = Arc::new(ExtensionHostManager::new(ExtensionHostOptions {
205 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node,
206 node_override: Some(root.path().join("missing-node")),
207 root: Some(root.path().join("absent-host")),
208 ..ExtensionHostOptions::default()
209 }));
210 let _manager = TestManagerGuard::install(unavailable);
211 let missing = root.path().join("missing-parser");
212 let document = extract_fetched_document(
213 Format::Raw,
214 "https://example.com/fixture.pdf",
215 "application/pdf",
216 bytes,
217 false,
218 true,
219 None,
220 PdfTextCommand::test(missing.as_os_str(), Duration::from_secs(1), None).with_context(&host),
221 )
222 .await
223 .unwrap();
224 assert_eq!(document.kind, DocumentKind::Pdf);
225 assert!(document.text.is_empty());
226 assert!(document.pdf_pages.is_none());
227 }
228
229 #[tokio::test(flavor = "current_thread")]
230 async fn raw_and_non_success_catches_do_not_hide_a_selected_host_failure() {
231 let _home = crate::test_support::SealedHome::new();
232 let root = tempfile::tempdir().unwrap();
233 let manager = std::sync::Arc::new(crate::extension_host::ExtensionHostManager::new(
234 crate::extension_host::ExtensionHostOptions {
235 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node,
236 node_override: Some(root.path().join("missing-node")),
237 root: Some(root.path().join("host")),
238 ..crate::extension_host::ExtensionHostOptions::default()
239 },
240 ));
241 let _manager = crate::extension_host::TestManagerGuard::install(manager);
242 let mut flags = codewhale_runtime::features::Features::with_defaults();
243 flags.enable(codewhale_runtime::features::Feature::WebExtractHost);
244 let context = ToolContext::new(root.path()).with_features(flags);
245 for (format, success) in [(Format::Raw, true), (Format::Text, false)] {
246 let error=extract_fetched_document(format,"https://example.com/private", "text/html",b"<body><main>Five meaningful words survive this valid complete document content.</main></body>",false,success,None,PdfTextCommand::system(Some(&context))).await.unwrap_err();
247 assert!(
248 !error.content(),
249 "operational Host failure cannot become raw decoded text"
250 );
251 }
252 }
253
253 lines RUST