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
// Enable rustc and Clippy lints that are disabled by default.
// https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html#unused-crate-dependencies
#![warn(unused_crate_dependencies)]
// https://rust-lang.github.io/rust-clippy/stable/index.html
#![warn(clippy::pedantic)]
// This lint is too noisy and enforces a style that reduces readability in many cases.
#![allow(clippy::module_name_repetitions)]

mod app;
mod build;
mod container_context;
mod container_port_mapping;
mod log;
mod macros;
mod pack;
mod util;

pub use crate::container_context::{ContainerContext, PrepareContainerContext};
use crate::pack::{PackBuildCommand, PullPolicy};
use bollard::image::RemoveImageOptions;
use bollard::Docker;
use std::collections::HashMap;
use std::env;
use std::env::VarError;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// Main type for libcnb integration tests.
///
/// # Dependencies
/// Integration tests require external tools to be available on the host to run:
/// - [pack](https://buildpacks.io/docs/tools/pack/)
/// - [Docker](https://www.docker.com/)
///
/// # Example
/// ```no_run
/// use libcnb_test::{IntegrationTest, BuildpackReference, assert_contains};
///
/// # fn call_test_fixture_service(addr: std::net::SocketAddr, payload: &str) -> Result<String, ()> {
/// #    unimplemented!()
/// # }
/// IntegrationTest::new("heroku/buildpacks:20", "test-fixtures/app")
///     .buildpacks(vec![
///         BuildpackReference::Other(String::from("heroku/openjdk")),
///         BuildpackReference::Crate,
///     ])
///     .run_test(|context| {
///         assert_contains!(context.pack_stdout, "---> Maven Buildpack");
///         assert_contains!(context.pack_stdout, "---> Installing Maven");
///         assert_contains!(context.pack_stdout, "---> Running mvn package");
///
///         context.prepare_container().expose_port(12345).start_with_default_process(|container| {
///             assert_eq!(
///                 call_test_fixture_service(
///                     container.address_for_port(12345).unwrap(),
///                     "Hagbard Celine"
///                 )
///                 .unwrap(),
///                 "enileC drabgaH"
///             );
///         });
///     });
/// ```
pub struct IntegrationTest {
    app_dir: PathBuf,
    target_triple: String,
    builder_name: String,
    buildpacks: Vec<BuildpackReference>,
    env: HashMap<String, String>,
    docker: Docker,
    tokio_runtime: tokio::runtime::Runtime,
}

/// References a Cloud Native Buildpack
#[derive(Eq, PartialEq, Debug)]
pub enum BuildpackReference {
    /// References the buildpack in the Rust Crate currently being tested
    Crate,
    /// References another buildpack by id, local directory or tarball
    Other(String),
}

impl IntegrationTest {
    /// Creates a new integration test.
    ///
    /// # Panics
    /// - When the connection to Docker failed
    /// - When the internal Tokio runtime could not be created
    pub fn new(builder_name: impl Into<String>, app_dir: impl AsRef<Path>) -> Self {
        let tokio_runtime =
            tokio::runtime::Runtime::new().expect("Could not create internal Tokio runtime");

        let docker = match env::var("DOCKER_HOST") {
            #[cfg(target_family = "unix")]
            Ok(docker_host) if docker_host.starts_with("unix://") => {
                Docker::connect_with_unix_defaults()
            }
            Ok(docker_host)
                if docker_host.starts_with("tcp://") || docker_host.starts_with("https://") =>
            {
                #[cfg(not(feature = "remote-docker"))]
                panic!("Cannot connect to DOCKER_HOST '{docker_host}' since it requires TLS. Please use a local Docker daemon instead (recommended), or else enable the experimental `remote-docker` feature.");
                #[cfg(feature = "remote-docker")]
                Docker::connect_with_ssl_defaults()
            }
            Ok(docker_host) => panic!("Cannot connect to unsupported DOCKER_HOST '{docker_host}'"),
            Err(VarError::NotPresent) => Docker::connect_with_local_defaults(),
            Err(VarError::NotUnicode(_)) => {
                panic!("DOCKER_HOST environment variable is not unicode encoded!")
            }
        }
        .expect("Could not connect to local Docker daemon");

        IntegrationTest {
            app_dir: PathBuf::from(app_dir.as_ref()),
            target_triple: String::from("x86_64-unknown-linux-musl"),
            builder_name: builder_name.into(),
            buildpacks: vec![BuildpackReference::Crate],
            env: HashMap::new(),
            docker,
            tokio_runtime,
        }
    }

