// Stashing these here for now, will resurrect eventually...
// #[cfg(test)]
// mod tests {
//     use mockito::Matcher;
//     use serde_json::Value;
//     use std::{
//         collections::HashMap,
//         sync::Arc,
//         thread::sleep,
//         time::{Duration, Instant},
//     };
//     use tokio::task::JoinSet;
//     use tokio_util::sync::CancellationToken;

//     use super::{ApicizeExecution, ApicizeExecutionItem, ApicizeResponse};
//     use crate::{
//         execution::test_runner::{dispatch_request, execute_request_test}, oauth2_client_tokens::TokenResult, ApicizeError, Certificate, IndexedEntities, IndexedRequests, NameValuePair, Proxy, Request, RequestEntry, RequestMethod, Workspace
//     };

//     use crate::oauth2_client_tokens::tests::MockOAuth2ClientTokens;

//     #[tokio::test]
//     async fn dispatch_requests_and_handles_bad_domain() {
//         let request = Request {
//             id: String::from(""),
//             name: String::from("test"),
//             url: String::from("https://foofooxxxxxx/"),
//             method: Some(RequestMethod::Post),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: None,
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };
//         let response =
//             dispatch_request(&request, &HashMap::new(), None, None, None, None, None).await;
//         match &response {
//             Ok(_) => {}
//             Err(err) => {
//                 println!("{}: {}", err.get_label(), err);
//             }
//         }
//         assert!(response.is_err());
//     }

//     #[tokio::test]
//     async fn dispatch_requests_and_handles_timeout() {
//         let mut server = mockito::Server::new_async().await;
//         let mock = server
//             .mock("GET", "/")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_chunked_body(|_| {
//                 sleep(Duration::from_secs(1));
//                 Ok({})
//             })
//             .create();

//         let request = Request {
//             id: String::from(""),
//             name: String::from("test"),
//             url: server.url(),
//             method: Some(RequestMethod::Get),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: Some(1),
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };
//         let response =
//             dispatch_request(&request, &HashMap::new(), None, None, None, None, None).await;
//         match &response {
//             Ok(_) => {}
//             Err(err) => {
//                 println!("{}: {}", err.get_label(), err);
//             }
//         }
//         assert!(response.is_err());
//         mock.assert();
//     }

//     #[tokio::test]
//     async fn dispatch_requests_with_substituted_variables() {
//         let mut server = mockito::Server::new_async().await;
//         let mock = server
//             .mock("POST", "/test")
//             .match_query(Matcher::AllOf(vec![Matcher::UrlEncoded(
//                 "abc".into(),
//                 "123".into(),
//             )]))
//             .match_header("xxx", "zzz")
//             .match_body("foo")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_body("ok")
//             .create();

