Skip to main content

haste_testscript_runner/
lib.rs

1use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
2use haste_fhir_client::{
3    FHIRClient,
4    http::{HeaderMap, HeaderName, HeaderValue, WithRequestHeaders},
5    request::{
6        DeleteRequest, DeleteResponse, FHIRBatchRequest, FHIRConditionalUpdateRequest,
7        FHIRCreateRequest, FHIRDeleteInstanceRequest, FHIRDeleteSystemRequest,
8        FHIRDeleteTypeRequest, FHIRHistoryInstanceRequest, FHIRHistorySystemRequest,
9        FHIRHistoryTypeRequest, FHIRInvokeInstanceRequest, FHIRInvokeSystemRequest,
10        FHIRInvokeTypeRequest, FHIRPatchRequest, FHIRReadRequest, FHIRRequest, FHIRResponse,
11        FHIRSearchTypeRequest, FHIRTransactionRequest, FHIRUpdateInstanceRequest,
12        FHIRVersionReadRequest, HistoryRequest, HistoryResponse, InvocationRequest, InvokeResponse,
13        Operation, SearchRequest, SearchResponse, UpdateRequest,
14    },
15    url::ParsedParameters,
16};
17use haste_fhir_model::r4::generated::{
18    resources::{
19        Resource, ResourceType, TestReport, TestReportSetup, TestReportSetupAction,
20        TestReportSetupActionAssert, TestReportSetupActionOperation, TestReportTeardown,
21        TestReportTeardownAction, TestReportTest, TestReportTestAction, TestScript,
22        TestScriptFixture, TestScriptSetup, TestScriptSetupAction, TestScriptSetupActionAssert,
23        TestScriptSetupActionOperation, TestScriptTeardown, TestScriptTeardownAction,
24        TestScriptTest, TestScriptTestAction, TestScriptVariable,
25    },
26    terminology::{
27        AssertDirectionCodes, AssertOperatorCodes, BoundCode, BundleType, IssueType,
28        ReportActionResultCodes, ReportResultCodes, ReportStatusCodes, TestscriptOperationCodes,
29    },
30    types::{FHIRId, FHIRMarkdown, FHIRString, Reference},
31};
32use haste_fhir_operation_error::OperationOutcomeError;
33use haste_pointer::{Key, TypedPointer};
34use haste_reflect::MetaValue;
35use regex::Regex;
36use std::{
37    any::Any,
38    collections::HashMap,
39    sync::{Arc, LazyLock},
40    time::Duration,
41};
42use tokio::sync::Mutex;
43
44use crate::conversion::ConvertedValue;
45
46mod conversion;
47
48#[derive(Debug)]
49pub enum TestScriptError {
50    ExecutionError(String),
51    ValidationError(String),
52    FixtureNotFound,
53    InvalidFixture,
54    OperationError(OperationOutcomeError),
55}
56
57#[derive(Debug, Clone)]
58enum Response {
59    FHIRResponse(Box<FHIRResponse>),
60    OperationError(Arc<OperationOutcomeError>),
61}
62
63#[derive(Debug)]
64enum Fixtures {
65    Resource(Resource),
66    Request(FHIRRequest),
67    Response(Response),
68}
69
70// Internal structure to hold current test result and testing fixtures.
71struct TestState {
72    fp_engine: haste_fhirpath::FPEngine,
73    fixtures: HashMap<String, Fixtures>,
74    latest_request: Option<FHIRRequest>,
75    latest_response: Option<Response>,
76    result: BoundCode<ReportResultCodes>,
77    /// Writes not yet confirmed visible to search. All are waited for, since a
78    /// search (a chained one especially) may filter on any of them.
79    unindexed_writes: Vec<IndexedWrite>,
80}
81
82/// A write that searches must see before they run. Search indexing is
83/// asynchronous, so a search sent straight after a write can miss it. The
84/// worker indexes a tenant's writes in order, so once the latest write is
85/// visible every earlier one is too.
86#[derive(Debug, Clone)]
87struct IndexedWrite {
88    resource_type: ResourceType,
89    id: String,
90    /// The version search should return; `None` for a delete, which search
91    /// should no longer return at all.
92    version_id: Option<String>,
93}
94
95impl TestState {
96    fn new() -> Self {
97        TestState {
98            fp_engine: haste_fhirpath::FPEngine::new(),
99            fixtures: HashMap::new(),
100            latest_request: None,
101            latest_response: None,
102            result: ReportResultCodes::pending(),
103            unindexed_writes: Vec::new(),
104        }
105    }
106    fn resolve_fixture<'a>(
107        &'a self,
108        fixture_id: &str,
109    ) -> Result<&'a dyn MetaValue, TestScriptError> {
110        let fixture = self
111            .fixtures
112            .get(fixture_id)
113            .ok_or(TestScriptError::FixtureNotFound)?;
114
115        match fixture {
116            Fixtures::Resource(res) => Ok(res),
117            Fixtures::Request(req) => {
118                request_to_meta_value(req).ok_or_else(|| TestScriptError::InvalidFixture)
119            }
120            Fixtures::Response(response) => {
121                response_to_meta_value(response).ok_or_else(|| TestScriptError::InvalidFixture)
122            }
123        }
124    }
125}
126
127struct TestResult<T> {
128    pub state: Arc<Mutex<TestState>>,
129    pub value: T,
130}
131
132fn response_to_meta_value(response: &Response) -> Option<&dyn MetaValue> {
133    match response {
134        Response::FHIRResponse(fhir_response) => match &**fhir_response {
135            FHIRResponse::Create(res) => Some(&res.resource),
136            FHIRResponse::Read(res) => Some(&res.resource),
137            FHIRResponse::VersionRead(res) => Some(&res.resource),
138            FHIRResponse::Update(res) => Some(&res.resource),
139            FHIRResponse::Patch(res) => Some(&res.resource),
140            FHIRResponse::Batch(res) => Some(&res.resource),
141            FHIRResponse::Transaction(res) => Some(&res.resource),
142
143            FHIRResponse::Capabilities(res) => Some(&res.capabilities),
144            FHIRResponse::Search(res) => match res {
145                SearchResponse::Type(res) => Some(&res.bundle),
146                SearchResponse::System(res) => Some(&res.bundle),
147            },
148            FHIRResponse::History(res) => match res {
149                HistoryResponse::Instance(res) => Some(&res.bundle),
150                HistoryResponse::Type(res) => Some(&res.bundle),
151                HistoryResponse::System(res) => Some(&res.bundle),
152            },
153            FHIRResponse::Invoke(res) => match res {
154                InvokeResponse::Instance(res) => Some(&res.resource),
155                InvokeResponse::Type(res) => Some(&res.resource),
156                InvokeResponse::System(res) => Some(&res.resource),
157            },
158
159            FHIRResponse::Delete(_) | FHIRResponse::Accepted(_) => None,
160        },
161        Response::OperationError(op_error) => {
162            let outcome = op_error.outcome();
163            Some(outcome)
164        }
165    }
166}
167
168fn request_to_meta_value(request: &FHIRRequest) -> Option<&dyn MetaValue> {
169    match request {
170        FHIRRequest::Create(req) => Some(&req.resource),
171
172        FHIRRequest::Update(update_request) => match update_request {
173            UpdateRequest::Conditional(req) => Some(&req.resource),
174            UpdateRequest::Instance(req) => Some(&req.resource),
175        },
176
177        FHIRRequest::Batch(req) => Some(&req.resource),
178        FHIRRequest::Transaction(req) => Some(&req.resource),
179        FHIRRequest::Invocation(req) => match req {
180            haste_fhir_client::request::InvocationRequest::Instance(req) => Some(&req.parameters),
181            haste_fhir_client::request::InvocationRequest::Type(req) => Some(&req.parameters),
182            haste_fhir_client::request::InvocationRequest::System(req) => Some(&req.parameters),
183        },
184        FHIRRequest::Read(_)
185        | FHIRRequest::VersionRead(_)
186        | FHIRRequest::Compartment(_)
187        | FHIRRequest::Patch(_)
188        | FHIRRequest::Delete(_)
189        | FHIRRequest::Capabilities
190        | FHIRRequest::Search(_)
191        | FHIRRequest::History(_) => None,
192    }
193}
194
195fn associate_request_response_variables(
196    state: &mut TestState,
197    operation: &TestScriptSetupActionOperation,
198    request: FHIRRequest,
199    response: Response,
200) {
201    if let Some(request_var) = operation
202        .requestId
203        .as_ref()
204        .and_then(|id| id.value.as_ref())
205    {
206        // Associate request variable in state
207        state
208            .fixtures
209            .insert(request_var.clone(), Fixtures::Request(request.clone()));
210    }
211
212    if let Some(response_var) = operation
213        .responseId
214        .as_ref()
215        .and_then(|id| id.value.as_ref())
216    {
217        // Associate response variable in state
218        state
219            .fixtures
220            .insert(response_var.clone(), Fixtures::Response(response.clone()));
221    }
222
223    state.latest_request = Some(request);
224    state.latest_response = Some(response);
225}
226
227/// Derive the resource type from operation or from the metavalue if not present on operation.
228fn derive_resource_type(
229    operation: &TestScriptSetupActionOperation,
230    target: Option<&dyn MetaValue>,
231    path: &str,
232) -> Result<ResourceType, TestScriptError> {
233    if let Some(operation_resource_type) = operation.resource.as_ref() {
234        let string_type = operation_resource_type.as_str();
235        ResourceType::try_from(string_type.unwrap_or_default()).map_err(|_| {
236            TestScriptError::ExecutionError(format!(
237                "Unsupported resource type '{operation_resource_type:?}' for operation at '{path}'."
238            ))
239        })
240    } else if let Some(target) = target {
241        ResourceType::try_from(target.fhir_type()).map_err(|_| {
242            TestScriptError::ExecutionError(format!(
243                "Unsupported resource type '{}' for operation at '{path}'.",
244                target.fhir_type()
245            ))
246        })
247    } else {
248        Err(TestScriptError::ExecutionError(format!(
249            "Failed to derive resource type for operation at '{path}'.",
250        )))
251    }
252}
253
254static EXPRESSION_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\$\{([^}]*)\}").unwrap());
255
256async fn get_variable(
257    state: &TestState,
258    variables: &[TestScriptVariable],
259    variable_id: &str,
260) -> Result<ConvertedValue, TestScriptError> {
261    let Some(variable) = variables
262        .iter()
263        .find(|v| v.name.value.as_deref() == Some(variable_id))
264    else {
265        return Err(TestScriptError::ExecutionError(format!(
266            "Variable with id '{variable_id}' not found."
267        )));
268    };
269
270    if let Some(expression) = variable
271        .expression
272        .as_ref()
273        .and_then(|exp| exp.value.as_ref())
274    {
275        let values =
276            if let Some(source_id) = variable.sourceId.as_ref().and_then(|id| id.value.as_ref()) {
277                let source = state.resolve_fixture(source_id)?;
278                vec![source]
279            } else {
280                vec![]
281            };
282
283        let eval_result = state
284            .fp_engine
285            .evaluate(expression, values)
286            .await
287            .map_err(|e| {
288                TestScriptError::ExecutionError(format!(
289                    "Failed to evaluate FHIRPath expression for variable '{variable_id}': {e}"
290                ))
291            })?;
292
293        let converted_values = eval_result
294            .iter()
295            .map(conversion::convert_meta_value)
296            .collect::<Vec<_>>();
297
298        if converted_values.len() == 1 {
299            Ok(converted_values.into_iter().next().unwrap())
300        } else {
301            Err(TestScriptError::ExecutionError(format!(
302                "Variable '{variable_id}' evaluation returned multiple values; only single value supported.",
303            )))
304        }
305    } else {
306        Err(TestScriptError::ExecutionError(format!(
307            "Only support variable with expression for variable id '{variable_id}'.",
308        )))
309    }
310}
311
312async fn evaluate_variable(
313    state: &TestState,
314    pointer: TypedPointer<TestScript, TestScript>,
315    value: &str,
316) -> Result<String, TestScriptError> {
317    let mut result = value.to_string();
318    let variable_pointer =
319        pointer.descend::<Vec<TestScriptVariable>>(&Key::Field("variable".to_string()));
320    let default_variables = vec![];
321
322    let variables = if let Some(pointer) = variable_pointer.as_ref() {
323        pointer.value().unwrap_or(&default_variables)
324    } else {
325        &default_variables
326    };
327
328    for reg_match in EXPRESSION_REGEX.captures_iter(value) {
329        let full_match = reg_match.get(0).map_or("", |m| m.as_str());
330        let Some(variable_id) = reg_match.get(1).map(|m| m.as_str()) else {
331            return Err(TestScriptError::ExecutionError(format!(
332                "Invalid variable expression in '{value}'."
333            )));
334        };
335
336        let variable = get_variable(state, variables, variable_id).await?;
337        result = result.replace(full_match, variable.to_string().as_str());
338    }
339
340    Ok(result)
341}
342
343async fn testscript_operation_to_fhir_request(
344    state: &TestState,
345    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
346) -> Result<FHIRRequest, TestScriptError> {
347    let operation = get_operation(pointer)?;
348    let op = get_operation_type(operation);
349
350    match op {
351        Some(op) if Some(op) == TestscriptOperationCodes::read().as_str() => {
352            read_request(state, pointer, operation)
353        }
354
355        Some(op) if Some(op) == TestscriptOperationCodes::vread().as_str() => {
356            version_read_request(state, pointer, operation)
357        }
358
359        Some(op) if Some(op) == TestscriptOperationCodes::search().as_str() => {
360            search_request(state, pointer, operation).await
361        }
362
363        Some(op) if Some(op) == TestscriptOperationCodes::history().as_str() => {
364            history_request(state, pointer, operation).await
365        }
366
367        Some(op) if Some(op) == TestscriptOperationCodes::transaction().as_str() => {
368            transaction_request(state, pointer, operation)
369        }
370
371        Some(op) if Some(op) == TestscriptOperationCodes::batch().as_str() => {
372            batch_request(state, pointer, operation)
373        }
374
375        Some(op) if Some(op) == TestscriptOperationCodes::create().as_str() => {
376            create_request(state, pointer, operation)
377        }
378
379        Some(op) if Some(op) == TestscriptOperationCodes::update().as_str() => {
380            update_request(state, pointer, operation)
381        }
382
383        Some(op) if Some(op) == TestscriptOperationCodes::update_create().as_str() => {
384            conditional_update_request(state, pointer, operation).await
385        }
386
387        Some(op) if Some(op) == TestscriptOperationCodes::patch().as_str() => {
388            patch_request(state, pointer, operation)
389        }
390
391        Some(op) if Some(op) == TestscriptOperationCodes::delete().as_str() => {
392            delete_request(state, pointer, operation)
393        }
394
395        Some(op)
396            if Some(op) == TestscriptOperationCodes::delete_cond_multiple().as_str()
397                || Some(op) == TestscriptOperationCodes::delete_cond_single().as_str() =>
398        {
399            conditional_delete_request(state, pointer, operation)
400        }
401
402        Some(op)
403            if Some(op) == TestscriptOperationCodes::capabilities().as_str()
404                || Some(op) == TestscriptOperationCodes::conforms().as_str() =>
405        {
406            Ok(FHIRRequest::Capabilities)
407        }
408
409        Some("invoke") => invoke_request(state, pointer, operation),
410
411        _ => Err(TestScriptError::ExecutionError(format!(
412            "Unsupported TestScript operation type: {op:?} at '{}'.",
413            pointer.path(),
414        ))),
415    }
416}
417
418fn read_request(
419    state: &TestState,
420    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
421    operation: &TestScriptSetupActionOperation,
422) -> Result<FHIRRequest, TestScriptError> {
423    let target_id = require_target_id(operation, pointer.path(), "Read")?;
424    let target = state.resolve_fixture(target_id)?;
425
426    Ok(FHIRRequest::Read(FHIRReadRequest {
427        resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
428        id: fixture_string_field(target, target_id, "id")?,
429    }))
430}
431
432fn version_read_request(
433    state: &TestState,
434    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
435    operation: &TestScriptSetupActionOperation,
436) -> Result<FHIRRequest, TestScriptError> {
437    let target_id = require_target_id(operation, pointer.path(), "Version Read")?;
438    let target = state.resolve_fixture(target_id)?;
439
440    Ok(FHIRRequest::VersionRead(FHIRVersionReadRequest {
441        resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
442        id: fixture_string_field(target, target_id, "id")?,
443        version_id: fixture_version_id(target, target_id)?.into(),
444    }))
445}
446
447async fn search_request(
448    state: &TestState,
449    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
450    operation: &TestScriptSetupActionOperation,
451) -> Result<FHIRRequest, TestScriptError> {
452    let query = operation
453        .params
454        .as_ref()
455        .and_then(|p| p.value.as_deref())
456        .unwrap_or_default();
457
458    let parameters =
459        parsed_parameters(state, pointer.root(), query, pointer.path(), "Search").await?;
460
461    if let Ok(resource_type) = derive_resource_type(operation, None, pointer.path()) {
462        Ok(FHIRRequest::Search(
463            haste_fhir_client::request::SearchRequest::Type(
464                haste_fhir_client::request::FHIRSearchTypeRequest {
465                    resource_type,
466                    parameters,
467                },
468            ),
469        ))
470    } else {
471        Ok(FHIRRequest::Search(
472            haste_fhir_client::request::SearchRequest::System(
473                haste_fhir_client::request::FHIRSearchSystemRequest { parameters },
474            ),
475        ))
476    }
477}
478
479async fn history_request(
480    state: &TestState,
481    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
482    operation: &TestScriptSetupActionOperation,
483) -> Result<FHIRRequest, TestScriptError> {
484    let parameters = parsed_parameters(
485        state,
486        pointer.root(),
487        operation
488            .params
489            .as_ref()
490            .and_then(|p| p.value.as_deref())
491            .unwrap_or_default(),
492        pointer.path(),
493        "History",
494    )
495    .await?;
496
497    if let Some(target_id) = operation
498        .targetId
499        .as_ref()
500        .and_then(|id| id.value.as_deref())
501    {
502        let target = state.resolve_fixture(target_id)?;
503
504        Ok(FHIRRequest::History(HistoryRequest::Instance(
505            FHIRHistoryInstanceRequest {
506                resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
507                id: fixture_string_field(target, target_id, "id")?,
508                parameters,
509            },
510        )))
511    } else if operation.resource.is_some() {
512        Ok(FHIRRequest::History(HistoryRequest::Type(
513            FHIRHistoryTypeRequest {
514                resource_type: derive_resource_type(operation, None, pointer.path())?,
515                parameters,
516            },
517        )))
518    } else {
519        Ok(FHIRRequest::History(HistoryRequest::System(
520            FHIRHistorySystemRequest { parameters },
521        )))
522    }
523}
524
525fn transaction_request(
526    state: &TestState,
527    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
528    operation: &TestScriptSetupActionOperation,
529) -> Result<FHIRRequest, TestScriptError> {
530    let source_id = require_source_id(operation, pointer.path(), "Transaction")?;
531    let source = state.resolve_fixture(source_id)?;
532    let resource = fixture_resource(source, source_id)?;
533
534    match resource {
535        Resource::Bundle(bundle) => {
536            if bundle.type_ != BundleType::transaction() {
537                return Err(TestScriptError::ExecutionError(format!(
538                    "Fixture must be a transaction bundle for transaction operations for sourceId '{source_id}'."
539                )));
540            }
541
542            Ok(FHIRRequest::Transaction(FHIRTransactionRequest {
543                resource: bundle,
544            }))
545        }
546        _ => Err(TestScriptError::ExecutionError(format!(
547            "Fixture '{source_id}' is not a transaction Bundle resource."
548        ))),
549    }
550}
551
552fn batch_request(
553    state: &TestState,
554    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
555    operation: &TestScriptSetupActionOperation,
556) -> Result<FHIRRequest, TestScriptError> {
557    let source_id = require_source_id(operation, pointer.path(), "Batch")?;
558    let source = state.resolve_fixture(source_id)?;
559    let resource = fixture_resource(source, source_id)?;
560
561    match resource {
562        Resource::Bundle(bundle) => {
563            if bundle.type_ != BundleType::batch() {
564                return Err(TestScriptError::ExecutionError(format!(
565                    "Fixture must be a batch bundle for batch operations for sourceId '{source_id}'."
566                )));
567            }
568
569            Ok(FHIRRequest::Batch(FHIRBatchRequest { resource: bundle }))
570        }
571        _ => Err(TestScriptError::ExecutionError(format!(
572            "Fixture '{source_id}' is not a batch Bundle resource."
573        ))),
574    }
575}
576
577fn create_request(
578    state: &TestState,
579    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
580    operation: &TestScriptSetupActionOperation,
581) -> Result<FHIRRequest, TestScriptError> {
582    let source_id = require_source_id(operation, pointer.path(), "Create")?;
583    let source = state.resolve_fixture(source_id)?;
584    let resource = fixture_resource(source, source_id)?;
585
586    Ok(FHIRRequest::Create(FHIRCreateRequest {
587        resource_type: derive_resource_type(operation, Some(source), pointer.path())?,
588        resource,
589    }))
590}
591
592fn update_request(
593    state: &TestState,
594    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
595    operation: &TestScriptSetupActionOperation,
596) -> Result<FHIRRequest, TestScriptError> {
597    let source_id = require_source_id(operation, pointer.path(), "Update")?;
598    let source = state.resolve_fixture(source_id)?;
599    let mut resource = fixture_resource(source, source_id)?;
600
601    let target_id = require_target_id(operation, pointer.path(), "Update")?;
602    let target = state.resolve_fixture(target_id)?;
603    let target_resource = fixture_resource(target, target_id)?;
604    let id = fixture_string_field(&target_resource, target_id, "id")?;
605
606    // A contained fixture's id is local to the TestScript. The update
607    // addresses the target, and the server refuses a body naming another id.
608    if let Some(body_id) = resource
609        .get_field_mut("id")
610        .and_then(|body_id| (body_id as &mut dyn Any).downcast_mut::<Option<String>>())
611    {
612        *body_id = Some(id.clone());
613    }
614
615    Ok(FHIRRequest::Update(UpdateRequest::Instance(
616        FHIRUpdateInstanceRequest {
617            resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
618            id,
619            resource,
620        },
621    )))
622}
623
624async fn conditional_update_request(
625    state: &TestState,
626    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
627    operation: &TestScriptSetupActionOperation,
628) -> Result<FHIRRequest, TestScriptError> {
629    let source_id = require_source_id(operation, pointer.path(), "UpdateCreate")?;
630    let source = state.resolve_fixture(source_id)?;
631    let resource = fixture_resource(source, source_id)?;
632
633    let parameters = parsed_parameters(
634        state,
635        pointer.root(),
636        operation
637            .params
638            .as_ref()
639            .and_then(|p| p.value.as_deref())
640            .unwrap_or_default(),
641        pointer.path(),
642        "UpdateCreate",
643    )
644    .await?;
645
646    Ok(FHIRRequest::Update(UpdateRequest::Conditional(
647        FHIRConditionalUpdateRequest {
648            resource_type: derive_resource_type(operation, Some(source), pointer.path())?,
649            parameters,
650            resource,
651        },
652    )))
653}
654
655fn delete_request(
656    state: &TestState,
657    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
658    operation: &TestScriptSetupActionOperation,
659) -> Result<FHIRRequest, TestScriptError> {
660    let target_id = require_target_id(operation, pointer.path(), "Delete")?;
661    let target = state.resolve_fixture(target_id)?;
662
663    Ok(FHIRRequest::Delete(DeleteRequest::Instance(
664        FHIRDeleteInstanceRequest {
665            resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
666            id: fixture_string_field(target, target_id, "id")?,
667        },
668    )))
669}
670
671fn conditional_delete_request(
672    _state: &TestState,
673    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
674    operation: &TestScriptSetupActionOperation,
675) -> Result<FHIRRequest, TestScriptError> {
676    let parameters = ParsedParameters::try_from(
677        operation
678            .params
679            .as_ref()
680            .and_then(|p| p.value.as_deref())
681            .unwrap_or_default(),
682    )
683    .map_err(|e| {
684        TestScriptError::ExecutionError(format!(
685            "Failed to parse parameters for conditional delete operation at '{}': {}",
686            pointer.path(),
687            e
688        ))
689    })?;
690
691    if operation.resource.is_some() {
692        Ok(FHIRRequest::Delete(DeleteRequest::Type(
693            FHIRDeleteTypeRequest {
694                resource_type: derive_resource_type(operation, None, pointer.path())?,
695                parameters,
696            },
697        )))
698    } else {
699        Ok(FHIRRequest::Delete(DeleteRequest::System(
700            FHIRDeleteSystemRequest { parameters },
701        )))
702    }
703}
704
705/// The patch source fixture must be a `Binary` resource carrying the JSON Patch
706/// document, base64-encoded in `data` with `contentType`
707/// `application/json-patch+json` — the standard way `TestScript` represents patch
708/// bodies, since there's no dedicated FHIR resource type for a JSON Patch document.
709fn patch_request(
710    state: &TestState,
711    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
712    operation: &TestScriptSetupActionOperation,
713) -> Result<FHIRRequest, TestScriptError> {
714    let target_id = require_target_id(operation, pointer.path(), "Patch")?;
715    let target = state.resolve_fixture(target_id)?;
716
717    let source_id = require_source_id(operation, pointer.path(), "Patch")?;
718    let source = state.resolve_fixture(source_id)?;
719    let Resource::Binary(binary) = fixture_resource(source, source_id)? else {
720        return Err(TestScriptError::ExecutionError(format!(
721            "Patch source fixture '{source_id}' must be a Binary resource containing the JSON Patch document."
722        )));
723    };
724
725    let content_type = binary.contentType.value.as_deref().unwrap_or_default();
726    if content_type != "application/json-patch+json" {
727        return Err(TestScriptError::ExecutionError(format!(
728            "Unsupported patch content type '{content_type}' for fixture '{source_id}'; only 'application/json-patch+json' is supported."
729        )));
730    }
731
732    let encoded = binary
733        .data
734        .as_ref()
735        .and_then(|d| d.value.as_deref())
736        .ok_or_else(|| {
737            TestScriptError::ExecutionError(format!(
738                "Patch source fixture '{source_id}' Binary resource has no 'data'."
739            ))
740        })?;
741
742    let decoded = BASE64.decode(encoded).map_err(|e| {
743        TestScriptError::ExecutionError(format!(
744            "Failed to base64-decode patch content for fixture '{source_id}': {e}"
745        ))
746    })?;
747
748    let patch: json_patch::Patch = serde_json::from_slice(&decoded).map_err(|e| {
749        TestScriptError::ExecutionError(format!(
750            "Failed to parse JSON Patch document for fixture '{source_id}': {e}"
751        ))
752    })?;
753
754    Ok(FHIRRequest::Patch(FHIRPatchRequest {
755        resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
756        id: fixture_string_field(target, target_id, "id")?,
757        patch,
758    }))
759}
760
761fn invoke_request(
762    state: &TestState,
763    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
764    operation: &TestScriptSetupActionOperation,
765) -> Result<FHIRRequest, TestScriptError> {
766    let op_code = operation
767        .url
768        .as_ref()
769        .and_then(|u| u.value.as_deref())
770        .ok_or_else(|| {
771            TestScriptError::ExecutionError(format!(
772                "Invoke operation requires url at '{}' which is used for the operation code.",
773                pointer.path()
774            ))
775        })?;
776
777    let fhir_operation = Operation::new(op_code);
778
779    let source_id = require_source_id(operation, pointer.path(), "Invoke")?;
780    let source = state.resolve_fixture(source_id)?;
781
782    let Resource::Parameters(parameters) = fixture_resource(source, source_id)? else {
783        return Err(TestScriptError::ExecutionError(format!(
784            "Source fixture '{source_id}' is not a Parameters resource."
785        )));
786    };
787
788    if let Some(target_id) = operation
789        .targetId
790        .as_ref()
791        .and_then(|id| id.value.as_deref())
792    {
793        let target = state.resolve_fixture(target_id)?;
794
795        Ok(FHIRRequest::Invocation(InvocationRequest::Instance(
796            FHIRInvokeInstanceRequest {
797                operation: fhir_operation,
798                resource_type: derive_resource_type(operation, Some(target), pointer.path())?,
799                id: fixture_string_field(target, target_id, "id")?,
800                parameters,
801            },
802        )))
803    } else if let Ok(resource_type) = derive_resource_type(operation, None, pointer.path()) {
804        Ok(FHIRRequest::Invocation(InvocationRequest::Type(
805            FHIRInvokeTypeRequest {
806                operation: fhir_operation,
807                resource_type,
808                parameters,
809            },
810        )))
811    } else {
812        Ok(FHIRRequest::Invocation(InvocationRequest::System(
813            FHIRInvokeSystemRequest {
814                operation: fhir_operation,
815                parameters,
816            },
817        )))
818    }
819}
820
821fn get_operation(
822    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
823) -> Result<&TestScriptSetupActionOperation, TestScriptError> {
824    pointer.value().ok_or_else(|| {
825        TestScriptError::ExecutionError(format!(
826            "Failed to retrieve TestScript operation at '{}'.",
827            pointer.path()
828        ))
829    })
830}
831
832fn get_operation_type(operation: &TestScriptSetupActionOperation) -> Option<&str> {
833    operation
834        .type_
835        .as_ref()
836        .and_then(|t| t.code.as_ref())
837        .and_then(|c| c.value.as_deref())
838}
839
840fn require_target_id<'a>(
841    operation: &'a TestScriptSetupActionOperation,
842    path: &str,
843    operation_name: &str,
844) -> Result<&'a str, TestScriptError> {
845    operation
846        .targetId
847        .as_ref()
848        .and_then(|id| id.value.as_deref())
849        .ok_or_else(|| {
850            TestScriptError::ExecutionError(format!(
851                "{operation_name} operation requires targetId at '{path}'."
852            ))
853        })
854}
855
856fn require_source_id<'a>(
857    operation: &'a TestScriptSetupActionOperation,
858    path: &str,
859    operation_name: &str,
860) -> Result<&'a str, TestScriptError> {
861    operation
862        .sourceId
863        .as_ref()
864        .and_then(|id| id.value.as_deref())
865        .ok_or_else(|| {
866            TestScriptError::ExecutionError(format!(
867                "{operation_name} operation requires sourceId at '{path}'."
868            ))
869        })
870}
871
872fn fixture_string_field(
873    fixture: &dyn MetaValue,
874    fixture_name: &str,
875    field: &str,
876) -> Result<String, TestScriptError> {
877    fixture
878        .get_field(field)
879        .ok_or_else(|| {
880            TestScriptError::ExecutionError(format!(
881                "Fixture '{fixture_name}' does not have '{field}' field."
882            ))
883        })?
884        .as_any()
885        .downcast_ref::<String>()
886        .cloned()
887        .ok_or_else(|| {
888            TestScriptError::ExecutionError(format!(
889                "Field '{field}' on fixture '{fixture_name}' is not a String."
890            ))
891        })
892}
893
894fn fixture_version_id(
895    fixture: &dyn MetaValue,
896    fixture_name: &str,
897) -> Result<String, TestScriptError> {
898    fixture
899        .get_field("meta")
900        .and_then(|meta| meta.get_field("versionId"))
901        .ok_or_else(|| {
902            TestScriptError::ExecutionError(format!(
903                "Fixture '{fixture_name}' does not have a 'versionId' field."
904            ))
905        })?
906        .as_any()
907        .downcast_ref::<Box<FHIRId>>()
908        .cloned()
909        .and_then(|v| v.value)
910        .ok_or_else(|| {
911            TestScriptError::ExecutionError(format!(
912                "Fixture '{fixture_name}' does not have a valid 'versionId' field."
913            ))
914        })
915}
916
917fn fixture_resource(
918    fixture: &dyn MetaValue,
919    fixture_name: &str,
920) -> Result<Resource, TestScriptError> {
921    (fixture as &dyn Any)
922        .downcast_ref::<Resource>()
923        .cloned()
924        .ok_or_else(|| {
925            TestScriptError::ExecutionError(format!("Fixture '{fixture_name}' is not a Resource."))
926        })
927}
928
929async fn parsed_parameters(
930    state: &TestState,
931    root: TypedPointer<TestScript, TestScript>,
932    raw: &str,
933    path: &str,
934    operation: &str,
935) -> Result<ParsedParameters, TestScriptError> {
936    let evaluated = evaluate_variable(state, root, raw).await?;
937
938    ParsedParameters::try_from(evaluated.as_str()).map_err(|e| {
939        TestScriptError::ExecutionError(format!(
940            "Failed to parse parameters for {operation} operation at '{path}': {e}"
941        ))
942    })
943}
944
945/// Builds the headers declared by an operation's `requestHeader` entries.
946///
947/// Values are variable-evaluated first, so a `TestScript` may parameterize a header
948/// the same way it parameterizes a URL or a search query.
949async fn testscript_request_headers(
950    state: &TestState,
951    pointer: &TypedPointer<TestScript, TestScriptSetupActionOperation>,
952    operation: &TestScriptSetupActionOperation,
953) -> Result<Option<HeaderMap>, TestScriptError> {
954    let Some(request_headers) = operation.requestHeader.as_ref() else {
955        return Ok(None);
956    };
957
958    let mut headers = HeaderMap::with_capacity(request_headers.len());
959
960    for request_header in request_headers {
961        let field = request_header.field.value.as_deref().ok_or_else(|| {
962            TestScriptError::ExecutionError(format!(
963                "Missing requestHeader field for operation at '{}'.",
964                pointer.path()
965            ))
966        })?;
967
968        let raw_value = request_header.value.value.as_deref().unwrap_or_default();
969        let value = evaluate_variable(state, pointer.root(), raw_value).await?;
970
971        let name = HeaderName::try_from(field).map_err(|e| {
972            TestScriptError::ExecutionError(format!(
973                "Invalid requestHeader field '{field}' for operation at '{}': {e}",
974                pointer.path()
975            ))
976        })?;
977
978        let value = HeaderValue::from_str(&value).map_err(|e| {
979            TestScriptError::ExecutionError(format!(
980                "Invalid requestHeader value for '{field}' for operation at '{}': {e}",
981                pointer.path()
982            ))
983        })?;
984
985        headers.insert(name, value);
986    }
987
988    Ok((!headers.is_empty()).then_some(headers))
989}
990
991/// How often search is polled while waiting for a write to be indexed.
992const INDEX_POLL_INTERVAL: Duration = Duration::from_millis(100);
993
994/// The write a response records, for requests that change a resource.
995fn indexed_write(response: &FHIRResponse) -> Option<IndexedWrite> {
996    let (resource, deleted) = match response {
997        FHIRResponse::Create(created) => (&created.resource, false),
998        FHIRResponse::Update(updated) => (&updated.resource, false),
999        FHIRResponse::Patch(patched) => (&patched.resource, false),
1000        FHIRResponse::Delete(DeleteResponse::Instance(deleted)) => (&deleted.resource, true),
1001        _ => return None,
1002    };
1003    let json = serde_json::to_value(resource).ok()?;
1004    Some(IndexedWrite {
1005        resource_type: ResourceType::try_from(json.get("resourceType")?.as_str()?).ok()?,
1006        id: json.get("id")?.as_str()?.to_string(),
1007        version_id: if deleted {
1008            None
1009        } else {
1010            Some(json.pointer("/meta/versionId")?.as_str()?.to_string())
1011        },
1012    })
1013}
1014
1015/// Whether a request's result depends on the search index.
1016fn reads_search_index(request: &FHIRRequest) -> bool {
1017    matches!(
1018        request,
1019        FHIRRequest::Search(_)
1020            | FHIRRequest::Delete(DeleteRequest::Type(_) | DeleteRequest::System(_))
1021            | FHIRRequest::Update(UpdateRequest::Conditional(_))
1022    )
1023}
1024
1025/// Polls search until `write` is visible (its version returned, or gone after
1026/// a delete) or `timeout` runs out. On timeout the caller carries on, and a
1027/// search that depended on the write fails its assertions as usual.
1028async fn wait_for_index<CTX: Clone, Client: FHIRClient<CTX, OperationOutcomeError>>(
1029    client: &Client,
1030    ctx: &CTX,
1031    write: &IndexedWrite,
1032    timeout: Duration,
1033) {
1034    let Ok(parameters) = ParsedParameters::try_from(format!("_id={}", write.id).as_str()) else {
1035        return;
1036    };
1037    let request = FHIRRequest::Search(SearchRequest::Type(FHIRSearchTypeRequest {
1038        resource_type: write.resource_type.clone(),
1039        parameters,
1040    }));
1041    let deadline = tokio::time::Instant::now() + timeout;
1042
1043    loop {
1044        let versions: Vec<String> = match client.request(ctx.clone(), request.clone()).await {
1045            Ok(FHIRResponse::Search(SearchResponse::Type(response))) => response
1046                .bundle
1047                .entry
1048                .unwrap_or_default()
1049                .into_iter()
1050                .filter_map(|entry| {
1051                    let json = serde_json::to_value(entry.resource?).ok()?;
1052                    Some(json.pointer("/meta/versionId")?.as_str()?.to_string())
1053                })
1054                .collect(),
1055            _ => vec![],
1056        };
1057        let visible = match &write.version_id {
1058            Some(version_id) => versions.contains(version_id),
1059            None => versions.is_empty(),
1060        };
1061        if visible {
1062            return;
1063        }
1064        if tokio::time::Instant::now() >= deadline {
1065            tracing::warn!(
1066                resource_type = write.resource_type.as_ref(),
1067                id = write.id,
1068                "Timed out waiting for a write to be indexed"
1069            );
1070            return;
1071        }
1072        tokio::time::sleep(INDEX_POLL_INTERVAL).await;
1073    }
1074}
1075
1076async fn run_operation<
1077    CTX: Clone + WithRequestHeaders,
1078    Client: FHIRClient<CTX, OperationOutcomeError>,
1079>(
1080    client: &Client,
1081    ctx: CTX,
1082    state: Arc<Mutex<TestState>>,
1083    pointer: TypedPointer<TestScript, TestScriptSetupActionOperation>,
1084    options: Arc<TestRunnerOptions>,
1085) -> Result<TestResult<TestReportSetupActionOperation>, TestScriptError> {
1086    let operation = pointer.value().ok_or_else(|| {
1087        TestScriptError::ExecutionError(format!(
1088            "Failed to retrieve TestScript operation at '{}'.",
1089            pointer.path()
1090        ))
1091    })?;
1092
1093    let mut state_guard = state.lock().await;
1094    let fhir_request = testscript_operation_to_fhir_request(&state_guard, &pointer).await?;
1095
1096    if let Some(timeout) = options.index_wait_timeout
1097        && reads_search_index(&fhir_request)
1098        && !state_guard.unindexed_writes.is_empty()
1099    {
1100        // One deadline for the whole set: the worker indexes them together.
1101        let deadline = tokio::time::Instant::now() + timeout;
1102        for write in std::mem::take(&mut state_guard.unindexed_writes) {
1103            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
1104            if remaining.is_zero() {
1105                break;
1106            }
1107            wait_for_index(client, &ctx, &write, remaining).await;
1108        }
1109    }
1110
1111    let ctx = match testscript_request_headers(&state_guard, &pointer, operation).await? {
1112        Some(headers) => ctx.with_request_headers(headers),
1113        None => ctx,
1114    };
1115
1116    let fhir_response = client.request(ctx, fhir_request.clone()).await;
1117    if let Some(wait_duration) = options.wait_between_operations {
1118        tokio::time::sleep(wait_duration).await;
1119    }
1120
1121    match fhir_response {
1122        Ok(fhir_response) => {
1123            if let Some(write) = indexed_write(&fhir_response) {
1124                state_guard.unindexed_writes.push(write);
1125            }
1126            associate_request_response_variables(
1127                &mut state_guard,
1128                operation,
1129                fhir_request,
1130                Response::FHIRResponse(Box::new(fhir_response)),
1131            );
1132
1133            drop(state_guard);
1134
1135            Ok(TestResult {
1136                state: state.clone(),
1137                value: TestReportSetupActionOperation {
1138                    result: ReportActionResultCodes::pass(),
1139                    ..Default::default()
1140                },
1141            })
1142        }
1143        Err(op_error) => {
1144            let op_error = Arc::new(op_error);
1145            tracing::warn!(
1146                path = pointer.path(),
1147                operation.label = operation
1148                    .label
1149                    .as_ref()
1150                    .and_then(|l| l.value.as_deref())
1151                    .unwrap_or("<no-label>"),
1152                operation.operation_type = get_operation_type(operation).unwrap_or("<unknown>"),
1153                error = %op_error,
1154                "TestScript operation failed"
1155            );
1156            associate_request_response_variables(
1157                &mut state_guard,
1158                operation,
1159                fhir_request,
1160                Response::OperationError(op_error.clone()),
1161            );
1162
1163            Ok(TestResult {
1164                state: state.clone(),
1165                value: TestReportSetupActionOperation {
1166                    result: ReportActionResultCodes::warning(),
1167                    message: Some(Box::new(FHIRMarkdown {
1168                        value: Some(format!("Operation failed: {op_error}")),
1169                        ..Default::default()
1170                    })),
1171                    ..Default::default()
1172                },
1173            })
1174        }
1175    }
1176}
1177
1178fn get_source<'a>(
1179    state: &'a TestState,
1180    assertion: &TestScriptSetupActionAssert,
1181) -> Result<Option<&'a dyn MetaValue>, TestScriptError> {
1182    if let Some(source_id) = assertion.sourceId.as_ref().and_then(|id| id.value.as_ref()) {
1183        let source = state.resolve_fixture(source_id)?;
1184        Ok(Some(source))
1185    } else {
1186        match assertion
1187            .direction
1188            .as_ref()
1189            .unwrap_or(&AssertDirectionCodes::response())
1190        {
1191            assertion if assertion == &AssertDirectionCodes::request() => {
1192                if let Some(request) = state.latest_request.as_ref() {
1193                    request_to_meta_value(request)
1194                        .ok_or_else(|| TestScriptError::InvalidFixture)
1195                        .map(Some)
1196                } else {
1197                    Ok(None)
1198                }
1199            }
1200            assertion if assertion == &AssertDirectionCodes::response() => {
1201                if let Some(response) = state.latest_response.as_ref() {
1202                    response_to_meta_value(response)
1203                        .ok_or_else(|| TestScriptError::InvalidFixture)
1204                        .map(Some)
1205                } else {
1206                    Ok(None)
1207                }
1208            }
1209            _ => Err(TestScriptError::ExecutionError(
1210                "Assert direction cannot be 'null' when sourceId is not provided.".to_string(),
1211            )),
1212        }
1213    }
1214}
1215
1216fn evaluate_operator(
1217    operator: &BoundCode<AssertOperatorCodes>,
1218    a: &Vec<conversion::ConvertedValue>,
1219    b: &Vec<conversion::ConvertedValue>,
1220) -> bool {
1221    match operator {
1222        operator
1223            if operator == &AssertOperatorCodes::equals()
1224                || operator == &AssertOperatorCodes::null() =>
1225        {
1226            a == b
1227        }
1228        operator if operator == &AssertOperatorCodes::not_equals() => !(a == b),
1229
1230        operator if operator == &AssertOperatorCodes::contains() => {
1231            if a.len() != 1 || b.len() != 1 {
1232                return false;
1233            }
1234
1235            match (&a[0], &b[0]) {
1236                (ConvertedValue::String(a_str), ConvertedValue::String(b_str)) => {
1237                    a_str.contains(b_str)
1238                }
1239                _ => false,
1240            }
1241        }
1242        operator if operator == &AssertOperatorCodes::empty() => {
1243            todo!("Empty operator not implemented")
1244        }
1245        operator if operator == &AssertOperatorCodes::eval() => {
1246            todo!("Eval operator not implemented")
1247        }
1248        operator if operator == &AssertOperatorCodes::greater_than() => {
1249            todo!("GreaterThan operator not implemented")
1250        }
1251        operator if operator == &AssertOperatorCodes::in_() => todo!("In operator not implemented"),
1252        operator if operator == &AssertOperatorCodes::less_than() => {
1253            todo!("LessThan operator not implemented")
1254        }
1255        operator if operator == &AssertOperatorCodes::not_contains() => {
1256            todo!("NotContains operator not implemented")
1257        }
1258        operator if operator == &AssertOperatorCodes::not_empty() => {
1259            todo!("NotEmpty operator not implemented")
1260        }
1261        operator if operator == &AssertOperatorCodes::not_in() => {
1262            todo!("NotIn operator not implemented")
1263        }
1264        _ => {
1265            todo!("Operator '{:?}' not implemented", operator)
1266        }
1267    }
1268    // a == b
1269}
1270
1271async fn derive_comparison_to(
1272    state: &TestState,
1273    assertion: &TestScriptSetupActionAssert,
1274) -> Result<Vec<ConvertedValue>, TestScriptError> {
1275    if let Some(comparision_fixture_id) = assertion
1276        .compareToSourceId
1277        .as_ref()
1278        .and_then(|c| c.value.as_ref())
1279    {
1280        let comparison_fixture = state.resolve_fixture(comparision_fixture_id)?;
1281
1282        let Some(comparison_expression) = assertion
1283            .compareToSourceExpression
1284            .as_ref()
1285            .and_then(|exp| exp.value.as_ref())
1286        else {
1287            return Err(TestScriptError::ExecutionError(
1288                "compareToSourceExpression is required when compareToSourceId is provided."
1289                    .to_string(),
1290            ));
1291        };
1292
1293        let result = state
1294            .fp_engine
1295            .evaluate(comparison_expression, vec![comparison_fixture])
1296            .await
1297            .map_err(|e| {
1298                TestScriptError::ExecutionError(format!(
1299                    "FHIRPath evaluation error for comparison fixture '{comparision_fixture_id}': {e}"
1300                ))
1301            })?;
1302
1303        Ok(result
1304            .iter()
1305            .map(conversion::convert_meta_value)
1306            .collect::<Vec<_>>())
1307    } else if let Some(value) = assertion.value.as_ref().and_then(|v| v.value.as_ref())
1308        && let Some(converted_value) = conversion::convert_string_value(value.as_ref())
1309    {
1310        Ok(vec![converted_value])
1311    } else {
1312        Err(TestScriptError::ExecutionError(
1313            "Failed to derive comparison value for assertion.".to_string(),
1314        ))
1315    }
1316}
1317
1318/// Assertions carry a `label`/`description` intended by the FHIR spec for
1319/// exactly this purpose: identifying an assertion in test engine output.
1320fn assert_label(assertion: &TestScriptSetupActionAssert) -> &str {
1321    assertion
1322        .label
1323        .as_ref()
1324        .and_then(|l| l.value.as_deref())
1325        .or_else(|| {
1326            assertion
1327                .description
1328                .as_ref()
1329                .and_then(|d| d.value.as_deref())
1330        })
1331        .unwrap_or("<no-label>")
1332}
1333
1334/// Assertions are what determine the testreports ultimate pass/fail status.
1335/// So set that within state here depending on assertion success/failure.
1336async fn run_assertion(
1337    state: Arc<Mutex<TestState>>,
1338    pointer: TypedPointer<TestScript, TestScriptSetupActionAssert>,
1339) -> Result<TestResult<TestReportSetupActionAssert>, TestScriptError> {
1340    let assertion = pointer.value().ok_or_else(|| {
1341        TestScriptError::ExecutionError(format!(
1342            "Failed to retrieve TestScript assertion at '{}'.",
1343            pointer.path()
1344        ))
1345    })?;
1346
1347    let mut state_guard = state.lock().await;
1348
1349    let Some(source) = get_source(&state_guard, assertion)? else {
1350        return Err(TestScriptError::ExecutionError(format!(
1351            "Failed to resolve source for assertion at '{}'.",
1352            pointer.path()
1353        )));
1354    };
1355
1356    let default = AssertOperatorCodes::equals();
1357    let operator = assertion.operator.as_ref().unwrap_or(&default);
1358
1359    // Keep all uses of `source` inside this scope so the immutable borrow
1360    // of `state_guard` ends before we mutate `state_guard`.
1361    let failure_message = if let Some(message) =
1362        evaluate_resource_assertion(assertion, pointer.path(), source, operator)
1363    {
1364        Some(message)
1365    } else if let Some(expression) = assertion.expression.as_ref().and_then(|e| e.value.as_ref()) {
1366        evaluate_expression_assertion(
1367            &state_guard,
1368            assertion,
1369            pointer.path(),
1370            source,
1371            operator,
1372            expression,
1373        )
1374        .await?
1375    } else {
1376        None
1377    };
1378
1379    let (result, message) = match failure_message {
1380        Some(message) => {
1381            tracing::error!(
1382                assert.label = assert_label(assertion),
1383                path = pointer.path(),
1384                "{message}"
1385            );
1386
1387            state_guard.result = ReportResultCodes::fail();
1388
1389            (
1390                ReportActionResultCodes::fail(),
1391                Some(Box::new(FHIRMarkdown {
1392                    value: Some(message),
1393                    ..Default::default()
1394                })),
1395            )
1396        }
1397        None => (ReportActionResultCodes::pass(), None),
1398    };
1399
1400    Ok(TestResult {
1401        state: state.clone(),
1402        value: TestReportSetupActionAssert {
1403            result,
1404            message,
1405            ..Default::default()
1406        },
1407    })
1408}
1409
1410fn evaluate_resource_assertion(
1411    assertion: &TestScriptSetupActionAssert,
1412    path: &str,
1413    source: &dyn MetaValue,
1414    operator: &BoundCode<AssertOperatorCodes>,
1415) -> Option<String> {
1416    let resource_string = assertion.resource.as_ref()?.as_str()?;
1417
1418    let operation_evaluation_result = evaluate_operator(
1419        operator,
1420        &vec![conversion::ConvertedValue::String(
1421            resource_string.to_string(),
1422        )],
1423        &vec![conversion::ConvertedValue::String(
1424            source.fhir_type().to_string(),
1425        )],
1426    );
1427
1428    if operation_evaluation_result {
1429        return None;
1430    }
1431
1432    Some(format!(
1433        "Assertion '{}' at '{}' failed: resource type '{resource_string}' does not match '{}'.",
1434        assert_label(assertion),
1435        path,
1436        source.fhir_type()
1437    ))
1438}
1439
1440async fn evaluate_expression_assertion(
1441    state_guard: &TestState,
1442    assertion: &TestScriptSetupActionAssert,
1443    path: &str,
1444    source: &dyn MetaValue,
1445    operator: &BoundCode<AssertOperatorCodes>,
1446    expression: &str,
1447) -> Result<Option<String>, TestScriptError> {
1448    let comparison_to = derive_comparison_to(state_guard, assertion).await?;
1449
1450    let Ok(result) = state_guard
1451        .fp_engine
1452        .evaluate(expression, vec![source])
1453        .await
1454    else {
1455        tracing::error!(
1456            assert.label = assert_label(assertion),
1457            path = path,
1458            expression = expression,
1459            "Assertion '{}' at '{}' failed: FHIRPath expression '{expression}' failed to evaluate.",
1460            assert_label(assertion),
1461            path,
1462        );
1463
1464        return Err(TestScriptError::ExecutionError(format!(
1465            "Assertion '{}' at '{}': FHIRPath expression '{expression}' failed to evaluate.",
1466            assert_label(assertion),
1467            path,
1468        )));
1469    };
1470
1471    let converted_values = result
1472        .iter()
1473        .map(conversion::convert_meta_value)
1474        .collect::<Vec<_>>();
1475
1476    let operation_evaluation_result =
1477        evaluate_operator(operator, &converted_values, &comparison_to);
1478
1479    if operation_evaluation_result {
1480        return Ok(None);
1481    }
1482
1483    Ok(Some(format!(
1484        "Assertion '{}' at '{}' failed: '{converted_values:?}' {operator:?} '{comparison_to:?}'.",
1485        assert_label(assertion),
1486        path,
1487    )))
1488}
1489
1490async fn run_action<
1491    CTX: Clone + WithRequestHeaders,
1492    Client: FHIRClient<CTX, OperationOutcomeError>,
1493>(
1494    client: &Client,
1495    ctx: CTX,
1496    state: Arc<Mutex<TestState>>,
1497    pointer: TypedPointer<TestScript, TestScriptTestAction>,
1498    options: Arc<TestRunnerOptions>,
1499) -> Result<TestResult<TestReportSetupAction>, TestScriptError> {
1500    tracing::info!("Running TestScript action at path: {}", pointer.path());
1501    let action = pointer.value().ok_or_else(|| {
1502        TestScriptError::ExecutionError(format!(
1503            "Failed to retrieve TestScript action at '{}'.",
1504            pointer.path()
1505        ))
1506    })?;
1507
1508    // Should be either an operation or an assert.
1509    // Both should not exist at the same time.
1510    if action.operation.is_some() {
1511        let Some(operation_pointer) =
1512            pointer.descend::<TestScriptSetupActionOperation>(&Key::Field("operation".to_string()))
1513        else {
1514            return Err(TestScriptError::ExecutionError(format!(
1515                "Failed to retrieve TestScript operation at '{}'.",
1516                pointer.path()
1517            )));
1518        };
1519
1520        let result = run_operation(client, ctx, state, operation_pointer, options).await?;
1521
1522        Ok(TestResult {
1523            state: result.state,
1524            value: TestReportSetupAction {
1525                operation: Some(result.value),
1526                ..Default::default()
1527            },
1528        })
1529    } else if action.assert.is_some() {
1530        let Some(assertion_pointer) =
1531            pointer.descend::<TestScriptSetupActionAssert>(&Key::Field("assert".to_string()))
1532        else {
1533            return Err(TestScriptError::ExecutionError(format!(
1534                "Failed to retrieve TestScript assertion at '{}'.",
1535                pointer.path()
1536            )));
1537        };
1538
1539        let assertion = run_assertion(state, assertion_pointer).await?;
1540
1541        Ok(TestResult {
1542            state: assertion.state,
1543            value: TestReportSetupAction {
1544                assert: Some(assertion.value),
1545                ..Default::default()
1546            },
1547        })
1548    } else {
1549        Err(TestScriptError::ExecutionError(format!(
1550            "TestScript action must have either an operation or an assert at '{}'.",
1551            pointer.path()
1552        )))
1553    }
1554}
1555
1556async fn run_setup_action<
1557    CTX: Clone + WithRequestHeaders,
1558    Client: FHIRClient<CTX, OperationOutcomeError>,
1559>(
1560    client: &Client,
1561    ctx: CTX,
1562    state: Arc<Mutex<TestState>>,
1563    pointer: TypedPointer<TestScript, TestScriptSetupAction>,
1564    options: Arc<TestRunnerOptions>,
1565) -> Result<TestResult<TestReportSetupAction>, TestScriptError> {
1566    let action = pointer.value().ok_or_else(|| {
1567        TestScriptError::ExecutionError(format!(
1568            "Failed to retrieve TestScript action at '{}'.",
1569            pointer.path()
1570        ))
1571    })?;
1572
1573    tracing::info!("Running TestScript action at path: {}", pointer.path());
1574
1575    // Should be either an operation or an assert.
1576    // Both should not exist at the same time.
1577    if action.operation.is_some() {
1578        let Some(operation_pointer) =
1579            pointer.descend::<TestScriptSetupActionOperation>(&Key::Field("operation".to_string()))
1580        else {
1581            return Err(TestScriptError::ExecutionError(format!(
1582                "Failed to retrieve TestScript operation at '{}'.",
1583                pointer.path()
1584            )));
1585        };
1586
1587        let result = run_operation(client, ctx, state, operation_pointer, options).await?;
1588
1589        Ok(TestResult {
1590            state: result.state,
1591            value: TestReportSetupAction {
1592                operation: Some(result.value),
1593                ..Default::default()
1594            },
1595        })
1596    } else if action.assert.is_some() {
1597        let Some(assertion_pointer) =
1598            pointer.descend::<TestScriptSetupActionAssert>(&Key::Field("assert".to_string()))
1599        else {
1600            return Err(TestScriptError::ExecutionError(format!(
1601                "Failed to retrieve TestScript assertion at '{}'.",
1602                pointer.path()
1603            )));
1604        };
1605
1606        let assertion = run_assertion(state, assertion_pointer).await?;
1607
1608        Ok(TestResult {
1609            state: assertion.state,
1610            value: TestReportSetupAction {
1611                assert: Some(assertion.value),
1612                ..Default::default()
1613            },
1614        })
1615    } else {
1616        Err(TestScriptError::ExecutionError(format!(
1617            "TestScript action must have either an operation or an assert at '{}'.",
1618            pointer.path()
1619        )))
1620    }
1621}
1622
1623async fn setup_fixtures<
1624    CTX: Clone + WithRequestHeaders,
1625    Client: FHIRClient<CTX, OperationOutcomeError>,
1626>(
1627    client: &Client,
1628    ctx: CTX,
1629    state: Arc<Mutex<TestState>>,
1630    pointer: TypedPointer<TestScript, TestScript>,
1631    _options: Arc<TestRunnerOptions>,
1632) -> Result<Arc<Mutex<TestState>>, OperationOutcomeError> {
1633    let mut state_lock = state.lock().await;
1634
1635    let Some(fixtures_pointer) =
1636        pointer.descend::<Vec<TestScriptFixture>>(&Key::Field("fixture".to_string()))
1637    else {
1638        return Ok(state.clone());
1639    };
1640
1641    let Some(fixtures) = fixtures_pointer.value() else {
1642        return Ok(state.clone());
1643    };
1644
1645    for fixture in fixtures {
1646        if let Some(reference_string) = fixture
1647            .resource
1648            .as_ref()
1649            .and_then(|r| r.reference.as_ref())
1650            .and_then(|refe| refe.value.as_ref())
1651        {
1652            let resolved_resource = if reference_string.starts_with('#')
1653                && let Some(contained) =
1654                    pointer.descend::<Vec<Resource>>(&Key::Field("contained".to_string()))
1655                && let Some(contained) = contained.value()
1656            {
1657                let local_id = &reference_string[1..];
1658                let Some(resource) = contained.iter().find(|res| {
1659                    if let Some(id) = res.get_field("id")
1660                        && let Some(id) = id.as_any().downcast_ref::<String>()
1661                    {
1662                        id.as_str() == local_id
1663                    } else {
1664                        false
1665                    }
1666                }) else {
1667                    return Err(OperationOutcomeError::error(
1668                        IssueType::not_found(),
1669                        format!("Contained resource with id '{local_id}' not found."),
1670                    ));
1671                };
1672
1673                resource.clone()
1674            } else {
1675                let parts = reference_string.split('/').collect::<Vec<&str>>();
1676                if parts.len() != 2 {
1677                    return Err(OperationOutcomeError::error(
1678                        IssueType::invalid(),
1679                        format!("Invalid fixture reference: {reference_string}"),
1680                    ));
1681                }
1682
1683                let resource_type = parts[0];
1684                let id = parts[1];
1685
1686                let Some(remote_resource) = client
1687                    .read(
1688                        ctx.clone(),
1689                        ResourceType::try_from(resource_type).map_err(|_| {
1690                            OperationOutcomeError::error(
1691                                IssueType::invalid(),
1692                                format!(
1693                                    "Invalid resource type in fixture reference: '{resource_type}'"
1694                                ),
1695                            )
1696                        })?,
1697                        id.to_string(),
1698                    )
1699                    .await?
1700                else {
1701                    return Err(OperationOutcomeError::error(
1702                        IssueType::not_found(),
1703                        format!("Resource '{resource_type}' with id '{id}' not found."),
1704                    ));
1705                };
1706
1707                remote_resource
1708            };
1709
1710            state_lock.fixtures.insert(
1711                fixture.id.clone().unwrap_or_default(),
1712                Fixtures::Resource(resolved_resource),
1713            );
1714        }
1715    }
1716
1717    drop(state_lock);
1718
1719    Ok(state)
1720}
1721
1722async fn run_setup<
1723    CTX: Clone + WithRequestHeaders,
1724    Client: FHIRClient<CTX, OperationOutcomeError>,
1725>(
1726    client: &Client,
1727    ctx: CTX,
1728    state: Arc<Mutex<TestState>>,
1729    pointer: TypedPointer<TestScript, TestScriptSetup>,
1730    options: Arc<TestRunnerOptions>,
1731) -> Result<TestResult<TestReportSetup>, TestScriptError> {
1732    let mut cur_state = state;
1733
1734    let mut setup_results = TestReportSetup {
1735        action: vec![],
1736        ..Default::default()
1737    };
1738
1739    let Some(setup) = pointer.value() else {
1740        return Ok(TestResult {
1741            state: cur_state,
1742            value: setup_results,
1743        });
1744    };
1745
1746    for action in setup.action.iter().enumerate() {
1747        let action_pointer = pointer
1748            .descend::<Vec<TestScriptSetupAction>>(&Key::Field("action".to_string()))
1749            .and_then(|p| p.descend::<TestScriptSetupAction>(&Key::Index(action.0)));
1750
1751        let action_pointer = action_pointer.ok_or_else(|| {
1752            TestScriptError::ExecutionError(format!(
1753                "Failed to retrieve TestScript action at index {}.",
1754                action.0
1755            ))
1756        })?;
1757
1758        let result = run_setup_action(
1759            client,
1760            ctx.clone(),
1761            cur_state,
1762            action_pointer,
1763            options.clone(),
1764        )
1765        .await?;
1766        cur_state = result.state;
1767
1768        setup_results.action.push(result.value);
1769    }
1770
1771    Ok(TestResult {
1772        state: cur_state,
1773        value: setup_results,
1774    })
1775}
1776
1777async fn run_teardown<
1778    CTX: Clone + WithRequestHeaders,
1779    Client: FHIRClient<CTX, OperationOutcomeError>,
1780>(
1781    client: &Client,
1782    ctx: CTX,
1783    state: Arc<Mutex<TestState>>,
1784    pointer: TypedPointer<TestScript, TestScriptTeardown>,
1785    options: Arc<TestRunnerOptions>,
1786) -> Result<TestResult<TestReportTeardown>, TestScriptError> {
1787    let mut cur_state = state;
1788
1789    let mut teardown_results = TestReportTeardown {
1790        action: vec![],
1791        ..Default::default()
1792    };
1793
1794    let Some(actions) = pointer.value() else {
1795        return Ok(TestResult {
1796            state: cur_state,
1797            value: teardown_results,
1798        });
1799    };
1800
1801    for action in actions.action.iter().enumerate() {
1802        let action_pointer = pointer
1803            .descend::<Vec<TestScriptTeardownAction>>(&Key::Field("action".to_string()))
1804            .and_then(|p| p.descend::<TestScriptTeardownAction>(&Key::Index(action.0)));
1805
1806        let action_pointer = action_pointer.ok_or_else(|| {
1807            TestScriptError::ExecutionError(format!(
1808                "Failed to retrieve TestScript teardown action at index {}.",
1809                action.0
1810            ))
1811        })?;
1812
1813        let operation_pointer = action_pointer
1814            .descend::<TestScriptSetupActionOperation>(&Key::Field("operation".to_string()))
1815            .ok_or_else(|| {
1816                TestScriptError::ExecutionError(format!(
1817                    "Failed to retrieve TestScript teardown operation at index {}.",
1818                    action.0
1819                ))
1820            })?;
1821
1822        let result = run_operation(
1823            client,
1824            ctx.clone(),
1825            cur_state,
1826            operation_pointer,
1827            options.clone(),
1828        )
1829        .await?;
1830        cur_state = result.state;
1831
1832        teardown_results.action.push(TestReportTeardownAction {
1833            operation: result.value,
1834            ..Default::default()
1835        });
1836    }
1837
1838    Ok(TestResult {
1839        state: cur_state,
1840        value: teardown_results,
1841    })
1842}
1843
1844async fn run_test<
1845    CTX: Clone + WithRequestHeaders,
1846    Client: FHIRClient<CTX, OperationOutcomeError>,
1847>(
1848    client: &Client,
1849    ctx: CTX,
1850    state: Arc<Mutex<TestState>>,
1851    pointer: TypedPointer<TestScript, TestScriptTest>,
1852    options: Arc<TestRunnerOptions>,
1853) -> Result<TestResult<TestReportTest>, TestScriptError> {
1854    let mut cur_state = state;
1855    let mut test_report_test = TestReportTest {
1856        action: vec![],
1857        ..Default::default()
1858    };
1859
1860    let test = pointer.value().ok_or_else(|| {
1861        TestScriptError::ExecutionError(format!(
1862            "Failed to retrieve TestScript test at '{}'.",
1863            pointer.path()
1864        ))
1865    })?;
1866
1867    for action in test.action.iter().enumerate() {
1868        let Some(action_pointer) = pointer
1869            .descend::<Vec<TestScriptTestAction>>(&Key::Field("action".to_string()))
1870            .and_then(|p| p.descend(&Key::Index(action.0)))
1871        else {
1872            return Err(TestScriptError::ExecutionError(format!(
1873                "Failed to retrieve TestScript test action at index {}.",
1874                action.0
1875            )));
1876        };
1877        let result = run_action(
1878            client,
1879            ctx.clone(),
1880            cur_state,
1881            action_pointer,
1882            options.clone(),
1883        )
1884        .await?;
1885        cur_state = result.state;
1886        test_report_test.action.push(TestReportTestAction {
1887            operation: result.value.operation,
1888            assert: result.value.assert,
1889            ..Default::default()
1890        });
1891    }
1892
1893    Ok(TestResult {
1894        state: cur_state,
1895        value: test_report_test,
1896    })
1897}
1898
1899async fn run_tests<
1900    CTX: Clone + WithRequestHeaders,
1901    Client: FHIRClient<CTX, OperationOutcomeError>,
1902>(
1903    client: &Client,
1904    ctx: CTX,
1905    state: Arc<Mutex<TestState>>,
1906    pointer: TypedPointer<TestScript, Vec<TestScriptTest>>,
1907    options: Arc<TestRunnerOptions>,
1908) -> Result<TestResult<Vec<TestReportTest>>, TestScriptError> {
1909    let mut test_results = vec![];
1910    let mut cur_state = state;
1911
1912    let Some(tests) = pointer.value() else {
1913        return Ok(TestResult {
1914            state: cur_state,
1915            value: test_results,
1916        });
1917    };
1918
1919    for test in tests.iter().enumerate() {
1920        let Some(test_pointer) = pointer.descend(&Key::Index(test.0)) else {
1921            return Err(TestScriptError::ExecutionError(format!(
1922                "Failed to retrieve TestScript test at index {}.",
1923                test.0
1924            )));
1925        };
1926        let test_result = run_test(
1927            client,
1928            ctx.clone(),
1929            cur_state,
1930            test_pointer,
1931            options.clone(),
1932        )
1933        .await?;
1934        cur_state = test_result.state;
1935        test_results.push(test_result.value);
1936    }
1937
1938    Ok(TestResult {
1939        state: cur_state,
1940        value: test_results,
1941    })
1942}
1943
1944pub struct TestRunnerOptions {
1945    pub wait_between_operations: Option<Duration>,
1946    /// Before a request that reads the search index (a search, conditional
1947    /// delete or conditional update), wait up to this long for the latest
1948    /// write to be indexed. Waits only as long as indexing takes, where
1949    /// `wait_between_operations` waits a fixed time after every operation.
1950    pub index_wait_timeout: Option<Duration>,
1951}
1952
1953/// Runs a FHIR `TestScript` using the provided client and execution context.
1954///
1955/// This executes the `TestScript` lifecycle:
1956/// - fixture setup
1957/// - setup actions
1958/// - test actions
1959/// - teardown actions
1960///
1961/// # Errors
1962///
1963/// Returns [`TestScriptError`] if:
1964/// - fixture setup fails
1965/// - setup actions fail
1966/// - test execution fails
1967/// - teardown execution fails
1968/// - an operation performed by the FHIR client fails
1969#[tracing::instrument(
1970    name = "testscript_run",
1971    skip_all,
1972    fields(
1973        testscript.id = test_script.id.as_deref().unwrap_or("<no-id>"),
1974        testscript.name = test_script.name.value.as_deref().unwrap_or("<unnamed>"),
1975        testscript.url = test_script.url.value.as_deref().unwrap_or("<no-url>"),
1976    )
1977)]
1978pub async fn run<
1979    CTX: Clone + WithRequestHeaders,
1980    Client: FHIRClient<CTX, OperationOutcomeError>,
1981>(
1982    client: &Client,
1983    ctx: CTX,
1984    test_script: Arc<TestScript>,
1985    options: Arc<TestRunnerOptions>,
1986) -> Result<TestReport, TestScriptError> {
1987    tracing::info!("Starting TestScript run");
1988
1989    let mut test_report = TestReport {
1990        status: ReportStatusCodes::completed(),
1991        testScript: Box::new(Reference {
1992            reference: Some(Box::new(FHIRString {
1993                value: Some(format!(
1994                    "Testscript/{}",
1995                    test_script.id.clone().unwrap_or_default()
1996                )),
1997                ..Default::default()
1998            })),
1999            ..Default::default()
2000        }),
2001        ..Default::default()
2002    };
2003
2004    let mut state = Arc::new(Mutex::new(TestState::new()));
2005    let pointer = TypedPointer::<TestScript, TestScript>::new(test_script);
2006
2007    state = setup_fixtures(client, ctx.clone(), state, pointer.clone(), options.clone())
2008        .await
2009        .map_err(TestScriptError::OperationError)?;
2010
2011    let mut running_state = Ok(());
2012
2013    // Run setup actions
2014    if let Some(setup_pointer) =
2015        pointer.descend::<TestScriptSetup>(&Key::Field("setup".to_string()))
2016    {
2017        tracing::info!("Running TestScript setup...");
2018        let setup_result = run_setup(
2019            client,
2020            ctx.clone(),
2021            state.clone(),
2022            setup_pointer,
2023            options.clone(),
2024        )
2025        .await;
2026        match setup_result {
2027            Ok(res) => {
2028                state = res.state;
2029                test_report.setup = Some(res.value);
2030            }
2031            Err(e) => {
2032                tracing::error!(phase = "setup", error = ?e, "TestScript run failed during setup");
2033                running_state = Err(e);
2034            }
2035        }
2036    }
2037
2038    // Run Test actions
2039    if running_state.is_ok()
2040        && let Some(test_pointer) =
2041            pointer.descend::<Vec<TestScriptTest>>(&Key::Field("test".to_string()))
2042    {
2043        tracing::info!("Running TestScript tests...");
2044        let test_result = run_tests(
2045            client,
2046            ctx.clone(),
2047            state.clone(),
2048            test_pointer,
2049            options.clone(),
2050        )
2051        .await;
2052
2053        match test_result {
2054            Ok(res) => {
2055                state = res.state;
2056                test_report.test = Some(res.value);
2057            }
2058
2059            Err(e) => {
2060                tracing::error!(phase = "test", error = ?e, "TestScript run failed during test execution");
2061                running_state = Err(e);
2062            }
2063        }
2064    }
2065
2066    if let Some(teardown_pointer) =
2067        pointer.descend::<TestScriptTeardown>(&Key::Field("teardown".to_string()))
2068    {
2069        tracing::info!("Running TestScript teardown...");
2070
2071        let result = run_teardown(
2072            client,
2073            ctx.clone(),
2074            state.clone(),
2075            teardown_pointer,
2076            options.clone(),
2077        )
2078        .await?;
2079
2080        // state = result.state;
2081        test_report.teardown = Some(result.value);
2082    }
2083
2084    running_state?;
2085
2086    let state_guard = state.lock().await;
2087    // Only set result to fail so if still pending can assume pass.
2088    // Flip to fail in assertion tests if any fail.
2089    match &state_guard.result {
2090        state if state == &ReportResultCodes::pending() => {
2091            test_report.result = ReportResultCodes::pass();
2092        }
2093        status => test_report.result = status.clone(),
2094    }
2095
2096    if test_report.result == ReportResultCodes::fail() {
2097        tracing::error!(result = ?test_report.result, "TestScript run finished with failures");
2098    } else {
2099        tracing::info!(result = ?test_report.result, "TestScript run finished");
2100    }
2101
2102    Ok(test_report)
2103}
2104
2105#[cfg(test)]
2106mod tests {
2107    use super::*;
2108    use haste_fhir_client::request::{FHIRCreateResponse, FHIRDeleteInstanceResponse};
2109
2110    fn patient(id: &str, version_id: &str) -> Resource {
2111        serde_json::from_value(serde_json::json!({
2112            "resourceType": "Patient",
2113            "id": id,
2114            "meta": { "versionId": version_id }
2115        }))
2116        .expect("valid Patient")
2117    }
2118
2119    #[test]
2120    fn writes_record_the_version_search_must_return() {
2121        let created = FHIRResponse::Create(FHIRCreateResponse {
2122            resource: patient("p1", "v1"),
2123        });
2124        let write = indexed_write(&created).expect("a create is a write");
2125        assert_eq!(write.resource_type, ResourceType::Patient);
2126        assert_eq!(write.id, "p1");
2127        assert_eq!(write.version_id.as_deref(), Some("v1"));
2128
2129        // A delete must be gone from search, whatever version it was.
2130        let deleted = FHIRResponse::Delete(DeleteResponse::Instance(Box::new(
2131            FHIRDeleteInstanceResponse {
2132                resource: patient("p1", "v2"),
2133            },
2134        )));
2135        assert_eq!(
2136            indexed_write(&deleted)
2137                .expect("a delete is a write")
2138                .version_id,
2139            None
2140        );
2141    }
2142
2143    #[test]
2144    fn only_index_backed_requests_wait() {
2145        let search = FHIRRequest::Search(SearchRequest::Type(FHIRSearchTypeRequest {
2146            resource_type: ResourceType::Patient,
2147            parameters: ParsedParameters::try_from("_tag=x").unwrap(),
2148        }));
2149        assert!(reads_search_index(&search));
2150
2151        let read = FHIRRequest::Read(FHIRReadRequest {
2152            resource_type: ResourceType::Patient,
2153            id: "p1".to_string(),
2154        });
2155        assert!(!reads_search_index(&read), "a read goes to the repository");
2156    }
2157}