azure_core_test 0.1.0

Utilities for testing client libraries built on azure_core.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

//! The [`Recording`] and other types used in recorded tests.

mod policy;

// cspell:ignore csprng seedable tpbwhbkhckmk
use crate::{
    credentials::{self, MockCredential},
    proxy::{
        client::{
            ClientAddSanitizerOptions, ClientRemoveSanitizersOptions, ClientSetMatcherOptions,
        },
        models::{SanitizerList, StartPayload, VariablePayload},
        policy::RecordingPolicy,
        Proxy, ProxyExt, RecordingId,
    },
    recording::policy::RecordingModePolicy,
    Matcher, Sanitizer,
};
use azure_core::{
    base64,
    credentials::TokenCredential,
    error::ErrorKind,
    http::{
        headers::{AsHeaders, Header, HeaderName, HeaderValue},
        ClientOptions,
    },
    test::TestMode,
};
use rand::{
    distr::{Alphanumeric, Distribution, SampleString, StandardUniform},
    rngs::SysRng,
    RngExt, SeedableRng,
};
use rand_chacha::ChaCha20Rng;
use std::{
    borrow::Cow,
    collections::HashMap,
    env,
    sync::{Arc, Mutex, OnceLock, RwLock},
};
use tracing::span::EnteredSpan;

/// Represents a playback or recording session using the [`Proxy`].
#[derive(Debug)]
pub struct Recording {
    test_mode: TestMode,
    // Keep the span open for our lifetime.
    #[allow(dead_code)]
    span: EnteredSpan,
    proxy: Option<Arc<Proxy>>,
    test_mode_policy: OnceLock<Arc<RecordingModePolicy>>,
    recording_policy: OnceLock<Arc<RecordingPolicy>>,
    service_directory: String,
    recording_file: String,
    recording_assets_file: Option<String>,
    id: Option<RecordingId>,
    variables: RwLock<HashMap<String, String>>,
    rand: OnceLock<Mutex<ChaCha20Rng>>,
}

// It's not 100% clear to me that Recording is Send, but it seems to be.
// TODO: See if there's a way to remove this explicit unsafe impl.
unsafe impl Send for Recording {}

impl Recording {
    /// Adds a [`Sanitizer`] to sanitize PII for the current test.
    pub async fn add_sanitizer<S>(&self, sanitizer: S) -> azure_core::Result<()>
    where
        S: Sanitizer,
        azure_core::Error: From<<S as AsHeaders>::Error>,
    {
        let Some(client) = self.proxy.client() else {
            return Ok(());
        };

        let options = ClientAddSanitizerOptions {
            recording_id: self.id.as_ref(),
            ..Default::default()
        };
        client.add_sanitizer(sanitizer, Some(options)).await
    }

    /// Gets a [`TokenCredential`] you can use for testing.
    ///
    /// # Panics
    ///
    /// Panics if the [`TokenCredential`] could not be created.
    pub fn credential(&self) -> Arc<dyn TokenCredential> {
        match self.test_mode {
            TestMode::Playback => Arc::new(MockCredential) as Arc<dyn TokenCredential>,
            _ => credentials::from_env(None).map_or_else(
                |err| panic!("failed to create DeveloperToolsCredential: {err}"),
                |cred| cred as Arc<dyn TokenCredential>,
            ),
        }
    }

    /// Instruments the [`ClientOptions`] to support recording and playing back of session records.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use azure_core_test::{recorded, TestContext};
    ///
    /// # struct MyClient;
    /// # #[derive(Default)]
    /// # struct MyClientOptions { client_options: azure_core::http::ClientOptions };
    /// # impl MyClient {
    /// #   fn new(endpoint: impl AsRef<str>, options: Option<MyClientOptions>) -> Self { todo!() }
    /// #   async fn invoke(&self) -> azure_core::Result<()> { todo!() }
    /// # }
    /// #[recorded::test]
    /// async fn test_invoke(ctx: TestContext) -> azure_core::Result<()> {
    ///     let recording = ctx.recording();
    ///
    ///     let mut options = MyClientOptions::default();
    ///     recording.instrument(&mut options.client_options);
    ///
    ///     let client = MyClient::new("https://azure.net", Some(options));
    ///     client.invoke().await
    /// }
    /// ```
    pub fn instrument(&self, options: &mut ClientOptions) {
        let Some(client) = self.proxy.client() else {
            return;
        };

        if self.test_mode == TestMode::Playback || self.test_mode == TestMode::Record {
            let test_mode_policy = self
                .test_mode_policy
                .get_or_init(|| {
                    Arc::new(RecordingModePolicy::new(
                        self.test_mode
                            .try_into()
                            .expect("supports only `Playback` and `Record`"),
                    ))
                })
                .clone();

            options.per_call_policies.push(test_mode_policy);
        }

        let recording_policy = self
            .recording_policy
            .get_or_init(|| {
                Arc::new(RecordingPolicy {
                    test_mode: self.test_mode,
                    host: Some(client.endpoint().clone()),
                    recording_id: self.id.clone(),
                    ..Default::default()
                })
            })
            .clone();

        options.per_try_policies.push(recording_policy);
    }

