@@ -30,6 +30,7 @@ class TestNSDictionary : XCTestCase {
30
30
( " test_equality " , test_equality) ,
31
31
( " test_copying " , test_copying) ,
32
32
( " test_mutableCopying " , test_mutableCopying) ,
33
+ ( " test_writeToFile " , test_writeToFile) ,
33
34
]
34
35
}
35
36
@@ -161,4 +162,52 @@ class TestNSDictionary : XCTestCase {
161
162
XCTAssertTrue ( dictMutableCopy2 == dictMutableCopy1)
162
163
}
163
164
165
+ func test_writeToFile( ) {
166
+ let testFilePath = createTestFile ( " TestFileOut.txt " , _contents: Data ( capacity: 256 ) )
167
+ if let _ = testFilePath {
168
+ let d1 : NSDictionary = [ " foo " : " bar " , " baz " : " qux " ]
169
+ let isWritten = d1. write ( toFile: testFilePath!, atomically: true )
170
+ if ( isWritten) {
171
+ do {
172
+ let plistDoc = try XMLDocument ( contentsOf: URL ( fileURLWithPath: testFilePath!, isDirectory: false ) , options: [ ] )
173
+ try plistDoc. validate ( )
174
+ XCTAssert ( plistDoc. rootElement ( ) ? . name == " plist " )
175
+ let plist = try PropertyListSerialization . propertyList ( from: plistDoc. xmlData, options: [ ] , format: nil ) as! [ String : Any ]
176
+ XCTAssert ( ( plist [ " foo " ] as? String ) == d1 [ " foo " ] as? String )
177
+ XCTAssert ( ( plist [ " baz " ] as? String ) == d1 [ " baz " ] as? String )
178
+ } catch {
179
+ XCTFail ( " XMLDocument failes to read / validate contenets " )
180
+ }
181
+ } else {
182
+ XCTFail ( " Write to file failed " )
183
+ }
184
+ removeTestFile ( testFilePath!)
185
+ } else {
186
+ XCTFail ( " Temporary file creation failed " )
187
+ }
188
+ }
189
+
190
+ private func createTestFile( _ path: String , _contents: Data ) -> String ? {
191
+ let tempDir = " /tmp/TestFoundation_Playground_ " + NSUUID( ) . uuidString + " / "
192
+ do {
193
+ try FileManager . default. createDirectory ( atPath: tempDir, withIntermediateDirectories: false , attributes: nil )
194
+ if FileManager . default. createFile ( atPath: tempDir + " / " + path, contents: _contents,
195
+ attributes: nil ) {
196
+ return tempDir + path
197
+ } else {
198
+ return nil
199
+ }
200
+ } catch _ {
201
+ return nil
202
+ }
203
+ }
204
+
205
+ private func removeTestFile( _ location: String ) {
206
+ do {
207
+ try FileManager . default. removeItem ( atPath: location)
208
+ } catch _ {
209
+
210
+ }
211
+ }
212
+
164
213
}
0 commit comments