HeartbeatLoggingIntegrationTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import XCTest
  15. @testable import FirebaseCoreInternal
  16. class HeartbeatLoggingIntegrationTests: XCTestCase {
  17. // 2021-11-01 @ 00:00:00 (EST)
  18. let date = Date(timeIntervalSince1970: 1_635_739_200)
  19. override func setUpWithError() throws {
  20. try HeartbeatLoggingTestUtils.removeUnderlyingHeartbeatStorageContainers()
  21. }
  22. override func tearDownWithError() throws {
  23. try HeartbeatLoggingTestUtils.removeUnderlyingHeartbeatStorageContainers()
  24. }
  25. /// This test may flake if it is executed during the transition from one day to the next.
  26. func testLogAndFlush() throws {
  27. // Given
  28. let heartbeatController = HeartbeatController(id: #function)
  29. let expectedDate = HeartbeatsPayload.dateFormatter.string(from: Date())
  30. // When
  31. heartbeatController.log("dummy_agent")
  32. let payload = heartbeatController.flush()
  33. // Then
  34. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  35. payload.headerValue(),
  36. """
  37. {
  38. "version": 2,
  39. "heartbeats": [
  40. {
  41. "agent": "dummy_agent",
  42. "dates": ["\(expectedDate)"]
  43. }
  44. ]
  45. }
  46. """
  47. )
  48. }
  49. /// This test may flake if it is executed during the transition from one day to the next.
  50. func testDoNotLogMoreThanOnceInACalendarDay() throws {
  51. // Given
  52. let heartbeatController = HeartbeatController(id: #function)
  53. heartbeatController.log("dummy_agent")
  54. heartbeatController.flush()
  55. // When
  56. heartbeatController.log("dummy_agent")
  57. // Then
  58. assertHeartbeatControllerFlushesEmptyPayload(heartbeatController)
  59. }
  60. /// This test may flake if it is executed during the transition from one day to the next.
  61. func testFlushHeartbeatFromToday() throws {
  62. // Given
  63. let heartbeatController = HeartbeatController(id: #function)
  64. let expectedDate = HeartbeatsPayload.dateFormatter.string(from: Date())
  65. // When
  66. heartbeatController.log("dummy_agent")
  67. let payload = heartbeatController.flushHeartbeatFromToday()
  68. // Then
  69. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  70. payload.headerValue(),
  71. """
  72. {
  73. "version": 2,
  74. "heartbeats": [
  75. {
  76. "agent": "dummy_agent",
  77. "dates": ["\(expectedDate)"]
  78. }
  79. ]
  80. }
  81. """
  82. )
  83. }
  84. func testMultipleControllersWithTheSameIDUseTheSameStorageInstance() throws {
  85. // Given
  86. let heartbeatController1 = HeartbeatController(id: #function, dateProvider: { self.date })
  87. let heartbeatController2 = HeartbeatController(id: #function, dateProvider: { self.date })
  88. // When
  89. heartbeatController1.log("dummy_agent")
  90. // Then
  91. let payload = heartbeatController2.flush()
  92. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  93. payload.headerValue(),
  94. """
  95. {
  96. "version": 2,
  97. "heartbeats": [
  98. {
  99. "agent": "dummy_agent",
  100. "dates": ["2021-11-01"]
  101. }
  102. ]
  103. }
  104. """
  105. )
  106. assertHeartbeatControllerFlushesEmptyPayload(heartbeatController1)
  107. }
  108. func testLogAndFlushConcurrencyStressTest() throws {
  109. // Given
  110. let heartbeatController = HeartbeatController(id: #function, dateProvider: { self.date })
  111. // When
  112. DispatchQueue.concurrentPerform(iterations: 100) { _ in
  113. heartbeatController.log("dummy_agent")
  114. }
  115. var payloads: [HeartbeatsPayload] = []
  116. DispatchQueue.concurrentPerform(iterations: 100) { _ in
  117. let payload = heartbeatController.flush()
  118. payloads.append(payload)
  119. }
  120. // Then
  121. let nonEmptyPayloads = payloads.filter { payload in
  122. // Filter out non-empty payloads.
  123. !payload.userAgentPayloads.isEmpty
  124. }
  125. XCTAssertEqual(nonEmptyPayloads.count, 1)
  126. let payload = try XCTUnwrap(nonEmptyPayloads.first)
  127. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  128. payload.headerValue(),
  129. """
  130. {
  131. "version": 2,
  132. "heartbeats": [
  133. {
  134. "agent": "dummy_agent",
  135. "dates": ["2021-11-01"]
  136. }
  137. ]
  138. }
  139. """
  140. )
  141. }
  142. func testLogAndFlushHeartbeatFromTodayConcurrencyStressTest() throws {
  143. // Given
  144. let heartbeatController = HeartbeatController(id: #function, dateProvider: { self.date })
  145. // When
  146. DispatchQueue.concurrentPerform(iterations: 100) { _ in
  147. heartbeatController.log("dummy_agent")
  148. }
  149. var payloads: [HeartbeatsPayload] = []
  150. DispatchQueue.concurrentPerform(iterations: 100) { _ in
  151. let payload = heartbeatController.flushHeartbeatFromToday()
  152. payloads.append(payload)
  153. }
  154. // Then
  155. let nonEmptyPayloads = payloads.filter { payload in
  156. // Filter out non-empty payloads.
  157. !payload.userAgentPayloads.isEmpty
  158. }
  159. XCTAssertEqual(nonEmptyPayloads.count, 1)
  160. let payload = try XCTUnwrap(nonEmptyPayloads.first)
  161. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  162. payload.headerValue(),
  163. """
  164. {
  165. "version": 2,
  166. "heartbeats": [
  167. {
  168. "agent": "dummy_agent",
  169. "dates": ["2021-11-01"],
  170. }
  171. ]
  172. }
  173. """
  174. )
  175. assertHeartbeatControllerFlushesEmptyPayload(heartbeatController)
  176. }
  177. func testLogRepeatedly_WithoutFlushing_LimitsOnWrite() throws {
  178. // Given
  179. var testdate = date
  180. let heartbeatController = HeartbeatController(id: #function, dateProvider: { testdate })
  181. // When
  182. // Iterate over 35 days and log a heartbeat each day.
  183. // - 30: The heartbeat logging library can store a max of 30 heartbeats. See
  184. // `HeartbeatController`'s `heartbeatsStorageCapacity` property.
  185. // - 5: Because of the above limit, expect 5 heartbeats to be overwritten.
  186. for day in 1 ... 35 {
  187. // A different user agent is logged based on the current iteration. There
  188. // is no particular reason for when each user agent is used– the goal is
  189. // to achieve a payload with multiple user agent groupings.
  190. if day < 5 {
  191. heartbeatController.log("dummy_agent_1")
  192. } else if day < 13 {
  193. heartbeatController.log("dummy_agent_2")
  194. } else {
  195. heartbeatController.log("dummy_agent_3")
  196. }
  197. testdate.addTimeInterval(60 * 60 * 24) // Advance the test date by 1 day.
  198. }
  199. // Then
  200. let payload = heartbeatController.flush()
  201. // The first 5 days of heartbeats (associated with `dummy_agent_1`) should
  202. // have been overwritten.
  203. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  204. payload.headerValue(),
  205. """
  206. {
  207. "version": 2,
  208. "heartbeats": [
  209. {
  210. "agent": "dummy_agent_2",
  211. "dates": [
  212. "2021-11-06",
  213. "2021-11-07",
  214. "2021-11-08",
  215. "2021-11-09",
  216. "2021-11-10",
  217. "2021-11-11",
  218. "2021-11-12"
  219. ]
  220. },
  221. {
  222. "agent": "dummy_agent_3",
  223. "dates": [
  224. "2021-12-01",
  225. "2021-12-02",
  226. "2021-12-03",
  227. "2021-12-04",
  228. "2021-12-05",
  229. "2021-11-13",
  230. "2021-11-14",
  231. "2021-11-15",
  232. "2021-11-16",
  233. "2021-11-17",
  234. "2021-11-18",
  235. "2021-11-19",
  236. "2021-11-20",
  237. "2021-11-21",
  238. "2021-11-22",
  239. "2021-11-23",
  240. "2021-11-24",
  241. "2021-11-25",
  242. "2021-11-26",
  243. "2021-11-27",
  244. "2021-11-28",
  245. "2021-11-29",
  246. "2021-11-30"
  247. ]
  248. }
  249. ]
  250. }
  251. """
  252. )
  253. }
  254. func testLogAndFlush_AfterUnderlyingStorageIsDeleted_CreatesNewStorage() throws {
  255. // Given
  256. let heartbeatController = HeartbeatController(id: #function, dateProvider: { self.date })
  257. heartbeatController.log("dummy_agent")
  258. _ = XCTWaiter.wait(for: [expectation(description: "Wait for async log.")], timeout: 0.1)
  259. // When
  260. XCTAssertNoThrow(try HeartbeatLoggingTestUtils.removeUnderlyingHeartbeatStorageContainers())
  261. // Then
  262. // 1. Assert controller flushes empty payload.
  263. assertHeartbeatControllerFlushesEmptyPayload(heartbeatController)
  264. // 2. Assert controller can log and flush non-empty payload.
  265. heartbeatController.log("dummy_agent")
  266. let payload = heartbeatController.flush()
  267. try HeartbeatLoggingTestUtils.assertEqualPayloadStrings(
  268. payload.headerValue(),
  269. """
  270. {
  271. "version": 2,
  272. "heartbeats": [
  273. {
  274. "agent": "dummy_agent",
  275. "dates": ["2021-11-01"]
  276. }
  277. ]
  278. }
  279. """
  280. )
  281. }
  282. func testInitializingControllerDoesNotModifyUnderlyingStorage() throws {
  283. // Given
  284. let id = #function
  285. // When
  286. _ = HeartbeatController(id: id)
  287. // Then
  288. #if os(tvOS)
  289. XCTAssertNil(
  290. UserDefaults(suiteName: HeartbeatLoggingTestUtils.Constants.heartbeatUserDefaultsSuiteName)?
  291. .object(forKey: "heartbeats-\(id)"),
  292. "Specified user defaults suite should be empty."
  293. )
  294. #else
  295. let heartbeatsDirectoryURL = FileManager.default
  296. .applicationSupportDirectory
  297. .appendingPathComponent(
  298. HeartbeatLoggingTestUtils.Constants.heartbeatFileStorageDirectoryPath,
  299. isDirectory: true
  300. )
  301. XCTAssertFalse(
  302. FileManager.default.fileExists(atPath: heartbeatsDirectoryURL.path),
  303. "Specified file path should not exist."
  304. )
  305. #endif
  306. }
  307. func testUnderlyingStorageLocationForRegressions() throws {
  308. // Given
  309. let id = #function
  310. let controller = HeartbeatController(id: id)
  311. // When
  312. controller.log("dummy_agent")
  313. _ = XCTWaiter.wait(for: [expectation(description: "Wait for async log.")], timeout: 0.1)
  314. // Then
  315. #if os(tvOS)
  316. XCTAssertNotNil(
  317. UserDefaults(suiteName: HeartbeatLoggingTestUtils.Constants.heartbeatUserDefaultsSuiteName)?
  318. .object(forKey: "heartbeats-\(id)"),
  319. "Data should not be nil."
  320. )
  321. #else
  322. let heartbeatsFileURL = FileManager.default
  323. .applicationSupportDirectory
  324. .appendingPathComponent(
  325. HeartbeatLoggingTestUtils.Constants.heartbeatFileStorageDirectoryPath,
  326. isDirectory: true
  327. )
  328. .appendingPathComponent(
  329. "heartbeats-\(id)", isDirectory: false
  330. )
  331. XCTAssertNotNil(try Data(contentsOf: heartbeatsFileURL), "Data should not be nil.")
  332. #endif
  333. }
  334. #if !os(tvOS)
  335. // Do not run on tvOS because tvOS uses UserDefaults to store heartbeats.
  336. func testControllerCreatesHeartbeatStorageWithSanitizedFileName() throws {
  337. // Given
  338. let appID = "1:123456789000:ios:abcdefghijklmnop"
  339. let sanitizedAppID = appID.replacingOccurrences(of: ":", with: "_")
  340. let controller = HeartbeatController(id: appID)
  341. // When
  342. // - Trigger the controller to write to the file system.
  343. controller.log("dummy_agent")
  344. _ = XCTWaiter.wait(for: [expectation(description: "Wait for async log.")], timeout: 0.1)
  345. // Then
  346. let heartbeatsDirectoryURL = FileManager.default
  347. .applicationSupportDirectory
  348. .appendingPathComponent(
  349. HeartbeatLoggingTestUtils.Constants.heartbeatFileStorageDirectoryPath,
  350. isDirectory: true
  351. )
  352. let directoryContents = try FileManager.default
  353. .contentsOfDirectory(atPath: heartbeatsDirectoryURL.path)
  354. XCTAssertEqual(directoryContents, ["heartbeats-\(sanitizedAppID)"])
  355. }
  356. #endif // !os(tvOS)
  357. }