envtest 0.2.0

A lightweight, type‑safe wrapper around the Kubernetes `envtest` Go package that lets you spin up a temporary control plane from Rust.
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
//! Helpers for creating short-lived Kubernetes envtest environments from Rust.
//!
//! # Examples
//!
//! ```rust
//! # tokio_test::block_on(async {
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let server = envtest::Environment::default().create().await?;
//! # #[cfg(not(feature = "_docsrs"))]
//! assert!(server.exist());
//! # #[cfg(feature = "kube")]
//! # {
//! let _ = server.kubeconfig()?;
//! let client = server.client()?;
//! let _ = client.apiserver_version().await?;
//! # }
//! server.destroy().await?;
//! # Ok(())
//! # }
//! # run().await.unwrap();
//! # })
//! ```
#[cfg(not(feature = "_docsrs"))]
pub mod binding {
    #![allow(warnings, errors)]
    rust2go::r2g_include_binding!();
}

/// Public API for managing a temporary Kubernetes environment.
///
/// This trait provides a bridge between Rust and Go for creating and destroying
/// temporary Kubernetes environments. Implementations of this trait are
/// generated by the `rust2go` crate on the Go side, allowing Rust code to
/// interact with Go-based test infrastructure.
#[cfg(not(feature = "_docsrs"))]
#[rust2go::r2g]
trait EnvTest {
    fn create(req: Environment) -> CreateResponse;
    fn exist(kubeconfig: String) -> bool;
    fn destroy(kubeconfig: String) -> DestroyResponse;
}

#[derive(Default)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
struct CreateResponse {
    err: Option<String>,
    error_type: Option<u8>,
    server: Server,
}

