Skip to content

Commit 44eece9

Browse files
authored
Merge pull request #1286 from spevans/pr_darwin_compatibility_tests
2 parents 6d6b20c + 7d963e1 commit 44eece9

16 files changed

+1002
-47
lines changed

DarwinCompatibilityTests.xcodeproj/project.pbxproj

Lines changed: 788 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// This source file is part of the Swift.org open source project
2+
//
3+
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
4+
// Licensed under Apache License v2.0 with Runtime Library Exception
5+
//
6+
// See http://swift.org/LICENSE.txt for license information
7+
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
8+
//
9+
10+
// These shims are used solely by the DarwinCompatibilityTests Xcode project to
11+
// allow the TestFoundation tests to compile and run against Darwin's native
12+
// Foundation.
13+
// It contains wrappers for methods (some experimental) added in
14+
// swift-corelibs-foundation which do not exist in Foundation, and other small
15+
// differences.
16+
17+
import Foundation
18+
19+
20+
public typealias unichar = UInt16
21+
22+
extension unichar : ExpressibleByUnicodeScalarLiteral {
23+
public typealias UnicodeScalarLiteralType = UnicodeScalar
24+
25+
public init(unicodeScalarLiteral scalar: UnicodeScalar) {
26+
self.init(scalar.value)
27+
}
28+
}
29+
30+
extension NSURL {
31+
func checkResourceIsReachable() throws -> Bool {
32+
var error: NSError?
33+
if checkResourceIsReachableAndReturnError(&error) {
34+
return true
35+
} else {
36+
if let e = error {
37+
throw e
38+
}
39+
}
40+
return false
41+
}
42+
}
43+
44+
extension Thread {
45+
class var mainThread: Thread {
46+
return Thread.main
47+
}
48+
}
49+
50+
extension Scanner {
51+
public func scanString(_ searchString: String) -> String? {
52+
var result: NSString? = nil
53+
if scanString(string, into: &result), let str = result {
54+
return str as String
55+
}
56+
return nil
57+
}
58+
}
59+
60+
extension JSONSerialization {
61+
class func writeJSONObject(_ obj: Any, toStream stream: OutputStream, options opt: WritingOptions) throws -> Int {
62+
var error: NSError?
63+
let ret = writeJSONObject(obj, to: stream, options: opt, error: &error)
64+
guard ret != 0 else {
65+
throw error!
66+
}
67+
return ret
68+
}
69+
}
70+
71+
extension NSIndexSet {
72+
func _bridgeToSwift() -> NSIndexSet {
73+
return self
74+
}
75+
}
76+
77+
extension CharacterSet {
78+
func _bridgeToSwift() -> CharacterSet {
79+
return self
80+
}
81+
}
82+
83+
extension NSCharacterSet {
84+
func _bridgeToSwift() -> CharacterSet {
85+
return self as CharacterSet
86+
}
87+
}

DarwinCompatibilityTests/Info.plist

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>CFBundleDevelopmentRegion</key>
6+
<string>$(DEVELOPMENT_LANGUAGE)</string>
7+
<key>CFBundleExecutable</key>
8+
<string>$(EXECUTABLE_NAME)</string>
9+
<key>CFBundleIdentifier</key>
10+
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11+
<key>CFBundleInfoDictionaryVersion</key>
12+
<string>6.0</string>
13+
<key>CFBundleName</key>
14+
<string>$(PRODUCT_NAME)</string>
15+
<key>CFBundlePackageType</key>
16+
<string>BNDL</string>
17+
<key>CFBundleShortVersionString</key>
18+
<string>1.0</string>
19+
<key>CFBundleVersion</key>
20+
<string>1</string>
21+
</dict>
22+
</plist>

TestFoundation/TestBundle.swift

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,16 @@
1818

1919

2020
internal func testBundle() -> Bundle {
21+
#if DARWIN_COMPATIBILITY_TESTS
22+
for bundle in Bundle.allBundles {
23+
if let bundleId = bundle.bundleIdentifier, bundleId == "org.swift.DarwinCompatibilityTests", bundle.resourcePath != nil {
24+
return bundle
25+
}
26+
}
27+
fatalError("Cant find test bundle")
28+
#else
2129
return Bundle.main
30+
#endif
2231
}
2332

