JSONImporterTests.swift 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // JSONImporterTests.swift
  3. // Trio
  4. //
  5. // Created by Cengiz Deniz on 21.04.25.
  6. //
  7. import CoreData
  8. import Foundation
  9. import Swinject
  10. import Testing
  11. @testable import Trio
  12. class BundleReference {}
  13. @Suite("JSON Importer Tests", .serialized) struct JSONImporterTests: Injectable {
  14. var coreDataStack: CoreDataStack!
  15. var context: NSManagedObjectContext!
  16. var importer: JSONImporter!
  17. init() async throws {
  18. // In-memory Core Data for tests
  19. coreDataStack = try await CoreDataStack.createForTests()
  20. context = coreDataStack.newTaskContext()
  21. importer = JSONImporter(context: context, coreDataStack: coreDataStack)
  22. }
  23. @Test("Import glucose history with value checks") func testImportGlucoseHistoryDetails() async throws {
  24. let testBundle = Bundle(for: BundleReference.self)
  25. let path = testBundle.path(forResource: "glucose", ofType: "json")!
  26. let url = URL(filePath: path)
  27. let now = Date("2025-04-28T19:32:52.000Z")!
  28. try await importer.importGlucoseHistory(url: url, now: now)
  29. // run the import againt to check our deduplication logic
  30. try await importer.importGlucoseHistory(url: url, now: now)
  31. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  32. ofType: GlucoseStored.self,
  33. onContext: context,
  34. predicate: NSPredicate(format: "TRUEPREDICATE"),
  35. key: "date",
  36. ascending: false
  37. ) as? [GlucoseStored] ?? []
  38. #expect(allReadings.count == 274)
  39. #expect(allReadings.first?.glucose == 115)
  40. #expect(allReadings.first?.date == Date("2025-04-28T19:32:51.727Z"))
  41. #expect(allReadings.last?.glucose == 127)
  42. #expect(allReadings.last?.date == Date("2025-04-27T19:37:50.327Z"))
  43. let manualCount = allReadings.filter({ $0.isManual }).count
  44. #expect(manualCount == 1)
  45. }
  46. @Test("Skip importing old glucose values") func testSkipImportOldGlucoseValues() async throws {
  47. let testBundle = Bundle(for: BundleReference.self)
  48. let path = testBundle.path(forResource: "glucose", ofType: "json")!
  49. let url = URL(filePath: path)
  50. // more than 24 hours in the future from the most recent entry
  51. let now = Date("2025-04-29T19:32:52.000Z")!
  52. try await importer.importGlucoseHistory(url: url, now: now)
  53. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  54. ofType: GlucoseStored.self,
  55. onContext: context,
  56. predicate: NSPredicate(format: "TRUEPREDICATE"),
  57. key: "date",
  58. ascending: false
  59. ) as? [GlucoseStored] ?? []
  60. #expect(allReadings.isEmpty)
  61. }
  62. }