    /// Update a recording with settings appropriate for a performance test.
    ///
    /// Instruments the [`ClientOptions`] to support recording and playing back of session records.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use azure_core_test::{recorded, perf::PerfTest, TestContext};
    /// # use std::sync::{OnceLock, Arc};
    /// # struct MyServiceClient;
    /// # impl MyServiceClient {
    /// #   fn new(endpoint: impl AsRef<str>, options: Option<MyServiceClientOptions>) -> Self { todo!() }
    /// #   async fn invoke(&self) -> azure_core::Result<()> { todo!() }
    /// # }
    /// # #[derive(Default)]
    /// # struct MyServiceClientOptions { client_options: azure_core::http::ClientOptions };
    /// # #[derive(Default)]
    /// # struct MyPerfTest { client: OnceLock<MyServiceClient> };
    /// #[async_trait::async_trait]
    /// impl PerfTest for MyPerfTest {
    ///   async fn setup(&self, ctx: Arc<TestContext>) -> azure_core::Result<()> {
    ///     let recording = ctx.recording();
    ///
    ///     let mut options = MyServiceClientOptions::default();
    ///     recording.instrument_perf(&mut options.client_options)?;
    ///
    ///     let client = MyServiceClient::new("https://azure.net", Some(options));
    ///     client.invoke().await
    ///   }
    ///   async fn run(&self, ctx: Arc<TestContext>) -> azure_core::Result<()>{ todo!()}
    ///   async fn cleanup(&self, ctx: Arc<TestContext>) -> azure_core::Result<()>{ todo!()}
    /// }
    /// ```
    ///
    /// Note that this function is a no-op for live tests - it only affects recorded tests
    /// in playback mode.
    ///
    pub fn instrument_perf(&self, options: &mut ClientOptions) -> azure_core::Result<()> {
        self.instrument(options);
        self.remove_recording(false)
    }

    /// Get random data from the OS or recording.
    ///
    /// This will always be the OS cryptographically secure pseudo-random number generator (CSPRNG) when running live.
    /// When recording, it will initialize from the OS CSPRNG but save the seed value to the recording file.
    /// When playing back, the saved seed value is read from the recording to reproduce the same sequence of random data.
    ///
    /// # Examples
    ///
    /// Generate a random integer.
    ///
    /// ```
    /// # let recording = azure_core_test::Recording::with_seed();
    /// let i: i32 = recording.random();
    /// # assert_eq!(i, 1054672670);
    /// ```
    ///
    /// Generate a symmetric data encryption key (DEK).
    ///
    /// ```
    /// # let recording = azure_core_test::Recording::with_seed();
    /// let dek: [u8; 32] = recording.random();
    /// # assert_eq!(azure_core::base64::encode(dek), "HumPRAN6RqKWf0YhFV2CAFWu/8L/pwh0LRzeam5VlGo=");
    /// ```
    ///
    /// Generate a UUID.
    ///
    /// ```
    /// use azure_core::Uuid;
    /// # let recording = azure_core_test::Recording::with_seed();
    /// let uuid: Uuid = Uuid::from_u128(recording.random());
    /// # assert_eq!(uuid.to_string(), "fe906b44-5838-cc8f-05e3-c7e93edd071e");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the recording variables cannot be locked for reading or writing,
    /// or if the random seed cannot be encoded or decoded properly.
    ///
    pub fn random<T>(&self) -> T
    where
        StandardUniform: Distribution<T>,
    {
        let rng = self.rng();
        let Ok(mut rng) = rng.lock() else {
            panic!("failed to lock RNG");
        };

        rng.random()
    }