2433
class TestBundle : XCTestCase {
@@ -88,14 +97,24 @@ class TestBundle : XCTestCase {
8897
let bundle = testBundle()
8998

9099
// bundleIdentifier
100+
#if DARWIN_COMPATIBILITY_TESTS
101+
XCTAssertEqual("org.swift.DarwinCompatibilityTests", bundle.bundleIdentifier)
102+
#else
91103
XCTAssertEqual("org.swift.TestFoundation", bundle.bundleIdentifier)
92-
104+
#endif
105+
93106
// infoDictionary
94107
let info = bundle.infoDictionary
95108
XCTAssertNotNil(info)
96-
XCTAssert("org.swift.TestFoundation" == info!["CFBundleIdentifier"] as! String)
109+
110+
#if DARWIN_COMPATIBILITY_TESTS
111+
XCTAssert("DarwinCompatibilityTests" == info!["CFBundleName"] as! String)
112+
XCTAssert("org.swift.DarwinCompatibilityTests" == info!["CFBundleIdentifier"] as! String)
113+
#else
97114
XCTAssert("TestFoundation" == info!["CFBundleName"] as! String)
98-
115+
XCTAssert("org.swift.TestFoundation" == info!["CFBundleIdentifier"] as! String)
116+
#endif
117+
99118
// localizedInfoDictionary
100119
XCTAssertNil(bundle.localizedInfoDictionary) // FIXME: Add a localized Info.plist for testing
101120
}
@@ -204,6 +223,4 @@ class TestBundle : XCTestCase {
204223
XCTAssertThrowsError(try bundle!.preflight())
205224
_cleanupPlayground(playground)
206225
}
207-
208-
209226
}

TestFoundation/TestCodable.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,13 +561,15 @@ class TestCodable : XCTestCase {
561561
]
562562

563563
func test_URLComponents_JSON() {
564+
#if !DARWIN_COMPATIBILITY_TESTS // crashes on native Darwin
564565
for (components) in urlComponentsValues {
565566
do {
566567
try expectRoundTripEqualityThroughJSON(for: components)
567568
} catch let error {
568569
XCTFail("\(error)")
569570
}
570571
}
572+
#endif
571573
}
572574
}
573575

TestFoundation/TestHTTPCookieStorage.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ class TestHTTPCookieStorage: XCTestCase {
247247
}
248248

249249
func test_cookieInXDGSpecPath() {
250-
#if !os(Android)
250+
#if !os(Android) && !DARWIN_COMPATIBILITY_TESTS
251251
//Test without setting the environment variable
252252
let testCookie = HTTPCookie(properties: [
253253
.name: "TestCookie0",

TestFoundation/TestJSONEncoder.swift

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -105,19 +105,27 @@ class TestJSONEncoder : XCTestCase {
105105
}
106106

107107
func test_encodingOutputFormattingSortedKeys() {
108+
let expectedJSON = "{\"email\":\"[email protected]\",\"name\":\"Johnny Appleseed\"}".data(using: .utf8)!
109+
let person = Person.testValue
110+
#if os(OSX) || DARWIN_COMPATIBILITY_TESTS
108111
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
109-
let expectedJSON = "{\"email\":\"[email protected]\",\"name\":\"Johnny Appleseed\"}".data(using: .utf8)!
110-
let person = Person.testValue
111112
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
112113
}
114+
#else
115+
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.sortedKeys])
116+
#endif
113117
}
114118

115119
func test_encodingOutputFormattingPrettyPrintedSortedKeys() {
120+
let expectedJSON = "{\n \"email\" : \"[email protected]\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: .utf8)!
121+
let person = Person.testValue
122+
#if os(OSX) || DARWIN_COMPATIBILITY_TESTS
116123
if #available(OSX 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *) {
117-
let expectedJSON = "{\n \"email\" : \"[email protected]\",\n \"name\" : \"Johnny Appleseed\"\n}".data(using: .utf8)!
118-
let person = Person.testValue
119124
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
120125
}
126+
#else
127+
_testRoundTrip(of: person, expectedJSON: expectedJSON, outputFormatting: [.prettyPrinted, .sortedKeys])
128+
#endif
121129
}
122130

123131
// MARK: - Date Strategy Tests
@@ -151,19 +159,18 @@ class TestJSONEncoder : XCTestCase {
151159
}
152160

