File: DataIOTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (305 lines) | stat: -rw-r--r-- 11,152 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if canImport(TestSupport)
import TestSupport
#endif

#if canImport(Glibc)
import Glibc
#endif

#if FOUNDATION_FRAMEWORK
@testable import Foundation
#else
@testable import FoundationEssentials
#endif // FOUNDATION_FRAMEWORK

class DataIOTests : XCTestCase {
    
    // MARK: - Helpers
    
    func testURL() -> URL {
        // Generate a random file name
        URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent("testfile-\(UUID().uuidString)")
    }
    
    func generateTestData(count: Int = 16_777_216) -> Data {
        let memory = malloc(count)!
        let ptr = memory.bindMemory(to: UInt8.self, capacity: count)
        
        // Set a few bytes so we're sure to not be all zeros
        let buf = UnsafeMutableBufferPointer(start: ptr, count: count)
        for i in 0..<15 {
            for j in 0..<128 {
                buf[j * 1024 + i] = UInt8.random(in: 1..<42)
            }
        }
        
        return Data(bytesNoCopy: ptr, count: count, deallocator: .free)
    }
            
    func writeAndVerifyTestData(to url: URL, writeOptions: Data.WritingOptions = [], readOptions: Data.ReadingOptions = []) throws {
        let data = generateTestData()
        try data.write(to: url, options: writeOptions)
        let readData = try Data(contentsOf: url, options: readOptions)
        XCTAssertEqual(data, readData)
    }
    
    func cleanup(at url: URL) {
        do {
            try FileManager.default.removeItem(at: url)
        } catch {
            // Ignore
        }
    }
    
    
    // MARK: - Tests
    
    func test_basicReadWrite() throws {
        let url = testURL()
        try writeAndVerifyTestData(to: url)
        cleanup(at: url)
    }
    
    func test_slicedReadWrite() throws {
        // Be sure to use progress reporting so we get tests of the chunking
        let url = testURL()
        let data = generateTestData()
        let slice = data[data.startIndex.advanced(by: 1 * 1024 * 1024)..<data.startIndex.advanced(by: 8 * 1024 * 1024)]

#if FOUNDATION_FRAMEWORK
        let p = Progress(totalUnitCount: 1)
        p.becomeCurrent(withPendingUnitCount: 1)
#endif
        try slice.write(to: url, options: [])
#if FOUNDATION_FRAMEWORK
        p.resignCurrent()
#endif
        let readData = try Data(contentsOf: url, options: [])
        XCTAssertEqual(readData, slice)
        cleanup(at: url)
    }

    // Atomic writing is a very different code path
    func test_readWriteAtomic() throws {
        let url = testURL()
        // Perform an atomic write to a file that does not exist
        try writeAndVerifyTestData(to: url, writeOptions: [.atomic])

        // Perform an atomic write to a file that already exists
        try writeAndVerifyTestData(to: url, writeOptions: [.atomic])

        cleanup(at: url)
    }

    func test_readWriteMapped() throws {
        let url = testURL()
        try writeAndVerifyTestData(to: url, readOptions: [.mappedIfSafe])

        cleanup(at: url)
    }

    func test_writeFailure() throws {
        let url = testURL()

        let data = Data()
        try data.write(to: url)

#if FOUNDATION_FRAMEWORK
        XCTAssertThrowsError(try data.write(to: url, options: [.withoutOverwriting])) { e in
            XCTAssertEqual((e as NSError).code, NSFileWriteFileExistsError)
        }
#else
        XCTAssertThrowsError(try data.write(to: url, options: [.withoutOverwriting]))
#endif
        
        cleanup(at: url)

        // Make sure clearing the error condition allows the write to succeed
        try data.write(to: url, options: [.withoutOverwriting])

        cleanup(at: url)
    }
    
#if FOUNDATION_FRAMEWORK
    // Progress is currently stubbed out for FoundationPreview
    func test_writeWithProgress() throws {
        let url = testURL()
        
        let p = Progress(totalUnitCount: 1)
        p.becomeCurrent(withPendingUnitCount: 1)
        try writeAndVerifyTestData(to: url)
        p.resignCurrent()
        
        XCTAssertEqual(p.completedUnitCount, 1)
        XCTAssertEqual(p.fractionCompleted, 1.0, accuracy: 0.1)
        cleanup(at: url)
    }
#endif
    
#if FOUNDATION_FRAMEWORK
    func test_writeWithAttributes() throws {
        let writeData = generateTestData()
        
        let url = testURL()
        // Data doesn't have a direct API to write with attributes, but our I/O code has it. Use it via @testable interface here.
        
        let writeAttrs: [String : Data] = [FileAttributeKey.hfsCreatorCode.rawValue : "abcd".data(using: .ascii)!]
        try writeToFile(path: .url(url), data: writeData, options: [], attributes: writeAttrs)
        
        // Verify attributes
        var readAttrs: [String : Data] = [:]
        let readData = try readDataFromFile(path: .url(url), reportProgress: false, options: [], attributesToRead: [FileAttributeKey.hfsCreatorCode.rawValue], attributes: &readAttrs)
        
        XCTAssertEqual(writeData, readData)
        XCTAssertEqual(writeAttrs, readAttrs)
        
        cleanup(at: url)
    }
#endif
        
