envtest 0.1.2

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
#[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 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
/// async fn test() -> Result<(), Box<dyn std::error::Error>> {
///     let env = envtest::Environment::default();
///     let server = env.create()?;
///     let kubeconfig = server.kubeconfig()?;
///     panic!("environment created");
///     Ok(())
/// }
/// ```
#[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,
}

#[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.
    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`.
    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(),
        }
    }
}

/// `CRDInstallOptions` is a struct that represents the CRD install options
#[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.
    paths: Vec<String>,

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

    /// Whether to error if a path does not exist.
    error_if_path_missing: bool,
}

impl Environment {
    /// Create a new [`Server`] based on the current configuration.
    ///
    /// # Errors
    ///
    /// Returns an [`EnvironmentError`] if the Go side reports any errors.
    pub fn create(&self) -> Result<Server, EnvironmentError> {
        #[cfg(feature = "_docsrs")]
        let res = CreateResponse::default();
        #[cfg(not(feature = "_docsrs"))]
        let res = EnvTestImpl::create(self.clone());

        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.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), envtest::EnvironmentError> {
    /// 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()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # 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.
#[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),
}

/// Represents a running test server.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(not(feature = "_docsrs"), derive(rust2go::R2G))]
pub struct Server {
    kubeconfig: String,
}

impl Server {
    /// Destroy the server and clean up resources.
    ///
    /// # Errors
    ///
    /// Errors returned by the Go side are converted into [`ServerError`].
    pub 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(())
    }

    /// 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`].
    ///
    /// ```rust
    /// # tokio_test::block_on(async {
    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
    /// let server = envtest::Environment::default().create()?;
    /// let client = server.client()?;
    /// server.destroy()?;
    /// # 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> {
        Ok(self.kubeconfig()?.try_into()?)
    }

    /// Deserialize the stored kubeconfig into the given type.
    ///
    /// ```rust
    /// let server = envtest::Environment::default().create()?;
    /// let cfg = server.kubeconfig()?;
    /// server.destroy()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # 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 _ = self.destroy();
    }
}

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

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

    #[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().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();
    }

    #[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()]
        );
    }
}