153161
func test_encodingDateISO8601() {
154-
if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
155-
let formatter = ISO8601DateFormatter()
156-
formatter.formatOptions = .withInternetDateTime
157-
158-
let timestamp = Date(timeIntervalSince1970: 1000)
159-
let expectedJSON = "[\"\(formatter.string(from: timestamp))\"]".data(using: .utf8)!
160-
161-
// We can't encode a top-level Date, so it'll be wrapped in an array.
162-
_testRoundTrip(of: TopLevelArrayWrapper(timestamp),
163-
expectedJSON: expectedJSON,
164-
dateEncodingStrategy: .iso8601,
165-
dateDecodingStrategy: .iso8601)
166-
}
162+
let formatter = ISO8601DateFormatter()
163+
formatter.formatOptions = .withInternetDateTime
164+
165+
let timestamp = Date(timeIntervalSince1970: 1000)
166+
let expectedJSON = "[\"\(formatter.string(from: timestamp))\"]".data(using: .utf8)!
167+
168+
// We can't encode a top-level Date, so it'll be wrapped in an array.
169+
_testRoundTrip(of: TopLevelArrayWrapper(timestamp),
170+
expectedJSON: expectedJSON,
171+
dateEncodingStrategy: .iso8601,
172+
dateDecodingStrategy: .iso8601)
173+
167174
}
168175

