-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathParserTest.swift
More file actions
1564 lines (1367 loc) · 52.8 KB
/
Copy pathParserTest.swift
File metadata and controls
1564 lines (1367 loc) · 52.8 KB
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
// Copyright © 2026 Apple Inc. and the container project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
import Containerization
import ContainerizationError
import ContainerizationExtras
import Foundation
import SystemPackage
import Testing
@testable import ContainerAPIClient
@testable import ContainerPersistence
struct ParserTest {
@Test
func testPublishPortParserTcp() throws {
let result = try Parser.publishPorts(["127.0.0.1:8080:8000/tcp"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("127.0.0.1")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8080))
#expect(result[0].containerPort == UInt16(8000))
#expect(result[0].proto == .tcp)
#expect(result[0].count == 1)
}
@Test
func testPublishPortParserUdp() throws {
let result = try Parser.publishPorts(["192.168.32.36:8000:8080/UDP"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("192.168.32.36")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8000))
#expect(result[0].containerPort == UInt16(8080))
#expect(result[0].proto == .udp)
#expect(result[0].count == 1)
}
@Test
func testPublishPortRange() throws {
let result = try Parser.publishPorts(["127.0.0.1:8080-8179:9000-9099/tcp"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("127.0.0.1")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8080))
#expect(result[0].containerPort == UInt16(9000))
#expect(result[0].proto == .tcp)
#expect(result[0].count == 100)
}
@Test
func testPublishPortRangeSingle() throws {
let result = try Parser.publishPorts(["127.0.0.1:8080-8080:9000-9000/tcp"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("127.0.0.1")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8080))
#expect(result[0].containerPort == UInt16(9000))
#expect(result[0].proto == .tcp)
#expect(result[0].count == 1)
}
@Test
func testPublishPortNoHostAddress() throws {
let result = try Parser.publishPorts(["8080:8000/tcp"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("0.0.0.0")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8080))
#expect(result[0].containerPort == UInt16(8000))
#expect(result[0].proto == .tcp)
#expect(result[0].count == 1)
}
@Test
func testPublishPortNoProtocol() throws {
let result = try Parser.publishPorts(["8080:8000"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("0.0.0.0")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8080))
#expect(result[0].containerPort == UInt16(8000))
#expect(result[0].proto == .tcp)
#expect(result[0].count == 1)
}
@Test
func testPublishPortParserIPv6() throws {
let result = try Parser.publishPorts(["[fe80::36f3:5e50:ed71:1bb]:8080:8000/tcp"])
#expect(result.count == 1)
let expectedAddress = try IPAddress("fe80::36f3:5e50:ed71:1bb")
#expect(result[0].hostAddress == expectedAddress)
#expect(result[0].hostPort == UInt16(8080))
#expect(result[0].containerPort == UInt16(8000))
#expect(result[0].proto == .tcp)
#expect(result[0].count == 1)
}
@Test
func testPublishPortOne() throws {
let result = try Parser.publishPorts(["127.0.0.1:1:1/tcp"])
#expect(result.count == 1)
#expect(result[0].hostPort == UInt16(1))
#expect(result[0].containerPort == UInt16(1))
#expect(result[0].count == 1)
}
@Test
func testPublishPortInvalidProtocol() throws {
#expect {
_ = try Parser.publishPorts(["8080:8000/sctp"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish protocol")
}
}
@Test
func testPublishPortInvalidValue() throws {
#expect {
_ = try Parser.publishPorts([""])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish value")
}
}
@Test
func testPublishPortMissingPort() throws {
#expect {
_ = try Parser.publishPorts(["1234"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish value")
}
}
@Test
func testPublishInvalidIPv4Address() throws {
#expect {
_ = try Parser.publishPorts(["1234:8080:8000"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish IPv4 address")
}
}
@Test
func testPublishInvalidIPv6Address() throws {
#expect {
_ = try Parser.publishPorts([
"[1234:5678]:8080:8000",
"[2001::db8::1]:8080:8080",
"[2001:db8:85a3::8a2e:370g:7334]:8080:8080",
"[2001:db8:85a3::][8a2e::7334]:8080:8080",
])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish IPv6 address")
}
}
@Test
func testPublishPortInvalidHostPort() throws {
#expect {
_ = try Parser.publishPorts(["65536:1234"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish host port")
}
}
@Test
func testPublishPortInvalidContainerPort() throws {
#expect {
_ = try Parser.publishPorts(["1234:65536"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish container port")
}
}
@Test
func testPublishPortRangeMismatch() throws {
#expect {
_ = try Parser.publishPorts(["8000-8000:9000-9001"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("counts are not equal")
}
}
@Test
func testPublishPortRangeInvalidHostPortStart() throws {
#expect {
_ = try Parser.publishPorts(["65536-65537:9000-9001"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish host port")
}
}
@Test
func testPublishPortRangeZeroHostPortStart() throws {
#expect {
_ = try Parser.publishPorts(["0-1:9000-9001"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish host port")
}
}
@Test
func testPublishPortRangeInvalidHostPortEnd() throws {
#expect {
_ = try Parser.publishPorts(["65535-65536:9000-9001"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish host port")
}
}
@Test
func testPublishPortRangeInvalidHostPortRange() throws {
#expect {
_ = try Parser.publishPorts(["8000-8001-8002:9000-9001"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish host port")
}
}
@Test
func testPublishPortRangeNegativeHostPortRange() throws {
#expect {
_ = try Parser.publishPorts(["8001-8000:9000-9001"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish host port")
}
}
@Test
func testPublishPortRangeInvalidContainerPortStart() throws {
#expect {
_ = try Parser.publishPorts(["8000-8001:65536-65537"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish container port")
}
}
@Test
func testPublishPortRangeZeroContainerPortStart() throws {
#expect {
_ = try Parser.publishPorts(["8000-8001:0-1"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish container port")
}
}
@Test
func testPublishPortRangeInvalidContainerPortEnd() throws {
#expect {
_ = try Parser.publishPorts(["8000-8001:65535-65536"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish container port")
}
}
@Test
func testPublishPortRangeInvalidContainerPortRange() throws {
#expect {
_ = try Parser.publishPorts(["8000-8001:9000-9001-9002"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish container port")
}
}
@Test
func testPublishPortRangeNegativeContainerPortRange() throws {
#expect {
_ = try Parser.publishPorts(["8000-8001:9001-9000"])
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid publish container port")
}
}
@Test
func testRelativePaths() throws {
// Test bind mount with relative path "."
do {
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("test-bind-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let result = try Parser.mount("type=bind,src=.,dst=/foo", relativeTo: tempDir)
switch result {
case .filesystem(let fs):
#expect(fs.source == tempDir.standardizedFileURL.path)
#expect(fs.destination == "/foo")
#expect(!fs.isVolume)
case .volume:
#expect(Bool(false), "Expected filesystem mount, got volume")
}
}
// Test volume with relative path "./"
do {
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("test-volume-rel-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let result = try Parser.volume("./:/foo", relativeTo: tempDir)
switch result {
case .filesystem(let fs):
let expectedPath = tempDir.standardizedFileURL.path
// Normalize trailing slashes for comparison
#expect(fs.source.trimmingCharacters(in: CharacterSet(charactersIn: "/")) == expectedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/")))
#expect(fs.destination == "/foo")
case .volume:
#expect(Bool(false), "Expected filesystem mount, got volume")
}
}
// Test volume with nested relative path "./subdir"
do {
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("test-volume-rel-nested-\(UUID().uuidString)")
let nestedDir = tempDir.appendingPathComponent("subdir")
try FileManager.default.createDirectory(at: nestedDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let result = try Parser.volume("./subdir:/foo", relativeTo: tempDir)
switch result {
case .filesystem(let fs):
let expectedPath = nestedDir.standardizedFileURL.path
// Normalize trailing slashes for comparison
#expect(fs.source.trimmingCharacters(in: CharacterSet(charactersIn: "/")) == expectedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/")))
#expect(fs.destination == "/foo")
case .volume:
#expect(Bool(false), "Expected filesystem mount, got volume")
}
}
// Test volume with bare "." as source (current directory)
do {
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("test-volume-dot-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let result = try Parser.volume(".:/docs:ro", relativeTo: tempDir)
switch result {
case .filesystem(let fs):
let expectedPath = tempDir.standardizedFileURL.path
#expect(fs.source.trimmingCharacters(in: CharacterSet(charactersIn: "/")) == expectedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/")))
#expect(fs.destination == "/docs")
#expect(fs.options.contains("ro"))
case .volume:
#expect(Bool(false), "Expected filesystem mount, got volume")
}
}
// Test volume with ".." as source (parent directory)
do {
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("test-volume-dotdot-\(UUID().uuidString)")
let childDir = tempDir.appendingPathComponent("child")
try FileManager.default.createDirectory(at: childDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let result = try Parser.volume("..:/data", relativeTo: childDir)
switch result {
case .filesystem(let fs):
let expectedPath = tempDir.standardizedFileURL.path
#expect(fs.source.trimmingCharacters(in: CharacterSet(charactersIn: "/")) == expectedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/")))
#expect(fs.destination == "/data")
case .volume:
#expect(Bool(false), "Expected filesystem mount, got volume")
}
}
}
@Test
func testMountBindAbsolutePath() throws {
let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent("test-bind-abs-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let result = try Parser.mount("type=bind,src=\(tempDir.path),dst=/foo")
switch result {
case .filesystem(let fs):
#expect(fs.source == tempDir.path)
#expect(fs.destination == "/foo")
#expect(!fs.isVolume)
case .volume:
#expect(Bool(false), "Expected filesystem mount, got volume")
}
}
@Test
func testMountVolumeValidName() throws {
let result = try Parser.mount("type=volume,src=myvolume,dst=/data")
switch result {
case .filesystem:
#expect(Bool(false), "Expected volume mount, got filesystem")
case .volume(let vol):
#expect(vol.name == "myvolume")
#expect(vol.destination == "/data")
}
}
@Test
func testMountVolumeInvalidName() throws {
#expect {
_ = try Parser.mount("type=volume,src=.,dst=/data")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid volume name")
}
}
@Test
func testMountBindNonExistentPath() throws {
#expect {
_ = try Parser.mount("type=bind,src=/nonexistent/path,dst=/foo")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("path") && error.description.contains("does not exist")
}
}
@Test
func testMountBindFileInsteadOfDirectory() throws {
let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent("test-file-\(UUID().uuidString)")
try "test content".write(to: tempFile, atomically: true, encoding: .utf8)
defer {
try? FileManager.default.removeItem(at: tempFile)
}
#expect {
_ = try Parser.mount("type=bind,src=\(tempFile.path),dst=/foo")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("path") && error.description.contains("is not a directory")
}
}
@Test
func testIsValidDomainNameOk() throws {
let names = [
"a",
"a.b",
"foo.bar",
"F-O.B-R",
[
String(repeating: "0", count: 63),
String(repeating: "1", count: 63),
String(repeating: "2", count: 63),
String(repeating: "3", count: 63),
].joined(separator: "."),
]
for name in names {
#expect(Parser.isValidDomainName(name))
}
}
@Test
func testIsValidDomainNameBad() throws {
let names = [
".foo",
"foo.",
".foo.bar",
"foo.bar.",
"-foo.bar",
"foo.bar-",
[
String(repeating: "0", count: 63),
String(repeating: "1", count: 63),
String(repeating: "2", count: 63),
String(repeating: "3", count: 62),
"4",
].joined(separator: "."),
]
for name in names {
#expect(!Parser.isValidDomainName(name))
}
}
// MARK: - Environment Variable Tests
@Test
func testEnvExplicitValue() throws {
let result = Parser.env(envList: ["FOO=bar", "BAZ=qux"])
#expect(result == ["FOO=bar", "BAZ=qux"])
}
@Test
func testEnvImplicitInheritance() throws {
guard let homeValue = ProcessInfo.processInfo.environment["PATH"] else {
Issue.record("PATH environment variable not set")
return
}
let result = Parser.env(envList: ["PATH"])
#expect(result == ["PATH=\(homeValue)"])
}
@Test
func testEnvImplicitUndefinedVariable() throws {
// A variable that doesn't exist should be silently skipped
let result = Parser.env(envList: ["THIS_VAR_DEFINITELY_DOES_NOT_EXIST_12345"])
#expect(result.isEmpty)
}
@Test
func testEnvMixedExplicitAndImplicit() throws {
guard let homeValue = ProcessInfo.processInfo.environment["HOME"] else {
Issue.record("HOME environment variable not set")
return
}
let result = Parser.env(envList: ["FOO=bar", "HOME", "BAZ=qux"])
#expect(result == ["FOO=bar", "HOME=\(homeValue)", "BAZ=qux"])
}
@Test
func testEnvEmptyValue() throws {
// Explicit empty value should be preserved
let result = Parser.env(envList: ["EMPTY="])
#expect(result == ["EMPTY="])
}
@Test
func testAllEnvUserOverridesImage() throws {
let result = try Parser.allEnv(
imageEnvs: ["FOO=fromimage", "BAR=kept"],
envFiles: [],
envs: ["FOO=fromuser"]
)
#expect(Set(result) == Set(["FOO=fromuser", "BAR=kept"]))
}
@Test
func testAllEnvFileOverridesImage() throws {
let tmpFile = try tmpFileWithContent("FOO=fromfile\n")
defer { try? FileManager.default.removeItem(at: tmpFile) }
let result = try Parser.allEnv(
imageEnvs: ["FOO=fromimage", "BAR=kept"],
envFiles: [tmpFile.path],
envs: []
)
#expect(Set(result) == Set(["FOO=fromfile", "BAR=kept"]))
}
@Test
func testAllEnvUserOverridesFileOverridesImage() throws {
let tmpFile = try tmpFileWithContent("FOO=fromfile\nBAZ=fromfile\n")
defer { try? FileManager.default.removeItem(at: tmpFile) }
let result = try Parser.allEnv(
imageEnvs: ["FOO=fromimage", "BAR=fromimage"],
envFiles: [tmpFile.path],
envs: ["FOO=fromuser"]
)
#expect(Set(result) == Set(["FOO=fromuser", "BAR=fromimage", "BAZ=fromfile"]))
}
@Test
func testAllEnvRejectsBareNameFromImage() throws {
// Image config is untrusted: a bare name (no "=") must be dropped rather
// than expanded from the host process's environment.
let result = try Parser.allEnv(
imageEnvs: ["PATH", "FOO=fromimage"],
envFiles: [],
envs: []
)
#expect(Set(result) == Set(["FOO=fromimage"]))
}
private func tmpFileWithContent(_ content: String) throws -> URL {
let tempDir = FileManager.default.temporaryDirectory
let tempFile = tempDir.appendingPathComponent("envfile-test-\(UUID().uuidString)")
try content.write(to: tempFile, atomically: true, encoding: .utf8)
return tempFile
}
// NOTE: A lot of these env-file tests are recreations of the docker cli's unit tests for their
// env-file support.
@Test
func testParseEnvFileGoodFile() throws {
var content = """
foo=bar
baz=quux
# comment
_foobar=foobaz
with.dots=working
and_underscore=working too
"""
content += "\n \t "
let tmpFile = try tmpFileWithContent(content)
defer { try? FileManager.default.removeItem(at: tmpFile) }
let lines = try Parser.envFile(path: tmpFile.path)
let expectedLines = [
"foo=bar",
"baz=quux",
"_foobar=foobaz",
"with.dots=working",
"and_underscore=working too",
]
#expect(lines == expectedLines)
}
@Test
func testParseEnvFileMultipleEqualsSigns() throws {
let content = """
URL=https://foo.bar?baz=woo
"""
let tmpFile = try tmpFileWithContent(content)
defer { try? FileManager.default.removeItem(at: tmpFile) }
let lines = try Parser.envFile(path: tmpFile.path)
let expectedLines = [
"URL=https://foo.bar?baz=woo"
]
#expect(lines == expectedLines)
}
@Test
func testParseEnvFileEmptyFile() throws {
let tmpFile = try tmpFileWithContent("")
defer { try? FileManager.default.removeItem(at: tmpFile) }
let lines = try Parser.envFile(path: tmpFile.path)
#expect(lines.isEmpty)
}
@Test
func testParseEnvFileNonExistentFile() throws {
#expect {
_ = try Parser.envFile(path: "/nonexistent/foo_bar_baz")
} throws: { error in
guard let error = error as? ContainerizationError,
let cause = error.cause
else {
return false
}
return String(describing: cause).contains("No such file or directory")
}
}
@Test
func testParseEnvFileBadlyFormattedFile() throws {
let content = """
foo=bar
f =quux
"""
let tmpFile = try tmpFileWithContent(content)
defer { try? FileManager.default.removeItem(at: tmpFile) }
#expect {
_ = try Parser.envFile(path: tmpFile.path)
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("contains whitespaces")
}
}
@Test
func testParseEnvFileRandomFile() throws {
let content = """
first line
another invalid line
"""
let tmpFile = try tmpFileWithContent(content)
defer { try? FileManager.default.removeItem(at: tmpFile) }
#expect {
_ = try Parser.envFile(path: tmpFile.path)
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("first line") && error.description.contains("contains whitespaces")
}
}
@Test
func testParseEnvVariableDefinitionsFile() throws {
let content = """
# comment=
UNDEFINED_VAR
HOME
"""
let tmpFile = try tmpFileWithContent(content)
defer { try? FileManager.default.removeItem(at: tmpFile) }
let variables = try Parser.envFile(path: tmpFile.path)
// HOME should be imported from environment
guard let homeValue = ProcessInfo.processInfo.environment["HOME"] else {
Issue.record("HOME environment variable not set")
return
}
#expect(variables.count == 1)
#expect(variables[0] == "HOME=\(homeValue)")
}
@Test
func testParseEnvVariableWithNoNameFile() throws {
let content = """
# comment=
=blank variable names are an error case
"""
let tmpFile = try tmpFileWithContent(content)
defer { try? FileManager.default.removeItem(at: tmpFile) }
#expect {
_ = try Parser.envFile(path: tmpFile.path)
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("no variable name")
}
}
@Test
func testParseEnvFileFromNamedPipe() throws {
let pipePath = FileManager.default.temporaryDirectory
.appendingPathComponent("envfile-pipe-\(UUID().uuidString)")
// Create a named pipe (FIFO)
let result = mkfifo(pipePath.path, 0o600)
guard result == 0 else {
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM)
}
defer { try? FileManager.default.removeItem(at: pipePath) }
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
do {
let handle = try FileHandle(forWritingTo: pipePath)
try handle.write(contentsOf: "SECRET_KEY=value123\n".data(using: .utf8)!)
try handle.close()
} catch {
Issue.record(error)
}
group.leave()
}
// Read from pipe (blocks until writer connects)
let lines = try Parser.envFile(path: pipePath.path)
// Wait for write to complete
group.wait()
#expect(lines == ["SECRET_KEY=value123"])
}
// MARK: Network Parser Tests
@Test
func testParseNetworkSimpleName() throws {
let result = try Parser.network("default")
#expect(result.name == "default")
#expect(result.macAddress == nil)
}
@Test
func testParseNetworkWithMACAddress() throws {
let result = try Parser.network("backend,mac=02:42:ac:11:00:02")
#expect(result.name == "backend")
#expect(result.macAddress == "02:42:ac:11:00:02")
}
@Test
func testParseNetworkWithMACAddressHyphenSeparator() throws {
let result = try Parser.network("backend,mac=02-42-ac-11-00-02")
#expect(result.name == "backend")
#expect(result.macAddress == "02-42-ac-11-00-02")
}
@Test
func testParseNetworkEmptyString() throws {
#expect {
_ = try Parser.network("")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("network specification cannot be empty")
}
}
@Test
func testParseNetworkEmptyName() throws {
#expect {
_ = try Parser.network(",mac=02:42:ac:11:00:02")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("network name cannot be empty")
}
}
@Test
func testParseNetworkEmptyMACAddress() throws {
#expect {
_ = try Parser.network("backend,mac=")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("mac address value cannot be empty")
}
}
@Test
func testParseNetworkUnknownProperty() throws {
#expect {
_ = try Parser.network("backend,unknown=value")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("unknown network property") && error.description.contains("unknown")
}
}
@Test
func testParseNetworkInvalidPropertyFormat() throws {
#expect {
_ = try Parser.network("backend,invalidproperty")
} throws: { error in
guard let error = error as? ContainerizationError else {
return false
}
return error.description.contains("invalid property format")
}
}
// MARK: - Relative Path Passthrough Tests
@Test
func testProcessEntrypointRelativePathPassthrough() throws {
let processFlags = try Flags.Process.parse(["--cwd", "/bin"])
let managementFlags = try Flags.Management.parse(["--entrypoint", "./uname"])
let result = try Parser.process(
arguments: [],
processFlags: processFlags,
managementFlags: managementFlags,
config: nil
)
#expect(result.executable == "./uname")
#expect(result.workingDirectory == "/bin")
}
@Test
func testUlimitParserSoftAndHard() throws {
let result = try Parser.rlimits(["nofile=1024:2048"])
#expect(result.count == 1)
#expect(result[0].limit == "RLIMIT_NOFILE")
#expect(result[0].soft == 1024)
#expect(result[0].hard == 2048)
}
@Test
func testUlimitParserSingleValue() throws {
let result = try Parser.rlimits(["nproc=512"])
#expect(result.count == 1)
#expect(result[0].limit == "RLIMIT_NPROC")
#expect(result[0].soft == 512)
#expect(result[0].hard == 512)
}
@Test
func testUlimitParserUnlimited() throws {
let result = try Parser.rlimits(["memlock=unlimited"])
#expect(result.count == 1)
#expect(result[0].limit == "RLIMIT_MEMLOCK")
#expect(result[0].soft == UInt64.max)
#expect(result[0].hard == UInt64.max)
}
@Test
func testUlimitParserUnlimitedHardOnly() throws {
let result = try Parser.rlimits(["stack=8192:unlimited"])
#expect(result.count == 1)
#expect(result[0].limit == "RLIMIT_STACK")
#expect(result[0].soft == 8192)
#expect(result[0].hard == UInt64.max)
}
@Test
func testUlimitParserMinusOneAsUnlimited() throws {
let result = try Parser.rlimits(["core=-1"])
#expect(result.count == 1)
#expect(result[0].limit == "RLIMIT_CORE")
#expect(result[0].soft == UInt64.max)
#expect(result[0].hard == UInt64.max)
}
@Test
func testUlimitParserMultipleUlimits() throws {
let result = try Parser.rlimits(["nofile=1024:2048", "nproc=256", "cpu=60:120"])
#expect(result.count == 3)