    /// Generate a random string with optional prefix.
    ///
    /// This will always be the OS cryptographically secure pseudo-random number generator (CSPRNG) when running live.
    /// When recording, it will initialize from the OS CSPRNG but save the seed value to the recording file.
    /// When playing back, the saved seed value is read from the recording to reproduce the same sequence of random data.
    ///
    /// # Examples
    ///
    /// Generate a random string.
    ///
    /// ```
    /// # let recording = azure_core_test::Recording::with_seed();
    /// let id = recording.random_string::<12>(Some("t")).to_ascii_lowercase();
    /// # assert_eq!(id, "tpbwhbkhckmk");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the recording variables cannot be locked for reading or writing,
    /// if the random seed cannot be encoded or decoded properly,
    /// if `LEN` is 0,
    /// or if the length of `prefix` is greater than or equal to `LEN`.
    ///
    /// ```should_panic
    /// # let recording = azure_core_test::Recording::with_seed();
    /// let vault_name = recording.random_string::<8>(Some("keyvault"));
    /// ```
    ///
    pub fn random_string<const LEN: usize>(&self, prefix: Option<&str>) -> String {
        struct NonZero<const N: usize>;
        impl<const N: usize> NonZero<N> {
            const ASSERT: () = assert!(N > 0, "LEN must be greater than 0");
        }
        #[allow(clippy::let_unit_value)]
        let _ = NonZero::<LEN>::ASSERT;
        let len = match prefix {
            Some(p) => {
                assert!(p.len() < LEN, "prefix length must be less than LEN");
                LEN - p.len()
            }
            None => LEN,
        };

        let rng = self.rng();
        let Ok(mut rng) = rng.lock() else {
            panic!("failed to lock RNG");
        };

        let value = Alphanumeric.sample_string(&mut *rng, len);
        match prefix {
            Some(prefix) => prefix.to_string() + &value,
            None => value.to_string(),
        }
    }
    /// Removes the list of sanitizers from the recording.
    ///
    /// You can find a list of default sanitizers in [source code](https://github.com/Azure/azure-sdk-tools/blob/main/tools/test-proxy/Azure.Sdk.Tools.TestProxy/Common/SanitizerDictionary.cs).
    pub async fn remove_sanitizers(&self, sanitizers: &[&str]) -> azure_core::Result<()> {
        let Some(client) = self.proxy.client() else {
            return Ok(());
        };

        let body = SanitizerList {
            sanitizers: Vec::from_iter(sanitizers.iter().map(|s| String::from(*s))),
        };
        let options = ClientRemoveSanitizersOptions {
            recording_id: self.id.as_ref(),
            ..Default::default()
        };
        client
            .remove_sanitizers(body.try_into()?, Some(options))
            .await?;

        Ok(())
    }

    /// Sets a [`Matcher`] to compare requests and/or responses.
    pub async fn set_matcher(&self, matcher: Matcher) -> azure_core::Result<()> {
        let Some(client) = self.proxy.client() else {
            return Ok(());
        };

        let options = ClientSetMatcherOptions {
            recording_id: self.id.as_ref(),
            ..Default::default()
        };
        client.set_matcher(matcher, Some(options)).await
    }

    /// Skip recording the request body, or the entire request and response until the [`SkipGuard`] is dropped.
    ///
    /// This only affects [`TestMode::Record`] mode and is intended for cleanup.
    /// When [`Recording::test_mode()`] is [`TestMode::Playback`] you should avoid sending those requests.
    pub fn skip(&self, skip: Skip) -> azure_core::Result<SkipGuard<'_>> {
        self.set_skip(Some(skip))?;
        Ok(SkipGuard(self))
    }

    pub(crate) fn remove_recording(&self, remove: bool) -> azure_core::Result<()> {
        self.set_remove_recording(Some(remove))?;
        Ok(())
    }

    /// Gets the current [`TestMode`].
    pub fn test_mode(&self) -> TestMode {
        self.test_mode
    }

    /// Gets a required variable from the environment or recording.
    pub fn var<K>(&self, key: K, options: Option<VarOptions>) -> String
    where
        K: AsRef<str>,
    {
        let key = key.as_ref();
        self.var_opt(key, options)
            .unwrap_or_else(|| panic!("{key} is not set"))
    }

    /// Gets an optional variable from the environment or recording.
    pub fn var_opt<K>(&self, key: K, options: Option<VarOptions>) -> Option<String>
    where
        K: AsRef<str>,
    {
        let key = key.as_ref();
        if self.test_mode == TestMode::Playback {
            let variables = self.variables.read().map_err(read_lock_error).ok()?;
            return variables.get(key).cloned();
        }

        // Get the environment variable or, if unset (None), the optional VarOptions::default_value.
        let options = options.unwrap_or_default();
        let (value, sanitized) = options.apply(self.env(key));

        if self.test_mode == TestMode::Live {
            return value;
        }

        // Do not record unset (None) environment variables.
        if let Some(sanitized) = sanitized {
            let mut variables = self.variables.write().map_err(write_lock_error).ok()?;
            variables.insert(key.into(), sanitized);
        }

        value
    }
}