/// Response returned from [`EnvTest::destroy`].
#[derive(Default)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
struct DestroyResponse {
    err: Option<String>,
    error_type: Option<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
enum CreateErrorType {
    SetupBinaryAssetsDirectory = 0,
    DecodeCrd = 1,
    StartEnvironment = 2,
    BuildKubeconfig = 3,
    StopEnvironment = 4,
    #[default]
    Generic = 5,
}

impl From<u8> for CreateErrorType {
    fn from(value: u8) -> Self {
        match value {
            0 => Self::SetupBinaryAssetsDirectory,
            1 => Self::DecodeCrd,
            2 => Self::StartEnvironment,
            3 => Self::BuildKubeconfig,
            4 => Self::StopEnvironment,
            _ => Self::default(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
enum DestroyErrorType {
    EnvMissing = 0,
    #[default]
    StopEnvironment = 1,
}

impl From<u8> for DestroyErrorType {
    fn from(value: u8) -> Self {
        match value {
            0 => Self::EnvMissing,
            _ => Self::default(),
        }
    }
}

/// Errors that can occur while creating an environment.
#[derive(thiserror::Error, Debug)]
pub enum EnvironmentError {
    #[error("Environment create error: {0}")]
    Create(String),
    #[error("Setup binary assets directory error: {0}")]
    SetupBinaryAssetsDirectory(String),
    #[error("CRD decode error: {0}")]
    DecodeCrd(String),
    #[error("Start environment error: {0}")]
    StartEnvironment(String),
    #[error("Build kubeconfig error: {0}")]
    BuildKubeconfig(String),
    #[error("Stop environment error: {0}")]
    StopEnvironment(String),
    #[error("CRD serialization error: {0}")]
    CrdSerialize(#[from] serde_json::Error),
    #[error("Unsupported CRD type. Expected object, or array of those.")]
    UnsupportedCrdType,
}

/// Represents a request to create a test environment.
///
/// # Examples
///
/// ```rust
/// # tokio_test::block_on(async {
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let env = envtest::Environment::default();
/// let server = env.create().await?;
/// server.destroy().await?;
/// # Ok(())
/// # }
/// # run().await.unwrap()
/// # })
/// ```
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
pub struct Environment {
    /// `crd_install_options` are the options for installing CRDs.
    pub crd_install_options: CRDInstallOptions,

    /// `binary_assets_settings` are the settings for downloading and using binary assets.
    pub binary_assets_settings: BinaryAssetsSettings,
}

/// Binary asset configuration used while starting an envtest control plane.
///
/// # Examples
///
/// ```rust
/// let settings = envtest::BinaryAssetsSettings {
///     download_binary_assets: false,
///     binary_assets_directory: Some("/tmp/envtest-assets".to_owned()),
///     ..Default::default()
/// };
///
/// assert!(!settings.download_binary_assets);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
pub struct BinaryAssetsSettings {
    /// `download_binary_assets` indicates that the envtest binaries should be downloaded.
    /// If `BinaryAssetsDirectory` is also set, it is used to store the downloaded binaries,
    /// otherwise a tmp directory is created.
    ///
    /// We default to downloading the binaries to ensure the environment can be created without
    /// additional configuration, but this can be set to `false` when the binaries are already
    /// available in the environment via [`BinaryAssetsSettings::binary_assets_directory`] or `KUBEBUILDER_ASSETS`.
    pub download_binary_assets: bool,

    /// `download_binary_assets_version` is the version of envtest binaries to download.
    /// Defaults to the latest stable version (i.e. excluding alpha / beta / RC versions).
    pub download_binary_assets_version: Option<String>,

    /// `download_binary_assets_index_url` is the index used to discover envtest binaries to download.
    /// Defaults to <https://raw.githubusercontent.com/kubernetes-sigs/controller-tools/HEAD/envtest-releases.yaml>.
    pub download_binary_assets_index_url: Option<String>,

    /// `binary_assets_directory` is the path where the binaries required for the envtest are
    /// located in the local environment. This field can be overridden by setting `KUBEBUILDER_ASSETS`.
    ///
    /// While defaulted to `None`, implementations of [`Environment::create`] uses `envtest.SetupEnvtestDefaultBinaryAssetsDirectory()`
    /// method which is recommended for shared use of envtest binaries across multiple test runs.
    ///
    /// The directory is dependent on operating system:
    ///
    /// - Windows: %LocalAppData%\kubebuilder-envtest
    /// - OSX: ~/Library/Application Support/io.kubebuilder.envtest
    /// - Others: ${XDG_DATA_HOME:-~/.local/share}/kubebuilder-envtest
    pub binary_assets_directory: Option<String>,
}

impl Default for BinaryAssetsSettings {
    fn default() -> Self {
        Self {
            download_binary_assets: true,
            download_binary_assets_version: Option::default(),
            download_binary_assets_index_url: Option::default(),
            binary_assets_directory: Option::default(),
        }
    }
}

/// CRD installation settings used during environment creation.
///
/// Control plane startup and shutdown timeouts are configured through the
/// `KUBEBUILDER_CONTROLPLANE_START_TIMEOUT` and
/// `KUBEBUILDER_CONTROLPLANE_STOP_TIMEOUT` environment variables. These are the
/// primary interface for timeout tuning and default to `20s` when unspecified.
///
/// # Examples
///
/// ```rust
/// let options = envtest::CRDInstallOptions {
///     paths: vec!["config/crd".to_owned()],
///     ..Default::default()
/// };
///
/// assert!(options.paths.contains(&"config/crd".to_owned()));
/// ```
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
pub struct CRDInstallOptions {
    /// Paths to directories or files containing CRDs. Can be used to install existing CRDs from the filesystem.
    pub paths: Vec<String>,

    /// Specific CRD jsons to install.
    pub crds: Vec<String>,
}

/// Represents the environment configuration for creating a test server.
///
impl Environment {
    /// Asynchronously create a new [`Server`] based on the current configuration.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = envtest::Environment::default().create().await?;
    /// # #[cfg(feature = "kube")]
    /// # {
    /// let client = server.client()?;
    /// # let _ = client;
    /// # }
    /// server.destroy().await?;
    /// # Ok(())
    /// # }
    /// # run().await.unwrap()
    /// # })
    /// ```
    ///
    /// # Errors
    ///
    /// Errors returned by the Go side are converted into [`EnvironmentError`].
    pub async fn create(&self) -> Result<Server, EnvironmentError> {
        #[cfg(feature = "_docsrs")]
        let res = CreateResponse::default();
        #[cfg(not(feature = "_docsrs"))]
        let this = self.clone();
        #[cfg(not(feature = "_docsrs"))]
        let res = smol::unblock(move || EnvTestImpl::create(this)).await;

        if let Some(err) = res.err {
            let err = match res.error_type.map(Into::into).unwrap_or_default() {
                CreateErrorType::SetupBinaryAssetsDirectory => {
                    EnvironmentError::SetupBinaryAssetsDirectory(err)
                }
                CreateErrorType::DecodeCrd => EnvironmentError::DecodeCrd(err),
                CreateErrorType::StartEnvironment => EnvironmentError::StartEnvironment(err),
                CreateErrorType::BuildKubeconfig => EnvironmentError::BuildKubeconfig(err),
                CreateErrorType::StopEnvironment => EnvironmentError::StopEnvironment(err),
                CreateErrorType::Generic => EnvironmentError::Create(err),
            };

            return Err(err);
        }

        Ok(res.server)
    }

    /// Add one or multiple CRDs to the environment. Can accept any serializable version of CRD,
    /// including typed structs like MyType::crd(), untyped `serde_json::Value`,
    /// or any combination of those in `Vec` or `Option`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let crd = serde_json::json!({
    ///     "apiVersion": "apiextensions.k8s.io/v1",
    ///     "kind": "CustomResourceDefinition",
    ///     "metadata": { "name": "widgets.example.com" },
    ///     "spec": {
    ///         "group": "example.com",
    ///         "scope": "Namespaced",
    ///         "names": {
    ///             "plural": "widgets",
    ///             "singular": "widget",
    ///             "kind": "Widget",
    ///             "listKind": "WidgetList"
    ///         },
    ///         "versions": [{
    ///             "name": "v1",
    ///             "served": true,
    ///             "storage": true,
    ///             "schema": {
    ///                 "openAPIV3Schema": {
    ///                     "type": "object"
    ///                 }
    ///             }
    ///         }]
    ///     }
    /// });
    ///
    /// let env = envtest::Environment::default().with_crds(crd)?;
    /// env.create().await?;
    /// # Ok(())
    /// # }
    /// # run().await.unwrap()
    /// # })
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an [`EnvironmentError::UnsupportedCrdType`] when serialization fails or an unsupported
    /// CRD value is provided. Actual CRD deserialization will be performed on `.create()`,
    /// which will return [`EnvironmentError::DecodeCrd`].
    pub fn with_crds(mut self, crds: impl serde::Serialize) -> Result<Self, EnvironmentError> {
        match serde_json::to_value(crds)? {
            serde_json::Value::Array(crds) => {
                for crd in crds {
                    self.crd_install_options
                        .crds
                        .push(serde_json::to_string(&crd)?);
                }
            }
            serde_json::Value::Object(crd) => {
                self.crd_install_options
                    .crds
                    .push(serde_json::to_string(&crd)?);
            }
            _ => return Err(EnvironmentError::UnsupportedCrdType),
        }

        Ok(self)
    }
}

/// Errors that can occur while destroying an environment or using a running server.
#[derive(thiserror::Error, Debug)]
pub enum ServerError {
    #[error("Environment destroy error: {0}")]
    Destroy(String),

    #[error("Stop environment error: {0}")]
    StopEnvironment(String),

    #[error("Stop environment error - missing for the provided kubeconfig: {0}")]
    EnvironmentMissing(String),

    #[error("Deserialize kubeconfig error: {0}")]
    Kubeconfig(#[from] serde_json::Error),

    #[cfg(feature = "kube")]
    #[error("Opening client error: {0}")]
    Client(#[from] kube::Error),

    #[cfg(feature = "kube")]
    #[error("Attempted to use client after the environment was destroyed")]
    EnvironmentDestroyed,
}

/// Represents a running test server.
///
/// A server holds the serialized kubeconfig returned by envtest and can be
/// queried, converted into a Kubernetes client, or destroyed explicitly.
///
/// # Examples
///
/// ```rust
/// # tokio_test::block_on(async {
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// let server = envtest::Environment::default().create().await?;
/// # #[cfg(not(feature = "_docsrs"))]
/// assert!(server.exist());
/// # #[cfg(feature = "kube")]
/// # {
/// let _ = server.kubeconfig()?;
/// let client = server.client()?;
/// let _ = client.apiserver_version().await?;
/// # }
/// server.destroy().await?;
/// assert!(!server.exist());
/// # Ok(())
/// # }
/// # run().await.unwrap();
/// # })
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
pub struct Server {
    kubeconfig: String,
}

impl Server {
    /// Asynchronously destroy the server and clean up resources.
    ///
    /// By default, the server will be automatically destroyed with best effort
    /// when it goes out of scope via [`Drop::drop`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = envtest::Environment::default().create().await?;
    /// server.destroy().await?;
    /// # Ok(())
    /// # }
    /// # run().await.unwrap()
    /// # })
    /// ```
    ///
    /// # Errors
    ///
    /// Errors returned by the Go side are converted into [`ServerError`].
    pub async fn destroy(&self) -> Result<(), ServerError> {
        #[cfg(feature = "_docsrs")]
        let res = DestroyResponse::default();
        #[cfg(not(feature = "_docsrs"))]
        let res = EnvTestImpl::destroy(self.kubeconfig.clone());
        if let Some(err) = res.err {
            let err = match res.error_type.map(Into::into).unwrap_or_default() {
                DestroyErrorType::StopEnvironment => ServerError::StopEnvironment(err),
                DestroyErrorType::EnvMissing => ServerError::EnvironmentMissing(err),
            };

            return Err(err);
        }

        Ok(())
    }

    /// Check whether this environment is still running.
    ///
    /// This queries the underlying envtest process registry using this
    /// server's serialized kubeconfig and returns `true` when the matching
    /// environment is still running.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = envtest::Environment::default().create().await?;
    ///
    /// # #[cfg(not(feature = "_docsrs"))]
    /// assert!(server.exist());
    ///
    /// server.destroy().await?;
    /// assert!(!server.exist());
    /// # Ok(())
    /// # }
    /// # run().await.unwrap();
    /// # })
    /// ```
    pub fn exist(&self) -> bool {
        #[cfg(feature = "_docsrs")]
        return false;
        #[cfg(not(feature = "_docsrs"))]
        return EnvTestImpl::exist(self.kubeconfig.clone());
    }

    /// Build a typed client from the stored kubeconfig.
    ///
    /// This first deserializes the kubeconfig using [`Self::kubeconfig`] and
    /// then converts it into [`kube::Client`] via [`TryFrom`].
    ///
    /// The returned [`kube::Client`] works against the temporary [`Server`], so
    /// the server must not be destroyed before the client is used last time.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = envtest::Environment::default().create().await?;
    /// let client = server.client()?;
    /// server.destroy().await?;
    /// # Ok(())
    /// # }
    /// # run().await.unwrap()
    /// # })
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`ServerError::Kubeconfig`] if [`kube::config::Kubeconfig`] deserialization fails,
    /// or [`ServerError::Client`] if conversion into [`kube::Client`] fails.
    #[cfg(feature = "kube")]
    #[inline]
    pub fn client(&self) -> Result<kube::Client, ServerError> {
        if !self.exist() {
            return Err(ServerError::EnvironmentDestroyed);
        }

        Ok(self.kubeconfig()?.try_into()?)
    }

    /// Deserialize the stored kubeconfig into the given type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = envtest::Environment::default().create().await?;
    /// let cfg = server.kubeconfig()?;
    /// server.destroy().await?;
    /// # Ok(())
    /// # }
    /// # run().await.unwrap();
    /// # })
    /// ```
    ///
    /// # Errors
    ///
    /// If the kubeconfig cannot be deserialized into the given type, a
    /// [`serde_json::Error`] is returned.
    #[cfg(feature = "kube")]
    #[inline]
    pub fn kubeconfig(&self) -> Result<kube::config::Kubeconfig, serde_json::Error> {
        serde_json::from_str(self.as_ref())
    }
}

impl AsRef<str> for Server {
    fn as_ref(&self) -> &str {
        &self.kubeconfig
    }
}

impl Drop for Server {
    /// Automatically destroy the server when it goes out of scope.
    fn drop(&mut self) {
        let _ = smol::block_on(self.destroy());
    }
}

#[cfg(test)]
mod tests {
    use super::Environment;

    #[cfg(feature = "kube")]
    use kube::{CustomResource, CustomResourceExt};

    #[cfg(feature = "kube")]
    #[derive(
        CustomResource, serde::Deserialize, serde::Serialize, Clone, Debug, schemars::JsonSchema,
    )]
    #[kube(
        group = "generated.example.com",
        version = "v1",
        kind = "GeneratedWidget",
        namespaced
    )]
    struct GeneratedWidgetSpec {
        replicas: i32,
    }

    #[tokio::test]
    async fn e2e() {
        let env = Environment::default();
        let server = env.create().await.unwrap();
        server.destroy().await.unwrap();
    }

    #[tokio::test]
    #[cfg(feature = "kube")]
    async fn destroyed_environment_is_checked_by_client() {
        let env = Environment::default();
        let server = env.create().await.unwrap();
        server.destroy().await.unwrap();

        assert!(matches!(
            server.client(),
            Err(super::ServerError::EnvironmentDestroyed)
        ));
    }

    #[cfg(feature = "kube")]
    #[tokio::test]
    async fn with_crds_accepts_simple_real_crd() {
        let crd = serde_json::json!({
            "apiVersion": "apiextensions.k8s.io/v1",
            "kind": "CustomResourceDefinition",
            "metadata": { "name": "widgets.example.com" },
            "spec": {
                "group": "example.com",
                "scope": "Namespaced",
                "names": {
                    "plural": "widgets",
                    "singular": "widget",
                    "kind": "Widget",
                    "listKind": "WidgetList"
                },
                "versions": [{
                    "name": "v1",
                    "served": true,
                    "storage": true,
                    "schema": {
                        "openAPIV3Schema": {
                            "type": "object"
                        }
                    }
                }]
            }
        });

        let env = Environment::default().with_crds(crd.clone()).unwrap();
        assert_eq!(env.crd_install_options.crds, vec![crd.to_string()]);
        let server = env.create().await.unwrap();
        let client = server.client().unwrap();
        let groups = client.list_api_groups().await.unwrap();
        groups
            .groups
            .iter()
            .find(|g| g.name == "example.com")
            .ok_or(())
            .unwrap();
    }

    #[cfg(feature = "kube")]
    #[tokio::test]
    async fn with_crds_accepts_kube_generated_crd() {
        let crd = GeneratedWidget::crd();

        let env = Environment::default().with_crds(crd.clone()).unwrap();
        assert_eq!(
            env.crd_install_options.crds,
            vec![serde_json::to_string(&crd).unwrap()]
        );

        let server = env.create().await.unwrap();
        let client = server.client().unwrap();
        let groups = client.list_api_groups().await.unwrap();
        groups
            .groups
            .iter()
            .find(|g| g.name == "generated.example.com")
            .ok_or(())
            .unwrap();
    }

    #[test]
    fn with_crds_accepts_option_single_vec_and_slice() {
        let crd_a =
            serde_json::json!({"kind": "CustomResourceDefinition", "metadata": {"name": "a"}});
        let crd_b =
            serde_json::json!({"kind": "CustomResourceDefinition", "metadata": {"name": "b"}});
        let crd_c =
            serde_json::json!({"kind": "CustomResourceDefinition", "metadata": {"name": "c"}});

        let env_single = Environment::default().with_crds(crd_a.clone()).unwrap();
        assert_eq!(env_single.crd_install_options.crds, vec![crd_a.to_string()]);

        let env_option = Environment::default()
            .with_crds(Some(crd_a.clone()))
            .unwrap();
        assert_eq!(env_option.crd_install_options.crds, vec![crd_a.to_string()]);

        let env_vec = Environment::default()
            .with_crds(vec![crd_a.clone(), crd_b.clone()])
            .unwrap();
        assert_eq!(
            env_vec.crd_install_options.crds,
            vec![crd_a.to_string(), crd_b.to_string()]
        );

        let crds = [crd_a.clone(), crd_b.clone(), crd_c.clone()];
        let env_slice = Environment::default().with_crds(&crds).unwrap();
        assert_eq!(
            env_slice.crd_install_options.crds,
            vec![crd_a.to_string(), crd_b.to_string(), crd_c.to_string()]
        );
    }

    #[cfg(feature = "kube")]
    seq_macro::seq!(N in 1..=50 {
        #[tokio::test]
        async fn parallel_test_case_~N() {
            let server = Environment::default().create().await.unwrap();
            let client = server.client().unwrap();
            client.apiserver_version().await.unwrap();
            server.destroy().await.unwrap();
        }
    });
}