    /// Sets the buildpacks order.
    ///
    /// Defaults to [`BuildpackReference::Crate`].
    pub fn buildpacks(&mut self, buildpacks: impl Into<Vec<BuildpackReference>>) -> &mut Self {
        self.buildpacks = buildpacks.into();
        self
    }

    /// Sets the target triple.
    ///
    /// Defaults to `x86_64-unknown-linux-musl`.
    pub fn target_triple(&mut self, target_triple: impl Into<String>) -> &mut Self {
        self.target_triple = target_triple.into();
        self
    }

    /// Inserts or updates an environment variable mapping for the build process.
    ///
    /// Note: This does not set this environment variable for running containers, it's only
    /// available during the build.
    ///
    /// # Example
    /// ```no_run
    /// use libcnb_test::IntegrationTest;
    ///
    /// IntegrationTest::new("heroku/buildpacks:20", "test-fixtures/app")
    ///     .env("ENV_VAR_ONE", "VALUE ONE")
    ///     .env("ENV_VAR_TWO", "SOME OTHER VALUE")
    ///     .run_test(|context| {
    ///         // ...
    ///     })
    /// ```
    pub fn env(&mut self, k: impl Into<String>, v: impl Into<String>) -> &mut Self {
        self.env.insert(k.into(), v.into());
        self
    }

    /// Adds or updates multiple environment variable mappings for the build process.
    ///
    /// Note: This does not set environment variables for running containers, they're only
    /// available during the build.
    ///
    /// # Example
    /// ```no_run
    /// use libcnb_test::IntegrationTest;
    ///
    /// IntegrationTest::new("heroku/buildpacks:20", "test-fixtures/app")
    ///     .envs(vec![("ENV_VAR_ONE", "VALUE ONE"), ("ENV_VAR_TWO", "SOME OTHER VALUE")])
    ///     .run_test(|context| {
    ///         // ...
    ///     })
    /// ```
    pub fn envs<K: Into<String>, V: Into<String>, I: IntoIterator<Item = (K, V)>>(
        &mut self,
        envs: I,
    ) -> &mut Self {
        envs.into_iter().for_each(|(key, value)| {
            self.env(key.into(), value.into());
        });

        self
    }

