ociman 0.4.0

Unified API for OCI container runtimes (Docker, Podman)
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
use indoc::indoc;

const ENV_TEST_VAR: cmd_proc::EnvVariableName<'static> =
    cmd_proc::EnvVariableName::from_static_or_panic("TEST_VAR");

/// Helper function to create a Definition with .remove() automatically set
/// to prevent container leaks in tests.
fn test_definition(
    backend: &ociman::Backend,
    reference: ociman::image::Reference,
) -> ociman::Definition {
    ociman::Definition::new(backend.clone(), reference).remove()
}

fn alpine_test_definition(backend: &ociman::Backend) -> ociman::Definition {
    test_definition(backend, ociman::testing::ALPINE_LATEST_IMAGE.clone())
}

fn alpine_dockerfile(body: &str) -> String {
    format!("FROM {}\n{body}", *ociman::testing::ALPINE_LATEST_IMAGE)
}

#[tokio::test]
async fn test_hello_world() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("echo")
        .argument("Hello, World!");

    let output = definition.run_capture_only_stdout().await;

    let stdout = std::str::from_utf8(&output).expect("invalid utf8 in output");

    assert_eq!(stdout.trim(), "Hello, World!");
}

#[tokio::test]
async fn test_backend_autodetect() {
    let _backend = ociman::test_backend_setup!();
}

#[tokio::test]
async fn test_container_with_env_vars() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "echo $TEST_VAR"])
        .environment_variable(ENV_TEST_VAR, "test_value");

    let output = definition.run_capture_only_stdout().await;
    let stdout = std::str::from_utf8(&output).expect("invalid utf8 in output");

    assert_eq!(stdout.trim(), "test_value");
}

#[tokio::test]
async fn test_container_exec() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "trap 'exit 0' TERM; sleep 30 & wait"]);

    definition
        .with_container(async |container| {
            let output = container
                .exec("echo")
                .argument("Container is running!")
                .build()
                .stdout_capture()
                .string()
                .await
                .unwrap();

            assert_eq!(output.trim(), "Container is running!");
        })
        .await;
}

#[tokio::test]
async fn test_container_exec_status_success() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "trap 'exit 0' TERM; sleep 30 & wait"]);

    definition
        .with_container(async |container| {
            assert!(container.exec("true").status().await.is_ok());
        })
        .await;
}

#[tokio::test]
async fn test_container_exec_status_failure() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "trap 'exit 0' TERM; sleep 30 & wait"]);

    definition
        .with_container(async |container| {
            let error = container.exec("false").status().await.unwrap_err();
            let cmd_proc::CommandError::ExitStatus(status) = error else {
                panic!("expected ExitStatus, got {error:?}");
            };
            assert_eq!(status.code(), Some(1));
        })
        .await;
}

#[tokio::test]
async fn test_container_exec_with_stdin() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "trap 'exit 0' TERM; sleep 30 & wait"]);

    definition
        .with_container(async |container| {
            let output = container
                .exec("cat")
                .stdin(b"hello from stdin")
                .build()
                .stdout_capture()
                .bytes()
                .await
                .unwrap();

            assert_eq!(output, b"hello from stdin");
        })
        .await;
}

#[tokio::test]
async fn test_read_host_tcp_port() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh".to_string())
        .arguments(vec![
            "-c".to_string(),
            "trap 'exit 0' TERM; sleep 30 & wait".to_string(),
        ])
        .publish(ociman::Publish::tcp(8080).host_ip(std::net::Ipv4Addr::LOCALHOST.into()));

    definition
        .with_container(async |container| {
            let host_port = container
                .read_host_tcp_port(8080)
                .await
                .expect("port 8080 should be published");

            assert!(host_port > 0);
        })
        .await;
}

#[tokio::test]
async fn test_read_host_tcp_port_not_published() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "trap 'exit 0' TERM; sleep 30 & wait"]);

    definition
        .with_container(async |container| {
            let host_port = container.read_host_tcp_port(8080).await;

            assert_eq!(host_port, None);
        })
        .await;
}

#[tokio::test]
async fn test_command_with_stdin() {
    let input = b"Hello from stdin!";
    let output = cmd_proc::Command::new("cat")
        .stdin_bytes(input.to_vec())
        .stdout_capture()
        .bytes()
        .await
        .unwrap();

    assert_eq!(output, input);
}

