-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathNetworkingTests.swift
More file actions
209 lines (180 loc) · 10.6 KB
/
Copy pathNetworkingTests.swift
File metadata and controls
209 lines (180 loc) · 10.6 KB
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
import Foundation
import XCTest
@testable import Networking
class NetworkingTests: XCTestCase {
let baseURL = "http://example.com"
func setAuthorizationHeaderCustomValue() async throws {
let networking = Networking(baseURL: baseURL)
let value = "hi-mom"
await networking.setAuthorizationHeader(headerValue: value)
let result: Result<JSONResponse, NetworkingError> = await networking.post("/post")
switch result {
case let .success(response):
let headers = httpbinEchoedMap(response, "headers")
XCTAssertEqual(value, headers["Authorization"])
case let .failure(error):
XCTFail(error.localizedDescription)
}
}
func setAuthorizationHeaderCustomHeaderKeyAndValue() async throws {
let networking = Networking(baseURL: baseURL)
let key = "Anonymous-Token"
let value = "hi-mom"
await networking.setAuthorizationHeader(headerKey: key, headerValue: value)
let result: Result<JSONResponse, NetworkingError> = await networking.post("/post")
switch result {
case let .success(response):
let headers = httpbinEchoedMap(response, "headers")
XCTAssertEqual(value, headers[key])
case let .failure(error):
XCTFail(error.localizedDescription)
}
}
func testURLForPath() throws {
let networking = Networking(baseURL: baseURL)
let url = try networking.composedURL(with: "/hello")
XCTAssertEqual(url.absoluteString, "http://example.com/hello")
}
func testURLForPathWithFullPath() throws {
let networking = Networking()
let url = try networking.composedURL(with: "http://example.com/hello")
XCTAssertEqual(url.absoluteString, "http://example.com/hello")
}
func testDestinationURL() throws {
let networking = Networking(baseURL: baseURL)
let path = "/image/png"
let destinationURL = try networking.destinationURL(for: path)
XCTAssertEqual(destinationURL.lastPathComponent, "http:--example.com-image-png")
}
func testDestinationURLWithFullPath() throws {
let networking = Networking()
let path = "http://example.com/image/png"
let destinationURL = try networking.destinationURL(for: path)
XCTAssertEqual(destinationURL.lastPathComponent, "http:--example.com-image-png")
}
func testDestinationURLWithSpecialCharactersInPath() throws {
let networking = Networking(baseURL: baseURL)
let path = "/h�sttur.jpg"
let destinationURL = try networking.destinationURL(for: path)
XCTAssertEqual(destinationURL.lastPathComponent, "http:--example.com-h%EF%BF%BDsttur.jpg")
}
func testDestinationURLWithSpecialCharactersInCacheName() throws {
let networking = Networking(baseURL: baseURL)
let path = "/the-url-doesnt-really-matter"
let destinationURL = try networking.destinationURL(for: path, cacheName: "h�sttur.jpg-25-03/small")
XCTAssertEqual(destinationURL.lastPathComponent, "h%EF%BF%BDsttur.jpg-25-03-small")
}
func testDestinationURLCache() throws {
let networking = Networking(baseURL: baseURL)
let path = "/image/png"
let cacheName = "png/png"
let destinationURL = try networking.destinationURL(for: path, cacheName: cacheName)
XCTAssertEqual(destinationURL.lastPathComponent, "png-png")
}
// A long URL would overflow the filesystem's 255-char filename limit; the cache hashes the component
// so the write still succeeds and the entry round-trips.
func testCachingALongURLSucceedsViaHashedFilename() throws {
let networking = Networking(baseURL: baseURL)
let longPath = "/" + String(repeating: "a", count: 300)
let payload = Data("payload".utf8)
XCTAssertNoThrow(
try networking.cacheOrPurgeData(data: payload, path: longPath, cacheName: nil, cachingLevel: .memoryAndFile)
)
let cached = try networking.objectFromCache(for: longPath, cacheName: nil, cachingLevel: .memoryAndFile, responseType: .data) as? Data
XCTAssertEqual(cached, payload)
}
// The clock is the file's modification date: fresh is warm, older-than-TTL is cold, no date is kept.
func testCacheExpiryUsesFileDate() {
let expiry = CacheExpiry(ttl: .seconds(60))
XCTAssertFalse(expiry.isExpired(fileDate: Date()))
XCTAssertTrue(expiry.isExpired(fileDate: Date(timeIntervalSinceNow: -120)))
XCTAssertFalse(expiry.isExpired(fileDate: nil), "unknown age is kept, not expired")
}
// A disk entry whose mtime is older than the TTL is cold: dropped and reported as a miss on read.
func testColdDiskEntryExpiresOnRead() throws {
let networking = Networking(baseURL: baseURL, cacheTTL: .seconds(60))
let path = "/cold-entry"
try networking.cacheOrPurgeData(data: Data("stale".utf8), path: path, cacheName: nil, cachingLevel: .memoryAndFile)
let url = try networking.destinationURL(for: path)
networking.cache.removeObject(forKey: url.absoluteString as AnyObject) // force the disk path
try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -120)], ofItemAtPath: url.path)
let object = try networking.objectFromCache(for: path, cacheName: nil, cachingLevel: .memoryAndFile, responseType: .data)
XCTAssertNil(object, "an entry idle beyond cacheTTL is expired on read")
}
// A disk hit re-warms the file's mtime, so an entry in active use never expires (sliding TTL).
func testDiskHitReWarmsFileDate() throws {
let networking = Networking(baseURL: baseURL, cacheTTL: .seconds(60))
let path = "/warm-entry"
try networking.cacheOrPurgeData(data: Data("fresh".utf8), path: path, cacheName: nil, cachingLevel: .memoryAndFile)
let url = try networking.destinationURL(for: path)
networking.cache.removeObject(forKey: url.absoluteString as AnyObject) // force the disk path
try FileManager.default.setAttributes([.modificationDate: Date(timeIntervalSinceNow: -30)], ofItemAtPath: url.path)
XCTAssertNotNil(try networking.objectFromCache(for: path, cacheName: nil, cachingLevel: .memoryAndFile, responseType: .data))
let mtime = try url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate!
XCTAssertLessThan(Date().timeIntervalSince(mtime), 5, "the disk hit should have re-warmed the mtime to ~now")
}
// (No test for "a memory hit doesn't re-stamp the disk mtime": NSCache can evict at any time, so a
// memory hit can't be forced deterministically — on eviction the read becomes a disk hit that *does*
// re-warm. The behavior is documented; testDiskHitReWarmsFileDate covers the deterministic disk path.)
// Cache files live under a one-hex-nibble shard directory so the per-launch sweep is O(N / shardCount).
func testCacheFilesAreSharded() throws {
let networking = Networking(baseURL: baseURL)
let url = try networking.destinationURL(for: "/image/png")
let shard = url.deletingLastPathComponent().lastPathComponent
XCTAssertEqual(shard.count, 1)
XCTAssertTrue(shard.allSatisfy { $0.isHexDigit })
XCTAssertEqual(url.deletingLastPathComponent().deletingLastPathComponent().lastPathComponent, Networking.domain)
}
// clearCache() empties both tiers — the bug the old disk-only static left behind was memory still
// serving deleted data.
func testClearCacheEmptiesMemory() async throws {
let networking = Networking(baseURL: baseURL)
let path = "/cached"
try networking.cacheOrPurgeData(data: Data("hi".utf8), path: path, cacheName: nil, cachingLevel: .memoryAndFile)
XCTAssertNotNil(try networking.objectFromCache(for: path, cacheName: nil, cachingLevel: .memoryAndFile, responseType: .data))
try await networking.clearCache()
XCTAssertNil(try networking.objectFromCache(for: path, cacheName: nil, cachingLevel: .memoryAndFile, responseType: .data))
}
func testStatusCodeType() {
XCTAssertEqual((URLError.cancelled.rawValue).statusCodeType, Networking.StatusCodeType.cancelled)
XCTAssertEqual(99.statusCodeType, Networking.StatusCodeType.unknown)
XCTAssertEqual(100.statusCodeType, Networking.StatusCodeType.informational)
XCTAssertEqual(199.statusCodeType, Networking.StatusCodeType.informational)
XCTAssertEqual(200.statusCodeType, Networking.StatusCodeType.successful)
XCTAssertEqual(299.statusCodeType, Networking.StatusCodeType.successful)
XCTAssertEqual(300.statusCodeType, Networking.StatusCodeType.redirection)
XCTAssertEqual(399.statusCodeType, Networking.StatusCodeType.redirection)
XCTAssertEqual(400.statusCodeType, Networking.StatusCodeType.clientError)
XCTAssertEqual(499.statusCodeType, Networking.StatusCodeType.clientError)
XCTAssertEqual(500.statusCodeType, Networking.StatusCodeType.serverError)
XCTAssertEqual(599.statusCodeType, Networking.StatusCodeType.serverError)
XCTAssertEqual(600.statusCodeType, Networking.StatusCodeType.unknown)
}
func testSplitBaseURLAndRelativePath() throws {
let (baseURL1, relativePath1) = try XCTUnwrap(Networking.splitBaseURLAndRelativePath(for: "https://rescuejuice.com/wp-content/uploads/2015/11/døgnvillburgere.jpg"))
XCTAssertEqual(baseURL1, "https://rescuejuice.com")
XCTAssertEqual(relativePath1, "/wp-content/uploads/2015/11/døgnvillburgere.jpg")
let (baseURL2, relativePath2) = try XCTUnwrap(Networking.splitBaseURLAndRelativePath(for: "http://example.com/basic-auth/user/passwd"))
XCTAssertEqual(baseURL2, "http://example.com")
XCTAssertEqual(relativePath2, "/basic-auth/user/passwd")
}
func testReset() async throws {
let networking = Networking(baseURL: baseURL)
await networking.setAuthorizationHeader(username: "user", password: "passwd")
await networking.setAuthorizationHeader(token: "token")
await networking.setHeaderFields(["HeaderKey": "HeaderValue"])
var token = await networking.token
var authKey = await networking.authorizationHeaderKey
var authValue = await networking.authorizationHeaderValue
XCTAssertEqual(token, "token")
XCTAssertEqual(authKey, "Authorization")
XCTAssertEqual(authValue, "Basic dXNlcjpwYXNzd2Q=")
try await networking.reset()
token = await networking.token
authKey = await networking.authorizationHeaderKey
authValue = await networking.authorizationHeaderValue
XCTAssertNil(token)
XCTAssertEqual(authKey, "Authorization")
XCTAssertNil(authValue)
}
}