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
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
class TestNSArray : XCTestCase {
func test_BasicConstruction() {
let array = NSArray()
let array2 : NSArray = ["foo", "bar"]
XCTAssertEqual(array.count, 0)
XCTAssertEqual(array2.count, 2)
}
func test_constructors() {
let arrayNil = NSArray(objects: nil, count: 0)
XCTAssertEqual(arrayNil.count, 0)
let array1 = NSArray(object: "foo")
XCTAssertEqual(array1.count, 1)
let testStrings: [AnyObject] = [NSString(string:"foo"), NSString(string: "bar")]
testStrings.withUnsafeBufferPointer { ptr in
let array2 = NSArray(objects: ptr.baseAddress, count: 1)
XCTAssertEqual(array1, array2)
}
let array3 = NSArray(objects: "foo" as NSString, "bar" as NSString, "baz" as NSString)
XCTAssertEqual(array3.count, 3)
let array4 = NSArray(array: ["foo", "bar", "baz"])
XCTAssertEqual(array4.count, 3)
let array5 = NSArray(arrayLiteral: "foo", "bar", "baz")
XCTAssertEqual(array5.count, 3)
XCTAssertEqual(array3, array4)
XCTAssertEqual(array3, array5)
XCTAssertEqual(array4, array5)
let mutArray = NSMutableArray(array: [1, 2, 3, 4])
let array6 = NSArray(array: mutArray)
XCTAssertEqual(array6, mutArray)
mutArray[0] = 0
XCTAssertNotEqual(array6, mutArray)
let array7 = NSMutableArray(array: mutArray)
XCTAssertEqual(array7, mutArray)
array7.removeObject(at: 3)
XCTAssertNotEqual(array7.count, mutArray.count)
}
func test_constructorWithCopyItems() {
let foo = "foo" as NSMutableString
let array1 = NSArray(array: [foo], copyItems: false)
let array2 = NSArray(array: [foo], copyItems: true)
XCTAssertEqual(array1[0] as! String, "foo")
XCTAssertEqual(array2[0] as! String, "foo")
foo.append("1")
XCTAssertEqual(array1[0] as! String, "foo1")
XCTAssertEqual(array2[0] as! String, "foo")
}
func test_enumeration() {
let array : NSArray = ["foo", "bar", "baz"]
let e = array.objectEnumerator()
XCTAssertEqual((e.nextObject() as! String), "foo")
XCTAssertEqual((e.nextObject() as! String), "bar")
XCTAssertEqual((e.nextObject() as! String), "baz")
XCTAssertNil(e.nextObject())
XCTAssertNil(e.nextObject())
let r = array.reverseObjectEnumerator()
XCTAssertEqual((r.nextObject() as! String), "baz")
XCTAssertEqual((r.nextObject() as! String), "bar")
XCTAssertEqual((r.nextObject() as! String), "foo")
XCTAssertNil(r.nextObject())
XCTAssertNil(r.nextObject())
let empty = NSArray().objectEnumerator()
XCTAssertNil(empty.nextObject())
XCTAssertNil(empty.nextObject())
let reverseEmpty = NSArray().reverseObjectEnumerator()
XCTAssertNil(reverseEmpty.nextObject())
XCTAssertNil(reverseEmpty.nextObject())
}
func test_enumerationUsingBlock() {
let array : NSArray = NSArray(array: Array(0..<100))
let createIndexesArrayHavingSeen = { (havingSeen: IndexSet) in
return (0 ..< array.count).map { havingSeen.contains($0) }
}
let noIndexes = IndexSet()
let allIndexes = IndexSet(integersIn: 0 ..< array.count)
let firstHalfOfIndexes = IndexSet(integersIn: 0 ..< array.count / 2)
let lastHalfOfIndexes = IndexSet(integersIn: array.count / 2 ..< array.count)
let evenIndexes : IndexSet = {
var indexes = IndexSet()
for index in allIndexes.filter({ $0 % 2 == 0 }) {
indexes.insert(index)
}
return indexes
}()
let testExpectingToSee = { (expectation: IndexSet, block: (inout UnsafeMutableBufferPointer<Bool>) -> Void) in
var indexesSeen = createIndexesArrayHavingSeen(noIndexes)
indexesSeen.withUnsafeMutableBufferPointer(block)
XCTAssertEqual(indexesSeen, createIndexesArrayHavingSeen(expectation))
}
// Test enumerateObjects(_:), allowing it to run to completion...
testExpectingToSee(allIndexes) { (indexesSeen) in
array.enumerateObjects { (value, index, stop) in
XCTAssertEqual(value as! NSNumber, array[index] as! NSNumber)
indexesSeen[index] = true
}
}
// ... and stopping after the first half:
testExpectingToSee(firstHalfOfIndexes) { (indexesSeen) in
array.enumerateObjects { (value, index, stop) in
XCTAssertEqual(value as! NSNumber, array[index] as! NSNumber)
if firstHalfOfIndexes.contains(index) {
indexesSeen[index] = true
} else {
stop.pointee = true
}
}
}
// -----
// Test enumerateObjects(options:using) and enumerateObjects(at:options:using:):
// Test each of these options combinations:
let optionsToTest : [NSEnumerationOptions] = [
[],
[.concurrent],
[.reverse],
[.concurrent, .reverse],
]
for options in optionsToTest {
// Run to completion,
testExpectingToSee(allIndexes) { (indexesSeen) in
array.enumerateObjects(options: options, using: { (value, index, stop) in
XCTAssertEqual(value as! NSNumber, array[index] as! NSNumber)
indexesSeen[index] = true
})
}
// run it only for half the indexes (use the right half depending on where we start),
let indexesForHalfEnumeration = options.contains(.reverse) ? lastHalfOfIndexes : firstHalfOfIndexes
testExpectingToSee(indexesForHalfEnumeration) { (indexesSeen) in
array.enumerateObjects(options: options, using: { (value, index, stop) in
XCTAssertEqual(value as! NSNumber, array[index] as! NSNumber)
if indexesForHalfEnumeration.contains(index) {
indexesSeen[index] = true
} else {
stop.pointee = true
}
})
}
// run only for a specific index set to test the at:… variant,
testExpectingToSee(evenIndexes) { (indexesSeen) in
array.enumerateObjects(at: evenIndexes, options: options, using: { (value, index, stop) in
XCTAssertEqual(value as! NSNumber, array[index] as! NSNumber)
indexesSeen[index] = true
})
}
// and run for some indexes only to test stopping.
var indexesForStaggeredEnumeration = indexesForHalfEnumeration
indexesForStaggeredEnumeration.formIntersection(evenIndexes)
let finalCount = indexesForStaggeredEnumeration.count
let lockForSeenCount = NSLock()
var seenCount = 0
testExpectingToSee(indexesForStaggeredEnumeration) { (indexesSeen) in
array.enumerateObjects(at: evenIndexes, options: options, using: { (value, index, stop) in
XCTAssertEqual(value as! NSNumber, array[index] as! NSNumber)
if (indexesForStaggeredEnumeration.contains(index)) {
indexesSeen[index] = true
lockForSeenCount.lock()
seenCount += 1
let currentCount = seenCount
lockForSeenCount.unlock()
if currentCount == finalCount {
stop.pointee = true
}
}
})
}
}
}
func test_sequenceType() {
let array : NSArray = ["foo", "bar", "baz"]
var res = [String]()
for obj in array {
res.append((obj as! String))
}
XCTAssertEqual(res, ["foo", "bar", "baz"])
}
// func test_getObjects() {
// let array : NSArray = ["foo", "bar", "baz", "foo1", "bar2", "baz3",].bridge()
// var objects = [AnyObject]()
// array.getObjects(&objects, range: NSRange(location: 1, length: 3))
// XCTAssertEqual(objects.count, 3)
// let fetched = [
// (objects[0] as! NSString).bridge(),
// (objects[1] as! NSString).bridge(),
// (objects[2] as! NSString).bridge(),
// ]
// XCTAssertEqual(fetched, ["bar", "baz", "foo1"])
// }
func test_objectAtIndex() {
let array : NSArray = ["foo", "bar"]
let foo = array.object(at: 0) as! String
XCTAssertEqual(foo, "foo")
let bar = array.object(at: 1) as! String
XCTAssertEqual(bar, "bar")
}
func test_binarySearch() {
let numbers: [AnyObject] = [
NSNumber(value: 0 as Int), NSNumber(value: 1 as Int), NSNumber(value: 2 as Int), NSNumber(value: 2 as Int), NSNumber(value: 3 as Int),
NSNumber(value: 4 as Int), NSNumber(value: 4 as Int), NSNumber(value: 6 as Int), NSNumber(value: 7 as Int), NSNumber(value: 7 as Int),
NSNumber(value: 7 as Int), NSNumber(value: 8 as Int), NSNumber(value: 9 as Int), NSNumber(value: 9 as Int)]
let array = NSArray(array: numbers)
// Not sure how to test fatal errors.
// NSArray throws NSInvalidArgument if range exceeds bounds of the array.
// let rangeOutOfArray = NSRange(location: 5, length: 15)
// let _ = array.indexOfObject(NSNumber(value: 9 as Int), inSortedRange: rangeOutOfArray, options: [.insertionIndex, .firstEqual], usingComparator: compareIntNSNumber)
// NSArray throws NSInvalidArgument if both .firstEqual and .lastEqual are specified
// let searchForBoth: NSBinarySearchingOptions = [.firstEqual, .lastEqual]
// let _ = objectIndexInArray(array, value: 9, startingFrom: 0, length: 13, options: searchForBoth)
let notFound = objectIndexInArray(array, value: 11, startingFrom: 0, length: 13)
XCTAssertEqual(notFound, NSNotFound, "NSArray return NSNotFound if object is not found.")
let notFoundInRange = objectIndexInArray(array, value: 7, startingFrom: 0, length: 5)
XCTAssertEqual(notFoundInRange, NSNotFound, "NSArray return NSNotFound if object is not found.")
let indexOfAnySeven = objectIndexInArray(array, value: 7, startingFrom: 0, length: 13)
XCTAssertTrue(Set([8, 9, 10]).contains(indexOfAnySeven), "If no options provided NSArray returns an arbitrary matching object's index.")
let indexOfFirstNine = objectIndexInArray(array, value: 9, startingFrom: 7, length: 6, options: [.firstEqual])
XCTAssertTrue(indexOfFirstNine == 12, "If .FirstEqual is set NSArray returns the lowest index of equal objects.")
let indexOfLastTwo = objectIndexInArray(array, value: 2, startingFrom: 1, length: 7, options: [.lastEqual])
XCTAssertTrue(indexOfLastTwo == 3, "If .LastEqual is set NSArray returns the highest index of equal objects.")
let anyIndexToInsertNine = objectIndexInArray(array, value: 9, startingFrom: 0, length: 13, options: [.insertionIndex])
XCTAssertTrue(Set([12, 13, 14]).contains(anyIndexToInsertNine), "If .InsertionIndex is specified and no other options provided NSArray returns any equal or one larger index than any matching object’s index.")
let lowestIndexToInsertTwo = objectIndexInArray(array, value: 2, startingFrom: 0, length: 5, options: [.insertionIndex, .firstEqual])
XCTAssertTrue(lowestIndexToInsertTwo == 2, "If both .InsertionIndex and .FirstEqual are specified NSArray returns the lowest index of equal objects.")
let highestIndexToInsertNine = objectIndexInArray(array, value: 9, startingFrom: 7, length: 6, options: [.insertionIndex, .lastEqual])
XCTAssertTrue(highestIndexToInsertNine == 13, "If both .InsertionIndex and .LastEqual are specified NSArray returns the index of the least greater object...")
let indexOfLeastGreaterObjectThanFive = objectIndexInArray(array, value: 5, startingFrom: 0, length: 10, options: [.insertionIndex, .lastEqual])
XCTAssertTrue(indexOfLeastGreaterObjectThanFive == 7, "If both .InsertionIndex and .LastEqual are specified NSArray returns the index of the least greater object...")
let rangeStart = 0
let rangeLength = 13
let endOfArray = objectIndexInArray(array, value: 10, startingFrom: rangeStart, length: rangeLength, options: [.insertionIndex, .lastEqual])
XCTAssertTrue(endOfArray == (rangeStart + rangeLength), "...or the index at the end of the array if the object is larger than all other elements.")
let arrayOfTwo = NSArray(array: [NSNumber(value: 0 as Int), NSNumber(value: 2 as Int)])
let indexInMiddle = objectIndexInArray(arrayOfTwo, value: 1, startingFrom: 0, length: 2, options: [.insertionIndex, .firstEqual])
XCTAssertEqual(indexInMiddle, 1, "If no match found item should be inserted before least greater object")
let indexInMiddle2 = objectIndexInArray(arrayOfTwo, value: 1, startingFrom: 0, length: 2, options: [.insertionIndex, .lastEqual])
XCTAssertEqual(indexInMiddle2, 1, "If no match found item should be inserted before least greater object")
let indexInMiddle3 = objectIndexInArray(arrayOfTwo, value: 1, startingFrom: 0, length: 2, options: [.insertionIndex])
XCTAssertEqual(indexInMiddle3, 1, "If no match found item should be inserted before least greater object")
}
func test_arrayReplacement() {
let numbers: [AnyObject] = [
NSNumber(value: 0 as Int), NSNumber(value: 1 as Int), NSNumber(value: 2 as Int), NSNumber(value: 3 as Int),
NSNumber(value: 4 as Int), NSNumber(value: 5 as Int), NSNumber(value: 7 as Int)]
let array = NSMutableArray(array: numbers)
array.replaceObjects(in: NSRange(location: 0, length: 2), withObjectsFrom: [NSNumber(value: 8 as Int), NSNumber(value: 9 as Int)])
XCTAssertTrue((array[0] as! NSNumber).intValue == 8)
XCTAssertTrue((array[1] as! NSNumber).intValue == 9)
XCTAssertTrue((array[2] as! NSNumber).intValue == 2)
}
func test_arrayReplaceObjectsInRangeFromRange() {
let numbers: [AnyObject] = [
NSNumber(value: 0 as Int), NSNumber(value: 1 as Int), NSNumber(value: 2 as Int), NSNumber(value: 3 as Int),
NSNumber(value: 4 as Int), NSNumber(value: 5 as Int), NSNumber(value: 7 as Int)]
let array = NSMutableArray(array: numbers)
array.replaceObjects(in: NSRange(location: 0, length: 2), withObjectsFrom: [NSNumber(value: 8 as Int), NSNumber(value: 9 as Int), NSNumber(value: 10 as Int)], range: NSRange(location: 1, length: 2))
XCTAssertTrue((array[0] as! NSNumber).intValue == 9)
XCTAssertTrue((array[1] as! NSNumber).intValue == 10)
XCTAssertTrue((array[2] as! NSNumber).intValue == 2)
}
func test_replaceObjectAtIndex() {
let numbers: [AnyObject] = [
NSNumber(value: 0 as Int), NSNumber(value: 1 as Int), NSNumber(value: 2 as Int), NSNumber(value: 3 as Int),
NSNumber(value: 4 as Int), NSNumber(value: 5 as Int), NSNumber(value: 7 as Int)]
let array = NSMutableArray(array: numbers)
// 1. Check replacement in the middle of the array
array.replaceObject(at: 3, with: NSNumber(value: 8 as Int))
XCTAssertEqual(array.count, 7)
XCTAssertEqual((array[3] as! NSNumber).intValue, 8)
// 2. Check replacement of the first element
array.replaceObject(at: 0, with: NSNumber(value: 7 as Int))
XCTAssertEqual(array.count, 7)
XCTAssertEqual((array[0] as! NSNumber).intValue, 7)
// 3. Check replacement of the last element
array.replaceObject(at: 6, with: NSNumber(value: 6 as Int))
XCTAssertEqual(array.count, 7)
XCTAssertEqual((array[6] as! NSNumber).intValue, 6)
}
func test_removeObjectsInArray() {
let numbers: [AnyObject] = [
NSNumber(value: 0 as Int), NSNumber(value: 1 as Int), NSNumber(value: 2 as Int), NSNumber(value: 3 as Int),
NSNumber(value: 4 as Int), NSNumber(value: 5 as Int), NSNumber(value: 7 as Int)]
let array = NSMutableArray(array: numbers)
let objectsToRemove: Array<AnyObject> = [
NSNumber(value: 1 as Int), NSNumber(value: 22 as Int), NSNumber(value: 7 as Int), NSNumber(value: 5 as Int)]
array.removeObjects(in: objectsToRemove)
XCTAssertEqual(array.count, 4)
XCTAssertEqual((array[0] as! NSNumber).intValue, 0)
XCTAssertEqual((array[1] as! NSNumber).intValue, 2)
XCTAssertEqual((array[2] as! NSNumber).intValue, 3)
XCTAssertEqual((array[3] as! NSNumber).intValue, 4)
}
func test_binarySearchFringeCases() {
let numbers: [AnyObject] = [
NSNumber(value: 0 as Int), NSNumber(value: 1 as Int), NSNumber(value: 2 as Int), NSNumber(value: 2 as Int), NSNumber(value: 3 as Int),
NSNumber(value: 4 as Int), NSNumber(value: 4 as Int), NSNumber(value: 6 as Int), NSNumber(value: 7 as Int), NSNumber(value: 7 as Int),
NSNumber(value: 7 as Int), NSNumber(value: 8 as Int), NSNumber(value: 9 as Int), NSNumber(value: 9 as Int)]
let array = NSArray(array: numbers)
let emptyArray = NSArray()
// Same as for non empty NSArray but error message ends with 'bounds for empty array'.
// let _ = objectIndexInArray(emptyArray, value: 0, startingFrom: 0, length: 1)
let notFoundInEmptyArray = objectIndexInArray(emptyArray, value: 9, startingFrom: 0, length: 0)
XCTAssertEqual(notFoundInEmptyArray, NSNotFound, "Empty NSArray return NSNotFound for any valid arguments.")
let startIndex = objectIndexInArray(emptyArray, value: 7, startingFrom: 0, length: 0, options: [.insertionIndex])
XCTAssertTrue(startIndex == 0, "For Empty NSArray any objects should be inserted at start.")
let rangeStart = 0
let rangeLength = 13
let leastSearch = objectIndexInArray(array, value: -1, startingFrom: rangeStart, length: rangeLength)
XCTAssertTrue(leastSearch == NSNotFound, "If object is less than least object in the range then there is no change it could be found.")
let greatestSearch = objectIndexInArray(array, value: 15, startingFrom: rangeStart, length: rangeLength)
XCTAssertTrue(greatestSearch == NSNotFound, "If object is greater than greatest object in the range then there is no change it could be found.")
let leastInsert = objectIndexInArray(array, value: -1, startingFrom: rangeStart, length: rangeLength, options: .insertionIndex)
XCTAssertTrue(leastInsert == rangeStart, "If object is less than least object in the range it should be inserted at range' location.")
let greatestInsert = objectIndexInArray(array, value: 15, startingFrom: rangeStart, length: rangeLength, options: .insertionIndex)
XCTAssertTrue(greatestInsert == (rangeStart + rangeLength), "If object is greater than greatest object in the range it should be inserted at range' end.")
}
func objectIndexInArray(_ array: NSArray, value: Int, startingFrom: Int, length: Int, options: NSBinarySearchingOptions = []) -> Int {
return array.index(of: NSNumber(value: value), inSortedRange: NSRange(location: startingFrom, length: length), options: options, usingComparator: compareIntNSNumber)
}
func compareIntNSNumber(_ lhs: Any, rhs: Any) -> ComparisonResult {
let lhsInt = (lhs as! NSNumber).intValue
let rhsInt = (rhs as! NSNumber).intValue
if lhsInt == rhsInt {
return .orderedSame
}
if lhsInt < rhsInt {
return .orderedAscending
}
return .orderedDescending
}
func test_replaceObjectsInRange_withObjectsFrom() {
let array1 = NSMutableArray(array:[
"foo1",
"bar1",
"baz1"])
let array2: [Any] = [
"foo2",
"bar2",
"baz2"]
array1.replaceObjects(in: NSRange(location: 0, length: 2), withObjectsFrom: array2)
XCTAssertEqual(array1[0] as? String, "foo2", "Expected foo2 but was \(array1[0])")
XCTAssertEqual(array1[1] as? String, "bar2", "Expected bar2 but was \(array1[1])")
XCTAssertEqual(array1[2] as? String, "baz2", "Expected baz2 but was \(array1[2])")
XCTAssertEqual(array1[3] as? String, "baz1", "Expected baz1 but was \(array1[3])")
}
func test_replaceObjectsInRange_withObjectsFrom_range() {
let array1 = NSMutableArray(array:[
"foo1",
"bar1",
"baz1"])
let array2: [Any] = [
"foo2",
"bar2",
"baz2"]
array1.replaceObjects(in: NSRange(location: 1, length: 1), withObjectsFrom: array2, range: NSRange(location: 1, length: 2))
XCTAssertEqual(array1[0] as? String, "foo1", "Expected foo1 but was \(array1[0])")
XCTAssertEqual(array1[1] as? String, "bar2", "Expected bar2 but was \(array1[1])")
XCTAssertEqual(array1[2] as? String, "baz2", "Expected baz2 but was \(array1[2])")
XCTAssertEqual(array1[3] as? String, "baz1", "Expected baz1 but was \(array1[3])")
}
func test_sortedArrayUsingComparator() {
// sort with localized caseInsensitive compare
let input = ["this", "is", "a", "test", "of", "sort", "with", "strings"]
let expectedResult: Array<String> = input.sorted()
let result = NSArray(array: input).sortedArray(comparator:) { left, right -> ComparisonResult in
let l = left as! String
let r = right as! String
return l.localizedCaseInsensitiveCompare(r)
}
XCTAssertEqual(result.map { ($0 as! String)} , expectedResult)
// sort empty array
let emptyArray = NSArray().sortedArray(comparator:) { _,_ in .orderedSame }
XCTAssertTrue(emptyArray.isEmpty)
// sort numbers
let inputNumbers = [0, 10, 25, 100, 21, 22]
let expectedNumbers = inputNumbers.sorted()
let resultNumbers = NSArray(array: inputNumbers).sortedArray(comparator:) { left, right -> ComparisonResult in
let l = (left as! NSNumber).intValue
let r = (right as! NSNumber).intValue
return l < r ? .orderedAscending : (l == r ? .orderedSame : .orderedDescending)
}
XCTAssertEqual(resultNumbers.map { ($0 as! NSNumber).intValue}, expectedNumbers)
}
func test_sortedArrayWithOptionsUsingComparator() {
// check that sortedArrayWithOptions:comparator: works in the way sortedArrayUsingComparator does
let input = NSArray(array: ["this", "is", "a", "test", "of", "sort", "with", "strings"])
let comparator: (Any, Any) -> ComparisonResult = { left, right -> ComparisonResult in
let l = left as! String
let r = right as! String
return l.localizedCaseInsensitiveCompare(r)
}
let result1 = NSArray(array: input.sortedArray(comparator: comparator))
let result2 = input.sortedArray(options: [], usingComparator: comparator)
XCTAssertTrue(result1.isEqual(to: result2))
// sort empty array
let emptyArray = NSArray().sortedArray(options: []) { _,_ in .orderedSame }
XCTAssertTrue(emptyArray.isEmpty)
}
func test_sortUsingFunction() {
let inputNumbers = [11, 120, 215, 11, 1, -22, 35, -89, 65]
let mutableInput = NSArray(array: inputNumbers).mutableCopy() as! NSMutableArray
let expectedNumbers = inputNumbers.sorted()
func compare(_ left: Any, right:Any, context: UnsafeMutableRawPointer?) -> Int {
let l = (left as! NSNumber).intValue
let r = (right as! NSNumber).intValue
return l < r ? -1 : (l == r ? 0 : 1)
}
mutableInput.sort(compare, context: UnsafeMutableRawPointer(bitPattern: 0))
XCTAssertEqual(mutableInput.map { ($0 as! NSNumber).intValue}, expectedNumbers)
}
func test_sortUsingComparator() {
// check behaviour with Array's sort method
let inputNumbers = [11, 120, 215, 11, 1, -22, 35, -89, 65]
let mutableInput = NSMutableArray(array: inputNumbers)
let expectedNumbers = inputNumbers.sorted()
mutableInput.sort { left, right -> ComparisonResult in
let l = (left as! NSNumber).intValue
let r = (right as! NSNumber).intValue
return l < r ? .orderedAscending : (l == r ? .orderedSame : .orderedDescending)
}
XCTAssertEqual(mutableInput.map { ($0 as! NSNumber).intValue}, expectedNumbers)
// check that it works in the way self.sortWithOptions([], usingComparator: cmptr) does
let inputStrings = ["this", "is", "a", "test", "of", "sort", "with", "strings"]
let mutableStringsInput1 = NSMutableArray(array: inputStrings)
let mutableStringsInput2 = NSMutableArray(array: inputStrings)
let comparator: (Any, Any) -> ComparisonResult = { left, right -> ComparisonResult in
let l = left as! String
let r = right as! String
return l.localizedCaseInsensitiveCompare(r)
}
mutableStringsInput1.sort(comparator: comparator)
mutableStringsInput2.sort(options: [], usingComparator: comparator)
XCTAssertTrue(mutableStringsInput1.isEqual(to: Array(mutableStringsInput2)))
}
func test_equality() {
let array1 = NSArray(array: ["this", "is", "a", "test", "of", "equal", "with", "strings"])
let array2 = NSArray(array: ["this", "is", "a", "test", "of", "equal", "with", "strings"])
let array3 = NSArray(array: ["this", "is", "a", "test", "of", "equal", "with", "objects"])
XCTAssertTrue(array1 == array2)
XCTAssertTrue(array1.isEqual(array2))
XCTAssertTrue(array1.isEqual(to: Array(array2)))
// if 2 arrays are equal, hashes should be equal as well. But not vise versa
XCTAssertEqual(array1.hash, array2.hash)
XCTAssertEqual(array1.hashValue, array2.hashValue)
XCTAssertFalse(array1 == array3)
XCTAssertFalse(array1.isEqual(array3))
XCTAssertFalse(array1.isEqual(to: Array(array3)))
XCTAssertFalse(array1.isEqual(nil))
XCTAssertFalse(array1.isEqual(NSObject()))
let objectsArray1 = NSArray(array: [NSArray(array: [0])])
let objectsArray2 = NSArray(array: [NSArray(array: [1])])
XCTAssertFalse(objectsArray1 == objectsArray2)
XCTAssertFalse(objectsArray1.isEqual(objectsArray2))
XCTAssertFalse(objectsArray1.isEqual(to: Array(objectsArray2)))
}
/// - Note: value type conversion will destroy identity. So use index(of:) instead of indexOfObjectIdentical(to:)
func test_copying() {
let array = NSArray(array: ["this", "is", "a", "test", "of", "copy", "with", "strings"])
let arrayCopy1 = array.copy() as! NSArray
XCTAssertTrue(array === arrayCopy1)
let arrayMutableCopy = array.mutableCopy() as! NSMutableArray
let arrayCopy2 = arrayMutableCopy.copy() as! NSArray
XCTAssertTrue(type(of: arrayCopy2) === NSArray.self)
XCTAssertFalse(arrayMutableCopy === arrayCopy2)
for entry in arrayCopy2 {
XCTAssertTrue(array.index(of: entry) != NSNotFound)
}
}
func test_mutableCopying() {
let array = NSArray(array: ["this", "is", "a", "test", "of", "mutableCopy", "with", "strings"])
let arrayMutableCopy1 = array.mutableCopy() as! NSMutableArray
XCTAssertTrue(type(of: arrayMutableCopy1) === NSMutableArray.self)
XCTAssertFalse(array === arrayMutableCopy1)
for entry in arrayMutableCopy1 {
XCTAssertTrue(array.index(of: entry) != NSNotFound)
}
let arrayMutableCopy2 = arrayMutableCopy1.mutableCopy() as! NSMutableArray
XCTAssertTrue(type(of: arrayMutableCopy2) === NSMutableArray.self)
XCTAssertFalse(arrayMutableCopy2 === arrayMutableCopy1)
for entry in arrayMutableCopy2 {
XCTAssertTrue(arrayMutableCopy1.index(of: entry) != NSNotFound)
}
}
@available(*, deprecated) // test of deprecated API, suppress deprecation warning
func test_initWithContentsOfFile() {
let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 234))
if let _ = testFilePath {
let a1: NSArray = ["foo", "bar"]
let isWritten = a1.write(toFile: testFilePath!, atomically: true)
if isWritten {
let array = NSArray.init(contentsOfFile: testFilePath!)
XCTAssert(array == a1)
} else {
XCTFail("Write to file failed")
}
removeTestFile(testFilePath!)
} else {
XCTFail("Temporary file creation failed")
}
}
@available(*, deprecated) // test of deprecated API, suppress deprecation warning
func test_initMutableWithContentsOfFile() {
if let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 234)) {
let a1: NSArray = ["foo", "bar"]
let isWritten = a1.write(toFile: testFilePath, atomically: true)
if isWritten {
let array = NSMutableArray.init(contentsOfFile: testFilePath)
XCTAssert(array == a1)
XCTAssertEqual(array?.count, 2)
array?.removeAllObjects()
XCTAssertEqual(array?.count, 0)
} else {
XCTFail("Write to file failed")
}
removeTestFile(testFilePath)
} else {
XCTFail("Temporary file creation failed")
}
}
@available(*, deprecated) // test of deprecated API, suppress deprecation warning
func test_initMutableWithContentsOfURL() {
if let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 234)) {
let a1: NSArray = ["foo", "bar"]
let isWritten = a1.write(toFile: testFilePath, atomically: true)
if isWritten {
let url = URL(fileURLWithPath: testFilePath, isDirectory: false)
let array = NSMutableArray.init(contentsOf: url)
XCTAssert(array == a1)
XCTAssertEqual(array?.count, 2)
array?.removeAllObjects()
XCTAssertEqual(array?.count, 0)
} else {
XCTFail("Write to file failed")
}
removeTestFile(testFilePath)
} else {
XCTFail("Temporary file creation failed")
}
}
@available(*, deprecated) // test of deprecated API, suppress deprecation warning
func test_writeToFile() {
let testFilePath = createTestFile("TestFileOut.txt", _contents: Data(capacity: 234))
if let _ = testFilePath {
let d1: NSArray = ["foo", "bar"]
let isWritten = d1.write(toFile: testFilePath!, atomically: true)
if isWritten {
do {
let plistDoc = try XMLDocument(contentsOf: URL(fileURLWithPath: testFilePath!, isDirectory: false), options: [])
XCTAssert(plistDoc.rootElement()?.name == "plist")
let plist = try PropertyListSerialization.propertyList(from: plistDoc.xmlData, options: [], format: nil) as! [Any]
XCTAssert((plist[0] as? String) == d1[0] as? String)
XCTAssert((plist[1] as? String) == d1[1] as? String)
} catch {
XCTFail("Failed to read and parse XMLDocument")
}
} else {
XCTFail("Write to file failed")
}
removeTestFile(testFilePath!)
} else {
XCTFail("Temporary file creation failed")
}
}
func test_readWriteURL() {
let data = NSArray(arrayLiteral: "one", "two", "three", "four", "five")
do {
let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString
try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
let testFile = tempDir + "/readWriteURL.txt"
let url = URL(fileURLWithPath: testFile)
let data2: NSArray
#if DARWIN_COMPATIBILITY_TESTS
if #available(macOS 10.13, *) {
try data.write(to: url)
data2 = try NSArray(contentsOf: url, error: ())
} else {
guard data.write(toFile: testFile, atomically: true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue)
}
data2 = NSArray(contentsOfFile: testFile)!
}
#else
try data.write(to: url)
data2 = try NSArray(contentsOf: url, error: ())
#endif
XCTAssertEqual(data, data2)
removeTestFile(testFile)
} catch {
XCTFail("Failed to write to file: \(error)")
}
}
func test_insertObjectAtIndex() {
let a1 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a1.insert("a", at: 0)
XCTAssertEqual(a1, ["a", "one", "two", "three", "four"])
let a2 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a2.insert("a", at: 4)
XCTAssertEqual(a2, ["one", "two", "three", "four", "a"])
let a3 = NSMutableArray()
a3.insert("a", at: 0)
XCTAssertEqual(a3, ["a"])
}
func test_insertObjectsAtIndexes() {
let a1 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a1.insert(["a", "b"], at: [0, 1])
XCTAssertEqual(a1, ["a", "b", "one", "two", "three", "four"])
let a2 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a2.insert(["a", "b"], at: [1, 3])
XCTAssertEqual(a2, ["one", "a", "two", "b", "three", "four"])
let a3 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a3.insert(["a", "b"], at: [5, 4])
XCTAssertEqual(a3, ["one", "two", "three", "four", "a", "b"])
let a4 = NSMutableArray()
a4.insert(["a", "b"], at: [0, 1])
XCTAssertEqual(a4, ["a", "b"])
}
func test_replaceObjectsAtIndexesWithObjects() {
let a1 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a1.replaceObjects(at: [0], with: ["a"])
XCTAssertEqual(a1, ["a", "two", "three", "four"])
let a2 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a2.replaceObjects(at: [1, 2], with: ["a", "b"])
XCTAssertEqual(a2, ["one", "a", "b", "four"])
let a3 = NSMutableArray(arrayLiteral: "one", "two", "three", "four")
a3.replaceObjects(at: [3, 2, 1, 0], with: ["a", "b", "c", "d"])
XCTAssertEqual(a3, ["a", "b", "c", "d"])
}
func test_pathsMatchingExtensions() {
let paths = NSArray(arrayLiteral: "file1.txt", "/tmp/file2.txt", "file3.jpg", "file3.png", "/file4.png", "txt", ".txt")
let match1 = paths.pathsMatchingExtensions(["txt"])
XCTAssertEqual(match1, ["file1.txt", "/tmp/file2.txt"])
let match2 = paths.pathsMatchingExtensions([])
XCTAssertEqual(match2, [])
let match3 = paths.pathsMatchingExtensions([".txt", "png"])
XCTAssertEqual(match3, ["file3.png", "/file4.png"])
let match4 = paths.pathsMatchingExtensions(["", ".tx", "tx"])
XCTAssertEqual(match4, [])
let match5 = paths.pathsMatchingExtensions(["..txt"])
XCTAssertEqual(match5, [])
}
func test_customMirror() {
let inputArray = ["this", "is", "a", "test", "of", "custom", "mirror"]
let array = NSArray(array: inputArray)
let arrayMirror = array.customMirror
XCTAssertEqual(array[0] as! String, arrayMirror.descendant(0) as! String)
XCTAssertEqual(array[1] as! String, arrayMirror.descendant(1) as! String)
XCTAssertEqual(array[2] as! String, arrayMirror.descendant(2) as! String)
XCTAssertEqual(array[3] as! String, arrayMirror.descendant(3) as! String)
XCTAssertEqual(array[4] as! String, arrayMirror.descendant(4) as! String)
XCTAssertEqual(array[5] as! String, arrayMirror.descendant(5) as! String)
XCTAssertEqual(array[6] as! String, arrayMirror.descendant(6) as! String)
}
private func createTestFile(_ path: String, _contents: Data) -> String? {
let tempDir = NSTemporaryDirectory() + "TestFoundation_Playground_" + NSUUID().uuidString + "/"
do {
try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
if FileManager.default.createFile(atPath: tempDir + "/" + path, contents: _contents, attributes: nil) {
return tempDir + path
} else {
return nil
}
} catch {
return nil
}
}
private func removeTestFile(_ location: String) {
try? FileManager.default.removeItem(atPath: location)
}
}
|