Skip to content
This repository was archived by the owner on Sep 15, 2025. It is now read-only.

Commit 9abe323

Browse files
committed
Add an unit test where HTTP response contains a large amount of data
1 parent 11a6e58 commit 9abe323

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

WordPressKitTests/Utilities/URLSessionHelperTests.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import Foundation
2+
import CryptoKit
23
import XCTest
34
import OHHTTPStubs
45

@@ -235,6 +236,54 @@ class URLSessionHelperTests: XCTestCase {
235236
let expectedBody = "--\(boundary)\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nvalue\r\n--\(boundary)--\r\n"
236237
XCTAssertEqual(String(data: requestBody, encoding: .utf8), expectedBody)
237238
}
239+
240+
func testGetLargeData() async throws {
241+
let file = try self.createLargeFile(megaBytes: 100)
242+
defer {
243+
try? FileManager.default.removeItem(at: file)
244+
}
245+
246+
stub(condition: isPath("/hello")) { _ in
247+
HTTPStubsResponse(fileURL: file, statusCode: 200, headers: nil)
248+
}
249+
250+
let builder = HTTPRequestBuilder(url: URL(string: "https://wordpress.org/hello")!)
251+
let response = try await session.perform(request: builder, errorType: TestError.self).get()
252+
253+
try XCTAssertEqual(
254+
sha256(XCTUnwrap(InputStream(url: file))),
255+
sha256(InputStream(data: response.body))
256+
)
257+
}
258+
259+
private func createLargeFile(megaBytes: Int) throws -> URL {
260+
let fileManager = FileManager.default
261+
let file = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
262+
.appendingPathComponent("large-file-\(UUID().uuidString).txt")
263+
fileManager.createFile(atPath: file.path, contents: nil)
264+
265+
let handle = try FileHandle(forUpdating: file)
266+
for _ in 0..<megaBytes {
267+
handle.write(Data(repeating: 46, count: 1_000_000))
268+
}
269+
try handle.close()
270+
return file
271+
}
272+
273+
private func sha256(_ stream: InputStream) -> SHA256Digest {
274+
stream.open()
275+
defer { stream.close() }
276+
277+
var hash = SHA256()
278+
let maxLength = 1024
279+
var buffer = [UInt8](repeating: 0, count: maxLength)
280+
while stream.hasBytesAvailable {
281+
let bytes = stream.read(&buffer, maxLength: maxLength)
282+
let data = Data(bytesNoCopy: &buffer, count: bytes, deallocator: .none)
283+
hash.update(data: data)
284+
}
285+
return hash.finalize()
286+
}
238287
}
239288

240289
class BackgroundURLSessionHelperTests: URLSessionHelperTests {

0 commit comments

Comments
 (0)