    func test_emptyFile() throws {
        let data = Data()
        let url = testURL()
        try data.write(to: url)
        let read = try Data(contentsOf: url, options: [])
        XCTAssertEqual(data, read)
        
        cleanup(at: url)
    }
    
#if FOUNDATION_FRAMEWORK
    // String(contentsOf:) is not available outside the framework yet
    func test_emptyFileString() {
        let data = Data()
        let url = testURL()
        
        do {
            try data.write(to: url)
            let readString = try String(contentsOf: url)
            XCTAssertEqual(readString, "")
            
            let readStringWithEncoding = try String(contentsOf: url, encoding: String._Encoding.utf8)
            XCTAssertEqual(readStringWithEncoding, "")
            
            cleanup(at: url)
        } catch {
            XCTFail("Could not read file: \(error)")
        }
    }
#endif
    
    func test_largeFile() throws {
#if !os(watchOS)
        // More than 2 GB
        let size = 0x80010000
        let url = testURL()

        let data = generateTestData(count: size)
        
        try data.write(to: url)
        let read = try! Data(contentsOf: url, options: .mappedIfSafe)

        // No need to compare the contents, but do compare the size
        XCTAssertEqual(data.count, read.count)
        
#if FOUNDATION_FRAMEWORK
        // Try the NSData path
        let readNS = try! NSData(contentsOf: url, options: .mappedIfSafe) as Data
        XCTAssertEqual(data.count, readNS.count)
#endif

        cleanup(at: url)
#endif // !os(watchOS)
    }
    
    func test_writeToSpecialFile() throws {
        #if !os(Linux) && !os(Windows)
        throw XCTSkip("This test is only supported on Linux and Windows")
        #else
        #if os(Windows)
        let path = URL(filePath: "CON", directoryHint: .notDirectory)
        #else
        let path = URL(filePath: "/dev/stdout", directoryHint: .notDirectory)
        #endif
        XCTAssertNoThrow(try Data("Output to STDOUT\n".utf8).write(to: path))
        #endif
    }
    
    func test_zeroSizeFile() throws {
        #if !os(Linux) && !os(Android)
        throw XCTSkip("This test is only applicable on Linux")
        #else
        // Some files in /proc report a file size of 0 bytes via a stat call
        // Ensure that these files can still be read despite appearing to be empty
        let maps = try String(contentsOfFile: "/proc/self/maps", encoding: String._Encoding.utf8)
        XCTAssertFalse(maps.isEmpty)
        #endif
    }

    // MARK: - String Path Tests
    func testStringDeletingLastPathComponent() {
        XCTAssertEqual("/a/b/c".deletingLastPathComponent(), "/a/b")
        XCTAssertEqual("".deletingLastPathComponent(), "")
        XCTAssertEqual("/".deletingLastPathComponent(), "/")
        XCTAssertEqual("q".deletingLastPathComponent(), "")
        XCTAssertEqual("/aaa".deletingLastPathComponent(), "/")
        XCTAssertEqual("/a/b/c/".deletingLastPathComponent(), "/a/b")
        XCTAssertEqual("hello".deletingLastPathComponent(), "")
        XCTAssertEqual("hello/".deletingLastPathComponent(), "")
        XCTAssertEqual("/hello/".deletingLastPathComponent(), "/")
        XCTAssertEqual("hello///".deletingLastPathComponent(), "")
        XCTAssertEqual("a/".deletingLastPathComponent(), "")
        XCTAssertEqual("a/b".deletingLastPathComponent(), "a")
        XCTAssertEqual("a/b/".deletingLastPathComponent(), "a")
        XCTAssertEqual("a//b//".deletingLastPathComponent(), "a")
    }
    
    func testAppendingPathComponent() {
        let comp = "test"
        XCTAssertEqual("/a/b/c".appendingPathComponent(comp), "/a/b/c/test")
        XCTAssertEqual("".appendingPathComponent(comp), "test")
        XCTAssertEqual("/".appendingPathComponent(comp), "/test")
        XCTAssertEqual("q".appendingPathComponent(comp), "q/test")
        XCTAssertEqual("/aaa".appendingPathComponent(comp), "/aaa/test")
        XCTAssertEqual("/a/b/c/".appendingPathComponent(comp), "/a/b/c/test")
        XCTAssertEqual("hello".appendingPathComponent(comp), "hello/test")
        XCTAssertEqual("hello/".appendingPathComponent(comp), "hello/test")
        
        XCTAssertEqual("hello/".appendingPathComponent("/test"), "hello/test")
        XCTAssertEqual("hello".appendingPathComponent("/test"), "hello/test")
        XCTAssertEqual("hello///".appendingPathComponent("///test"), "hello/test")
        XCTAssertEqual("hello".appendingPathComponent("test/"), "hello/test")
        XCTAssertEqual("hello".appendingPathComponent("test/test2"), "hello/test/test2")
        XCTAssertEqual("hello".appendingPathComponent("test/test2/"), "hello/test/test2")
        XCTAssertEqual("hello".appendingPathComponent("test///test2/"), "hello/test/test2")
        XCTAssertEqual("hello".appendingPathComponent("/"), "hello")
        XCTAssertEqual("//".appendingPathComponent("/"), "/")
        XCTAssertEqual("".appendingPathComponent(""), "")
    }
    
    func testStringLastPathComponent() {
        XCTAssertEqual("/a/b/c".lastPathComponent, "c")
        XCTAssertEqual("".lastPathComponent, "")
        XCTAssertEqual("/".lastPathComponent, "/")
        XCTAssertEqual("q".lastPathComponent, "q")
        XCTAssertEqual("/aaa".lastPathComponent, "aaa")
        XCTAssertEqual("/a/b/c/".lastPathComponent, "c")
        XCTAssertEqual("hello".lastPathComponent, "hello")
        XCTAssertEqual("hello/".lastPathComponent, "hello")
        XCTAssertEqual("hello///".lastPathComponent, "hello")
        XCTAssertEqual("//a//".lastPathComponent, "a")
    }
}