#[tokio::test]
async fn test_image_build_from_instructions() {
    let backend = ociman::test_backend_setup!();

    let dockerfile = alpine_dockerfile(indoc! {"
        RUN echo 'test_image_build_from_instructions' > /test-id
        RUN touch dirty && echo 'test build from instructions'
    "});

    let definition = ociman::BuildDefinition::from_instructions(
        &backend,
        ociman::testing::test_reference("ociman-test-instructions:latest"),
        dockerfile,
    );

    let reference = definition.build().await;

    assert!(
        backend.is_image_present(&reference).await,
        "Image should exist after build"
    );

    backend.remove_image(&reference).await;
}

#[tokio::test]
async fn test_image_build_from_directory() {
    let backend = ociman::test_backend_setup!();

    let definition = ociman::BuildDefinition::from_directory(
        &backend,
        ociman::testing::test_reference("ociman-test-directory:latest"),
        "tests/fixtures/test-build",
    );

    let reference = definition.build().await;

    assert!(
        backend.is_image_present(&reference).await,
        "Image should exist after build"
    );

    backend.remove_image(&reference).await;
}

#[tokio::test]
async fn test_image_build_if_absent() {
    let backend = ociman::test_backend_setup!();

    let dockerfile = alpine_dockerfile(indoc! {"
        RUN echo 'test_image_build_if_absent' > /test-id
        RUN touch dirty && echo 'test build if absent'
    "});

    let definition = ociman::BuildDefinition::from_instructions(
        &backend,
        ociman::testing::test_reference("ociman-test-if-absent:latest"),
        dockerfile,
    );

    let reference1 = definition.build_if_absent().await;
    assert!(backend.is_image_present(&reference1).await);

    let reference2 = definition.build_if_absent().await;
    assert!(backend.is_image_present(&reference2).await);

    assert_eq!(reference1, reference2);

    backend.remove_image(&reference1).await;
}

#[tokio::test]
async fn test_image_tag() {
    let backend = ociman::test_backend_setup!();

    let source = ociman::testing::ALPINE_LATEST_IMAGE.clone();
    let target: ociman::image::Reference =
        ociman::testing::test_reference("ociman-test-tagged:latest");

    backend.pull_image_if_absent(&source).await;

    assert!(!backend.is_image_present(&target).await);

    backend.tag_image(&source, &target).await;

    assert!(backend.is_image_present(&source).await);
    assert!(backend.is_image_present(&target).await);

    backend.remove_image(&target).await;
}

#[tokio::test]
async fn test_image_pull_if_absent() {
    let backend = ociman::test_backend_setup!();

    let reference = ociman::testing::ALPINE_LATEST_IMAGE.clone();

    backend.pull_image_if_absent(&reference).await;
    assert!(backend.is_image_present(&reference).await);
}

#[tokio::test]
async fn test_image_build_from_instructions_hash() {
    let backend = ociman::test_backend_setup!();

    let dockerfile = alpine_dockerfile(indoc! {"
        RUN echo 'test_image_build_from_instructions_hash' > /test-id
        RUN touch dirty && echo 'test hash'
    "});

    let definition = ociman::BuildDefinition::from_instructions_hash(
        &backend,
        ociman::testing::test_name("ociman-test-hash"),
        &*dockerfile,
    );

    let reference = definition.build().await;
    assert!(backend.is_image_present(&reference).await);

    let definition2 = ociman::BuildDefinition::from_instructions_hash(
        &backend,
        ociman::testing::test_name("ociman-test-hash"),
        &*dockerfile,
    );
    let reference2 = definition2.build().await;
    assert_eq!(reference, reference2);

    backend.remove_image(&reference).await;
}

#[tokio::test]
async fn test_image_build_from_directory_hash() {
    let backend = ociman::test_backend_setup!();

    let definition = ociman::BuildDefinition::from_directory_hash(
        &backend,
        ociman::testing::test_name("ociman-test-dir-hash"),
        "tests/fixtures/test-build-hash",
    );

    let reference1 = definition.build().await;
    assert!(backend.is_image_present(&reference1).await);

    let definition2 = ociman::BuildDefinition::from_directory_hash(
        &backend,
        ociman::testing::test_name("ociman-test-dir-hash"),
        "tests/fixtures/test-build-hash",
    );
    let reference2 = definition2.build().await;
    assert_eq!(reference1, reference2);

    backend.remove_image(&reference1).await;
}

#[tokio::test]
async fn test_image_build_with_build_args() {
    let backend = ociman::test_backend_setup!();

    let dockerfile = alpine_dockerfile(indoc! {"
        RUN echo 'test_image_build_with_build_args' > /test-id
        ARG TEST_ARG
        RUN touch dirty && echo \"Build arg value: $TEST_ARG\" > /test-output
    "});

    let definition = ociman::BuildDefinition::from_instructions(
        &backend,
        ociman::testing::test_reference("ociman-test-build-args:latest"),
        dockerfile,
    )
    .build_argument("TEST_ARG".parse().unwrap(), "test_value");

    let reference = definition.build().await;
    assert!(backend.is_image_present(&reference).await);

    // Verify the build arg was used by checking the file created during build
    let def = test_definition(&backend, reference.clone())
        .entrypoint("cat")
        .arguments(["/test-output"]);

    let output = def.run_capture_only_stdout().await;
    let stdout = std::str::from_utf8(&output).expect("invalid utf8 in output");

    assert!(stdout.contains("test_value"));

    backend.remove_image(&reference).await;
}

#[tokio::test]
async fn test_image_build_args_affect_hash() {
    let backend = ociman::test_backend_setup!();

    let dockerfile = alpine_dockerfile(indoc! {"
        RUN echo 'test_image_build_args_affect_hash' > /test-id
        ARG VERSION
        RUN touch dirty && echo \"Version: $VERSION\"
    "});

    let definition1 = ociman::BuildDefinition::from_instructions_hash(
        &backend,
        ociman::testing::test_name("ociman-test-args-hash"),
        &*dockerfile,
    )
    .build_argument("VERSION".parse().unwrap(), "1.0");
    let reference1 = definition1.build().await;

    let definition2 = ociman::BuildDefinition::from_instructions_hash(
        &backend,
        ociman::testing::test_name("ociman-test-args-hash"),
        &*dockerfile,
    )
    .build_argument("VERSION".parse().unwrap(), "2.0");
    let reference2 = definition2.build().await;

    assert_ne!(
        reference1, reference2,
        "Different build arguments should produce different image tags"
    );

    let definition3 = ociman::BuildDefinition::from_instructions_hash(
        &backend,
        ociman::testing::test_name("ociman-test-args-hash"),
        &*dockerfile,
    )
    .build_argument("VERSION".parse().unwrap(), "1.0");
    let reference3 = definition3.build().await;

    assert_eq!(
        reference1, reference3,
        "Same build arguments should produce same image tag"
    );

    backend.remove_image(&reference1).await;
    backend.remove_image(&reference2).await;
}

#[test]
fn test_build_argument_key_cannot_be_empty() {
    let result: Result<ociman::BuildArgumentKey, _> = "".parse();
    assert!(matches!(result, Err(ociman::BuildArgumentKeyError::Empty)));
}

#[test]
fn test_build_argument_key_cannot_contain_equals() {
    let result: Result<ociman::BuildArgumentKey, _> = "KEY=VALUE".parse();
    assert!(matches!(
        result,
        Err(ociman::BuildArgumentKeyError::ContainsEquals)
    ));
}

#[tokio::test]
async fn test_run_with_successful_exit() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend).entrypoint("true");

    assert!(definition.run().await.is_ok());
}

#[tokio::test]
async fn test_run_with_nonzero_exit() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend).entrypoint("false");

    let error = definition.run().await.unwrap_err();
    let cmd_proc::CommandError::ExitStatus(status) = error else {
        panic!("expected ExitStatus, got {error:?}");
    };
    assert_eq!(status.code(), Some(1));
}

#[tokio::test]
async fn test_container_with_workdir() {
    let backend = ociman::test_backend_setup!();

    let definition = alpine_test_definition(&backend)
        .entrypoint("pwd")
        .workdir("/tmp");

    let output = definition.run_capture_only_stdout().await;
    let stdout = std::str::from_utf8(&output).expect("invalid utf8 in output");

    assert_eq!(stdout.trim(), "/tmp");
}

#[tokio::test]
async fn test_container_commit() {
    let backend = ociman::test_backend_setup!();

    let target_reference: ociman::image::Reference =
        ociman::testing::test_reference("ociman-test-commit:latest");

    // Ensure target image doesn't exist before test
    if backend.is_image_present(&target_reference).await {
        backend.remove_image(&target_reference).await;
    }

    let definition = alpine_test_definition(&backend)
        .entrypoint("sh")
        .arguments(["-c", "trap 'exit 0' TERM; sleep 30 & wait"]);

    let commit_target = target_reference.clone();
    definition
        .with_container(async |container| {
            container
                .exec("touch")
                .argument("/committed-file")
                .status()
                .await
                .unwrap();
            container.commit(&commit_target, true).await.unwrap();
        })
        .await;

    assert!(
        backend.is_image_present(&target_reference).await,
        "Committed image should exist"
    );

    // Verify the committed file exists in the new image
    let verify_definition = test_definition(&backend, target_reference.clone())
        .entrypoint("ls")
        .arguments(["/committed-file"]);

    let output = verify_definition.run_capture_only_stdout().await;
    let stdout = std::str::from_utf8(&output).expect("invalid utf8 in output");

    assert_eq!(stdout.trim(), "/committed-file");

    backend.remove_image(&target_reference).await;
}

#[tokio::test]
async fn test_bridge_subnets() {
    let backend = ociman::test_backend_setup!();

    let subnets = backend.bridge_subnets().await.unwrap();

    assert!(!subnets.is_empty(), "Expected at least one bridge subnet");

    for subnet in &subnets {
        assert!(
            subnet.prefix_len() < 32,
            "Expected a network subnet, got host: {subnet}"
        );
    }
}