-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIPDataClientTests.swift
More file actions
314 lines (259 loc) · 12 KB
/
IPDataClientTests.swift
File metadata and controls
314 lines (259 loc) · 12 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
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
import XCTest
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
@testable import IPData
// MARK: - Mock URL Protocol
final class MockURLProtocol: URLProtocol {
static var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))?
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
guard let handler = MockURLProtocol.requestHandler else {
XCTFail("No request handler set")
return
}
do {
let (response, data) = try handler(request)
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
} catch {
client?.urlProtocol(self, didFailWithError: error)
}
}
override func stopLoading() {}
}
// MARK: - Client Tests
final class IPDataClientTests: XCTestCase {
private var session: URLSession!
private var client: IPDataClient!
override func setUp() {
super.setUp()
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [MockURLProtocol.self]
session = URLSession(configuration: config)
client = IPDataClient(apiKey: "test-api-key", session: session)
}
override func tearDown() {
MockURLProtocol.requestHandler = nil
session = nil
client = nil
super.tearDown()
}
// MARK: - Request Building
func testLookupIPSendsCorrectRequest() async throws {
MockURLProtocol.requestHandler = { request in
XCTAssertEqual(request.httpMethod, "GET")
XCTAssertTrue(request.url!.path.contains("/8.8.8.8"))
XCTAssertTrue(request.url!.query!.contains("api-key=test-api-key"))
XCTAssertEqual(request.value(forHTTPHeaderField: "api-key"), "test-api-key")
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"{"ip": "8.8.8.8"}"#.data(using: .utf8)!
return (response, data)
}
let info = try await client.lookup("8.8.8.8")
XCTAssertEqual(info.ip, "8.8.8.8")
}
func testLookupCurrentIPSendsCorrectPath() async throws {
MockURLProtocol.requestHandler = { request in
// Path should end with / (no IP specified)
let path = request.url!.path
XCTAssertTrue(path.hasSuffix("/"), "Path should be root: \(path)")
XCTAssertFalse(path.contains("8.8.8.8"))
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"{"ip": "203.0.113.1"}"#.data(using: .utf8)!
return (response, data)
}
let info = try await client.lookup()
XCTAssertEqual(info.ip, "203.0.113.1")
}
func testLookupWithFieldsParameter() async throws {
MockURLProtocol.requestHandler = { request in
let query = request.url!.query!
XCTAssertTrue(query.contains("fields=ip,city,country_name"), "Query: \(query)")
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"{"ip": "8.8.8.8", "city": "Mountain View"}"#.data(using: .utf8)!
return (response, data)
}
let info = try await client.lookup("8.8.8.8", fields: ["ip", "city", "country_name"])
XCTAssertEqual(info.city, "Mountain View")
}
func testLookupFieldReturnsRawData() async throws {
let asnJSON = #"{"asn": "AS15169", "name": "Google LLC"}"#
MockURLProtocol.requestHandler = { request in
XCTAssertTrue(request.url!.path.contains("/8.8.8.8/asn"))
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return (response, asnJSON.data(using: .utf8)!)
}
let data = try await client.lookupField("8.8.8.8", field: "asn")
let str = String(data: data, encoding: .utf8)
XCTAssertEqual(str, asnJSON)
}
// MARK: - EU Endpoint
func testEUEndpointUsesCorrectBaseURL() async throws {
let euClient = IPDataClient(apiKey: "test-api-key", baseURL: IPDataClient.euBaseURL, session: session)
MockURLProtocol.requestHandler = { request in
XCTAssertTrue(request.url!.absoluteString.contains("eu-api.ipdata.co"))
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"{"ip": "8.8.8.8"}"#.data(using: .utf8)!
return (response, data)
}
let info = try await euClient.lookup("8.8.8.8")
XCTAssertEqual(info.ip, "8.8.8.8")
}
// MARK: - Bulk Lookup
func testBulkLookupSendsPostWithIPsInBody() async throws {
MockURLProtocol.requestHandler = { request in
XCTAssertEqual(request.httpMethod, "POST")
XCTAssertTrue(request.url!.path.contains("/bulk"))
XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json")
XCTAssertEqual(request.value(forHTTPHeaderField: "api-key"), "test-api-key")
let body = try! JSONDecoder().decode([String].self, from: request.httpBody!)
XCTAssertEqual(body, ["1.1.1.1", "8.8.8.8"])
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"[{"ip": "1.1.1.1"}, {"ip": "8.8.8.8"}]"#.data(using: .utf8)!
return (response, data)
}
let results = try await client.bulkLookup(["1.1.1.1", "8.8.8.8"])
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0].ip, "1.1.1.1")
XCTAssertEqual(results[1].ip, "8.8.8.8")
}
// MARK: - ASN Lookup
func testASNLookupPrependsASPrefix() async throws {
MockURLProtocol.requestHandler = { request in
XCTAssertTrue(request.url!.path.contains("/AS15169"), "Path: \(request.url!.path)")
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"{"asn": "AS15169", "name": "Google LLC"}"#.data(using: .utf8)!
return (response, data)
}
let detail = try await client.lookupASN("15169")
XCTAssertEqual(detail.asn, "AS15169")
}
func testASNLookupKeepsExistingPrefix() async throws {
MockURLProtocol.requestHandler = { request in
// Should NOT double-prefix to "ASAS15169"
XCTAssertTrue(request.url!.path.contains("/AS15169"), "Path: \(request.url!.path)")
XCTAssertFalse(request.url!.path.contains("ASAS"))
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = #"{"asn": "AS15169", "name": "Google LLC"}"#.data(using: .utf8)!
return (response, data)
}
let detail = try await client.lookupASN("AS15169")
XCTAssertEqual(detail.name, "Google LLC")
}
// MARK: - Error Mapping
func testBadRequestError() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 400, httpVersion: nil, headerFields: nil)!
let data = #"{"message": "1.2.3.4.5 does not appear to be an IPv4 or IPv6 address"}"#.data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookup("1.2.3.4.5")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .badRequest(let msg) = error else {
return XCTFail("Expected .badRequest, got \(error)")
}
XCTAssertTrue(msg.contains("does not appear to be"))
}
}
func testUnauthorizedError() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 401, httpVersion: nil, headerFields: nil)!
let data = #"{"message": "You have not provided a valid API Key."}"#.data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookup("8.8.8.8")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .unauthorized(let msg) = error else {
return XCTFail("Expected .unauthorized, got \(error)")
}
XCTAssertTrue(msg.contains("valid API Key"))
}
}
func testForbiddenError() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 403, httpVersion: nil, headerFields: nil)!
let data = #"{"message": "You have exceeded your daily quota."}"#.data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookup("8.8.8.8")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .forbidden(let msg) = error else {
return XCTFail("Expected .forbidden, got \(error)")
}
XCTAssertTrue(msg.contains("quota"))
}
}
func testNotFoundError() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 404, httpVersion: nil, headerFields: nil)!
let data = #"{"message": "Not found"}"#.data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookupASN("AS99999999")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .notFound = error else {
return XCTFail("Expected .notFound, got \(error)")
}
}
}
func testUnexpectedStatusError() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 500, httpVersion: nil, headerFields: nil)!
let data = #"{"message": "Internal server error"}"#.data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookup("8.8.8.8")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .unexpectedStatus(let code, let msg) = error else {
return XCTFail("Expected .unexpectedStatus, got \(error)")
}
XCTAssertEqual(code, 500)
XCTAssertTrue(msg.contains("Internal server error"))
}
}
func testErrorFallsBackToRawBody() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 400, httpVersion: nil, headerFields: nil)!
let data = "plain text error".data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookup("bad")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .badRequest(let msg) = error else {
return XCTFail("Expected .badRequest, got \(error)")
}
XCTAssertEqual(msg, "plain text error")
}
}
func testDecodingError() async throws {
MockURLProtocol.requestHandler = { request in
let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
let data = "not json at all".data(using: .utf8)!
return (response, data)
}
do {
_ = try await client.lookup("8.8.8.8")
XCTFail("Expected error")
} catch let error as IPDataError {
guard case .decodingFailed = error else {
return XCTFail("Expected .decodingFailed, got \(error)")
}
}
}
}