-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLogStorageTests.swift
More file actions
533 lines (357 loc) · 19.1 KB
/
LogStorageTests.swift
File metadata and controls
533 lines (357 loc) · 19.1 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//
// LogStorageTests.swift
// PredixMobileReferenceApp
//
// Created by Johns, Andy (GE Corporate) on 2/22/16.
// Copyright © 2016 GE. All rights reserved.
//
import XCTest
import PredixMobileSDK
@testable import PredixMobileiOS
class LogStorageTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// Ensure disk logs are clear before testings
_ = try? FileManager.default.removeItem(at: LogStorage().logLocation as URL)
}
override func tearDown() {
// ensure no services are registered after testing
ServiceRouter.sharedInstance.unregisterService(MockDBService.self)
ServiceRouter.sharedInstance.unregisterService(MockCDBService.self)
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testLogStorageInit() {
let logStorage = LogStorage()
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
// now logs should be going to the storage array
let testString = "test log"
Logger.info(testString)
// Wait briefly, logs are written asynchronously.
let group = DispatchGroup()
group.enter()
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.1) {
group.leave()
}
group.wait()
if let lastEntry = logStorage.logStore.last {
if let logEntry = lastEntry[LogEntryKeys.LogEntry] as? String {
XCTAssertTrue(logEntry.hasSuffix(testString), "Log entry did not match expected value")
} else {
XCTFail("Log dictionary did not contain a string for key: \(LogEntryKeys.LogEntry) : lastEntry[LogEntryKeys.LogEntry]")
}
} else {
XCTFail("Log store did not contain any entries after log entry was made.")
}
}
func testLogArrayToJSONInvalidJSON() {
let logStorage = LogStorage()
// create an array that cannot be JSON serialized
let testLogArrayToFail: [[String : Any]] = [["foo": Date()], ["foo": Date()]]
let result = logStorage.logArrayToJSON(testLogArrayToFail)
XCTAssertNil(result, "result of logArrayToJSON was expected to be nil")
}
func testLogArrayToJSON() {
let logStorage = LogStorage()
let testString = "test log"
let dateString = logStorage.logDataFormatter.string(from: Date())
// create an array to serialize
let testLogArray: [[String : Any]] = [[LogEntryKeys.Date: dateString, LogEntryKeys.LogEntry: testString]]
let result = logStorage.logArrayToJSON(testLogArray)
XCTAssertNotNil(result, "result of logArrayToJSON was not expected to be nil")
let deserializedData = try? JSONSerialization.jsonObject(with: result!, options: JSONSerialization.ReadingOptions(rawValue: 0))
XCTAssertNotNil(deserializedData, "result of JSONObjectWithData was not expected to be nil")
if let documentDictionary = deserializedData as? [String : Any] {
let logs = documentDictionary[LogDocumentKeys.Logs] as? [[String : Any]]
let deviceId = documentDictionary[LogDocumentKeys.DeviceId] as? String
let docType = documentDictionary[LogDocumentKeys.DocumentType] as? String
XCTAssertEqual(deviceId, UIDevice.current.identifierForVendor?.uuidString, "Device Id not as expected")
XCTAssertEqual(docType, logStorage.LogDocumentType, "Document Type not as expected")
XCTAssertNotNil(logs, "Log array was not in data")
XCTAssertEqual(logs?.count, 1, "Count of decoded log array was not as expected")
let logItem = (logs?.first)! as [String : Any]
let logEntry = logItem[LogEntryKeys.LogEntry] as? String
XCTAssertEqual(testString, logEntry, "Log entry did not match expected value")
} else {
XCTFail("result of JSONObjectWithData was not expected data type: \(String(describing: deserializedData))")
}
}
func testPersistLogsToDisk() {
let logStorage = LogStorage()
XCTAssertFalse(logStorage.hasLogsOnDisk(), "Logs found on disk when not expected")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
// now logs should be going to the storeage array
let testString = "test log"
Logger.info(testString)
logStorage.persistLogToDisk()
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
}
func testPersistLogsToDatabase() {
let logStorage = LogStorage()
// register our mock database service
ServiceRouter.sharedInstance.registerService(MockCDBService.self)
// for this test we should succeed
MockCDBService.serviceShouldReturnFailure = false
MockCDBService.expectation = self.expectation(description: "database service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
let logData = logStorage.logArrayToJSON(logStorage.logStore)!
let expectation = self.expectation(description: "On Complete expectation")
logStorage.persistLogToDatabase(logData) { (success: Bool) -> Void in
XCTAssertTrue(success, "persistLogToDatabase onComplete returned false success")
expectation.fulfill()
}
self.waitForExpectations(timeout: 10, handler: nil)
}
func testPersistLogsToDatabaseWithFailure() {
let logStorage = LogStorage()
// register our mock database service
ServiceRouter.sharedInstance.registerService(MockCDBService.self)
// for this test we should fail
MockCDBService.serviceShouldReturnFailure = true
MockCDBService.expectation = self.expectation(description: "database service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
let logData = logStorage.logArrayToJSON(logStorage.logStore)!
let expectation = self.expectation(description: "On Complete expectation")
logStorage.persistLogToDatabase(logData) { (success: Bool) -> Void in
XCTAssertFalse(success, "persistLogToDatabase onComplete returned false success")
expectation.fulfill()
}
self.waitForExpectations(timeout: 10, handler: nil)
}
// tests the persistLog method when database is not ready
// In this case logs should be written to disk, and an observer should have been created watching for database ready
func testPersistLogNotReady() {
let logStorage = LogStorage()
// register our mock DB service
ServiceRouter.sharedInstance.registerService(MockDBService.self)
// for this test we should return not ready
MockDBService.serviceShouldReturnNotReady = true
MockDBService.expectation = self.expectation(description: "db service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
logStorage.persistLog(logStorage.logStore)
self.waitForExpectations(timeout: 10, handler: nil)
XCTAssertNotNil(logStorage.databaseReadyObserver, "database ready observer should have been created")
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
}
// tests the persistLog method when database is ready.
// In this case logs should be written to database
func testPersistLogDatabaseReady() {
let logStorage = LogStorage()
// register our mock connectivity service
ServiceRouter.sharedInstance.registerService(MockDBService.self)
// for this test we should return ready
MockDBService.serviceShouldReturnNotReady = false
MockDBService.expectation = self.expectation(description: "connectivity service called expectation")
// register our mock database service
ServiceRouter.sharedInstance.registerService(MockCDBService.self)
// for this test we should succeed
MockCDBService.serviceShouldReturnFailure = false
MockCDBService.expectation = self.expectation(description: "database service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
logStorage.persistLog(logStorage.logStore)
self.waitForExpectations(timeout: 10, handler: nil)
XCTAssertNil(logStorage.databaseReadyObserver, "Database ready observer should not have been created")
XCTAssertFalse(logStorage.hasLogsOnDisk(), "Logs found on disk when not expected")
}
// tests conversion of logs from disk to database
func testTransferLogsFromDiskToDatabase() {
let logStorage = LogStorage()
// register our mock database service
ServiceRouter.sharedInstance.registerService(MockCDBService.self)
// for this test we should succeed
MockCDBService.serviceShouldReturnFailure = false
MockCDBService.expectation = self.expectation(description: "database service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
// write the log to disk
logStorage.persistLogToDisk()
// verify log was written to disk
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
logStorage.transferLogsFromDiskToDatabase()
self.waitForExpectations(timeout: 10, handler: nil)
// verify logs removed from disk
XCTAssertFalse(logStorage.hasLogsOnDisk(), "Logs found on disk when not expected")
}
// tests conversion of logs from disk to database ensuring if database write fails logs are not deleted
func testTransferLogsFromDiskToDatabaseFail() {
let logStorage = LogStorage()
// register our mock database service
ServiceRouter.sharedInstance.registerService(MockCDBService.self)
// for this test we should fail
MockCDBService.serviceShouldReturnFailure = true
MockCDBService.expectation = self.expectation(description: "database service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
// write the log to disk
logStorage.persistLogToDisk()
// verify log was written to disk
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
logStorage.transferLogsFromDiskToDatabase()
self.waitForExpectations(timeout: 10, handler: nil)
// verify logs not removed from disk
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
}
// tests that the log is preseved when we hit the max log entries limit
func testLogWriteOnMaxLogEntries() {
// for this test reduce our max log entries to a smaller number
let logStorage = LogStorage(maxLogEntries: 10)
// We only want warning logs in this test, so other system processes don't interfere with count compared below.
Logger.shared.loggerLevel = .warn
// register our mock connectivity service
ServiceRouter.sharedInstance.registerService(MockDBService.self)
// for this test we should return not ready
MockDBService.serviceShouldReturnNotReady = true
MockDBService.expectation = self.expectation(description: "connectivity service called expectation")
for count in 1...logStorage.MaxLogEntries {
Logger.warn("test log # \(count)")
}
// Wait briefly, logs are written asynchronously.
let group = DispatchGroup()
group.enter()
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.1) {
group.leave()
}
group.wait()
self.waitForExpectations(timeout: 10, handler: nil)
//verify logs were written
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
XCTAssertEqual(logStorage.logStore.count, 0, "Log entry count was not as expected")
}
// tests that previously disk-saved logs are sent to the database after it's ready
func testDatabaseReadyObserver() {
let logStorage = LogStorage()
// register our mock connectivity service
ServiceRouter.sharedInstance.registerService(MockDBService.self)
// for now we should return not ready
MockDBService.serviceShouldReturnNotReady = true
MockDBService.expectation = self.expectation(description: "connectivity service called expectation")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
let testString = "test log"
Logger.info(testString)
logStorage.persistLog(logStorage.logStore)
self.waitForExpectations(timeout: 10, handler: nil)
XCTAssertNotNil(logStorage.databaseReadyObserver, "Database ready observer should have been created")
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
// register our mock database service
ServiceRouter.sharedInstance.registerService(MockCDBService.self)
// for this test we should succeed
MockCDBService.serviceShouldReturnFailure = false
MockCDBService.expectation = self.expectation(description: "database service called expectation")
// now send pmInitialReplicationComplete notification
NotificationCenter.default.post(name: .pmInitialReplicationComplete, object: nil)
self.waitForExpectations(timeout: 10, handler: nil)
XCTAssertNil(logStorage.databaseReadyObserver, "Database ready observer should have been removed")
XCTAssertFalse(logStorage.hasLogsOnDisk(), "Logs found on disk when not expected")
}
func testPersistLogsOnLowMemory() {
let logStorage = LogStorage()
XCTAssertFalse(logStorage.hasLogsOnDisk(), "Logs found on disk when not expected")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
// now logs should be going to the storeage array
let testString = "test log"
Logger.info(testString)
NotificationCenter.default.post(name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
}
func testPersistLogsOnBackgrounding() {
let logStorage = LogStorage()
XCTAssertFalse(logStorage.hasLogsOnDisk(), "Logs found on disk when not expected")
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
// now logs should be going to the storeage array
let testString = "test log"
Logger.info(testString)
NotificationCenter.default.post(name: UIApplication.didEnterBackgroundNotification, object: nil)
XCTAssertTrue(logStorage.hasLogsOnDisk(), "Logs not found on disk when expected")
}
func testStopStoringLogs() {
let logStorage = LogStorage()
// ensure every log level is being written to the log system
Logger.shared.loggerLevel = .trace
// now logs should be going to the storeage array
let testString = "test log"
Logger.info(testString)
// Wait briefly, logs are written asynchronously.
let group = DispatchGroup()
group.enter()
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.1) {
group.leave()
}
group.wait()
// ensure we have some logs
XCTAssertTrue(logStorage.logStore.count > 0, "No logs entries found unexpectedly")
// stopping logging should persist what's currently in memory
logStorage.stopStoringLogs()
// verify we don't have any log entries
XCTAssertTrue(logStorage.logStore.count == 0, "logs entries found unexpectedly")
// now write more logs
Logger.info(testString)
// still should have no log entries
XCTAssertTrue(logStorage.logStore.count == 0, "logs entries found unexpectedly")
}
}
// Mock services used for testing
class MockCDBService: ServiceProtocol {
static var expectation: XCTestExpectation?
static var serviceShouldReturnFailure = false
@objc static var serviceIdentifier: String {return ServiceId.CDB}
@objc static func performRequest(_ request: URLRequest, response: HTTPURLResponse, responseReturn: @escaping responseReturnBlock, dataReturn: @escaping dataReturnBlock, requestComplete: @escaping requestCompleteBlock) {
// tracking that we actually called the service
if let expectation = self.expectation {
expectation.fulfill()
}
if self.serviceShouldReturnFailure {
let failResponse = HTTPURLResponse(url: response.url!, statusCode: Http.StatusCode.internalServerError.rawValue, httpVersion: Http.version, headerFields: response.allHeaderFields as? [String: String])
responseReturn(failResponse)
let returnDictionary = ["ok": false]
let data = try! JSONSerialization.data(withJSONObject: returnDictionary, options: JSONSerialization.WritingOptions(rawValue: 0))
dataReturn(data)
requestComplete()
} else {
// return success
responseReturn(response)
let returnDictionary = ["ok": true]
let data = try! JSONSerialization.data(withJSONObject: returnDictionary, options: JSONSerialization.WritingOptions(rawValue: 0))
dataReturn(data)
requestComplete()
}
}
}
class MockDBService: ServiceProtocol {
static var expectation: XCTestExpectation?
static var serviceShouldReturnNotReady = false
@objc static var serviceIdentifier: String {return ServiceId.DB}
@objc static func performRequest(_ request: URLRequest, response: HTTPURLResponse, responseReturn: @escaping responseReturnBlock, dataReturn: @escaping dataReturnBlock, requestComplete: @escaping requestCompleteBlock) {
// tracking that we actually called the service
if let expectation = self.expectation {
expectation.fulfill()
}
var thisResponse = response
if self.serviceShouldReturnNotReady {
thisResponse = HTTPURLResponse(url: response.url!, statusCode: Http.StatusCode.notFound.rawValue, httpVersion: Http.version, headerFields: response.allHeaderFields as? [String: String])!
}
responseReturn(thisResponse)
requestComplete()
}
}