CarbValueTests.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // CarbValueTests.swift
  3. // LoopKitTests
  4. //
  5. // Created by Darin Krauss on 5/4/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import XCTest
  9. import HealthKit
  10. @testable import LoopKit
  11. class CarbValueCodableTests: XCTestCase {
  12. func testCodable() throws {
  13. try assertCarbValueCodable(CarbValue(startDate: dateFormatter.date(from: "2020-05-14T12:18:14Z")!,
  14. endDate: dateFormatter.date(from: "2020-05-14T13:18:14Z")!,
  15. quantity: HKQuantity(unit: .gram(), doubleValue: 34.5)),
  16. encodesJSON: """
  17. {
  18. "endDate" : "2020-05-14T13:18:14Z",
  19. "quantity" : 34.5,
  20. "quantityUnit" : "g",
  21. "startDate" : "2020-05-14T12:18:14Z"
  22. }
  23. """
  24. )
  25. }
  26. private func assertCarbValueCodable(_ original: CarbValue, encodesJSON string: String) throws {
  27. let data = try encoder.encode(original)
  28. XCTAssertEqual(String(data: data, encoding: .utf8), string)
  29. let decoded = try decoder.decode(CarbValue.self, from: data)
  30. XCTAssertEqual(decoded, original)
  31. }
  32. private let dateFormatter = ISO8601DateFormatter()
  33. private let encoder: JSONEncoder = {
  34. let encoder = JSONEncoder()
  35. encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
  36. encoder.dateEncodingStrategy = .iso8601
  37. return encoder
  38. }()
  39. private let decoder: JSONDecoder = {
  40. let decoder = JSONDecoder()
  41. decoder.dateDecodingStrategy = .iso8601
  42. return decoder
  43. }()
  44. }