356 lines
10 KiB
Rust
356 lines
10 KiB
Rust
mod support;
|
|
|
|
use support::RuntimeExecutorTestExt;
|
|
|
|
use std::{
|
|
collections::BTreeMap,
|
|
sync::{
|
|
Arc, Mutex,
|
|
atomic::{AtomicUsize, Ordering},
|
|
},
|
|
};
|
|
|
|
use async_trait::async_trait;
|
|
use crank_core::{
|
|
AdapterResponse, ExecutionConfig, ExecutionMode, OperationId, Protocol, ProtocolAdapter,
|
|
ProtocolAdapterError, Target, ToolDescription,
|
|
};
|
|
use crank_import::rest::{RestImportCandidate, preview_document};
|
|
use crank_runtime::{RuntimeExecutorBuilder, RuntimeOperation};
|
|
use serde_json::{Value, json};
|
|
|
|
#[derive(Clone)]
|
|
struct CaptureAdapter {
|
|
calls: Arc<AtomicUsize>,
|
|
prepared: Arc<Mutex<Option<crank_core::PreparedRequest>>>,
|
|
response: AdapterResponse,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ProtocolAdapter for CaptureAdapter {
|
|
fn protocol(&self) -> Protocol {
|
|
Protocol::Rest
|
|
}
|
|
|
|
fn supports_mode(&self, mode: ExecutionMode) -> bool {
|
|
mode == ExecutionMode::Unary
|
|
}
|
|
|
|
async fn invoke_unary(
|
|
&self,
|
|
_target: &Target,
|
|
prepared: &crank_core::PreparedRequest,
|
|
_context: &crank_core::RuntimeRequestContext,
|
|
) -> Result<AdapterResponse, ProtocolAdapterError> {
|
|
self.calls.fetch_add(1, Ordering::SeqCst);
|
|
*self.prepared.lock().expect("prepared lock") = Some(prepared.clone());
|
|
Ok(self.response.clone())
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn imported_media_selector_is_validated_before_adapter_and_travels_out_of_band() {
|
|
let operation = imported_operation(
|
|
r#"
|
|
openapi: 3.0.3
|
|
info: { title: Media }
|
|
servers: [{ url: https://example.invalid }]
|
|
paths:
|
|
/events:
|
|
post:
|
|
requestBody:
|
|
required: true
|
|
content:
|
|
application/json:
|
|
schema: { type: object, required: [name], properties: { name: { type: string } } }
|
|
application/x-www-form-urlencoded:
|
|
schema: { type: object, required: [title], properties: { title: { type: string } } }
|
|
responses: { '204': { description: Empty } }
|
|
"#,
|
|
);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let prepared = Arc::new(Mutex::new(None));
|
|
let executor = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CaptureAdapter {
|
|
calls: Arc::clone(&calls),
|
|
prepared: Arc::clone(&prepared),
|
|
response: response(204, BTreeMap::new(), Value::Null),
|
|
}))
|
|
.build();
|
|
|
|
for invalid in [
|
|
json!({"body": {"name": "Ada"}}),
|
|
json!({"content_type": "text/plain", "body": {"name": "Ada"}}),
|
|
json!({"content_type": "application/json", "body": {"title": "wrong branch"}}),
|
|
] {
|
|
assert!(executor.execute(&operation, &invalid).await.is_err());
|
|
}
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
|
|
assert!(
|
|
executor
|
|
.execute(
|
|
&operation,
|
|
&json!({"content_type": "application/json", "body": {"name": "Ada"}}),
|
|
)
|
|
.await
|
|
.is_ok()
|
|
);
|
|
let prepared = prepared.lock().expect("prepared lock").clone().unwrap();
|
|
assert_eq!(prepared.body, Some(json!({"name": "Ada"})));
|
|
assert_eq!(
|
|
prepared.body_content_type.as_deref(),
|
|
Some("application/json")
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn imported_single_body_preserves_empty_object_and_required_file_fails_before_adapter() {
|
|
let empty_operation = imported_operation(
|
|
r#"
|
|
openapi: 3.0.3
|
|
info: { title: Empty }
|
|
servers: [{ url: https://example.invalid }]
|
|
paths:
|
|
/empty:
|
|
post:
|
|
requestBody:
|
|
required: true
|
|
content:
|
|
application/json: { schema: { type: object } }
|
|
responses: { '204': { description: Empty } }
|
|
"#,
|
|
);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let prepared = Arc::new(Mutex::new(None));
|
|
let executor = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CaptureAdapter {
|
|
calls: Arc::clone(&calls),
|
|
prepared: Arc::clone(&prepared),
|
|
response: response(204, BTreeMap::new(), Value::Null),
|
|
}))
|
|
.build();
|
|
assert!(
|
|
executor
|
|
.execute(&empty_operation, &json!({"body": {}}))
|
|
.await
|
|
.is_ok()
|
|
);
|
|
assert_eq!(
|
|
prepared
|
|
.lock()
|
|
.expect("prepared lock")
|
|
.as_ref()
|
|
.unwrap()
|
|
.body,
|
|
Some(json!({}))
|
|
);
|
|
|
|
let file_operation = imported_operation(
|
|
r#"
|
|
openapi: 3.0.3
|
|
info: { title: Upload }
|
|
servers: [{ url: https://example.invalid }]
|
|
paths:
|
|
/upload:
|
|
post:
|
|
requestBody:
|
|
required: true
|
|
content:
|
|
multipart/form-data:
|
|
schema:
|
|
type: object
|
|
required: [file]
|
|
properties: { file: { type: string, format: binary } }
|
|
responses: { '204': { description: Empty } }
|
|
"#,
|
|
);
|
|
assert!(
|
|
executor
|
|
.execute(&file_operation, &json!({"body": {}}))
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn response_status_selects_its_linked_output_schema_branch() {
|
|
let operation = imported_operation(
|
|
r#"
|
|
openapi: 3.0.3
|
|
info: { title: Responses }
|
|
servers: [{ url: https://example.invalid }]
|
|
paths:
|
|
/items:
|
|
get:
|
|
responses:
|
|
'200':
|
|
description: Full
|
|
content:
|
|
application/json:
|
|
schema: { type: object, required: [id], properties: { id: { type: string } } }
|
|
'206':
|
|
description: Partial
|
|
content:
|
|
application/json:
|
|
schema: { type: array, items: { type: string } }
|
|
"#,
|
|
);
|
|
let executor = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CaptureAdapter {
|
|
calls: Arc::new(AtomicUsize::new(0)),
|
|
prepared: Arc::new(Mutex::new(None)),
|
|
response: response(
|
|
200,
|
|
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
|
|
json!(["schema-for-206"]),
|
|
),
|
|
}))
|
|
.build();
|
|
|
|
assert!(executor.execute(&operation, &json!({})).await.is_err());
|
|
|
|
for (status, body) in [(200, json!({"id": "full"})), (206, json!(["partial"]))] {
|
|
let executor = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CaptureAdapter {
|
|
calls: Arc::new(AtomicUsize::new(0)),
|
|
prepared: Arc::new(Mutex::new(None)),
|
|
response: response(
|
|
status,
|
|
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
|
|
body.clone(),
|
|
),
|
|
}))
|
|
.build();
|
|
assert_eq!(
|
|
executor.execute(&operation, &json!({})).await.unwrap(),
|
|
body
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn single_response_preserves_all_source_composition_branches() {
|
|
let operation = imported_operation(
|
|
r#"
|
|
openapi: 3.0.3
|
|
info: {title: Response union}
|
|
servers: [{url: https://example.invalid}]
|
|
paths:
|
|
/items:
|
|
get:
|
|
responses:
|
|
'200':
|
|
description: Either
|
|
content:
|
|
application/json:
|
|
schema:
|
|
oneOf:
|
|
- {type: string}
|
|
- {type: integer}
|
|
"#,
|
|
);
|
|
let Target::Rest(target) = &operation.target;
|
|
assert_eq!(target.response_contract.len(), 1);
|
|
assert_eq!(operation.output_schema.variants.len(), 2);
|
|
for body in [json!("text"), json!(42)] {
|
|
let executor = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CaptureAdapter {
|
|
calls: Arc::new(AtomicUsize::new(0)),
|
|
prepared: Arc::new(Mutex::new(None)),
|
|
response: response(
|
|
200,
|
|
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
|
|
body.clone(),
|
|
),
|
|
}))
|
|
.build();
|
|
assert_eq!(
|
|
executor.execute(&operation, &json!({})).await.unwrap(),
|
|
body
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn optional_single_body_distinguishes_omission_empty_object_and_null() {
|
|
let operation = imported_operation(
|
|
r#"
|
|
openapi: 3.0.3
|
|
info: {title: Optional body}
|
|
servers: [{url: https://example.invalid}]
|
|
paths:
|
|
/items:
|
|
post:
|
|
requestBody:
|
|
required: false
|
|
content:
|
|
application/json:
|
|
schema: {type: object, nullable: true}
|
|
responses: {'204': {description: Empty}}
|
|
"#,
|
|
);
|
|
let prepared = Arc::new(Mutex::new(None));
|
|
let executor = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CaptureAdapter {
|
|
calls: Arc::new(AtomicUsize::new(0)),
|
|
prepared: Arc::clone(&prepared),
|
|
response: response(204, BTreeMap::new(), Value::Null),
|
|
}))
|
|
.build();
|
|
for (input, expected) in [
|
|
(json!({}), None),
|
|
(json!({"body": {}}), Some(json!({}))),
|
|
(json!({"body": null}), Some(Value::Null)),
|
|
] {
|
|
executor.execute(&operation, &input).await.unwrap();
|
|
assert_eq!(prepared.lock().unwrap().as_ref().unwrap().body, expected);
|
|
}
|
|
}
|
|
|
|
fn imported_operation(document: &str) -> RuntimeOperation {
|
|
let preview = preview_document(document).expect("preview");
|
|
let draft = preview.groups[0].operations[0].draft.clone();
|
|
runtime_operation(draft)
|
|
}
|
|
|
|
fn runtime_operation(draft: RestImportCandidate) -> RuntimeOperation {
|
|
RuntimeOperation {
|
|
operation_id: OperationId::new("op_http_contract"),
|
|
operation_version: 1,
|
|
tool_name: draft.name,
|
|
protocol: Protocol::Rest,
|
|
target: Target::Rest(draft.target),
|
|
input_schema: draft.input_schema,
|
|
output_schema: draft.output_schema,
|
|
input_mapping: draft.input_mapping,
|
|
output_mapping: draft.output_mapping,
|
|
execution_config: ExecutionConfig {
|
|
timeout_ms: 1_000,
|
|
retry_policy: None,
|
|
response_cache: None,
|
|
idempotency: None,
|
|
safety: None,
|
|
approval_policy: None,
|
|
auth_profile_ref: None,
|
|
headers: BTreeMap::new(),
|
|
},
|
|
tool_description: ToolDescription {
|
|
title: draft.tool_description.title,
|
|
description: draft.tool_description.description,
|
|
tags: draft.tool_description.tags,
|
|
examples: draft.tool_description.examples,
|
|
},
|
|
}
|
|
}
|
|
|
|
fn response(status_code: u16, headers: BTreeMap<String, String>, body: Value) -> AdapterResponse {
|
|
AdapterResponse {
|
|
status_code,
|
|
headers,
|
|
data: body.clone(),
|
|
body,
|
|
}
|
|
}
|