GlucoseSmoothingTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import CoreData
  2. import Foundation
  3. import LoopKitUI
  4. import Swinject
  5. import Testing
  6. @testable import Trio
  7. @Suite("Glucose Smoothing Tests", .serialized) struct GlucoseSmoothingTests: Injectable {
  8. let resolver: Resolver
  9. var coreDataStack: CoreDataStack!
  10. var testContext: NSManagedObjectContext!
  11. var fetchGlucoseManager: BaseFetchGlucoseManager!
  12. var openAPS: OpenAPS!
  13. init() async throws {
  14. coreDataStack = try await CoreDataStack.createForTests()
  15. testContext = coreDataStack.newTaskContext()
  16. let assembler = Assembler([
  17. StorageAssembly(),
  18. ServiceAssembly(),
  19. APSAssembly(),
  20. NetworkAssembly(),
  21. UIAssembly(),
  22. SecurityAssembly(),
  23. TestAssembly(testContext: testContext)
  24. ])
  25. resolver = assembler.resolver
  26. injectServices(resolver)
  27. fetchGlucoseManager = resolver.resolve(FetchGlucoseManager.self)! as? BaseFetchGlucoseManager
  28. let fileStorage = resolver.resolve(FileStorage.self)!
  29. openAPS = OpenAPS(storage: fileStorage, tddStorage: MockTDDStorage())
  30. }
  31. // MARK: - Exponential Smoothing Tests
  32. @Test(
  33. "Exponential smoothing writes smoothed glucose for CGM values when enough data exists"
  34. ) func testExponentialSmoothingStoresSmoothedValues() async throws {
  35. let glucoseValues: [Int16] = [100, 105, 110, 115, 120, 125]
  36. await createGlucoseSequence(values: glucoseValues, interval: 5 * 60, isManual: false)
  37. await fetchGlucoseManager.exponentialSmoothingGlucose(context: testContext)
  38. let fetchedAscending = try await fetchAndSortGlucose()
  39. // We expect at least the most recent few values to get smoothed values written.
  40. // The Kotlin/port writes to data[i] for i in 0..<limit, where data is newest-first.
  41. // With 6 values:
  42. // - recordCount = 6
  43. // - validWindowCount starts at 5, no gap => remains 5
  44. // - smoothing produces blended.count == 5
  45. // - apply limit = min(5, 6) = 5 => most recent 5 entries get smoothedGlucose
  46. //
  47. // In ascending order, "most recent 5" are indices 1...5. Oldest (index 0) is not guaranteed to be updated.
  48. #expect(fetchedAscending.count == 6)
  49. let smoothedValues = fetchedAscending.compactMap { $0.smoothedGlucose?.decimalValue }
  50. #expect(smoothedValues.count >= 5, "Expected at least 5 smoothed values to be stored.")
  51. for (i, value) in smoothedValues.enumerated() {
  52. #expect(value >= 39, "Smoothed glucose at index \(i) should be clamped to at least 39, got \(value).")
  53. #expect(
  54. value == value.rounded(toPlaces: 0),
  55. "Smoothed glucose at index \(i) should be rounded to an integer, got \(value)."
  56. )
  57. }
  58. }
  59. @Test("Exponential smoothing does not smooth manual glucose entries") func testExponentialSmoothingIgnoresManual() async throws {
  60. // GIVEN: Mixed manual + CGM values
  61. await createGlucoseSequence(values: [100, 105, 110, 115, 120].map(Int16.init), interval: 5 * 60, isManual: false)
  62. await createGlucose(glucose: 130, smoothed: nil, isManual: true, date: Date().addingTimeInterval(6 * 5 * 60))
  63. // WHEN
  64. await fetchGlucoseManager.exponentialSmoothingGlucose(context: testContext)
  65. // THEN
  66. let allAscending = try await fetchAndSortGlucose()
  67. let manual = allAscending.first(where: { $0.isManual })
  68. #expect(manual != nil, "Expected a manual glucose entry.")
  69. #expect(manual?.smoothedGlucose == nil, "Manual entries must not be smoothed/stored.")
  70. }
  71. @Test(
  72. "Exponential smoothing clamps smoothed glucose to >= 39 and rounds to integer"
  73. ) func testExponentialSmoothingClampAndRounding() async throws {
  74. // GIVEN
  75. let glucoseValues: [Int16] = [40, 39, 41, 42, 43, 44]
  76. await createGlucoseSequence(values: glucoseValues, interval: 5 * 60, isManual: false)
  77. // WHEN
  78. await fetchGlucoseManager.exponentialSmoothingGlucose(context: testContext)
  79. // THEN
  80. let fetchedAscending = try await fetchAndSortGlucose()
  81. let smoothedValues = fetchedAscending
  82. .compactMap { $0.smoothedGlucose?.decimalValue }
  83. .filter { $0 > 0 }
  84. #expect(!smoothedValues.isEmpty, "Expected at least one smoothed glucose value to be stored.")
  85. for (index, smoothed) in smoothedValues.enumerated() {
  86. #expect(
  87. smoothed >= 39,
  88. "Smoothed glucose must be clamped to >= 39, got \(smoothed) at index \(index)."
  89. )
  90. #expect(
  91. smoothed == smoothed.rounded(toPlaces: 0),
  92. "Smoothed glucose must be an integer value, got \(smoothed) at index \(index)."
  93. )
  94. }
  95. }
  96. @Test(
  97. "Exponential smoothing stops window at gaps >= 12 minutes; fallback fills smoothed glucose"
  98. ) func testExponentialSmoothingGapStopsWindow() async throws {
  99. // GIVEN:
  100. let now = Date()
  101. let dates: [Date] = [
  102. now.addingTimeInterval(0), // oldest
  103. now.addingTimeInterval(5 * 60),
  104. now.addingTimeInterval(10 * 60),
  105. now.addingTimeInterval(25 * 60), // gap of 15 minutes
  106. now.addingTimeInterval(30 * 60),
  107. now.addingTimeInterval(35 * 60) // newest
  108. ]
  109. let values: [Int16] = [100, 105, 110, 115, 120, 125]
  110. await createGlucoseSequence(values: values, dates: dates, isManual: false)
  111. // WHEN
  112. await fetchGlucoseManager.exponentialSmoothingGlucose(context: testContext)
  113. // THEN
  114. let ascending = try await fetchAndSortGlucose()
  115. #expect(ascending.count == 6)
  116. let smoothedValues = ascending
  117. .filter { !$0.isManual }
  118. .compactMap { $0.smoothedGlucose?.decimalValue }
  119. .filter { $0 > 0 }
  120. #expect(
  121. smoothedValues.count == 6,
  122. "Fallback path should fill smoothedGlucose for all CGM entries when the gap reduces the window below minimum size."
  123. )
  124. for (index, smoothed) in smoothedValues.enumerated() {
  125. #expect(
  126. smoothed >= 39,
  127. "Fallback smoothed glucose must be clamped to >= 39, got \(smoothed) at index \(index)."
  128. )
  129. #expect(
  130. smoothed == smoothed.rounded(toPlaces: 0),
  131. "Fallback smoothed glucose must be rounded to an integer, got \(smoothed) at index \(index)."
  132. )
  133. }
  134. }
  135. @Test(
  136. "Exponential smoothing treats 38 mg/dL as xDrip error and clamps stored smoothed glucose"
  137. ) func testExponentialSmoothingXDrip38StopsWindow() async throws {
  138. // GIVEN
  139. let values: [Int16] = [100, 105, 110, 38, 120, 125]
  140. await createGlucoseSequence(values: values, interval: 5 * 60, isManual: false)
  141. // WHEN
  142. await fetchGlucoseManager.exponentialSmoothingGlucose(context: testContext)
  143. // THEN
  144. let ascending = try await fetchAndSortGlucose()
  145. #expect(ascending.count == 6)
  146. let smoothedValues = ascending
  147. .compactMap { $0.smoothedGlucose?.decimalValue }
  148. .filter { $0 > 0 }
  149. #expect(
  150. !smoothedValues.isEmpty,
  151. "Expected at least one smoothed glucose value to be stored."
  152. )
  153. for (index, smoothed) in smoothedValues.enumerated() {
  154. #expect(
  155. smoothed >= 39,
  156. "Smoothed glucose must be clamped to >= 39 even around xDrip 38, got \(smoothed) at index \(index)."
  157. )
  158. #expect(
  159. smoothed == smoothed.rounded(toPlaces: 0),
  160. "Smoothed glucose must be rounded to an integer, got \(smoothed) at index \(index)."
  161. )
  162. }
  163. }
  164. // MARK: - OpenAPS Glucose Selection Tests
  165. @Test("Algorithm uses smoothed glucose when enabled") func testAlgorithmUsesSmoothedGlucose() async throws {
  166. await createGlucose(glucose: 150, smoothed: 140, isManual: false, date: Date())
  167. let algorithmInput = try await runFetchAndProcessGlucose(smoothGlucose: true)
  168. #expect(algorithmInput.count == 1, "Expected to process one glucose entry.")
  169. #expect(
  170. algorithmInput.first?.glucose == 140,
  171. "Algorithm should have used the smoothed glucose value (140), but used \(algorithmInput.first?.glucose ?? 0)."
  172. )
  173. }
  174. @Test("Algorithm uses raw glucose when smoothing is disabled") func testAlgorithmUsesRawGlucose() async throws {
  175. await createGlucose(glucose: 150, smoothed: 140, isManual: false, date: Date())
  176. let algorithmInput = try await runFetchAndProcessGlucose(smoothGlucose: false)
  177. #expect(algorithmInput.count == 1, "Expected to process one glucose entry.")
  178. #expect(
  179. algorithmInput.first?.glucose == 150,
  180. "Algorithm should have used the raw glucose value (150), but used \(algorithmInput.first?.glucose ?? 0)."
  181. )
  182. }
  183. @Test("Algorithm falls back to raw glucose if smoothed value is missing") func testAlgorithmFallbackToRawGlucose() async throws {
  184. await createGlucose(glucose: 150, smoothed: nil, isManual: false, date: Date())
  185. let algorithmInput = try await runFetchAndProcessGlucose(smoothGlucose: true)
  186. #expect(algorithmInput.count == 1, "Expected to process one glucose entry.")
  187. #expect(
  188. algorithmInput.first?.glucose == 150,
  189. "Algorithm should have fallen back to the raw glucose value (150), but used \(algorithmInput.first?.glucose ?? 0)."
  190. )
  191. }
  192. @Test("Algorithm ignores smoothed value for manual glucose entries") func testAlgorithmIgnoresSmoothedManualGlucose() async throws {
  193. await createGlucose(glucose: 150, smoothed: 140, isManual: true, date: Date())
  194. let algorithmInput = try await runFetchAndProcessGlucose(smoothGlucose: true)
  195. #expect(algorithmInput.count == 1, "Expected to process one glucose entry.")
  196. #expect(
  197. algorithmInput.first?.glucose == 150,
  198. "Algorithm should have ignored smoothing for a manual entry and used the raw value (150), but used \(algorithmInput.first?.glucose ?? 0)."
  199. )
  200. }
  201. // MARK: - Helpers
  202. private func runFetchAndProcessGlucose(smoothGlucose: Bool) async throws -> [AlgorithmGlucose] {
  203. let jsonString = try await openAPS.fetchAndProcessGlucose(
  204. context: testContext,
  205. shouldSmoothGlucose: smoothGlucose,
  206. fetchLimit: 10
  207. )
  208. let data = jsonString.data(using: .utf8)!
  209. let decoder = JSONDecoder()
  210. decoder.dateDecodingStrategy = .custom { decoder in
  211. let container = try decoder.singleValueContainer()
  212. let dateDouble = try container.decode(Double.self)
  213. return Date(timeIntervalSince1970: dateDouble / 1000)
  214. }
  215. return try decoder.decode([AlgorithmGlucose].self, from: data)
  216. }
  217. private func createGlucose(glucose: Int16, smoothed: Decimal?, isManual: Bool, date: Date) async {
  218. await testContext.perform {
  219. let object = GlucoseStored(context: self.testContext)
  220. object.date = date
  221. object.glucose = glucose
  222. object.smoothedGlucose = smoothed as NSDecimalNumber?
  223. object.isManual = isManual
  224. object.id = UUID()
  225. try! self.testContext.save()
  226. }
  227. }
  228. private func createGlucoseSequence(values: [Int16], dates: [Date], isManual: Bool) async {
  229. precondition(values.count == dates.count)
  230. await testContext.perform {
  231. for (i, value) in values.enumerated() {
  232. let object = GlucoseStored(context: self.testContext)
  233. object.date = dates[i]
  234. object.glucose = value
  235. object.smoothedGlucose = nil
  236. object.isManual = isManual
  237. object.id = UUID()
  238. }
  239. try! self.testContext.save()
  240. }
  241. }
  242. private func createGlucoseSequence(values: [Int16], interval: TimeInterval, isManual: Bool) async {
  243. let now = Date()
  244. let dates = values.indices.map { now.addingTimeInterval(Double($0) * interval) }
  245. await createGlucoseSequence(values: values, dates: dates, isManual: isManual)
  246. }
  247. private func fetchAndSortGlucose() async throws -> [GlucoseStored] {
  248. try await coreDataStack.fetchEntitiesAsync(
  249. ofType: GlucoseStored.self,
  250. onContext: testContext,
  251. predicate: .all,
  252. key: "date",
  253. ascending: true
  254. ) as? [GlucoseStored] ?? []
  255. }
  256. }