-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathAttachmentTests.swift
More file actions
973 lines (844 loc) · 32.6 KB
/
AttachmentTests.swift
File metadata and controls
973 lines (844 loc) · 32.6 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
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//
@testable @_spi(ForToolsIntegrationOnly) import Testing
private import _TestingInternals
#if canImport(AppKit) && canImport(_Testing_AppKit)
import AppKit
@_spi(Experimental) import _Testing_AppKit
#endif
#if canImport(Foundation) && canImport(_Testing_Foundation)
import Foundation
import _Testing_Foundation
#endif
#if canImport(CoreGraphics) && canImport(_Testing_CoreGraphics)
import CoreGraphics
@_spi(Experimental) import _Testing_CoreGraphics
#endif
#if canImport(CoreImage) && canImport(_Testing_CoreImage)
import CoreImage
@_spi(Experimental) import _Testing_CoreImage
#endif
#if canImport(UIKit) && canImport(_Testing_UIKit)
import UIKit
@_spi(Experimental) import _Testing_UIKit
#endif
#if canImport(UniformTypeIdentifiers)
import UniformTypeIdentifiers
#endif
#if canImport(WinSDK) && canImport(_Testing_WinSDK)
import WinSDK
@testable @_spi(Experimental) import _Testing_WinSDK
#endif
@Suite("Attachment Tests")
struct AttachmentTests {
@Test func saveValue() {
let attachableValue = MyAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: "AttachmentTests.saveValue.html")
Attachment.record(attachment)
}
@Test func description() {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: "AttachmentTests.saveValue.html")
#expect(String(describing: attachment).contains(#""\#(attachment.preferredName)""#))
#expect(attachment.description.contains("MySendableAttachable("))
}
@Test func moveOnlyDescription() {
let attachableValue = MyAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: "AttachmentTests.saveValue.html")
#expect(attachment.description.contains(#""\#(attachment.preferredName)""#))
#expect(attachment.description.contains("'MyAttachable'"))
}
#if !SWT_NO_FILE_IO
func compare(_ attachableValue: borrowing MySendableAttachable, toContentsOfFileAtPath filePath: String) throws {
let file = try FileHandle(forReadingAtPath: filePath)
let bytes = try file.readToEnd()
let decodedValue = if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
try #require(String(validating: bytes, as: UTF8.self))
} else {
String(decoding: bytes, as: UTF8.self)
}
#expect(decodedValue == attachableValue.string)
}
@Test func writeAttachment() throws {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: "loremipsum.html")
// Write the attachment to disk, then read it back.
let filePath = try attachment.write(toFileInDirectoryAtPath: temporaryDirectory())
defer {
remove(filePath)
}
try compare(attachableValue, toContentsOfFileAtPath: filePath)
}
@Test func writeAttachmentWithNameConflict() throws {
// A sequence of suffixes that are guaranteed to cause conflict.
let randomBaseValue = UInt64.random(in: 0 ..< (.max - 10))
var suffixes = (randomBaseValue ..< randomBaseValue + 10).lazy
.flatMap { [$0, $0, $0] }
.map { String($0, radix: 36) }
.makeIterator()
let baseFileName = "\(UInt64.random(in: 0 ..< .max))loremipsum.html"
var createdFilePaths = [String]()
defer {
for filePath in createdFilePaths {
remove(filePath)
}
}
for i in 0 ..< 5 {
let attachableValue = MySendableAttachable(string: "<!doctype html>\(i)")
let attachment = Attachment(attachableValue, named: baseFileName)
// Write the attachment to disk, then read it back.
let filePath = try attachment.write(toFileInDirectoryAtPath: temporaryDirectory(), appending: suffixes.next()!)
createdFilePaths.append(filePath)
let filePathComponents = filePath.split { $0 == "/" || $0 == #"\"# }
let fileName = try #require(filePathComponents.last)
if i == 0 {
#expect(fileName == baseFileName)
} else {
#expect(fileName != baseFileName)
}
try compare(attachableValue, toContentsOfFileAtPath: filePath)
}
}
@Test func writeAttachmentWithMultiplePathExtensions() throws {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: "loremipsum.tgz.gif.jpeg.html")
// Write the attachment to disk once to ensure the original filename is not
// available and we add a suffix.
let originalFilePath = try attachment.write(toFileInDirectoryAtPath: temporaryDirectory())
defer {
remove(originalFilePath)
}
// Write the attachment to disk, then read it back.
let suffix = String(UInt64.random(in: 0 ..< .max), radix: 36)
let filePath = try attachment.write(toFileInDirectoryAtPath: temporaryDirectory(), appending: suffix)
defer {
remove(filePath)
}
let filePathComponents = filePath.split { $0 == "/" || $0 == #"\"# }
let fileName = try #require(filePathComponents.last)
#expect(fileName == "loremipsum-\(suffix).tgz.gif.jpeg.html")
try compare(attachableValue, toContentsOfFileAtPath: filePath)
}
#if os(Windows)
static let maximumNameCount = Int(_MAX_FNAME)
#else
static let maximumNameCount = Int(NAME_MAX)
#endif
@Test(arguments: [
#"/\:"#,
String(repeating: "a", count: maximumNameCount),
String(repeating: "a", count: maximumNameCount + 1),
String(repeating: "a", count: maximumNameCount + 2),
]) func writeAttachmentWithBadName(name: String) throws {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: name)
// Write the attachment to disk, then read it back.
let filePath = try attachment.write(toFileInDirectoryAtPath: temporaryDirectory())
defer {
remove(filePath)
}
try compare(attachableValue, toContentsOfFileAtPath: filePath)
}
@Test func fileSystemPathIsSetAfterWritingViaEventHandler() async throws {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
try await confirmation("Attachment detected") { valueAttached in
var configuration = Configuration()
configuration.attachmentsPath = try temporaryDirectory()
configuration.eventHandler = { event, _ in
guard case let .valueAttached(attachment) = event.kind else {
return
}
valueAttached()
// BUG: We could use #expect(throws: Never.self) here, but the Swift 6.1
// compiler crashes trying to expand the macro (rdar://138997009)
do {
let filePath = try #require(attachment.fileSystemPath)
defer {
remove(filePath)
}
try compare(attachableValue, toContentsOfFileAtPath: filePath)
} catch {
Issue.record(error)
}
}
await Test {
let attachment = Attachment(attachableValue, named: "loremipsum.html")
Attachment.record(attachment)
}.run(configuration: configuration)
}
}
#endif
@Test func attachValue() async {
await confirmation("Attachment detected", expectedCount: 2) { valueAttached in
var configuration = Configuration()
configuration.eventHandler = { event, _ in
guard case let .valueAttached(attachment) = event.kind else {
return
}
#expect(attachment.sourceLocation.fileID == #fileID)
valueAttached()
}
await Test {
let attachableValue1 = MyAttachable(string: "<!doctype html>")
Attachment.record(attachableValue1)
let attachableValue2 = MyAttachable(string: "<!doctype html>")
Attachment.record(Attachment(attachableValue2))
}.run(configuration: configuration)
}
}
@Test func attachSendableValue() async {
await confirmation("Attachment detected", expectedCount: 2) { valueAttached in
var configuration = Configuration()
configuration.eventHandler = { event, _ in
guard case let .valueAttached(attachment) = event.kind else {
return
}
#expect(attachment.attachableValue is MySendableAttachable)
#expect(attachment.sourceLocation.fileID == #fileID)
valueAttached()
}
await Test {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
Attachment.record(attachableValue)
Attachment.record(Attachment(attachableValue))
}.run(configuration: configuration)
}
}
@Test func issueRecordedWhenAttachingNonSendableValueThatThrows() async {
await confirmation("Attachment detected", expectedCount: 0) { valueAttached in
await confirmation("Issue recorded") { issueRecorded in
var configuration = Configuration()
configuration.eventHandler = { event, _ in
if case let .valueAttached(attachment) = event.kind {
#expect(attachment.sourceLocation.fileID == #fileID)
valueAttached()
} else if case let .issueRecorded(issue) = event.kind,
case let .valueAttachmentFailed(error) = issue.kind,
error is MyError {
#expect(issue.sourceLocation?.fileID == #fileID)
issueRecorded()
}
}
await Test {
var attachableValue = MyAttachable(string: "<!doctype html>")
attachableValue.errorToThrow = MyError()
Attachment.record(Attachment(attachableValue, named: "loremipsum"))
}.run(configuration: configuration)
}
}
}
#if canImport(Foundation) && canImport(_Testing_Foundation)
#if !SWT_NO_FILE_IO
@Test func attachContentsOfFileURL() async throws {
let data = try #require("<!doctype html>".data(using: .utf8))
let temporaryFileName = "\(UUID().uuidString).html"
let temporaryPath = try appendPathComponent(temporaryFileName, to: temporaryDirectory())
let temporaryURL = URL(fileURLWithPath: temporaryPath, isDirectory: false)
try data.write(to: temporaryURL)
defer {
try? FileManager.default.removeItem(at: temporaryURL)
}
await confirmation("Attachment detected") { valueAttached in
var configuration = Configuration()
configuration.eventHandler = { event, _ in
guard case let .valueAttached(attachment) = event.kind else {
return
}
#expect(attachment.preferredName == temporaryFileName)
#expect(throws: Never.self) {
try attachment.withUnsafeBytes { buffer in
#expect(buffer.count == data.count)
}
}
valueAttached()
}
await Test {
let attachment = try await Attachment(contentsOf: temporaryURL)
Attachment.record(attachment)
}.run(configuration: configuration)
}
}
#if !SWT_NO_PROCESS_SPAWNING
@Test func attachContentsOfDirectoryURL() async throws {
let temporaryDirectoryName = UUID().uuidString
let temporaryPath = try appendPathComponent(temporaryDirectoryName, to: temporaryDirectory())
let temporaryURL = URL(fileURLWithPath: temporaryPath, isDirectory: false)
try FileManager.default.createDirectory(at: temporaryURL, withIntermediateDirectories: true)
let fileData = try #require("Hello world".data(using: .utf8))
try fileData.write(to: temporaryURL.appendingPathComponent("loremipsum.txt"), options: [.atomic])
await confirmation("Attachment detected") { valueAttached in
var configuration = Configuration()
configuration.eventHandler = { event, _ in
guard case let .valueAttached(attachment) = event.kind else {
return
}
#expect(attachment.preferredName == "\(temporaryDirectoryName).zip")
try! attachment.withUnsafeBytes { buffer in
#expect(buffer.count > 32)
#expect(buffer[0] == UInt8(ascii: "P"))
#expect(buffer[1] == UInt8(ascii: "K"))
if #available(_regexAPI, *) {
#expect(buffer.contains("loremipsum.txt".utf8))
}
}
valueAttached()
}
await Test {
let attachment = try await Attachment(contentsOf: temporaryURL)
Attachment.record(attachment)
}.run(configuration: configuration)
}
}
#endif
@Test func attachUnsupportedContentsOfURL() async throws {
let url = try #require(URL(string: "https://www.example.com"))
await #expect(throws: CocoaError.self) {
_ = try await Attachment(contentsOf: url)
}
}
#endif
struct CodableAttachmentArguments: Sendable, CustomTestArgumentEncodable, CustomTestStringConvertible {
var forSecureCoding: Bool
var pathExtension: String?
var firstCharacter: Character
var decode: @Sendable (Data) throws -> String
@Sendable static func decodeWithJSONDecoder(_ data: Data) throws -> String {
try JSONDecoder().decode(MyCodableAttachable.self, from: data).string
}
@Sendable static func decodeWithPropertyListDecoder(_ data: Data) throws -> String {
try PropertyListDecoder().decode(MyCodableAttachable.self, from: data).string
}
@Sendable static func decodeWithNSKeyedUnarchiver(_ data: Data) throws -> String {
let result = try NSKeyedUnarchiver.unarchivedObject(ofClass: MySecureCodingAttachable.self, from: data)
return try #require(result).string
}
static func all() -> [Self] {
var result = [Self]()
for forSecureCoding in [false, true] {
let decode = forSecureCoding ? decodeWithNSKeyedUnarchiver : decodeWithPropertyListDecoder
result += [
Self(
forSecureCoding: forSecureCoding,
firstCharacter: forSecureCoding ? "b" : "{",
decode: forSecureCoding ? decodeWithNSKeyedUnarchiver : decodeWithJSONDecoder
)
]
result += [
Self(forSecureCoding: forSecureCoding, pathExtension: "xml", firstCharacter: "<", decode: decode),
Self(forSecureCoding: forSecureCoding, pathExtension: "plist", firstCharacter: "b", decode: decode),
]
if !forSecureCoding {
result += [
Self(forSecureCoding: forSecureCoding, pathExtension: "json", firstCharacter: "{", decode: decodeWithJSONDecoder),
]
}
}
return result
}
func encodeTestArgument(to encoder: some Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(pathExtension)
try container.encode(forSecureCoding)
try container.encode(firstCharacter.asciiValue!)
}
var testDescription: String {
"(forSecureCoding: \(forSecureCoding), extension: \(String(describingForTest: pathExtension)))"
}
}
@Test("Attach Codable- and NSSecureCoding-conformant values", .serialized, arguments: CodableAttachmentArguments.all())
func attachCodable(args: CodableAttachmentArguments) async throws {
var name = "loremipsum"
if let ext = args.pathExtension {
name = "\(name).\(ext)"
}
func open<T>(_ attachment: borrowing Attachment<T>) throws where T: Attachable {
try attachment.attachableValue.withUnsafeBytes(for: attachment) { bytes in
#expect(bytes.first == args.firstCharacter.asciiValue)
let decodedStringValue = try args.decode(Data(bytes))
#expect(decodedStringValue == "stringly speaking")
}
}
if args.forSecureCoding {
let attachableValue = MySecureCodingAttachable(string: "stringly speaking")
let attachment = Attachment(attachableValue, named: name)
try open(attachment)
} else {
let attachableValue = MyCodableAttachable(string: "stringly speaking")
let attachment = Attachment(attachableValue, named: name)
try open(attachment)
}
}
@Test("Attach NSSecureCoding-conformant value but with a JSON type")
func attachNSSecureCodingAsJSON() async throws {
let attachableValue = MySecureCodingAttachable(string: "stringly speaking")
let attachment = Attachment(attachableValue, named: "loremipsum.json")
#expect(throws: CocoaError.self) {
try attachment.attachableValue.withUnsafeBytes(for: attachment) { _ in }
}
}
@Test("Attach NSSecureCoding-conformant value but with a nonsensical type")
func attachNSSecureCodingAsNonsensical() async throws {
let attachableValue = MySecureCodingAttachable(string: "stringly speaking")
let attachment = Attachment(attachableValue, named: "loremipsum.gif")
#expect(throws: CocoaError.self) {
try attachment.attachableValue.withUnsafeBytes(for: attachment) { _ in }
}
}
#endif
}
extension AttachmentTests {
@Suite("Built-in conformances")
struct BuiltInConformances {
func test(_ value: some Attachable) throws {
#expect(value.estimatedAttachmentByteCount == 6)
let attachment = Attachment(value)
try attachment.withUnsafeBytes { buffer in
#expect(buffer.elementsEqual("abc123".utf8))
#expect(buffer.count == 6)
}
}
@Test func uint8Array() throws {
let value: [UInt8] = Array("abc123".utf8)
try test(value)
}
@Test func uint8ContiguousArray() throws {
let value: ContiguousArray<UInt8> = ContiguousArray("abc123".utf8)
try test(value)
}
@Test func uint8ArraySlice() throws {
let value: ArraySlice<UInt8> = Array("abc123".utf8)[...]
try test(value)
}
@Test func string() throws {
let value = "abc123"
try test(value)
}
@Test func substring() throws {
let value: Substring = "abc123"[...]
try test(value)
}
#if canImport(Foundation) && canImport(_Testing_Foundation)
@Test func data() throws {
let value = try #require("abc123".data(using: .utf8))
try test(value)
}
#endif
}
}
extension AttachmentTests {
@Suite("Image tests")
struct ImageTests {
enum ImageTestError: Error {
case couldNotCreateCGContext
case couldNotCreateCGGradient
case couldNotCreateCGImage
}
#if canImport(CoreGraphics) && canImport(_Testing_CoreGraphics)
static let cgImage = Result<CGImage, any Error> {
let size = CGSize(width: 32.0, height: 32.0)
let rgb = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.premultipliedFirst.rawValue
guard let context = CGContext(
data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: Int(size.width) * 4,
space: rgb,
bitmapInfo: bitmapInfo
) else {
throw ImageTestError.couldNotCreateCGContext
}
guard let gradient = CGGradient(
colorsSpace: rgb,
colors: [
CGColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0),
CGColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0),
CGColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0),
] as CFArray,
locations: nil
) else {
throw ImageTestError.couldNotCreateCGGradient
}
context.drawLinearGradient(
gradient,
start: .zero,
end: CGPoint(x: size.width, y: size.height),
options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]
)
guard let image = context.makeImage() else {
throw ImageTestError.couldNotCreateCGImage
}
return image
}
@available(_uttypesAPI, *)
@Test func attachCGImage() throws {
let image = try Self.cgImage.get()
let attachment = Attachment(image, named: "diamond")
#expect(attachment.attachableValue === image)
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
Attachment.record(attachment)
}
@available(_uttypesAPI, *)
@Test func attachCGImageDirectly() async throws {
await confirmation("Attachment detected") { valueAttached in
var configuration = Configuration()
configuration.eventHandler = { event, _ in
if case .valueAttached = event.kind {
valueAttached()
}
}
await Test {
let image = try Self.cgImage.get()
Attachment.record(image, named: "diamond.jpg")
}.run(configuration: configuration)
}
}
@available(_uttypesAPI, *)
@Test(arguments: [Float(0.0).nextUp, 0.25, 0.5, 0.75, 1.0], [.png as UTType?, .jpeg, .gif, .image, nil])
func attachCGImage(quality: Float, type: UTType?) throws {
let image = try Self.cgImage.get()
let format = type.map { AttachableImageFormat($0, encodingQuality: quality) }
let attachment = Attachment(image, named: "diamond", as: format)
#expect(attachment.attachableValue === image)
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
if let ext = type?.preferredFilenameExtension {
#expect(attachment.preferredName == ("diamond" as NSString).appendingPathExtension(ext))
}
}
@available(_uttypesAPI, *)
@Test(arguments: [AttachableImageFormat.png, .jpeg, .jpeg(withEncodingQuality: 0.5), .init(.tiff)])
func attachCGImage(format: AttachableImageFormat) throws {
let image = try Self.cgImage.get()
let attachment = Attachment(image, named: "diamond", as: format)
#expect(attachment.attachableValue === image)
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
if let ext = format.contentType.preferredFilenameExtension {
#expect(attachment.preferredName == ("diamond" as NSString).appendingPathExtension(ext))
}
}
#if !SWT_NO_EXIT_TESTS
@available(_uttypesAPI, *)
@Test func cannotAttachCGImageWithNonImageType() async {
await #expect(processExitsWith: .failure) {
let format = AttachableImageFormat(.mp3)
let attachment = Attachment(try Self.cgImage.get(), named: "diamond", as: format)
try attachment.attachableValue.withUnsafeBytes(for: attachment) { _ in }
}
}
#endif
#if canImport(CoreImage) && canImport(_Testing_CoreImage)
@available(_uttypesAPI, *)
@Test func attachCIImage() throws {
let image = CIImage(cgImage: try Self.cgImage.get())
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue === image)
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}
#endif
#if canImport(AppKit) && canImport(_Testing_AppKit)
static var nsImage: NSImage {
get throws {
let cgImage = try cgImage.get()
let size = CGSize(width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
return NSImage(cgImage: cgImage, size: size)
}
}
@available(_uttypesAPI, *)
@Test func attachNSImage() throws {
let image = try Self.nsImage
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}
@available(_uttypesAPI, *)
@Test func attachNSImageWithCustomRep() throws {
let image = NSImage(size: NSSize(width: 32.0, height: 32.0), flipped: false) { rect in
NSColor.red.setFill()
rect.fill()
return true
}
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}
@available(_uttypesAPI, *)
@Test func attachNSImageWithSubclassedNSImage() throws {
let image = MyImage(size: NSSize(width: 32.0, height: 32.0))
image.addRepresentation(NSCustomImageRep(size: image.size, flipped: false) { rect in
NSColor.green.setFill()
rect.fill()
return true
})
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue === image)
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}
@available(_uttypesAPI, *)
@Test func attachNSImageWithSubclassedRep() throws {
let image = NSImage(size: NSSize(width: 32.0, height: 32.0))
image.addRepresentation(MyImageRep<Int>())
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue.size == image.size) // NSImage makes a copy
let firstRep = try #require(attachment.attachableValue.representations.first)
#expect(!(firstRep is MyImageRep<Int>))
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
}
#endif
#if canImport(UIKit) && canImport(_Testing_UIKit)
@available(_uttypesAPI, *)
@Test func attachUIImage() throws {
let image = UIImage(cgImage: try Self.cgImage.get())
let attachment = Attachment(image, named: "diamond.jpg")
#expect(attachment.attachableValue === image)
try attachment.attachableValue.withUnsafeBytes(for: attachment) { buffer in
#expect(buffer.count > 32)
}
Attachment.record(attachment)
}
#endif
#endif
#if canImport(WinSDK) && canImport(_Testing_WinSDK)
private func copyHICON() throws -> HICON {
try #require(LoadIconA(nil, swt_IDI_SHIELD()))
}
@MainActor @Test func attachHICON() throws {
let icon = try copyHICON()
defer {
DestroyIcon(icon)
}
let attachment = Attachment(icon, named: "diamond.jpeg")
try attachment.withUnsafeBytes { buffer in
#expect(buffer.count > 32)
}
}
private func copyHBITMAP() throws -> HBITMAP {
let (width, height) = (GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON))
let icon = try copyHICON()
defer {
DestroyIcon(icon)
}
let screenDC = try #require(GetDC(nil))
defer {
ReleaseDC(nil, screenDC)
}
let dc = try #require(CreateCompatibleDC(nil))
defer {
DeleteDC(dc)
}
let bitmap = try #require(CreateCompatibleBitmap(screenDC, width, height))
let oldSelectedObject = SelectObject(dc, bitmap)
defer {
_ = SelectObject(dc, oldSelectedObject)
}
DrawIcon(dc, 0, 0, icon)
return bitmap
}
@MainActor @Test func attachHBITMAP() throws {
let bitmap = try copyHBITMAP()
defer {
DeleteObject(bitmap)
}
let attachment = Attachment(bitmap, named: "diamond.png")
try attachment.withUnsafeBytes { buffer in
#expect(buffer.count > 32)
}
Attachment.record(attachment)
}
@MainActor @Test func attachHBITMAPAsJPEG() throws {
let bitmap = try copyHBITMAP()
defer {
DeleteObject(bitmap)
}
let hiFi = Attachment(bitmap, named: "hifi", as: .jpeg(withEncodingQuality: 1.0))
let loFi = Attachment(bitmap, named: "lofi", as: .jpeg(withEncodingQuality: 0.1))
try hiFi.withUnsafeBytes { hiFi in
try loFi.withUnsafeBytes { loFi in
#expect(hiFi.count > loFi.count)
}
}
Attachment.record(loFi)
}
private func copyIWICBitmap() throws -> UnsafeMutablePointer<IWICBitmap> {
let factory = try IWICImagingFactory.create()
defer {
_ = factory.pointee.lpVtbl.pointee.Release(factory)
}
let bitmap = try copyHBITMAP()
defer {
DeleteObject(bitmap)
}
var wicBitmap: UnsafeMutablePointer<IWICBitmap>?
let rCreate = factory.pointee.lpVtbl.pointee.CreateBitmapFromHBITMAP(factory, bitmap, nil, WICBitmapUsePremultipliedAlpha, &wicBitmap)
guard rCreate == S_OK, let wicBitmap else {
throw ImageAttachmentError.comObjectCreationFailed(IWICBitmap.self, rCreate)
}
return wicBitmap
}
@MainActor @Test func attachIWICBitmap() throws {
let wicBitmap = try copyIWICBitmap()
defer {
_ = wicBitmap.pointee.lpVtbl.pointee.Release(wicBitmap)
}
let attachment = Attachment(wicBitmap, named: "diamond.png")
try attachment.withUnsafeBytes { buffer in
#expect(buffer.count > 32)
}
Attachment.record(attachment)
}
@MainActor @Test func attachIWICBitmapSource() throws {
let wicBitmapSource = try copyIWICBitmap().cast(to: IWICBitmapSource.self)
defer {
_ = wicBitmapSource.pointee.lpVtbl.pointee.Release(wicBitmapSource)
}
let attachment = Attachment(wicBitmapSource, named: "diamond.png")
try attachment.withUnsafeBytes { buffer in
#expect(buffer.count > 32)
}
Attachment.record(attachment)
}
@MainActor @Test func pathExtensionAndCLSID() {
let pngCLSID = AttachableImageFormat.png.clsid
let pngFilename = AttachableImageFormat.appendPathExtension(for: pngCLSID, to: "example")
#expect(pngFilename == "example.png")
let jpegCLSID = AttachableImageFormat.jpeg.clsid
let jpegFilename = AttachableImageFormat.appendPathExtension(for: jpegCLSID, to: "example")
#expect(jpegFilename == "example.jpeg")
let pngjpegFilename = AttachableImageFormat.appendPathExtension(for: jpegCLSID, to: "example.png")
#expect(pngjpegFilename == "example.png.jpeg")
let jpgjpegFilename = AttachableImageFormat.appendPathExtension(for: jpegCLSID, to: "example.jpg")
#expect(jpgjpegFilename == "example.jpg")
}
#endif
#if (canImport(CoreGraphics) && canImport(_Testing_CoreGraphics)) || (canImport(WinSDK) && canImport(_Testing_WinSDK))
@available(_uttypesAPI, *)
@Test func imageFormatFromPathExtension() {
let format = AttachableImageFormat(pathExtension: "png")
#expect(format != nil)
}
#endif
}
}
// MARK: - Fixtures
struct MyAttachable: Attachable, ~Copyable {
var string: String
var errorToThrow: (any Error)?
func withUnsafeBytes<R>(for attachment: borrowing Attachment<Self>, _ body: (UnsafeRawBufferPointer) throws -> R) throws -> R {
if let errorToThrow {
throw errorToThrow
}
var string = string
return try string.withUTF8 { buffer in
try body(.init(buffer))
}
}
}
@available(*, unavailable)
extension MyAttachable: Sendable {}
struct MySendableAttachable: Attachable, Sendable {
var string: String
func withUnsafeBytes<R>(for attachment: borrowing Attachment<Self>, _ body: (UnsafeRawBufferPointer) throws -> R) throws -> R {
#expect(attachment.attachableValue.string == string)
var string = string
return try string.withUTF8 { buffer in
try body(.init(buffer))
}
}
}
struct MySendableAttachableWithDefaultByteCount: Attachable, Sendable {
var string: String
func withUnsafeBytes<R>(for attachment: borrowing Attachment<Self>, _ body: (UnsafeRawBufferPointer) throws -> R) throws -> R {
var string = string
return try string.withUTF8 { buffer in
try body(.init(buffer))
}
}
}
#if canImport(Foundation) && canImport(_Testing_Foundation)
struct MyCodableAttachable: Codable, Attachable, Sendable {
var string: String
}
final class MySecureCodingAttachable: NSObject, NSSecureCoding, Attachable, Sendable {
let string: String
init(string: String) {
self.string = string
}
static var supportsSecureCoding: Bool {
true
}
func encode(with coder: NSCoder) {
coder.encode(string, forKey: "string")
}
required init?(coder: NSCoder) {
string = (coder.decodeObject(of: NSString.self, forKey: "string") as? String) ?? ""
}
}
final class MyCodableAndSecureCodingAttachable: NSObject, Codable, NSSecureCoding, Attachable, Sendable {
let string: String
static var supportsSecureCoding: Bool {
true
}
func encode(with coder: NSCoder) {
coder.encode(string, forKey: "string")
}
required init?(coder: NSCoder) {
string = (coder.decodeObject(of: NSString.self, forKey: "string") as? String) ?? ""
}
}
#endif
#if canImport(AppKit) && canImport(_Testing_AppKit)
private final class MyImage: NSImage {
override init(size: NSSize) {
super.init(size: size)
}
required init(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) {
fatalError("Unimplemented")
}
required init(coder: NSCoder) {
fatalError("Unimplemented")
}
override func copy(with zone: NSZone?) -> Any {
// Intentionally make a copy as NSImage instead of MyImage to exercise the
// cast-failed code path in the overlay.
NSImage()
}
}
private final class MyImageRep<T>: NSImageRep {
override init() {
super.init()
size = NSSize(width: 32.0, height: 32.0)
}
required init?(coder: NSCoder) {
fatalError("Unimplemented")
}
override func draw() -> Bool {
NSColor.blue.setFill()
NSRect(origin: .zero, size: size).fill()
return true
}
}
#endif