HeartbeatTests.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. @testable import FirebaseCoreInternal
  15. import XCTest
  16. class TimePeriodTests: XCTestCase {
  17. override func setUpWithError() throws {
  18. XCTAssertEqual(TimePeriod.allCases, [.daily])
  19. }
  20. func testTimeIntervals() throws {
  21. for period in TimePeriod.allCases {
  22. XCTAssertEqual(period.timeInterval, Double(period.rawValue) * 86400)
  23. }
  24. }
  25. func testTimePeriodRawValues() throws {
  26. let dailyTimePeriod = TimePeriod.daily
  27. XCTAssertEqual(dailyTimePeriod.rawValue, 1)
  28. }
  29. }
  30. class HeartbeatTests: XCTestCase {
  31. var heartbeat: Heartbeat!
  32. var heartbeatData: Data!
  33. var deterministicEncoder: JSONEncoder = {
  34. let encoder = JSONEncoder()
  35. encoder.outputFormatting = .sortedKeys
  36. return encoder
  37. }()
  38. override func setUpWithError() throws {
  39. heartbeat = Heartbeat(
  40. agent: "dummy_agent",
  41. date: Date(timeIntervalSince1970: 1_635_739_200), // 2021-11-01
  42. timePeriods: [.daily],
  43. version: 100
  44. )
  45. heartbeatData = try deterministicEncoder.encode(heartbeat)
  46. }
  47. func testHeartbeatCurrentVersion() throws {
  48. XCTAssertEqual(Heartbeat(agent: #function, date: Date()).version, 0)
  49. }
  50. func testDecodeAndEncode() throws {
  51. // Given
  52. let json = """
  53. {
  54. "agent": "dummy_agent",
  55. "date": 657432000,
  56. "timePeriods": [1],
  57. "version": 100
  58. }
  59. """
  60. let data = try XCTUnwrap(json.data(using: .utf8))
  61. // When
  62. let decodedHeartbeat = try JSONDecoder()
  63. .decode(Heartbeat.self, from: data)
  64. let encodedHeartbeat = try deterministicEncoder
  65. .encode(decodedHeartbeat)
  66. // Then
  67. XCTAssertEqual(decodedHeartbeat.agent, heartbeat.agent)
  68. XCTAssertEqual(decodedHeartbeat.date, heartbeat.date)
  69. XCTAssertEqual(decodedHeartbeat.timePeriods, heartbeat.timePeriods)
  70. XCTAssertEqual(decodedHeartbeat.version, heartbeat.version)
  71. XCTAssertEqual(encodedHeartbeat, heartbeatData)
  72. }
  73. }