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
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// Please keep this import statement as-is; this file is also used by the GenerateTestFixtures project, which doesn't have TestImports.swift.
#if canImport(SwiftFoundation)
import SwiftFoundation
#else
import Foundation
#endif
import XCTest
// -----
extension Calendar {
static var neutral: Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
calendar.locale = NSLocale.system
return calendar
}
}
enum Fixtures {
static nonisolated(unsafe) let mutableAttributedString = TypedFixture<NSMutableAttributedString>("NSMutableAttributedString") {
let string = NSMutableAttributedString(string: "0123456789")
// Should have: .xyyzzxyx.
let attrs1: [NSAttributedString.Key: Any] = [.init("Font"): "Helvetica", .init("Size"): 123]
let attrs2: [NSAttributedString.Key: Any] = [.init("Font"): "Times", .init("Size"): 456]
let attrs3NS = attrs2 as NSDictionary
let attrs3Maybe: [NSAttributedString.Key: Any]?
if let attrs3Swift = attrs3NS as? [String: Any] {
attrs3Maybe = Dictionary(attrs3Swift.map { (NSAttributedString.Key($0.key), $0.value) }, uniquingKeysWith: { $1 })
} else {
attrs3Maybe = nil
}
let attrs3 = try XCTUnwrap(attrs3Maybe)
string.setAttributes(attrs1, range: NSMakeRange(1, string.length - 2))
string.setAttributes(attrs2, range: NSMakeRange(2, 2))
string.setAttributes(attrs3, range: NSMakeRange(4, 2))
string.setAttributes(attrs2, range: NSMakeRange(8, 1))
return string
}
static nonisolated(unsafe) let attributedString = TypedFixture<NSAttributedString>("NSAttributedString") {
return NSAttributedString(attributedString: try Fixtures.mutableAttributedString.make())
}
// ===== ByteCountFormatter =====
static nonisolated(unsafe) let byteCountFormatterDefault = TypedFixture<ByteCountFormatter>("ByteCountFormatter-Default") {
return ByteCountFormatter()
}
static nonisolated(unsafe) let byteCountFormatterAllFieldsSet = TypedFixture<ByteCountFormatter>("ByteCountFormatter-AllFieldsSet") {
let f = ByteCountFormatter()
f.allowedUnits = [.useBytes, .useKB]
f.countStyle = .decimal
f.formattingContext = .beginningOfSentence
f.zeroPadsFractionDigits = true
f.includesCount = true
f.allowsNonnumericFormatting = false
f.includesUnit = false
f.includesCount = false
f.isAdaptive = false
return f
}
// ===== DateIntervalFormatter =====
static nonisolated(unsafe) let dateIntervalFormatterDefault = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-Default") {
let dif = DateIntervalFormatter()
let calendar = Calendar.neutral
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
return dif
}
static nonisolated(unsafe) let dateIntervalFormatterValuesSetWithoutTemplate = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-ValuesSetWithoutTemplate") {
let dif = DateIntervalFormatter()
var calendar = Calendar.neutral
calendar.locale = Locale(identifier: "ja-JP")
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
dif.dateStyle = .long
dif.timeStyle = .none
dif.timeZone = TimeZone(secondsFromGMT: 60 * 60)
return dif
}
static nonisolated(unsafe) let dateIntervalFormatterValuesSetWithTemplate = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-ValuesSetWithTemplate") {
let dif = DateIntervalFormatter()
var calendar = Calendar.neutral
calendar.locale = Locale(identifier: "ja-JP")
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
dif.dateTemplate = "dd mm yyyy HH:MM"
dif.timeZone = TimeZone(secondsFromGMT: 60 * 60)
return dif
}
// ===== ISO8601DateFormatter =====
static nonisolated(unsafe) let iso8601FormatterDefault = TypedFixture<ISO8601DateFormatter>("ISO8601DateFormatter-Default") {
let idf = ISO8601DateFormatter()
idf.timeZone = Calendar.neutral.timeZone
return idf
}
static nonisolated(unsafe) let iso8601FormatterOptionsSet = TypedFixture<ISO8601DateFormatter>("ISO8601DateFormatter-OptionsSet") {
let idf = ISO8601DateFormatter()
idf.timeZone = Calendar.neutral.timeZone
idf.formatOptions = [ .withDay, .withWeekOfYear, .withMonth, .withTimeZone, .withColonSeparatorInTimeZone, .withDashSeparatorInDate ]
return idf
}
// ===== NSTextCheckingResult =====
static nonisolated(unsafe) let textCheckingResultSimpleRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-SimpleRegex") {
let string = "aaa"
let regexp = try NSRegularExpression(pattern: "aaa", options: [])
let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first)
return result
}
static nonisolated(unsafe) let textCheckingResultExtendedRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-ExtendedRegex") {
let string = "aaaaaa"
let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a)))))", options: [])
let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first)
return result
}
static nonisolated(unsafe) let textCheckingResultComplexRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-ComplexRegex") {
let string = "aaaaaaaaa"
let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a(a(a(a))))))))", options: [])
let result = try XCTUnwrap(regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first)
return result
}
// ===== NSIndexSet =====
static nonisolated(unsafe) let indexSetEmpty = TypedFixture<NSIndexSet>("NSIndexSet-Empty") {
return NSIndexSet(indexesIn: NSMakeRange(0, 0))
}
static nonisolated(unsafe) let indexSetOneRange = TypedFixture<NSIndexSet>("NSIndexSet-OneRange") {
return NSIndexSet(indexesIn: NSMakeRange(0, 50))
}
static nonisolated(unsafe) let indexSetManyRanges = TypedFixture<NSIndexSet>("NSIndexSet-ManyRanges") {
let indexSet = NSMutableIndexSet()
indexSet.add(in: NSMakeRange(0, 50))
indexSet.add(in: NSMakeRange(100, 50))
indexSet.add(in: NSMakeRange(1000, 50))
indexSet.add(in: NSMakeRange(Int.max - 50, 50))
return indexSet.copy() as! NSIndexSet
}
static nonisolated(unsafe) let mutableIndexSetEmpty = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-Empty") {
return (try Fixtures.indexSetEmpty.make()).mutableCopy() as! NSMutableIndexSet
}
static nonisolated(unsafe) let mutableIndexSetOneRange = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-OneRange") {
return (try Fixtures.indexSetOneRange.make()).mutableCopy() as! NSMutableIndexSet
}
static nonisolated(unsafe) let mutableIndexSetManyRanges = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-ManyRanges") {
return (try Fixtures.indexSetManyRanges.make()).mutableCopy() as! NSMutableIndexSet
}
// ===== NSIndexPath =====
static nonisolated(unsafe) let indexPathEmpty = TypedFixture<NSIndexPath>("NSIndexPath-Empty") {
return NSIndexPath()
}
static nonisolated(unsafe) let indexPathOneIndex = TypedFixture<NSIndexPath>("NSIndexPath-OneIndex") {
return NSIndexPath(index: 52)
}
static nonisolated(unsafe) let indexPathManyIndices = TypedFixture<NSIndexPath>("NSIndexPath-ManyIndices") {
var indexPath = IndexPath()
indexPath.append([4, 8, 15, 16, 23, 42])
return indexPath as NSIndexPath
}
// ===== NSSet, NSMutableSet =====
static nonisolated(unsafe) let setOfNumbers = TypedFixture<NSSet>("NSSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSSet(array: numbers)
}
static nonisolated(unsafe) let setEmpty = TypedFixture<NSSet>("NSSet-Empty") {
return NSSet()
}
static nonisolated(unsafe) let mutableSetOfNumbers = TypedFixture<NSMutableSet>("NSMutableSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSMutableSet(array: numbers)
}
static nonisolated(unsafe) let mutableSetEmpty = TypedFixture<NSMutableSet>("NSMutableSet-Empty") {
return NSMutableSet()
}
// ===== NSCountedSet =====
static nonisolated(unsafe) let countedSetOfNumbersAppearingOnce = TypedFixture<NSCountedSet>("NSCountedSet-NumbersAppearingOnce") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSCountedSet(array: numbers)
}
static nonisolated(unsafe) let countedSetOfNumbersAppearingSeveralTimes = TypedFixture<NSCountedSet>("NSCountedSet-NumbersAppearingSeveralTimes") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
let set = NSCountedSet()
for _ in 0 ..< 5 {
for number in numbers {
set.add(number)
}
}
return set
}
static nonisolated(unsafe) let countedSetEmpty = TypedFixture<NSCountedSet>("NSCountedSet-Empty") {
return NSCountedSet()
}
// ===== NSCharacterSet, NSMutableCharacterSet =====
static nonisolated(unsafe) let characterSetEmpty = TypedFixture<NSCharacterSet>("NSCharacterSet-Empty") {
return NSCharacterSet()
}
static nonisolated(unsafe) let characterSetRange = TypedFixture<NSCharacterSet>("NSCharacterSet-Range") {
return NSCharacterSet(range: NSMakeRange(0, 255))
}
static nonisolated(unsafe) let characterSetString = TypedFixture<NSCharacterSet>("NSCharacterSet-String") {
return NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz")
}
static nonisolated(unsafe) let characterSetBitmap = TypedFixture<NSCharacterSet>("NSCharacterSet-Bitmap") {
let someSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz")
return NSCharacterSet(bitmapRepresentation: someSet.bitmapRepresentation)
}
static nonisolated(unsafe) let characterSetBuiltin = TypedFixture<NSCharacterSet>("NSCharacterSet-Builtin") {
return NSCharacterSet.alphanumerics as NSCharacterSet
}
// ===== NSOrderedSet, NSMutableOrderedSet =====
static nonisolated(unsafe) let orderedSetOfNumbers = TypedFixture<NSOrderedSet>("NSOrderedSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSOrderedSet(array: numbers)
}
static nonisolated(unsafe) let orderedSetEmpty = TypedFixture<NSOrderedSet>("NSOrderedSet-Empty") {
return NSOrderedSet()
}
static nonisolated(unsafe) let mutableOrderedSetOfNumbers = TypedFixture<NSMutableOrderedSet>("NSMutableOrderedSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSMutableOrderedSet(array: numbers)
}
static nonisolated(unsafe) let mutableOrderedSetEmpty = TypedFixture<NSMutableOrderedSet>("NSMutableOrderedSet-Empty") {
return NSMutableOrderedSet()
}
// ===== NSMeasurement =====
static nonisolated(unsafe) let zeroMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Zero") {
let noUnit = Unit(symbol: "")
return NSMeasurement(doubleValue: 0, unit: noUnit)
}
static nonisolated(unsafe) let lengthMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Length") {
return NSMeasurement(doubleValue: 45, unit: UnitLength.miles)
}
static nonisolated(unsafe) let frequencyMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Frequency") {
return NSMeasurement(doubleValue: 1400, unit: UnitFrequency.megahertz)
}
static nonisolated(unsafe) let angleMeasurement = TypedFixture<NSMeasurement>("NSMeasurement-Angle") {
return NSMeasurement(doubleValue: 90, unit: UnitAngle.degrees)
}
// ===== Fixture list =====
static nonisolated(unsafe) let _listOfAllFixtures: [AnyFixture] = [
AnyFixture(Fixtures.mutableAttributedString),
AnyFixture(Fixtures.attributedString),
AnyFixture(Fixtures.byteCountFormatterDefault),
AnyFixture(Fixtures.byteCountFormatterAllFieldsSet),
AnyFixture(Fixtures.dateIntervalFormatterDefault),
AnyFixture(Fixtures.dateIntervalFormatterValuesSetWithTemplate),
AnyFixture(Fixtures.dateIntervalFormatterValuesSetWithoutTemplate),
AnyFixture(Fixtures.iso8601FormatterDefault),
AnyFixture(Fixtures.iso8601FormatterOptionsSet),
AnyFixture(Fixtures.textCheckingResultSimpleRegex),
AnyFixture(Fixtures.textCheckingResultExtendedRegex),
AnyFixture(Fixtures.textCheckingResultComplexRegex),
AnyFixture(Fixtures.indexSetEmpty),
AnyFixture(Fixtures.indexSetOneRange),
AnyFixture(Fixtures.indexSetManyRanges),
AnyFixture(Fixtures.mutableIndexSetEmpty),
AnyFixture(Fixtures.mutableIndexSetOneRange),
AnyFixture(Fixtures.mutableIndexSetManyRanges),
AnyFixture(Fixtures.indexPathEmpty),
AnyFixture(Fixtures.indexPathOneIndex),
AnyFixture(Fixtures.indexPathManyIndices),
AnyFixture(Fixtures.setOfNumbers),
AnyFixture(Fixtures.setEmpty),
AnyFixture(Fixtures.mutableSetOfNumbers),
AnyFixture(Fixtures.mutableSetEmpty),
AnyFixture(Fixtures.countedSetOfNumbersAppearingOnce),
AnyFixture(Fixtures.countedSetOfNumbersAppearingSeveralTimes),
AnyFixture(Fixtures.countedSetEmpty),
AnyFixture(Fixtures.characterSetEmpty),
AnyFixture(Fixtures.characterSetRange),
AnyFixture(Fixtures.characterSetString),
AnyFixture(Fixtures.characterSetBitmap),
AnyFixture(Fixtures.characterSetBuiltin),
AnyFixture(Fixtures.orderedSetOfNumbers),
AnyFixture(Fixtures.orderedSetEmpty),
AnyFixture(Fixtures.mutableOrderedSetOfNumbers),
AnyFixture(Fixtures.mutableOrderedSetEmpty),
AnyFixture(Fixtures.zeroMeasurement),
AnyFixture(Fixtures.lengthMeasurement),
AnyFixture(Fixtures.frequencyMeasurement),
AnyFixture(Fixtures.angleMeasurement),
]
// This ensures that we do not have fixtures with duplicate identifiers:
static nonisolated(unsafe) var all: [AnyFixture] {
return Array(Fixtures.allFixturesByIdentifier.values)
}
static nonisolated(unsafe) var allFixturesByIdentifier: [String: AnyFixture] = {
let keysAndValues = Fixtures._listOfAllFixtures.map { ($0.identifier, $0) }
return Dictionary(keysAndValues, uniquingKeysWith: { _, _ in fatalError("No two keys should be the same in fixtures. Double-check keys in FixtureValues.swift to make sure they're all unique.") })
}()
}
// -----
// Support for the above:
enum FixtureVariant: String, CaseIterable {
case macOS10_14 = "macOS-10.14"
func url(fixtureRepository: URL) -> URL {
return URL(fileURLWithPath: self.rawValue, relativeTo: fixtureRepository)
}
}
protocol Fixture {
associatedtype ValueType
var identifier: String { get }
func make() throws -> ValueType
var supportsSecureCoding: Bool { get }
}
struct TypedFixture<ValueType: NSObject & NSCoding>: Fixture {
var identifier: String
private var creationHandler: () throws -> ValueType
init(_ identifier: String, creationHandler: @escaping () throws -> ValueType) {
self.identifier = identifier
self.creationHandler = creationHandler
}
func make() throws -> ValueType {
return try creationHandler()
}
var supportsSecureCoding: Bool {
let kind: Any.Type
if let made = try? make() {
kind = type(of: made)
} else {
kind = ValueType.self
}
return (kind as? NSSecureCoding.Type)?.supportsSecureCoding == true
}
}
struct AnyFixture: Fixture {
var identifier: String
private var creationHandler: () throws -> NSObject & NSCoding
let supportsSecureCoding: Bool
init<T: Fixture>(_ fixture: T) {
self.identifier = fixture.identifier
self.creationHandler = { return try fixture.make() as! (NSObject & NSCoding) }
self.supportsSecureCoding = fixture.supportsSecureCoding
}
func make() throws -> NSObject & NSCoding {
return try creationHandler()
}
}
enum FixtureError: Error {
case noneFound
}
extension Fixture where ValueType: NSObject & NSCoding {
func load(fixtureRepository: URL, variant: FixtureVariant) throws -> ValueType? {
let data = try Data(contentsOf: url(inFixtureRepository: fixtureRepository, variant: variant))
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
unarchiver.requiresSecureCoding = self.supportsSecureCoding
unarchiver.decodingFailurePolicy = .setErrorAndReturn
let value = unarchiver.decodeObject(of: ValueType.self, forKey: NSKeyedArchiveRootObjectKey)
if let error = unarchiver.error {
throw error
}
return value
}
func url(inFixtureRepository fixtureRepository: URL, variant: FixtureVariant) -> URL {
return variant.url(fixtureRepository: fixtureRepository)
.appendingPathComponent(identifier)
.appendingPathExtension("archive")
}
func loadEach(fixtureRepository: URL, handler: (ValueType, FixtureVariant) throws -> Void) throws {
var foundAny = false
for variant in FixtureVariant.allCases {
let fileURL = url(inFixtureRepository: fixtureRepository, variant: variant)
guard (try? fileURL.checkResourceIsReachable()) == true else { continue }
foundAny = true
if let value = try load(fixtureRepository: fixtureRepository, variant: variant) {
try handler(value, variant)
}
}
guard foundAny else { throw FixtureError.noneFound }
}
}
|