    /// Starts a new integration test run.
    ///
    /// This function will copy the application to a temporary directory, cross-compiles this crate,
    /// packages it as a buildpack and then invokes [pack](https://buildpacks.io/docs/tools/pack/)
    /// to build a new Docker image with the buildpacks specified by this integration test instance.
    ///
    /// Since this function is supposed to only be used in integration tests, failures are not
    /// signalled via [`Result`](Result) values. Instead, this function panics whenever an unexpected error
    /// occurred to simplify testing code.
    ///
    /// # Panics
    /// - When the app could not be copied
    /// - When this crate could not be packed as a buildpack
    /// - When the "pack" command unexpectedly fails
    ///
    /// # Example
    /// ```no_run
    /// use libcnb_test::{IntegrationTest, assert_contains};
    ///
    /// IntegrationTest::new("heroku/buildpacks:20", "test-fixtures/app")
    ///     .run_test(|context| {
    ///         assert_contains!(context.pack_stdout, "---> Ruby Buildpack");
    ///         assert_contains!(context.pack_stdout, "---> Installing bundler");
    ///         assert_contains!(context.pack_stdout, "---> Installing gems");
    ///     })
    /// ```
    pub fn run_test<F: FnOnce(IntegrationTestContext)>(&mut self, f: F) {
        let app_dir = if self.app_dir.is_relative() {
            env::var("CARGO_MANIFEST_DIR")
                .map(PathBuf::from)
                .expect("Could not determine Cargo manifest directory")
                .join(&self.app_dir)
        } else {
            self.app_dir.clone()
        };

        let temp_app_dir =
            app::copy_app(&app_dir).expect("Could not copy app to temporary location");

        let temp_crate_buildpack_dir = if self.buildpacks.contains(&BuildpackReference::Crate) {
            Some(
                build::package_crate_buildpack(&self.target_triple)
                    .expect("Could not package current crate as buildpack"),
            )
        } else {
            None
        };

        let image_name = util::random_docker_identifier();

        let mut pack_command = PackBuildCommand::new(
            &self.builder_name,
            temp_app_dir.path(),
            &image_name,
            // Prevent redundant image-pulling, which slows tests and risks hitting registry rate limits.
            PullPolicy::IfNotPresent,
        );

        self.env.iter().for_each(|(key, value)| {
            pack_command.env(key, value);
        });

        for buildpack in &self.buildpacks {
            match buildpack {
                BuildpackReference::Crate => {
                    pack_command.buildpack(temp_crate_buildpack_dir.as_ref()
                        .expect("Test references crate buildpack, but crate wasn't packaged as a buildpack. This is an internal libcnb-test error, please report any occurrences."))
                }
                BuildpackReference::Other(id) => pack_command.buildpack(id.clone()),
            };
        }

        let output = Command::from(pack_command)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Could not spawn external 'pack' process")
            .wait_with_output()
            .expect("Error while waiting on external 'pack' process");

        let integration_test_context = IntegrationTestContext {
            pack_stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            pack_stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            image_name,
            app_dir: PathBuf::from(temp_app_dir.path()),
            integration_test: self,
        };

        if output.status.success() {
            f(integration_test_context);
        } else {
            panic!(
                "pack command failed with exit-code {}!\n\npack stdout:\n{}\n\npack stderr:\n{}",
                output
                    .status
                    .code()
                    .map_or(String::from("<unknown>"), |exit_code| exit_code.to_string()),
                integration_test_context.pack_stdout,
                integration_test_context.pack_stderr
            )
        }
    }
}

/// Context for a currently executing integration test.
pub struct IntegrationTestContext<'a> {
    /// Standard output of `pack`, interpreted as an UTF-8 string.
    pub pack_stdout: String,
    /// Standard error of `pack`, interpreted as an UTF-8 string.
    pub pack_stderr: String,
    /// The name of the image this integration test created.
    pub image_name: String,
    /// The directory of the app this integration test uses.
    ///
    /// This is a copy of the `app_dir` directory passed to [`IntegrationTest::new`] and unique to
    /// this integration test run. It is safe to modify the directory contents inside the test.
    pub app_dir: PathBuf,

    integration_test: &'a IntegrationTest,
}

impl<'a> IntegrationTestContext<'a> {
    /// Prepares a new container with the image from the integration test.
    ///
    /// This will not create nor run the container immediately. Use the returned
    /// `PrepareContainerContext` to configure the container, then call
    /// [`start_with_default_process`](PrepareContainerContext::start_with_default_process) on it
    /// to actually create and start the container.
    ///
    /// # Example:
    ///
    /// ```no_run
    /// use libcnb_test::IntegrationTest;
    ///
    /// IntegrationTest::new("heroku/buildpacks:20", "test-fixtures/empty-app").run_test(|context| {
    ///     context.prepare_container().start_with_default_process(|container| {
    ///         // ...
    ///     });
    /// });
    /// ```
    #[must_use]
    pub fn prepare_container(&self) -> PrepareContainerContext {
        PrepareContainerContext::new(self)
    }
}

impl<'a> Drop for IntegrationTestContext<'a> {
    fn drop(&mut self) {
        // We do not care if image removal succeeded or not. Panicking here would result in
        // SIGILL since this function might be called in a Tokio runtime.
        let _image_delete_result = self.integration_test.tokio_runtime.block_on(
            self.integration_test.docker.remove_image(
                &self.image_name,
                Some(RemoveImageOptions {
                    force: true,
                    ..RemoveImageOptions::default()
                }),
                None,
            ),
        );
    }
}

// This runs the README.md as a doctest, ensuring the code examples in it are valid.
// It will not be part of the final crate.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;