forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestNSKeyedArchiver.swift
377 lines (315 loc) · 13.1 KB
/
TestNSKeyedArchiver.swift
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
// 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
//
public class NSUserClass : NSObject, NSSecureCoding {
var ivar : Int
public class var supportsSecureCoding: Bool {
return true
}
public func encode(with aCoder : NSCoder) {
aCoder.encode(ivar, forKey:"$ivar") // also test escaping
}
init(_ value: Int) {
self.ivar = value
}
public required init?(coder aDecoder: NSCoder) {
self.ivar = aDecoder.decodeInteger(forKey: "$ivar")
}
public override var description: String {
get {
return "NSUserClass \(ivar)"
}
}
public override func isEqual(_ object: Any?) -> Bool {
if let custom = object as? NSUserClass {
return self.ivar == custom.ivar
} else {
return false
}
}
}
public class UserClass : NSObject, NSSecureCoding {
var ivar : Int
public class var supportsSecureCoding: Bool {
return true
}
public func encode(with aCoder : NSCoder) {
aCoder.encode(ivar, forKey:"$ivar") // also test escaping
}
init(_ value: Int) {
self.ivar = value
super.init()
}
public required init?(coder aDecoder: NSCoder) {
self.ivar = aDecoder.decodeInteger(forKey: "$ivar")
super.init()
}
public override var description: String {
get {
return "UserClass \(ivar)"
}
}
public override func isEqual(_ other: Any?) -> Bool {
guard let other = other as? UserClass else {
return false
}
return ivar == other.ivar
}
}
class TestNSKeyedArchiver : XCTestCase {
static var allTests: [(String, (TestNSKeyedArchiver) -> () throws -> Void)] {
return [
("test_archive_array", test_archive_array),
("test_archive_charptr", test_archive_charptr),
("test_archive_concrete_value", test_archive_concrete_value),
("test_archive_dictionary", test_archive_dictionary),
("test_archive_generic_objc", test_archive_generic_objc),
("test_archive_locale", test_archive_locale),
("test_archive_string", test_archive_string),
("test_archive_mutable_array", test_archive_mutable_array),
("test_archive_mutable_dictionary", test_archive_mutable_dictionary),
("test_archive_ns_user_class", test_archive_ns_user_class),
("test_archive_nspoint", test_archive_nspoint),
("test_archive_nsrange", test_archive_nsrange),
("test_archive_nsrect", test_archive_nsrect),
("test_archive_null", test_archive_null),
("test_archive_set", test_archive_set),
("test_archive_url", test_archive_url),
("test_archive_user_class", test_archive_user_class),
("test_archive_uuid_bvref", test_archive_uuid_byref),
("test_archive_uuid_byvalue", test_archive_uuid_byvalue),
("test_archive_unhashable", test_archive_unhashable),
("test_archiveRootObject_String", test_archiveRootObject_String),
("test_archiveRootObject_URLRequest()", test_archiveRootObject_URLRequest),
]
}
private func test_archive(_ encode: (NSKeyedArchiver) -> Bool,
decode: (NSKeyedUnarchiver) -> Bool) {
// Archiving using custom NSMutableData instance
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
XCTAssertTrue(encode(archiver))
archiver.finishEncoding()
let unarchiver = NSKeyedUnarchiver(forReadingWith: Data._unconditionallyBridgeFromObjectiveC(data))
XCTAssertTrue(decode(unarchiver))
// Archiving using the default initializer
let archiver1 = NSKeyedArchiver()
XCTAssertTrue(encode(archiver1))
let archivedData = archiver1.encodedData
let unarchiver1 = NSKeyedUnarchiver(forReadingWith: archivedData)
XCTAssertTrue(decode(unarchiver1))
// Archiving using the secure initializer
let archiver2 = NSKeyedArchiver(requiringSecureCoding: true)
XCTAssertTrue(encode(archiver2))
let archivedData2 = archiver2.encodedData
let unarchiver2 = NSKeyedUnarchiver(forReadingWith: archivedData2)
XCTAssertTrue(decode(unarchiver2))
}
private func test_archive(_ object: Any, classes: [AnyClass], allowsSecureCoding: Bool = true, outputFormat: PropertyListSerialization.PropertyListFormat) {
test_archive({ archiver -> Bool in
archiver.requiresSecureCoding = allowsSecureCoding
archiver.outputFormat = outputFormat
archiver.encode(object, forKey: NSKeyedArchiveRootObjectKey)
archiver.finishEncoding()
return true
},
decode: { unarchiver -> Bool in
unarchiver.requiresSecureCoding = allowsSecureCoding
guard let rootObj = unarchiver.decodeObject(of: classes, forKey: NSKeyedArchiveRootObjectKey) else {
XCTFail("Unable to decode data")
return false
}
if unarchiver.error != nil {
XCTAssertNotNil(unarchiver.error)
return false
}
XCTAssertEqual(object as? AnyHashable, rootObj as? AnyHashable, "unarchived object \(rootObj) does not match \(object)")
return true
})
}
private func test_archive(_ object: Any, classes: [AnyClass], allowsSecureCoding: Bool = true) {
// test both XML and binary encodings
test_archive(object, classes: classes, allowsSecureCoding: allowsSecureCoding, outputFormat: .xml)
test_archive(object, classes: classes, allowsSecureCoding: allowsSecureCoding, outputFormat: .binary)
}
private func test_archive(_ object: AnyObject, allowsSecureCoding: Bool = true) {
return test_archive(object, classes: [type(of: object)], allowsSecureCoding: allowsSecureCoding)
}
func test_archive_array() {
let array = NSArray(array: ["one", "two", "three"])
test_archive(array)
}
func test_archive_concrete_value() {
let array: Array<UInt64> = [12341234123, 23452345234, 23475982345, 9893563243, 13469816598]
let objctype = "[5Q]"
array.withUnsafeBufferPointer { cArray in
let concrete = NSValue(bytes: cArray.baseAddress!, objCType: objctype)
test_archive(concrete)
}
}
func test_archive_dictionary() {
let dictionary = NSDictionary(dictionary: ["one" : 1, "two" : 2, "three" : 3])
test_archive(dictionary)
}
func test_archive_generic_objc() {
let array: Array<Int32> = [1234, 2345, 3456, 10000]
test_archive({ archiver -> Bool in
array.withUnsafeBufferPointer { cArray in
archiver.encodeValue(ofObjCType: "[4i]", at: cArray.baseAddress!)
}
return true
},
decode: {unarchiver -> Bool in
var expected: Array<Int32> = [0, 0, 0, 0]
expected.withUnsafeMutableBufferPointer {(p: inout UnsafeMutableBufferPointer<Int32>) in
unarchiver.decodeValue(ofObjCType: "[4i]", at: UnsafeMutableRawPointer(p.baseAddress!))
}
XCTAssertEqual(expected, array)
return true
})
}
func test_archive_locale() {
let locale = Locale.current
test_archive(locale._bridgeToObjectiveC())
}
func test_archive_string() {
let string = NSString(string: "hello")
test_archive(string)
}
func test_archive_mutable_array() {
let array = NSMutableArray(array: ["one", "two", "three"])
test_archive(array)
}
func test_archive_mutable_dictionary() {
let one: NSNumber = NSNumber(value: Int(1))
let two: NSNumber = NSNumber(value: Int(2))
let three: NSNumber = NSNumber(value: Int(3))
let dict: [String : Any] = [
"one": one,
"two": two,
"three": three,
]
let mdictionary = NSMutableDictionary(dictionary: dict)
test_archive(mdictionary)
}
func test_archive_nspoint() {
let point = NSValue(point: NSPoint(x: CGFloat(20.0), y: CGFloat(35.0)))
test_archive(point)
}
func test_archive_nsrange() {
let range = NSValue(range: NSRange(location: 1234, length: 5678))
test_archive(range)
}
func test_archive_nsrect() {
let point = NSPoint(x: CGFloat(20.0), y: CGFloat(35.4))
let size = NSSize(width: CGFloat(50.0), height: CGFloat(155.0))
let rect = NSValue(rect: NSRect(origin: point, size: size))
test_archive(rect)
}
func test_archive_null() {
let null = NSNull()
test_archive(null)
}
func test_archive_set() {
let set = NSSet(array: [NSNumber(value: Int(1234234)),
NSNumber(value: Int(2374853)),
NSString(string: "foobarbarbar"),
NSValue(point: NSPoint(x: CGFloat(5.0), y: CGFloat(Double(1.5))))])
test_archive(set, classes: [NSValue.self, NSSet.self])
}
func test_archive_url() {
let url = NSURL(string: "index.html", relativeTo: URL(string: "http://www.apple.com"))!
test_archive(url)
}
func test_archive_charptr() {
let charArray = [CChar]("Hello world, we are testing!\0".utf8CString)
var charPtr = UnsafeMutablePointer(mutating: charArray)
test_archive({ archiver -> Bool in
let value = NSValue(bytes: &charPtr, objCType: "*")
archiver.encode(value, forKey: "root")
return true
},
decode: {unarchiver -> Bool in
guard let value = unarchiver.decodeObject(of: NSValue.self, forKey: "root") else {
return false
}
return withExtendedLifetime(value) { value in
var expectedCharPtr: UnsafeMutablePointer<CChar>? = nil
value.getValue(&expectedCharPtr)
let s1 = String(cString: charPtr)
let s2 = String(cString: expectedCharPtr!)
return s1 == s2
}
})
}
func test_archive_user_class() {
#if !DARWIN_COMPATIBILITY_TESTS // Causes SIGABRT
let userClass = UserClass(1234)
test_archive(userClass)
#endif
}
func test_archive_ns_user_class() {
let nsUserClass = NSUserClass(5678)
test_archive(nsUserClass)
}
func test_archive_uuid_byref() {
let uuid = NSUUID()
test_archive(uuid)
}
func test_archive_uuid_byvalue() {
let uuid = UUID()
return test_archive(uuid, classes: [NSUUID.self])
}
func test_archive_unhashable() {
let data = """
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Accept-Language": "en",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "TestFoundation (unknown version) curl/7.54.0"
},
"origin": "0.0.0.0",
"url": "https://httpbin.org/get"
}
""".data(using: .utf8)!
do {
let json = try JSONSerialization.jsonObject(with: data)
_ = NSKeyedArchiver.archivedData(withRootObject: json)
XCTAssert(true, "NSKeyedArchiver.archivedData handles unhashable")
}
catch {
XCTFail("test_archive_unhashable, de-serialization error \(error)")
}
}
func test_archiveRootObject_String() {
let filePath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
let result = NSKeyedArchiver.archiveRootObject("Hello", toFile: filePath)
XCTAssertTrue(result)
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
XCTFail("Failed to clean up file")
}
}
func test_archiveRootObject_URLRequest() {
let filePath = NSTemporaryDirectory() + "testdir\(NSUUID().uuidString)"
let url = URL(string: "http://swift.org")!
let request = URLRequest(url: url)._bridgeToObjectiveC()
let result = NSKeyedArchiver.archiveRootObject(request, toFile: filePath)
XCTAssertTrue(result)
do {
try FileManager.default.removeItem(atPath: filePath)
} catch {
XCTFail("Failed to clean up file")
}
}
}