返回 CodeWhale
test_cases_07.rs
根目录 / crates / engine / src / client / test_cases_07.rs
1
2 #[test]
3 fn untethered_cross_protocol_rebound_fails_closed_without_config() {
4 // #6320: the #5042 early-outs cover the already-exact route, but a
5 // cross-protocol rebound with no Config to rebuild from still fails
6 // closed — this is what still guards half-bound dispatch.
7 let (_config, route) =
8 deepseek_route_for_test("https://api.deepseek.com/beta", "deepseek-v4-pro");
9 let client = CodewhaleClient::new(&route.config).expect("pro client resolves");
10 assert_eq!(client.wire_format, WireFormat::ChatCompletions);
11 let err = match client.rebound_for_model_protocol(None, "deepseek-v4-flash") {
12 Ok(_) => panic!("cross-protocol rebound without config fails closed"),
13 Err(err) => err,
14 };
15 assert!(
16 err.to_string().contains("no configuration is available"),
17 "{err}"
18 );
19 }
20
21 #[test]
22 fn from_candidate_binds_custom_provider_base_url_and_model() {
23 // #1519: a custom OpenAI-compatible provider resolves to a candidate
24 // whose endpoint/model come from the named `[providers.<name>]` table,
25 // and `from_candidate` must bind that verbatim base URL + wire model.
26 let mut custom = std::collections::HashMap::new();
27 custom.insert(
28 "my_thing".to_string(),
29 ProviderConfig {
30 kind: Some("openai-compatible".to_string()),
31 base_url: Some("https://api.example.com/v1".to_string()),
32 model: Some("custom-model-v1".to_string()),
33 api_key_env: Some("EXAMPLE_API_KEY_FROM_CANDIDATE_TEST".to_string()),
34 ..Default::default()
35 },
36 );
37 let config = {
38 let __cw_config_init_0_0 = Some("my_thing".to_string());
39 let __cw_config_init_0_1 = Some(ProvidersConfig {
40 custom,
41 ..Default::default()
42 });
43 let mut __cw_config_init_0_value: Config = Config::default();
44 __cw_config_init_0_value.provider = __cw_config_init_0_0;
45 __cw_config_init_0_value.providers = __cw_config_init_0_1;
46 __cw_config_init_0_value
47 };
48
49 // The config names a custom provider, so it must resolve as Custom.
50 assert_eq!(
51 config.active_provider_identity().unwrap().provider,
52 ProviderKind::Custom
53 );
54
55 let route =
56 crate::route_runtime::resolve_runtime_route(&config, ProviderKind::Custom, None)
57 .expect("custom route should resolve");
58
59 // Provide the key the route's auth path will read.
60 let client = {
61 let _env = crate::test_support::lock_test_env();
62 let _key = crate::test_support::EnvVarGuard::set(
63 "EXAMPLE_API_KEY_FROM_CANDIDATE_TEST",
64 "sk-custom",
65 );
66 CodewhaleClient::from_candidate(&route.config, &route.candidate)
67 .expect("client should construct from custom candidate")
68 };
69
70 assert_eq!(client.base_url, "https://api.example.com/v1");
71 assert_eq!(client.default_model, "custom-model-v1");
72 assert_eq!(client.api_provider, ProviderKind::Custom);
73 // The candidate carried the custom endpoint + verbatim wire model.
74 assert_eq!(
75 route.candidate.endpoint().base_url,
76 "https://api.example.com/v1"
77 );
78 assert_eq!(route.candidate.wire_model_id().as_str(), "custom-model-v1");
79 }
80 #[tokio::test]
81 async fn incomplete_translation_keeps_exact_route_and_usage_before_rejection() {
82 let server = MockServer::start().await;
83 Mock::given(method("POST"))
84 .and(path("/v1/messages"))
85 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
86 "id": "msg_partial",
87 "type": "message",
88 "role": "assistant",
89 "content": [{"type": "text", "text": "Parcial"}],
90 // A provider-returned alias must not replace the admitted
91 // route/model in the frozen cost receipt.
92 "model": "provider-alias-after-dispatch",
93 "stop_reason": "max_tokens",
94 "stop_sequence": null,
95 "usage": {"input_tokens": 7, "output_tokens": 2}
96 })))
97 .expect(1)
98 .mount(&server)
99 .await;
100
101 let client = deepseek_anthropic_client(&server);
102 let response = client
103 .translate_with_usage(
104 "Hello",
105 "deepseek-chat",
106 "Spanish",
107 &crate::cost_status::NativeUsageSource::capture(
108 format!("translation-test:{}", uuid::Uuid::new_v4()),
109 crate::cost_status::UsageSpendOwner::Auxiliary,
110 ),
111 )
112 .await
113 .expect("decoded provider response retains its receipt");
114
115 assert!(
116 response.translated.is_err(),
117 "partial text must be rejected"
118 );
119 let usage = response.usage.expect("provider-reported usage");
120 assert_eq!(usage.input_tokens, 7);
121 assert_eq!(usage.output_tokens, 2);
122 assert_eq!(response.route.provider, ProviderKind::DeepseekAnthropic);
123 assert_eq!(response.route.model, "deepseek-chat");
124 assert_eq!(response.route.provider_identity, "deepseek-anthropic");
125 assert!(response.route.endpoint_fingerprint.is_some());
126 }
127
128 #[tokio::test]
129 async fn chat_translation_without_usage_keeps_unreceipted_success_outcome() {
130 let server = MockServer::start().await;
131 Mock::given(method("POST"))
132 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
133 "id": "chatcmpl-no-usage",
134 "model": "deepseek-chat",
135 "choices": [{
136 "index": 0,
137 "message": {"role": "assistant", "content": "Hola"},
138 "finish_reason": "stop"
139 }]
140 })))
141 .expect(1)
142 .mount(&server)
143 .await;
144
145 let client = deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri());
146 let response = client
147 .translate_with_usage(
148 "Hello",
149 "deepseek-chat",
150 "Spanish",
151 &crate::cost_status::NativeUsageSource::capture(
152 format!("translation-test:{}", uuid::Uuid::new_v4()),
153 crate::cost_status::UsageSpendOwner::Auxiliary,
154 ),
155 )
156 .await
157 .expect("provider success must retain its frozen route");
158 assert_eq!(
159 response
160 .translated
161 .expect("useful output remains deliverable"),
162 "Hola"
163 );
164 assert_eq!(response.usage, None, "must not mint a priced-zero receipt");
165 assert_eq!(response.route.provider, ProviderKind::Deepseek);
166 assert_eq!(
167 response.route.model,
168 codewhale_config::route::resolve_model(
169 ProviderKind::Deepseek,
170 "deepseek-chat",
171 Some("https://api.deepseek.com/v1"),
172 )
173 .unwrap()
174 .wire_id
175 );
176 }
177
178 #[tokio::test]
179 async fn chat_translation_http_error_is_not_a_provider_success_outcome() {
180 let server = MockServer::start().await;
181 Mock::given(method("POST"))
182 .respond_with(ResponseTemplate::new(429).set_body_json(json!({
183 "error": {"message": "rate limited"}
184 })))
185 .mount(&server)
186 .await;
187
188 let mut client =
189 deepseek_request_boundary_client("https://api.deepseek.com/v1", server.uri());
190 client.retry.enabled = false;
191 client.retry.max_retries = 0;
192 let error = match client
193 .translate_with_usage(
194 "Hello",
195 "deepseek-chat",
196 "Spanish",
197 &crate::cost_status::NativeUsageSource::capture(
198 format!("translation-test:{}", uuid::Uuid::new_v4()),
199 crate::cost_status::UsageSpendOwner::Auxiliary,
200 ),
201 )
202 .await
203 {
204 Ok(_) => panic!("HTTP failure must not become a provider-success receipt"),
205 Err(error) => error,
206 };
207 let display = error.to_string();
208 assert!(
209 display.to_ascii_lowercase().contains("rate limit"),
210 "{display}"
211 );
212 assert!(!display.contains("chatcmpl"), "{display}");
213 }
214
215 #[tokio::test]
216 async fn custom_catalog_schema_ignores_table_name() {
217 // The same enriched body served from a non-Baseten endpoint takes
218 // the generic branch for every identity: the table name selects
219 // ownership, never the wire parser (#6289). Baseten enrichment
220 // itself stays covered at the parser's fixture tests.
221 let server = MockServer::start().await;
222 Mock::given(method("GET"))
223 .and(path("/v1/models"))
224 .and(header("authorization", "Bearer test-custom-key"))
225 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
226 "data": [{
227 "id": "synthetic/custom-model",
228 "context_length": 1_048_576,
229 "pricing": {
230 "prompt": 0.0000014,
231 "completion": 0.0000044
232 },
233 "supported_features": ["reasoning", "tools", "structured_outputs", "vision"]
234 }]
235 })))
236 .mount(&server)
237 .await;
238
239 for identity in ["baseten", "renamed-host"] {
240 let client = custom_mock_client_for_identity(&server, identity);
241 assert_eq!(client.catalog_provider_id(), identity);
242 let delta = client.fetch_catalog_delta().await.expect("delta");
243 assert_eq!(delta.provider, identity);
244 assert_eq!(delta.offerings.len(), 1);
245 let offering = &delta.offerings[0];
246 assert_eq!(offering.wire_model_id, "synthetic/custom-model");
247 assert_eq!(offering.provider, identity);
248 let limit = offering.limit.as_ref().expect("stated context_length");
249 assert_eq!(limit.context, Some(1_048_576));
250 assert_eq!(limit.input, None);
251 assert_eq!(limit.output, None);
252 assert_eq!(offering.reasoning, Some(true));
253 assert_eq!(offering.tool_call, Some(true));
254 assert_eq!(offering.structured_output, Some(true));
255 assert!(offering.cost.is_none());
256 assert!(offering.modalities.is_none());
257 }
258 }
259
260 #[test]
261 fn baseten_dialect_recognized_by_endpoint_not_name() {
262 fn client_for(identity: &str, base_url: &str) -> CodewhaleClient {
263 let mut providers = ProvidersConfig::default();
264 providers.custom.insert(
265 identity.to_string(),
266 ProviderConfig {
267 kind: Some("openai-compatible".to_string()),
268 api_key: Some("test-key".to_string()),
269 base_url: Some(base_url.to_string()),
270 model: Some("synthetic/custom-model".to_string()),
271 ..ProviderConfig::default()
272 },
273 );
274 CodewhaleClient::new(&{
275 let __cw_config_init_1_0 = Some(identity.to_string());
276 let __cw_config_init_1_1 = Some(providers);
277 let mut __cw_config_init_1_value: Config = Config::default();
278 __cw_config_init_1_value.provider = __cw_config_init_1_0;
279 __cw_config_init_1_value.providers = __cw_config_init_1_1;
280 __cw_config_init_1_value
281 })
282 .expect("client")
283 }
284
285 let baseten_url = codewhale_config::catalog::BASETEN_BASE_URL;
286 assert!(client_for("baseten", baseten_url).catalog_endpoint_is_baseten());
287 assert!(client_for("renamed-host", baseten_url).catalog_endpoint_is_baseten());
288 assert!(
289 client_for("baseten", &format!("{baseten_url}/")).catalog_endpoint_is_baseten(),
290 "a trailing slash still recognizes the host"
291 );
292 assert!(!client_for("baseten", "https://127.0.0.1:9/v1").catalog_endpoint_is_baseten());
293 assert!(
294 !client_for("groq", "https://api.groq.com/openai/v1").catalog_endpoint_is_baseten()
295 );
296 }
297
297 lines RUST