const RANDOM_SEED_NAME: &str = "RandomSeed";

impl Recording {
    pub(crate) fn new(
        test_mode: TestMode,
        span: EnteredSpan,
        proxy: Option<Arc<Proxy>>,
        service_directory: &'static str,
        recording_file: String,
        recording_assets_file: Option<String>,
    ) -> Self {
        Self {
            test_mode,
            span,
            proxy,
            test_mode_policy: OnceLock::new(),
            recording_policy: OnceLock::new(),
            service_directory: service_directory.into(),
            recording_file,
            recording_assets_file,
            id: None,
            variables: RwLock::new(HashMap::new()),
            rand: OnceLock::new(),
        }
    }

    // #[cfg(any(test, doctest))] // BUGBUG: https://github.com/rust-lang/rust/issues/67295
    #[doc(hidden)]
    pub fn with_seed() -> Self {
        let span = tracing::trace_span!("Recording::with_seed");
        Self {
            test_mode: TestMode::Playback,
            span: span.entered(),
            proxy: None,
            test_mode_policy: OnceLock::new(),
            recording_policy: OnceLock::new(),
            service_directory: String::from("sdk/core"),
            recording_file: String::from("none"),
            recording_assets_file: None,
            id: None,
            variables: RwLock::new(HashMap::from([(
                RANDOM_SEED_NAME.into(),
                (&"test8S9UCR2yV8LU01tq+VNEwGssAXVUbL0Hd488GAYVosM="[4..]).into(), // Prefix but then drop is to avoid CredScan false positives
            )])),
            rand: OnceLock::new(),
        }
    }

    fn env<K>(&self, key: K) -> Option<String>
    where
        K: AsRef<str>,
    {
        const AZURE_PREFIX: &str = "AZURE_";

        env::var_os(self.service_directory.clone() + "_" + key.as_ref())
            .or_else(|| env::var_os(key.as_ref()))
            .or_else(|| env::var_os(String::from(AZURE_PREFIX) + key.as_ref()))
            .and_then(|value| value.into_string().ok())
    }

    fn rng(&self) -> &Mutex<ChaCha20Rng> {
        // Use ChaCha20 for a deterministic, portable CSPRNG.
        self.rand.get_or_init(|| match self.test_mode {
            TestMode::Live => ChaCha20Rng::try_from_rng(&mut SysRng).unwrap().into(),
            TestMode::Playback => {
                let variables = self
                    .variables
                    .read()
                    .map_err(read_lock_error)
                    .unwrap_or_else(|err| panic!("{err}"));
                let seed = variables
                    .get(RANDOM_SEED_NAME)
                    .unwrap_or_else(|| panic!("random seed variable not set"));
                let seed = base64::decode(seed)
                    .unwrap_or_else(|err| panic!("failed to decode random seed: {err}"));
                let seed = seed
                    .first_chunk::<32>()
                    .unwrap_or_else(|| panic!("insufficient random seed variable"));

                ChaCha20Rng::from_seed(*seed).into()
            }
            TestMode::Record => {
                let rng = ChaCha20Rng::try_from_rng(&mut SysRng).unwrap();
                let seed = rng.get_seed();
                let seed = base64::encode(seed);

                let mut variables = self
                    .variables
                    .write()
                    .map_err(write_lock_error)
                    .unwrap_or_else(|err| panic!("{err}"));
                variables.insert(RANDOM_SEED_NAME.to_string(), seed);

                rng.into()
            }
        })
    }

    fn set_skip(&self, skip: Option<Skip>) -> azure_core::Result<()> {
        let Some(policy) = self.recording_policy.get() else {
            return Ok(());
        };

        let mut options = policy
            .options
            .write()
            .map_err(|err| azure_core::Error::with_message(ErrorKind::Other, err.to_string()))?;
        options.skip = skip;

        Ok(())
    }

    fn set_remove_recording(&self, remove: Option<bool>) -> azure_core::Result<()> {
        let Some(policy) = self.recording_policy.get() else {
            return Ok(());
        };

        let mut options = policy
            .options
            .write()
            .map_err(|err| azure_core::Error::with_message(ErrorKind::Other, err.to_string()))?;
        options.remove_recording = remove;

        Ok(())
    }