169176
func test_encodingDateFormatted() {

TestFoundation/TestJSONSerialization.swift

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1415,6 +1415,7 @@ extension TestJSONSerialization {
14151415
}
14161416

14171417
func test_jsonObjectToOutputStreamInsufficientBuffer() {
1418+
#if !DARWIN_COMPATIBILITY_TESTS // Hangs
14181419
let dict = ["a":["b":1]]
14191420
let buffer = Array<UInt8>(repeating: 0, count: 10)
14201421
let outputStream = OutputStream(toBuffer: UnsafeMutablePointer(mutating: buffer), capacity: buffer.count)
@@ -1428,6 +1429,7 @@ extension TestJSONSerialization {
14281429
} catch {
14291430
XCTFail("Error occurred while writing to stream")
14301431
}
1432+
#endif
14311433
}
14321434

14331435
func test_booleanJSONObject() {
@@ -1469,18 +1471,23 @@ extension TestJSONSerialization {
14691471
XCTFail("Failed during serialization")
14701472
}
14711473
}
1472-
1473-
func test_serializeSortedKeys() {
1474-
var dict: [String: Any]
1475-
1476-
dict = ["z": 1, "y": 1, "x": 1, "w": 1, "v": 1, "u": 1, "t": 1, "s": 1, "r": 1, "q": 1, ]
1477-
XCTAssertEqual(try trySerialize(dict, options: .sortedKeys), "{\"q\":1,\"r\":1,\"s\":1,\"t\":1,\"u\":1,\"v\":1,\"w\":1,\"x\":1,\"y\":1,\"z\":1}")
1478-
1479-
dict = ["aaaa": 1, "aaa": 1, "aa": 1, "a": 1]
1480-
XCTAssertEqual(try trySerialize(dict, options: .sortedKeys), "{\"a\":1,\"aa\":1,\"aaa\":1,\"aaaa\":1}")
14811474

1482-
dict = ["c": ["c":1,"b":1,"a":1],"b":["c":1,"b":1,"a":1],"a":["c":1,"b":1,"a":1]]
1483-
XCTAssertEqual(try trySerialize(dict, options: .sortedKeys), "{\"a\":{\"a\":1,\"b\":1,\"c\":1},\"b\":{\"a\":1,\"b\":1,\"c\":1},\"c\":{\"a\":1,\"b\":1,\"c\":1}}")
1475+
func test_serializeSortedKeys() {
1476+
let dict1 = ["z": 1, "y": 1, "x": 1, "w": 1, "v": 1, "u": 1, "t": 1, "s": 1, "r": 1, "q": 1, ]
1477+
let dict2 = ["aaaa": 1, "aaa": 1, "aa": 1, "a": 1]
1478+
let dict3 = ["c": ["c":1,"b":1,"a":1],"b":["c":1,"b":1,"a":1],"a":["c":1,"b":1,"a":1]]
1479+
1480+
#if DARWIN_COMPATIBILITY_TESTS
1481+
if #available(OSX 10.13, *) {
1482+
XCTAssertEqual(try trySerialize(dict1, options: .sortedKeys), "{\"q\":1,\"r\":1,\"s\":1,\"t\":1,\"u\":1,\"v\":1,\"w\":1,\"x\":1,\"y\":1,\"z\":1}")
1483+
XCTAssertEqual(try trySerialize(dict2, options: .sortedKeys), "{\"a\":1,\"aa\":1,\"aaa\":1,\"aaaa\":1}")
1484+
XCTAssertEqual(try trySerialize(dict3, options: .sortedKeys), "{\"a\":{\"a\":1,\"b\":1,\"c\":1},\"b\":{\"a\":1,\"b\":1,\"c\":1},\"c\":{\"a\":1,\"b\":1,\"c\":1}}")
1485+
}
1486+
#else
1487+
XCTAssertEqual(try trySerialize(dict1, options: .sortedKeys), "{\"q\":1,\"r\":1,\"s\":1,\"t\":1,\"u\":1,\"v\":1,\"w\":1,\"x\":1,\"y\":1,\"z\":1}")
1488+
XCTAssertEqual(try trySerialize(dict2, options: .sortedKeys), "{\"a\":1,\"aa\":1,\"aaa\":1,\"aaaa\":1}")
1489+
XCTAssertEqual(try trySerialize(dict3, options: .sortedKeys), "{\"a\":{\"a\":1,\"b\":1,\"c\":1},\"b\":{\"a\":1,\"b\":1,\"c\":1},\"c\":{\"a\":1,\"b\":1,\"c\":1}}")
1490+
#endif
14841491
}
14851492

14861493
func test_serializePrettyPrinted() {

TestFoundation/TestNSArray.swift

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,8 +559,21 @@ class TestNSArray : XCTestCase {
559559
try FileManager.default.createDirectory(atPath: tempDir, withIntermediateDirectories: false, attributes: nil)
560560
let testFile = tempDir + "/readWriteURL.txt"
561561
let url = URL(fileURLWithPath: testFile)
562+
let data2: NSArray
563+
#if DARWIN_COMPATIBILITY_TESTS
564+
if #available(OSX 10.13, *) {
565+
try data.write(to: url)
566+
data2 = try NSArray(contentsOf: url, error: ())
567+
} else {
568+
guard data.write(toFile: testFile, atomically: true) else {
569+
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue)
570+
}
571+
data2 = NSArray(contentsOfFile: testFile)!
572+
}
573+
#else
562574
try data.write(to: url)
563-
let data2 = try NSArray(contentsOf: url, error: ())
575+
data2 = try NSArray(contentsOf: url, error: ())
576+
#endif
564577
XCTAssertEqual(data, data2)
565578
removeTestFile(testFile)
566579
} catch let e {

TestFoundation/TestNSData.swift

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3999,33 +3999,37 @@ extension TestNSData {
39993999
}
40004000
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
40014001
}
4002-
4002+
40034003
func test_validateMutation_slice_mutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
4004+
#if !DARWIN_COMPATIBILITY_TESTS // Crashes on native Darwin
40044005
var base = Data(referencing: NSData(bytes: "hello world", length: 11))
40054006
base.append(contentsOf: [1, 2, 3, 4, 5, 6])
40064007
var data = base[4..<6]
40074008
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
40084009
ptr.advanced(by: 1).pointee = 0xFF
40094010
}
40104011
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
4012+
#endif
40114013
}
4012-
4014+
40134015
func test_validateMutation_slice_customBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
40144016
var data = Data(referencing: AllOnesImmutableData(length: 10))[4..<6]
40154017
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
40164018
ptr.advanced(by: 1).pointee = 0xFF
40174019
}
40184020
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
40194021
}
4020-
4022+
40214023
func test_validateMutation_slice_customMutableBacking_withUnsafeMutableBytes_lengthLessThanLowerBound() {
4024+
#if !DARWIN_COMPATIBILITY_TESTS // Crashes on native Darwin
40224025
var base = Data(referencing: AllOnesData(length: 1))
40234026
base.count = 10
40244027
var data = base[4..<6]
40254028
data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) in
40264029
ptr.advanced(by: 1).pointee = 0xFF
40274030
}
40284031
XCTAssertEqual(data[data.startIndex.advanced(by: 1)], 0xFF)
4032+
#endif
40294033
}
40304034
}
40314035

TestFoundation/TestNSKeyedArchiver.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,18 +285,21 @@ class TestNSKeyedArchiver : XCTestCase {
285285

286286
let s1 = String(cString: charPtr)
287287
let s2 = String(cString: expectedCharPtr!)
288-
288+
289+
#if !DEPLOYMENT_RUNTIME_OBJC
289290
// On Darwin decoded strings would belong to the autorelease pool, but as we don't have
290291
// one in SwiftFoundation let's explicitly deallocate it here.
291292
expectedCharPtr!.deallocate()
292-
293+
#endif
293294
return s1 == s2
294295
})
295296
}
296297

297298
func test_archive_user_class() {
299+
#if !DARWIN_COMPATIBILITY_TESTS // Causes SIGABRT
298300
let userClass = UserClass(1234)
299301
test_archive(userClass)
302+
#endif
300303
}
301304

302305
func test_archive_ns_user_class() {

0 commit comments

Comments
 (0)