//         let request = Request {
//             id: String::from(""),
//             name: String::from("test"),
//             url: server.url() + "/{{page}}",
//             method: Some(RequestMethod::Post),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: None,
//             keep_alive: None,
//             runs: 1,
//             headers: Some(vec![NameValuePair {
//                 name: String::from("xxx"),
//                 value: String::from("{{xxx}}"),
//                 disabled: None,
//             }]),
//             query_string_params: Some(vec![NameValuePair {
//                 name: String::from("abc"),
//                 value: String::from("{{abc}}"),
//                 disabled: None,
//             }]),
//             body: Some(crate::RequestBody::Text {
//                 data: String::from("{{stuff}}"),
//             }),
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let variables = HashMap::from([
//             (String::from("page"), Value::from("test")),
//             (String::from("abc"), Value::from("123")),
//             (String::from("xxx"), Value::from("zzz")),
//             (String::from("stuff"), Value::from("foo")),
//         ]);
//         let response = dispatch_request(&request, &variables, None, None, None, None, None).await;
//         mock.assert();
//         assert_eq!(response.unwrap().1.status, 200);
//     }

//     #[tokio::test]
//     async fn dispatch_requests_with_basic_auth() {
//         let mut server = mockito::Server::new_async().await;
//         let mock = server
//             .mock("POST", "/test")
//             .match_header("Authorization", "Basic bmFtZTpzaGho")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_body("ok")
//             .create();

//         let request = Request {
//             id: String::from(""),
//             name: String::from("test"),
//             url: server.url() + "/test",
//             method: Some(RequestMethod::Post),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: None,
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let response = dispatch_request(
//             &request,
//             &HashMap::new(),
//             Some(&crate::Authorization::Basic {
//                 id: String::from(""),
//                 name: String::from(""),
//                 username: String::from("name"),
//                 password: String::from("shhh"),
//             }),
//             None,
//             None,
//             None,
//             None,
//         )
//         .await;
//         mock.assert();
//         assert_eq!(response.unwrap().1.status, 200);
//     }

//     #[tokio::test]
//     async fn dispatch_requests_with_api_key_auth() {
//         let mut server = mockito::Server::new_async().await;
//         let mock = server
//             .mock("POST", "/test")
//             .match_header("x-api-key", "abc")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_body("ok")
//             .create();

//         let request = Request {
//             id: String::from(""),
//             name: String::from("test"),
//             url: server.url() + "/test",
//             method: Some(RequestMethod::Post),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: None,
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let response = dispatch_request(
//             &request,
//             &HashMap::new(),
//             Some(&crate::Authorization::ApiKey {
//                 id: String::from(""),
//                 name: String::from(""),
//                 header: String::from("x-api-key"),
//                 value: String::from("abc"),
//             }),
//             None,
//             None,
//             None,
//             None,
//         )
//         .await;
//         mock.assert();
//         assert_eq!(response.unwrap().1.status, 200);
//     }

//     #[tokio::test]
//     async fn dispatch_requests_with_oauth2_auth() {
//         let mut server = mockito::Server::new_async().await;
//         let mock = server
//             .mock("POST", "/test")
//             .match_header("authorization", "Bearer ***TOKEN***")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_body("ok")
//             .create();

//         let request = Request {
//             id: String::from(""),
//             name: String::from("test"),
//             url: server.url() + "/test",
//             method: Some(RequestMethod::Post),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: None,
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let oauth2_context = MockOAuth2ClientTokens::get_oauth2_client_credentials_context();
//         oauth2_context
//             .expect()
//             .withf(
//                 |id, url, _client_id, _client_secret, _scope, _certificaite, _proxy| {
//                     id == String::from("11111") && url == String::from("https://server")
//                 },
//             )
//             .returning(
//                 |_id: &str,
//                  _token_url: &str,
//                  _client_id: &str,
//                  _client_secret: &str,
//                  _scope: &Option<String>,
//                  _certificate: Option<&Certificate>,
//                  _proxy: Option<&Proxy>| {
//                     Ok(TokenResult {
//                         token: String::from("***TOKEN***"),
//                         cached: true,
//                         url: None,
//                         certificate: None,
//                         proxy: None,
//                     })
//                 },
//             );

//         let response = dispatch_request(
//             &request,
//             &HashMap::new(),
//             Some(&crate::Authorization::OAuth2Client {
//                 id: String::from("11111"),
//                 name: String::from("My Token"),
//                 access_token_url: String::from("https://server"),
//                 client_id: String::from("me"),
//                 client_secret: String::from("shhh"),
//                 scope: Some(String::from("x")),
//                 selected_certificate: None,
//                 selected_proxy: None,
//             }),
//             None,
//             None,
//             None,
//             None,
//         )
//         .await;
//         mock.assert();
//         assert_eq!(response.unwrap().1.status, 200);
//     }

//     #[tokio::test]
//     async fn execute_request_test_runs_test() {
//         let request = Request {
//             id: String::from("xxx"),
//             name: String::from("xxx"),
//             test: Some(String::from("describe('test', () => { it('runs', () => { expect(response.status).to.equal(200) }) })")),
//             url: String::from("http://foo"),
//             method: Some(RequestMethod::Get),
//             timeout: Some(5000),
//             headers: None,
//             query_string_params: None,
//             body: None,
//             keep_alive: None,
//             runs: 1,
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let response = ApicizeResponse {
//             status: 200,
//             status_text: String::from("Ok"),
//             headers: None,
//             body: None,
//             oauth2_token: None,
//         };

//         let variables: HashMap<String, Value> = HashMap::new();

//         let tests_started = Arc::new(Instant::now());

//         let result = execute_request_test(&request, &response, &variables, &tests_started);

//         let mut successes = 0;
//         let mut failures = 0;
//         for test_result in result.unwrap().unwrap().results.unwrap().iter() {
//             // if let Some(logs) = &test_result.logs {
//             //     println!("Logs: {}", logs.join("; "));
//             // }
//             // if let Some(error) = &test_result.error {
//             //     println!("Error: {}", error);
//             // }

//             if test_result.success {
//                 successes += 1;
//             } else {
//                 failures += 1;
//             }
//         }

//         assert_eq!(successes, 1);
//         assert_eq!(failures, 0);
//     }

//     #[tokio::test]
//     async fn execute_request_test_includes_jsonpath() {
//         let request = Request {
//             id: String::from("xxx"),
//             name: String::from("xxx"),
//             test: Some(String::from("describe('test', () => { it('works', () => { var foo = { \"abc\": 123 }; expect(jsonpath('$.abc', foo)[0]).to.equal(123) }) })")),
//             url: String::from("http://foo"),
//             method: Some(RequestMethod::Get),
//             timeout: Some(5000),
//             headers: None,
//             query_string_params: None,
//             body: None,
//             keep_alive: None,
//             runs: 1,
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let response = ApicizeResponse {
//             status: 200,
//             status_text: String::from("Ok"),
//             headers: None,
//             body: None,
//             oauth2_token: None,
//         };

//         let variables: HashMap<String, Value> = HashMap::new();

//         let tests_started = Arc::new(Instant::now());

//         let result = execute_request_test(&request, &response, &variables, &tests_started);

//         let mut successes = 0;
//         let mut failures = 0;
//         for test_result in result.unwrap().unwrap().results.unwrap().iter() {
//             // if let Some(logs) = &test_result.logs {
//             //     println!("Logs: {}", logs.join("; "));
//             // }
//             // if let Some(error) = &test_result.error {
//             //     println!("Error: {}", error);
//             // }
//             if test_result.success {
//                 successes += 1;
//             } else {
//                 failures += 1;
//             }
//         }

//         assert_eq!(successes, 1);
//         assert_eq!(failures, 0);
//     }

//     #[tokio::test]
//     async fn execute_request_test_includes_xpath() {
//         let request = Request {
//             id: String::from("xxx"),
//             name: String::from("xxx"),
//             test: Some(String::from("describe('test', () => { it('works', () => { const xml = \"<foo><bar>test</bar></foo>\"; const doc = new dom().parseFromString(xml, 'text/xml'); expect(xpath.select('//bar', doc)[0].firstChild.data).to.equal('test') }) })")),
//             url: String::from("http://foo"),
//             method: Some(RequestMethod::Get),
//             timeout: Some(5000),
//             headers: None,
//             query_string_params: None,
//             body: None,
//             keep_alive: None,
//             runs: 1,
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         };

//         let response = ApicizeResponse {
//             status: 200,
//             status_text: String::from("Ok"),
//             headers: None,
//             body: None,
//             oauth2_token: None,
//         };

//         let variables: HashMap<String, Value> = HashMap::new();

//         let tests_started = Arc::new(Instant::now());

//         let result = execute_request_test(&request, &response, &variables, &tests_started);

//         let mut successes = 0;
//         let mut failures = 0;
//         for test_result in result.unwrap().unwrap().results.unwrap().iter() {
//             // if let Some(logs) = &test_result.logs {
//             //     println!("Logs: {}", logs.join("; "));
//             // }
//             // if let Some(error) = &test_result.error {
//             //     println!("Error: {}", error);
//             // }
//             if test_result.success {
//                 successes += 1;
//             } else {
//                 failures += 1;
//             }
//         }

//         assert_eq!(successes, 1);
//         assert_eq!(failures, 0);
//     }

//     async fn wait_and_cancel(
//         cancellation: CancellationToken,
//     ) -> Result<ApicizeExecution, ApicizeError> {
//         sleep(Duration::from_millis(10));
//         cancellation.cancel();
//         Ok(ApicizeExecution {
//             duration: 0,
//             items: vec![],
//             success: false,
//             requests_with_passed_tests_count: 0,
//             requests_with_failed_tests_count: 0,
//             requests_with_errors: 0,
//             test_pass_count: 0,
//             test_fail_count: 0,
//         })
//     }

//     #[tokio::test]
//     async fn run_honors_override_number_of_runs() {
//         let mut server = mockito::Server::new_async().await;
//         server
//             .mock("GET", "/")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_body("Ok")
//             .create();

//         let request = RequestEntry::Info(Request {
//             id: String::from("123"),
//             name: String::from("test"),
//             url: server.url(),
//             method: Some(RequestMethod::Get),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: Some(500),
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         });

//         let workspace = Workspace {
//             requests: IndexedRequests {
//                 top_level_ids: vec![String::from("123")],
//                 entities: HashMap::from([(String::from("123"), request)]),
//                 child_ids: None,
//             },
//             scenarios: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             authorizations: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             certificates: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             proxies: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             defaults: None,
//             warnings: None,
//         };

//         let tests_started = Arc::new(Instant::now());
//         let cancellation = CancellationToken::new();

//         let attempt = super::run(
//             Arc::new(workspace),
//             Some(vec![String::from("123")]),
//             Some(cancellation.clone()),
//             tests_started,
//             Some(4),
//         )
//         .await;

//         let runs = if let ApicizeExecutionItem::Request(result) =
//             attempt.unwrap().items.first().unwrap()
//         {
//             result.runs.len()
//         } else {
//             0
//         };
//         assert_eq!(runs, 4)
//     }

//     #[tokio::test]
//     async fn run_honors_cancel() {
//         let mut server = mockito::Server::new_async().await;
//         server
//             .mock("GET", "/")
//             .with_status(200)
//             .with_header("Content-Type", "text/plain")
//             .with_chunked_body(|_| {
//                 sleep(Duration::from_secs(5000));
//                 Ok({})
//             })
//             .create();

//         let request = RequestEntry::Info(Request {
//             id: String::from("123"),
//             name: String::from("test"),
//             url: server.url(),
//             method: Some(RequestMethod::Get),
//             multi_run_execution: crate::ExecutionConcurrency::Sequential,
//             timeout: Some(60000),
//             keep_alive: None,
//             runs: 1,
//             headers: None,
//             query_string_params: None,
//             body: None,
//             test: None,
//             selected_scenario: None,
//             selected_authorization: None,
//             selected_certificate: None,
//             selected_proxy: None,
//             warnings: None,
//         });

//         let workspace = Workspace {
//             requests: IndexedRequests {
//                 top_level_ids: vec![String::from("123")],
//                 entities: HashMap::from([(String::from("123"), request)]),
//                 child_ids: None,
//             },
//             scenarios: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             authorizations: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             certificates: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             proxies: IndexedEntities {
//                 top_level_ids: vec![],
//                 entities: HashMap::new(),
//             },
//             defaults: None,
//             warnings: None,
//         };

//         let tests_started = Arc::new(Instant::now());
//         let cancellation = CancellationToken::new();

//         let mut results: JoinSet<Result<ApicizeExecution, ApicizeError>> = JoinSet::new();

//         let attempt = super::run(
//             Arc::new(workspace),
//             Some(vec![String::from("123")]),
//             Some(cancellation.clone()),
//             tests_started,
//             None,
//         );

//         results.spawn(attempt);
//         let cloned_cancellation = cancellation.clone();
//         results.spawn(wait_and_cancel(cloned_cancellation));

//         let completed_results = results.join_all().await;
//         let has_cancelled_result = completed_results
//             .iter()
//             .any(|r| r.as_ref().is_err_and(|err| err.get_label() == "Cancelled"));
//         assert!(has_cancelled_result);
//     }
// }