    /// Starts recording or playback.
    ///
    /// If playing back a recording, environment variable that were recorded will be reloaded.
    pub(crate) async fn start(&mut self) -> azure_core::Result<()> {
        let Some(client) = self.proxy.client() else {
            // Assumes running live test.
            return Ok(());
        };

        let payload = StartPayload {
            recording_file: self.recording_file.clone(),
            recording_assets_file: self.recording_assets_file.clone(),
        };

        // TODO: Should RecordingId be used everywhere and models implement AsHeaders and FromHeaders?
        let recording_id = match self.test_mode {
            TestMode::Playback => {
                let result = client.playback_start(payload.try_into()?, None).await?;
                let mut variables = self.variables.write().map_err(write_lock_error)?;
                variables.extend(result.variables);

                result.recording_id
            }
            TestMode::Record => {
                client
                    .record_start(payload.try_into()?, None)
                    .await?
                    .recording_id
            }
            mode => panic!("{mode:?} not supported"),
        };
        self.id = Some(recording_id.parse()?);

        Ok(())
    }

    /// Stops the recording or playback.
    ///
    /// If recording, environment variables that were retrieved will be recorded.
    pub(crate) async fn stop(&self) -> azure_core::Result<()> {
        let Some(client) = self.proxy.client() else {
            // Assumes running live test.
            return Ok(());
        };

        let Some(recording_id) = self.id.as_ref() else {
            // Do not return an error or we hide any test-proxy client or client under test error.
            return Ok(());
        };

        match self.test_mode {
            TestMode::Playback => client.playback_stop(recording_id.as_ref(), None).await,
            TestMode::Record => {
                let payload = {
                    let variables = self.variables.read().map_err(read_lock_error)?;
                    VariablePayload {
                        variables: HashMap::from_iter(
                            variables
                                .iter()
                                .map(|(k, value)| (k.clone(), value.clone())),
                        ),
                    }
                };
                client
                    .record_stop(recording_id.as_ref(), payload.try_into()?, None)
                    .await
            }
            mode => panic!("{mode:?} not supported"),
        }
    }
}

impl Drop for Recording {
    /// Stops the recording or playback.
    fn drop(&mut self) {
        futures::executor::block_on(self.stop()).unwrap_or_else(|err| panic!("{err}"));
    }
}

fn read_lock_error(_: impl std::error::Error) -> azure_core::Error {
    azure_core::Error::with_message(ErrorKind::Other, "failed to lock variables for read")
}

fn write_lock_error(_: impl std::error::Error) -> azure_core::Error {
    azure_core::Error::with_message(ErrorKind::Other, "failed to lock variables for write")
}

/// What to skip when recording to a file.
///
/// This only affects [`TestMode::Record`] mode and is intended for cleanup.
/// When [`Recording::test_mode()`] is [`TestMode::Playback`] you should avoid sending those requests.
#[derive(Debug)]
pub enum Skip {
    /// Skip recording only the request body.
    RequestBody,

    /// Skip recording both the request and response entirely.
    RequestResponse,
}

impl Header for Skip {
    fn name(&self) -> HeaderName {
        HeaderName::from_static("x-recording-skip")
    }

    fn value(&self) -> HeaderValue {
        match self {
            Self::RequestBody => HeaderValue::from_static("request-body"),
            Self::RequestResponse => HeaderValue::from_static("request-response"),
        }
    }
}

/// When the `SkipGuard` is dropped, recording requests and responses will begin again.
///
/// Returned from [`Recording::skip()`].
pub struct SkipGuard<'a>(&'a Recording);

impl Drop for SkipGuard<'_> {
    fn drop(&mut self) {
        if self.0.test_mode == TestMode::Record {
            let _ = self.0.set_skip(None);
        }
    }
}

/// Whether to remove records during recording playback.
///
/// This option is used for test recordings, if true, the recording will be removed from the test-proxy when retrieved,
/// otherwise it will be kept. The default is true.
///
#[derive(Debug)]
pub struct RemoveRecording(pub bool);

impl Header for RemoveRecording {
    fn name(&self) -> HeaderName {
        HeaderName::from_static("x-recording-remove")
    }

    fn value(&self) -> HeaderValue {
        HeaderValue::from_static(if self.0 { "true" } else { "false" })
    }
}

