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
|
//
// 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(Experimental) @_spi(ForToolsIntegrationOnly) import Testing
private import _TestingInternals
#if canImport(Foundation)
import Foundation
@_spi(Experimental) import _Testing_Foundation
#endif
@Suite("Attachment Tests")
struct AttachmentTests {
@Test func saveValue() {
let attachableValue = MyAttachable(string: "<!doctype html>")
let attachment = Attachment(attachableValue, named: "AttachmentTests.saveValue.html")
attachment.attach()
}
#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 fileName = try #require(filePath.split { $0 == "/" || $0 == #"\"# }.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 fileName = try #require(filePath.split { $0 == "/" || $0 == #"\"# }.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.attach()
}.run(configuration: configuration)
}
}
#endif
@Test func attachValue() async {
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 == "loremipsum")
#expect(attachment.sourceLocation.fileID == #fileID)
valueAttached()
}
await Test {
let attachableValue = MyAttachable(string: "<!doctype html>")
Attachment(attachableValue, named: "loremipsum").attach()
}.run(configuration: configuration)
}
}
@Test func attachSendableValue() async {
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 == "loremipsum")
#expect(attachment.attachableValue is MySendableAttachable)
#expect(attachment.sourceLocation.fileID == #fileID)
valueAttached()
}
await Test {
let attachableValue = MySendableAttachable(string: "<!doctype html>")
Attachment(attachableValue, named: "loremipsum").attach()
}.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(attachableValue, named: "loremipsum").attach()
}.run(configuration: configuration)
}
}
}
#if canImport(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.withUnsafeBufferPointer { buffer in
#expect(buffer.count == data.count)
}
}
valueAttached()
}
await Test {
let attachment = try await Attachment(contentsOf: temporaryURL)
attachment.attach()
}.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).tgz")
valueAttached()
}
await Test {
let attachment = try await Attachment(contentsOf: temporaryURL)
attachment.attach()
}.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.withUnsafeBufferPointer(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.withUnsafeBufferPointer(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.withUnsafeBufferPointer(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.withUnsafeBufferPointer { 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)
@Test func data() throws {
let value = try #require("abc123".data(using: .utf8))
try test(value)
}
#endif
}
}
// MARK: - Fixtures
struct MyAttachable: Attachable, ~Copyable {
var string: String
var errorToThrow: (any Error)?
func withUnsafeBufferPointer<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 withUnsafeBufferPointer<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 withUnsafeBufferPointer<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)
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
|