/// Options for getting variables from a [`Recording`].
#[derive(Clone, Debug)]
pub struct VarOptions {
    /// The value to return if not already recorded.
    pub default_value: Option<Cow<'static, str>>,

    /// Whether to sanitize the variable value with [`VarOptions::sanitize_value`].
    pub sanitize: bool,

    /// The value to use for sanitized variables.
    ///
    /// The default is "Sanitized".
    pub sanitize_value: Cow<'static, str>,
}

impl VarOptions {
    /// Returns a tuple of the `value` or [`VarOptions::default_value`], and the sanitized value.
    ///
    /// The `value` is only replaced with the `VarOptions::default_value` if `None`. This is returned as the first tuple field.
    ///
    /// The [`VarOptions::sanitize_value`] is only `Some` if [`VarOptions::sanitize`] is `true`. This is returned as the second tuple field.
    fn apply<S: Into<String>>(self, value: Option<S>) -> (Option<String>, Option<String>) {
        let value = value.map_or_else(
            || self.default_value.as_deref().map(ToString::to_string),
            |value| Some(value.into()),
        );
        let sanitized = match value.as_deref() {
            None => None,
            Some(_) if self.sanitize => Some(self.sanitize_value.to_string()),
            Some(v) => Some(v.to_string()),
        };
        (value, sanitized)
    }
}

impl Default for VarOptions {
    fn default() -> Self {
        Self {
            default_value: None,
            sanitize: false,
            sanitize_value: Cow::Borrowed(crate::DEFAULT_SANITIZED_VALUE),
        }
    }
}

#[test]
fn test_var_options_apply() {
    let (value, ..) = VarOptions::default().apply(None::<String>);
    assert_eq!(value, None);

    let (value, ..) = VarOptions::default().apply(Some("".to_string()));
    assert_eq!(value, Some(String::new()));

    let (value, ..) = VarOptions::default().apply(Some("test".to_string()));
    assert_eq!(value, Some("test".into()));

    let (value, ..) = VarOptions {
        default_value: None,
        ..Default::default()
    }
    .apply(None::<String>);
    assert_eq!(value, None);

    let (value, ..) = VarOptions {
        default_value: Some("".into()),
        ..Default::default()
    }
    .apply(None::<String>);
    assert_eq!(value, Some("".into()));

    let (value, ..) = VarOptions {
        default_value: Some("test".into()),
        ..Default::default()
    }
    .apply(None::<String>);
    assert_eq!(value, Some("test".into()));

    let (value, ..) = VarOptions {
        default_value: Some("default".into()),
        ..Default::default()
    }
    .apply(Some("".to_string()));
    assert_eq!(value, Some("".into()));

    let (value, ..) = VarOptions {
        default_value: Some("default".into()),
        ..Default::default()
    }
    .apply(Some("test".to_string()));
    assert_eq!(value, Some("test".into()));
}

#[test]
fn test_var_options_apply_sanitized() {
    let (value, sanitized) = VarOptions::default().apply(None::<String>);
    assert_eq!(value, None);
    assert_eq!(sanitized, None);

    let (value, sanitized) = VarOptions {
        sanitize: true,
        ..Default::default()
    }
    .apply(None::<String>);
    assert_eq!(value, None);
    assert_eq!(sanitized, None);

    let (value, sanitized) = VarOptions {
        sanitize: true,
        ..Default::default()
    }
    .apply(Some("".to_string()));
    assert_eq!(value, Some("".to_string()));
    assert_eq!(sanitized, Some("Sanitized".into()));

    let (value, sanitized) = VarOptions {
        sanitize: true,
        ..Default::default()
    }
    .apply(Some("test".to_string()));
    assert_eq!(value, Some("test".to_string()));
    assert_eq!(sanitized, Some("Sanitized".into()));

    let (value, sanitized) = VarOptions {
        sanitize: true,
        sanitize_value: "*****".into(),
        ..Default::default()
    }
    .apply(None::<String>);
    assert_eq!(value, None);
    assert_eq!(sanitized, None);

    let (value, sanitized) = VarOptions {
        sanitize: true,
        sanitize_value: "*****".into(),
        ..Default::default()
    }
    .apply(Some("".to_string()));
    assert_eq!(value, Some("".to_string()));
    assert_eq!(sanitized, Some("*****".into()));

    let (value, sanitized) = VarOptions {
        sanitize: true,
        sanitize_value: "*****".into(),
        ..Default::default()
    }
    .apply(Some("test".to_string()));
    assert_eq!(value, Some("test".to_string()));
    assert_eq!(sanitized, Some("*****".into()));
}