BolusCalculatorTests.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. import Foundation
  2. import Testing
  3. @testable import Trio
  4. /// ⚠️ NOTE:
  5. /// If tests in this suite are failing unexpectedly (e.g. sudden unexplainable mismatches for decimal places for calculated values),
  6. /// try running the test suite on a clean simulator.
  7. ///
  8. /// You can reset the simulator from the menu: **Device > Erase All Content and Settings**
  9. /// or by launching with `-com.apple.CoreData.SQLDebug 1` for more insight into the issue.
  10. ///
  11. @Suite("Bolus Calculator Tests") struct BolusCalculatorTests: Injectable {
  12. @Injected() var calculator: BolusCalculationManager!
  13. @Injected() var settingsManager: SettingsManager!
  14. @Injected() var fileStorage: FileStorage!
  15. @Injected() var apsManager: APSManager!
  16. let resolver = TrioApp().resolver
  17. init() {
  18. injectServices(resolver)
  19. }
  20. @Test("Calculator is correctly initialized") func testCalculatorInitialization() {
  21. #expect(calculator != nil, "BolusCalculationManager should be injected")
  22. #expect(calculator is BaseBolusCalculationManager, "Calculator should be of type BaseBolusCalculationManager")
  23. }
  24. @Test("Calculate insulin for standard meal") func testStandardMealCalculation() async throws {
  25. // STEP 1: Setup test scenario
  26. // We need to provide a CalculationInput struct
  27. let carbs: Decimal = 80
  28. let currentBG: Decimal = 180 // 80 points above target, should result in 2U correction
  29. let deltaBG: Decimal = 5 // Rising trend, should add small correction
  30. let target: Decimal = 100
  31. let isf: Decimal = 40
  32. let carbRatio: Decimal = 10 // Should result in 8U for carbs
  33. let iob: Decimal = 1.0 // Should subtract from final result
  34. let cob: Int16 = 20
  35. let useFattyMealCorrectionFactor: Bool = false
  36. let useSuperBolus: Bool = false
  37. let fattyMealFactor: Decimal = 0.8
  38. let sweetMealFactor: Decimal = 2
  39. let basal: Decimal = 1.5
  40. let fraction: Decimal = 0.8
  41. let maxBolus: Decimal = 10
  42. let maxIOB: Decimal = 15.0
  43. let maxCOB: Decimal = 120.0
  44. let minPredBG: Decimal = 80.0
  45. // STEP 2: Create calculation input
  46. let input = CalculationInput(
  47. carbs: carbs,
  48. currentBG: currentBG,
  49. deltaBG: deltaBG,
  50. target: target,
  51. isf: isf,
  52. carbRatio: carbRatio,
  53. iob: iob,
  54. cob: cob,
  55. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  56. fattyMealFactor: fattyMealFactor,
  57. useSuperBolus: useSuperBolus,
  58. sweetMealFactor: sweetMealFactor,
  59. basal: basal,
  60. fraction: fraction,
  61. maxBolus: maxBolus,
  62. maxIOB: maxIOB,
  63. maxCOB: maxCOB,
  64. minPredBG: minPredBG,
  65. lastLoopDate: Date()
  66. )
  67. // STEP 3: Calculate insulin
  68. let result = await calculator.calculateInsulin(input: input)
  69. // STEP 4: Verify results
  70. // Expected calculation breakdown:
  71. // wholeCob = 80g + 20g COB = 100g
  72. // wholeCobInsulin = 100g ÷ 10 g/U = 10U
  73. // targetDifference = currentBG - target = 180 - 100 = 80 mg/dL
  74. // targetDifferenceInsulin = 80 mg/dL ÷ 40 mg/dL/U = 2U
  75. // fifteenMinutesInsulin = 5 mg/dL ÷ 40 mg/dL/U = 0.125U
  76. // correctionInsulin = targetDifferenceInsulin = 2U
  77. // iobInsulinReduction = 1U
  78. // superBolusInsulin = 0U (disabled)
  79. // no adjustment for reduced bolus (disabled)
  80. // wholeCalc = round(wholeCobInsulin + correctionInsulin + fifteenMinutesInsulin - iobInsulinReduction, 3) = 11.125U
  81. // insulinCalculated = round(wholeCalc × fraction, 3) = 8.9U
  82. // Calculate expected values
  83. let wholeCobInsulin = Decimal(100) / Decimal(10) // 10U
  84. let targetDifferenceInsulin = Decimal(80) / Decimal(40) // 2U
  85. let fifteenMinutesInsulin = Decimal(5) / Decimal(40)
  86. let wholeCalc = wholeCobInsulin + targetDifferenceInsulin + fifteenMinutesInsulin - Decimal(1) // 11.125U
  87. let expectedInsulinCalculated = apsManager.roundBolus(amount: wholeCalc * fraction) // 8.9U
  88. #expect(
  89. result.insulinCalculated == expectedInsulinCalculated,
  90. """
  91. Incorrect insulin calculation
  92. Expected: \(expectedInsulinCalculated)U
  93. Actual: \(result.insulinCalculated)U
  94. Components from CalculationResult:
  95. - insulinCalculated: \(result.insulinCalculated)U (expected: \(expectedInsulinCalculated)U)
  96. - wholeCalc: \(result.wholeCalc)U (expected: \(wholeCalc)U)
  97. - iobInsulinReduction: \(result.iobInsulinReduction)U (expected: 1U)
  98. - superBolusInsulin: \(result.superBolusInsulin)U (expected: 0U)
  99. - targetDifference: \(result.targetDifference) mg/dL (expected: 80 mg/dL)
  100. - targetDifferenceInsulin: \(result.targetDifferenceInsulin)U (expected: \(targetDifferenceInsulin)U)
  101. - fifteenMinutesInsulin: \(result.fifteenMinutesInsulin)U (expected: \(fifteenMinutesInsulin)U)
  102. - wholeCob: \(result.wholeCob)g (expected: 100g)
  103. - wholeCobInsulin: \(result.wholeCobInsulin)U (expected: \(wholeCobInsulin)U)
  104. """
  105. )
  106. // Verify each component from CalculationResult struct with rounded values
  107. #expect(
  108. result.insulinCalculated == expectedInsulinCalculated,
  109. "Final calculated insulin amount should be \(expectedInsulinCalculated)U"
  110. )
  111. #expect(result.wholeCalc == wholeCalc, "Total calculation before fraction should be \(wholeCalc)U")
  112. #expect(result.iobInsulinReduction == -1.0, "Absolute IOB reduction amount should be 1U, hence -1U")
  113. #expect(result.superBolusInsulin == 0, "Additional insulin for super bolus should be 0U")
  114. #expect(result.targetDifference == 80, "Difference from target BG should be 80 mg/dL")
  115. #expect(
  116. result.targetDifferenceInsulin == targetDifferenceInsulin,
  117. "Insulin needed for target difference should be \(targetDifferenceInsulin)U"
  118. )
  119. #expect(
  120. result.fifteenMinutesInsulin == fifteenMinutesInsulin,
  121. "Trend-based insulin adjustment should be \(fifteenMinutesInsulin)U"
  122. )
  123. #expect(result.wholeCob == 100, "Total carbs (COB + new carbs) should be 100g")
  124. #expect(result.wholeCobInsulin == wholeCobInsulin, "Insulin for total carbs should be \(wholeCobInsulin)U")
  125. }
  126. @Test("Calculate insulin for reduced bolus") func testFattyMealCalculation() async throws {
  127. // STEP 1: Setup test scenario
  128. // We need to provide a CalculationInput struct
  129. let carbs: Decimal = 80
  130. let currentBG: Decimal = 180 // 80 points above target, should result in 2U correction
  131. let deltaBG: Decimal = 5 // Rising trend, should add small correction
  132. let target: Decimal = 100
  133. let isf: Decimal = 40
  134. let carbRatio: Decimal = 10 // Should result in 8U for carbs
  135. let iob: Decimal = 1.0 // Should subtract from final result
  136. let cob: Int16 = 20
  137. let useFattyMealCorrectionFactor: Bool = true // now set to true
  138. let useSuperBolus: Bool = false
  139. let fattyMealFactor: Decimal = 0.8
  140. let sweetMealFactor: Decimal = 2
  141. let basal: Decimal = 1.5
  142. let fraction: Decimal = 0.8
  143. let maxBolus: Decimal = 10
  144. let maxIOB: Decimal = 15.0
  145. let maxCOB: Decimal = 120.0
  146. let minPredBG: Decimal = 80.0
  147. // STEP 2: Create calculation input
  148. let input = CalculationInput(
  149. carbs: carbs,
  150. currentBG: currentBG,
  151. deltaBG: deltaBG,
  152. target: target,
  153. isf: isf,
  154. carbRatio: carbRatio,
  155. iob: iob,
  156. cob: cob,
  157. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  158. fattyMealFactor: fattyMealFactor,
  159. useSuperBolus: useSuperBolus,
  160. sweetMealFactor: sweetMealFactor,
  161. basal: basal,
  162. fraction: fraction,
  163. maxBolus: maxBolus,
  164. maxIOB: maxIOB,
  165. maxCOB: maxCOB,
  166. minPredBG: minPredBG,
  167. lastLoopDate: Date()
  168. )
  169. // STEP 3: Calculate insulin with reduced bolus enabled
  170. let fattyMealResult = await calculator.calculateInsulin(input: input)
  171. // STEP 4: Calculate insulin with reduced bolus disabled for comparison
  172. let standardInput = CalculationInput(
  173. carbs: carbs,
  174. currentBG: currentBG,
  175. deltaBG: deltaBG,
  176. target: target,
  177. isf: isf,
  178. carbRatio: carbRatio,
  179. iob: iob,
  180. cob: cob,
  181. useFattyMealCorrectionFactor: false, // Disabled for comparison
  182. fattyMealFactor: fattyMealFactor,
  183. useSuperBolus: useSuperBolus,
  184. sweetMealFactor: sweetMealFactor,
  185. basal: basal,
  186. fraction: fraction,
  187. maxBolus: maxBolus,
  188. maxIOB: maxIOB,
  189. maxCOB: maxCOB,
  190. minPredBG: minPredBG,
  191. lastLoopDate: Date()
  192. )
  193. let standardResult = await calculator.calculateInsulin(input: standardInput)
  194. // STEP 5: Verify results
  195. // Reduced bolus should reduce the insulin amount by the reduced bolus factor (0.8)
  196. let expectedReduction = fattyMealFactor
  197. let actualReduction = Decimal(
  198. (Double(fattyMealResult.insulinCalculated) / Double(standardResult.insulinCalculated) * 10.0).rounded() / 10.0
  199. )
  200. #expect(
  201. actualReduction == expectedReduction,
  202. """
  203. Reduced bolus calculation incorrect
  204. Expected reduction factor: \(expectedReduction)
  205. Actual reduction factor: \(actualReduction)
  206. Standard calculation: \(standardResult.insulinCalculated)U
  207. Reduced bolus calculation: \(fattyMealResult.insulinCalculated)U
  208. """
  209. )
  210. }
  211. @Test("Calculate insulin with super bolus") func testSuperBolusCalculation() async throws {
  212. // STEP 1: Setup test scenario
  213. // We need to provide a CalculationInput struct
  214. let carbs: Decimal = 80
  215. let currentBG: Decimal = 180 // 80 points above target, should result in 2U correction
  216. let deltaBG: Decimal = 5 // Rising trend, should add small correction
  217. let target: Decimal = 100
  218. let isf: Decimal = 40
  219. let carbRatio: Decimal = 10 // Should result in 8U for carbs
  220. let iob: Decimal = 1.0 // Should subtract from final result
  221. let cob: Int16 = 20
  222. let useFattyMealCorrectionFactor: Bool = false
  223. let useSuperBolus: Bool = true // Super bolus enabled
  224. let fattyMealFactor: Decimal = 0.8
  225. let sweetMealFactor: Decimal = 2
  226. let basal: Decimal = 1.5 // Will be added to insulin calculation when super bolus is enabled
  227. let fraction: Decimal = 0.8
  228. let maxBolus: Decimal = 10
  229. let maxIOB: Decimal = 15.0
  230. let maxCOB: Decimal = 120.0
  231. let minPredBG: Decimal = 80.0
  232. // STEP 2: Create calculation input with super bolus enabled
  233. let input = CalculationInput(
  234. carbs: carbs,
  235. currentBG: currentBG,
  236. deltaBG: deltaBG,
  237. target: target,
  238. isf: isf,
  239. carbRatio: carbRatio,
  240. iob: iob,
  241. cob: cob,
  242. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  243. fattyMealFactor: fattyMealFactor,
  244. useSuperBolus: useSuperBolus,
  245. sweetMealFactor: sweetMealFactor,
  246. basal: basal,
  247. fraction: fraction,
  248. maxBolus: maxBolus,
  249. maxIOB: maxIOB,
  250. maxCOB: maxCOB,
  251. minPredBG: minPredBG,
  252. lastLoopDate: Date()
  253. )
  254. // STEP 3: Calculate insulin with super bolus enabled
  255. let superBolusResult = await calculator.calculateInsulin(input: input)
  256. // STEP 4: Calculate insulin with super bolus disabled for comparison
  257. let standardInput = CalculationInput(
  258. carbs: carbs,
  259. currentBG: currentBG,
  260. deltaBG: deltaBG,
  261. target: target,
  262. isf: isf,
  263. carbRatio: carbRatio,
  264. iob: iob,
  265. cob: cob,
  266. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  267. fattyMealFactor: fattyMealFactor,
  268. useSuperBolus: false, // Disabled for comparison
  269. sweetMealFactor: sweetMealFactor,
  270. basal: basal,
  271. fraction: fraction,
  272. maxBolus: maxBolus,
  273. maxIOB: maxIOB,
  274. maxCOB: maxCOB,
  275. minPredBG: minPredBG,
  276. lastLoopDate: Date()
  277. )
  278. let standardResult = await calculator.calculateInsulin(input: standardInput)
  279. // STEP 5: Verify results
  280. // Super bolus should add basal rate * sweetMealFactor to the insulin calculation
  281. let expectedSuperBolusInsulin = basal * sweetMealFactor
  282. #expect(
  283. superBolusResult.superBolusInsulin == expectedSuperBolusInsulin,
  284. """
  285. Super bolus insulin incorrect
  286. Expected: \(expectedSuperBolusInsulin)U (basal \(basal)U × sweetMealFactor \(sweetMealFactor))
  287. Actual: \(superBolusResult.superBolusInsulin)U
  288. """
  289. )
  290. #expect(
  291. superBolusResult.insulinCalculated > standardResult.insulinCalculated,
  292. """
  293. Super bolus calculation incorrect
  294. Expected super bolus calculation to be higher than standard
  295. Super bolus: \(superBolusResult.insulinCalculated)U
  296. Standard: \(standardResult.insulinCalculated)U
  297. Difference: \(superBolusResult.insulinCalculated - standardResult.insulinCalculated)U
  298. """
  299. )
  300. // The difference should be the difference of super bolus (= standard dose + the basal rate * sweetMealFactor) limited by max bolus, and the standard dose.
  301. let actualDifference = (superBolusResult.insulinCalculated - standardResult.insulinCalculated)
  302. let expectedDifference = min(superBolusResult.insulinCalculated, maxBolus) - standardResult.insulinCalculated
  303. #expect(
  304. actualDifference == expectedDifference,
  305. """
  306. Super bolus difference incorrect
  307. Expected difference: min(\(expectedSuperBolusInsulin), \(maxBolus)) U (basal \(basal)U × sweetMealFactor \(sweetMealFactor) + standard dose \(standardResult
  308. .insulinCalculated)) - standard dose \(standardResult.insulinCalculated)
  309. Actual difference: \(actualDifference)U
  310. Standard result: \(standardResult)
  311. SuperBolus result: \(superBolusResult)
  312. """
  313. )
  314. }
  315. @Test("Calculate insulin with low glucose forecast (minPredBG < 54)") func testMinPredBGGuardBolusCalculation() async throws {
  316. // STEP 1: Setup test scenario
  317. // We need to provide a CalculationInput struct
  318. let carbs: Decimal = 80
  319. let currentBG: Decimal = 180 // 80 points above target, should result in 2U correction
  320. let deltaBG: Decimal = 5 // Rising trend, should add small correction
  321. let target: Decimal = 100
  322. let isf: Decimal = 40
  323. let carbRatio: Decimal = 10 // Should result in 8U for carbs
  324. let iob: Decimal = 1.0 // Should subtract from final result
  325. let cob: Int16 = 20
  326. let useFattyMealCorrectionFactor: Bool = false
  327. let useSuperBolus: Bool = false
  328. let fattyMealFactor: Decimal = 0.8
  329. let sweetMealFactor: Decimal = 2
  330. let basal: Decimal = 1.5 // Will be added to insulin calculation when super bolus is enabled
  331. let fraction: Decimal = 0.8
  332. let maxBolus: Decimal = 10
  333. let maxIOB: Decimal = 15.0
  334. let maxCOB: Decimal = 120.0
  335. let minPredBG: Decimal = 45.0 // Severe Hypo forecasted
  336. // STEP 2: Create calculation input with severe hypo forecasted minPredBG
  337. let input = CalculationInput(
  338. carbs: carbs,
  339. currentBG: currentBG,
  340. deltaBG: deltaBG,
  341. target: target,
  342. isf: isf,
  343. carbRatio: carbRatio,
  344. iob: iob,
  345. cob: cob,
  346. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  347. fattyMealFactor: fattyMealFactor,
  348. useSuperBolus: useSuperBolus,
  349. sweetMealFactor: sweetMealFactor,
  350. basal: basal,
  351. fraction: fraction,
  352. maxBolus: maxBolus,
  353. maxIOB: maxIOB,
  354. maxCOB: maxCOB,
  355. minPredBG: minPredBG,
  356. lastLoopDate: Date()
  357. )
  358. // STEP 3: Calculate insulin with super bolus enabled
  359. let minPredBGResult = await calculator.calculateInsulin(input: input)
  360. // STEP 4: Calculate insulin with super bolus disabled for comparison
  361. let standardInput = CalculationInput(
  362. carbs: carbs,
  363. currentBG: currentBG,
  364. deltaBG: deltaBG,
  365. target: target,
  366. isf: isf,
  367. carbRatio: carbRatio,
  368. iob: iob,
  369. cob: cob,
  370. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  371. fattyMealFactor: fattyMealFactor,
  372. useSuperBolus: false, // Disabled for comparison
  373. sweetMealFactor: sweetMealFactor,
  374. basal: basal,
  375. fraction: fraction,
  376. maxBolus: maxBolus,
  377. maxIOB: maxIOB,
  378. maxCOB: maxCOB,
  379. minPredBG: 80,
  380. lastLoopDate: Date()
  381. )
  382. let standardResult = await calculator.calculateInsulin(input: standardInput)
  383. // STEP 5: Verify results
  384. #expect(minPredBGResult.insulinCalculated == 0, "Severe Hypo forecasted; insulin calculated set to 0 U for safety!")
  385. #expect(
  386. standardResult.insulinCalculated > minPredBGResult.insulinCalculated,
  387. """
  388. Super bolus calculation incorrect
  389. Expected super bolus calculation to be higher than standard
  390. MinPred <54 bolus: \(minPredBGResult.insulinCalculated) U
  391. Standard: \(standardResult.insulinCalculated) U
  392. Difference: \(standardResult.insulinCalculated - minPredBGResult.insulinCalculated) U
  393. """
  394. )
  395. }
  396. @Test("Calculate insulin with stale loop (longer than 15min ago)") func testStaleLoopBolusCalculation() async throws {
  397. // STEP 1: Setup test scenario
  398. // We need to provide a CalculationInput struct
  399. let carbs: Decimal = 80
  400. let currentBG: Decimal = 180 // 80 points above target, should result in 2U correction
  401. let deltaBG: Decimal = 5 // Rising trend, should add small correction
  402. let target: Decimal = 100
  403. let isf: Decimal = 40
  404. let carbRatio: Decimal = 10 // Should result in 8U for carbs
  405. let iob: Decimal = 1.0 // Should subtract from final result
  406. let cob: Int16 = 20
  407. let useFattyMealCorrectionFactor: Bool = false
  408. let useSuperBolus: Bool = false
  409. let fattyMealFactor: Decimal = 0.8
  410. let sweetMealFactor: Decimal = 2
  411. let basal: Decimal = 1.5 // Will be added to insulin calculation when super bolus is enabled
  412. let fraction: Decimal = 0.8
  413. let maxBolus: Decimal = 10
  414. let maxIOB: Decimal = 15.0
  415. let maxCOB: Decimal = 120.0
  416. let minPredBG: Decimal = 80
  417. // STEP 2: Create calculation input with severe hypo forecasted minPredBG
  418. let input = CalculationInput(
  419. carbs: carbs,
  420. currentBG: currentBG,
  421. deltaBG: deltaBG,
  422. target: target,
  423. isf: isf,
  424. carbRatio: carbRatio,
  425. iob: iob,
  426. cob: cob,
  427. useFattyMealCorrectionFactor: useFattyMealCorrectionFactor,
  428. fattyMealFactor: fattyMealFactor,
  429. useSuperBolus: useSuperBolus,
  430. sweetMealFactor: sweetMealFactor,
  431. basal: basal,
  432. fraction: fraction,
  433. maxBolus: maxBolus,
  434. maxIOB: maxIOB,
  435. maxCOB: maxCOB,
  436. minPredBG: minPredBG,
  437. lastLoopDate: Date().addingTimeInterval(TimeInterval(-15 * 60)) // 15min ago
  438. )
  439. // STEP 3: Calculate insulin with super bolus enabled
  440. let result = await calculator.calculateInsulin(input: input)
  441. // STEP 4: Verify results
  442. #expect(result.insulinCalculated == 0, "Loop is stale; insulin calculated set to 0 U for safety!")
  443. }
  444. @Test("Calculate insulin with zero carbs") func testZeroCarbsCalculation() async throws {
  445. // Given
  446. let carbs: Decimal = 0
  447. // When
  448. let result = await calculator.handleBolusCalculation(
  449. carbs: carbs,
  450. useFattyMealCorrection: false,
  451. useSuperBolus: false,
  452. lastLoopDate: Date(),
  453. minPredBG: nil,
  454. simulatedCOB: nil,
  455. isBackdated: false
  456. )
  457. // Then
  458. #expect(result.wholeCobInsulin == 0, "Zero carbs should require no insulin for carbs")
  459. }
  460. @Test("Verify settings retrieval") func testGetSettings() async throws {
  461. // Given - Save original settings to restore later
  462. let originalSettings = settingsManager.settings
  463. // Setup test settings
  464. let expectedUnits = GlucoseUnits.mgdL
  465. let expectedFraction: Decimal = 0.7
  466. let expectedFattyMealFactor: Decimal = 0.8
  467. let expectedSweetMealFactor: Decimal = 2
  468. let expectedMaxCarbs: Decimal = 150
  469. // Update settings through settings manager
  470. settingsManager.settings.units = expectedUnits
  471. settingsManager.settings.overrideFactor = expectedFraction
  472. settingsManager.settings.fattyMealFactor = expectedFattyMealFactor
  473. settingsManager.settings.sweetMealFactor = expectedSweetMealFactor
  474. settingsManager.settings.maxCarbs = expectedMaxCarbs
  475. // Save settings to storage
  476. fileStorage.save(settingsManager.settings, as: OpenAPS.Settings.settings)
  477. // When
  478. let (units, fraction, fattyMealFactor, sweetMealFactor, maxCarbs) = await getSettings()
  479. // Then
  480. #expect(units == expectedUnits, "Units should match settings")
  481. #expect(fraction == expectedFraction, "Override factor should match settings")
  482. #expect(fattyMealFactor == expectedFattyMealFactor, "Reduced bolus factor should match settings")
  483. #expect(sweetMealFactor == expectedSweetMealFactor, "Sweet meal factor should match settings")
  484. #expect(maxCarbs == expectedMaxCarbs, "Max carbs should match settings")
  485. // Cleanup - Restore original settings
  486. settingsManager.settings = originalSettings
  487. fileStorage.save(originalSettings, as: OpenAPS.Settings.settings)
  488. }
  489. @Test("Verify getCurrentSettingValue returns correct values based on time") func testGetCurrentSettingValue() async throws {
  490. // STEP 1: Backup current settings
  491. let originalBasalProfile = await fileStorage.retrieveAsync(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self)
  492. let originalCarbRatios = await fileStorage.retrieveAsync(OpenAPS.Settings.carbRatios, as: CarbRatios.self)
  493. let originalBGTargets = await fileStorage.retrieveAsync(OpenAPS.Settings.bgTargets, as: BGTargets.self)
  494. let originalISFValues = await fileStorage.retrieveAsync(
  495. OpenAPS.Settings.insulinSensitivities,
  496. as: InsulinSensitivities.self
  497. )
  498. // STEP 2: Setup test data with known values
  499. // Note: Entries must be sorted by time for the algorithm to work correctly
  500. let basalProfile = [
  501. BasalProfileEntry(start: "00:00", minutes: 0, rate: 1.0), // 12:00 AM - 6:00 AM: 1.0
  502. BasalProfileEntry(start: "06:00", minutes: 360, rate: 1.2), // 6:00 AM - 12:00 PM: 1.2
  503. BasalProfileEntry(start: "12:00", minutes: 720, rate: 1.1), // 12:00 PM - 6:00 PM: 1.1
  504. BasalProfileEntry(start: "18:00", minutes: 1080, rate: 0.9) // 6:00 PM - 12:00 AM: 0.9
  505. ]
  506. let carbRatios = CarbRatios(
  507. units: .grams,
  508. schedule: [
  509. CarbRatioEntry(start: "00:00", offset: 0, ratio: 10), // 12:00 AM - 12:00 PM: 10
  510. CarbRatioEntry(start: "12:00", offset: 720, ratio: 12) // 12:00 PM - 12:00 AM: 12
  511. ]
  512. )
  513. let bgTargets = BGTargets(
  514. units: .mgdL,
  515. userPreferredUnits: .mgdL,
  516. targets: [
  517. BGTargetEntry(low: 100, high: 120, start: "00:00", offset: 0), // 12:00 AM - 8:00 AM: 100
  518. BGTargetEntry(low: 90, high: 110, start: "08:00", offset: 480) // 8:00 AM - 12:00 AM: 90
  519. ]
  520. )
  521. let isfValues = InsulinSensitivities(
  522. units: .mgdL,
  523. userPreferredUnits: .mgdL,
  524. sensitivities: [
  525. InsulinSensitivityEntry(sensitivity: 40, offset: 0, start: "00:00"), // 12:00 AM - 2:00 PM: 40
  526. InsulinSensitivityEntry(sensitivity: 45, offset: 840, start: "14:00") // 2:00 PM - 12:00 AM: 45
  527. ]
  528. )
  529. // STEP 3: Store test data
  530. fileStorage.save(basalProfile, as: OpenAPS.Settings.basalProfile)
  531. fileStorage.save(carbRatios, as: OpenAPS.Settings.carbRatios)
  532. fileStorage.save(bgTargets, as: OpenAPS.Settings.bgTargets)
  533. fileStorage.save(isfValues, as: OpenAPS.Settings.insulinSensitivities)
  534. // STEP 4: Define test cases with specific times and expected values
  535. // Format: (hour, minute, [setting type: expected value])
  536. let testTimes: [(hour: Int, minute: Int, expected: [SettingType: Decimal])] = [
  537. // Test midnight values (00:00)
  538. (
  539. hour: 0, minute: 0,
  540. expected: [
  541. .basal: 1.0, // First basal rate
  542. .carbRatio: 10, // First carb ratio
  543. .bgTarget: 100, // First target
  544. .isf: 40 // First ISF
  545. ]
  546. ),
  547. // Test mid-morning values (7:00)
  548. (
  549. hour: 7, minute: 0,
  550. expected: [
  551. .basal: 1.2, // Second basal rate (after 6:00)
  552. .carbRatio: 10, // Still first carb ratio
  553. .bgTarget: 100, // Still first target
  554. .isf: 40 // Still first ISF
  555. ]
  556. ),
  557. // Test afternoon values (15:00)
  558. (
  559. hour: 15, minute: 0,
  560. expected: [
  561. .basal: 1.1, // Third basal rate (after 12:00)
  562. .carbRatio: 12, // Second carb ratio (after 12:00)
  563. .bgTarget: 90, // Second target
  564. .isf: 45 // Second ISF (after 14:00)
  565. ]
  566. )
  567. ]
  568. // STEP 5: Test each time point
  569. for testTime in testTimes {
  570. // Create a date object for the test time
  571. let calendar = Calendar.current
  572. var components = calendar.dateComponents([.year, .month, .day], from: Date())
  573. components.hour = testTime.hour
  574. components.minute = testTime.minute
  575. components.second = 0
  576. guard let testDate = calendar.date(from: components) else {
  577. throw TestError("Failed to create test date")
  578. }
  579. // Test each setting type at this time
  580. for (type, expectedValue) in testTime.expected {
  581. // Get the actual value for this setting at the test time
  582. let value = await getCurrentSettingValue(for: type, at: testDate)
  583. // Compare with expected value
  584. #expect(
  585. value == expectedValue,
  586. """
  587. Failed at \(testTime.hour):\(String(format: "%02d", testTime.minute))
  588. Setting: \(type)
  589. Expected: \(expectedValue)
  590. Actual: \(value)
  591. """
  592. )
  593. }
  594. }
  595. // STEP 6: Cleanup - Restore original settings
  596. if let originalBasalProfile = originalBasalProfile {
  597. fileStorage.save(originalBasalProfile, as: OpenAPS.Settings.basalProfile)
  598. }
  599. if let originalCarbRatios = originalCarbRatios {
  600. fileStorage.save(originalCarbRatios, as: OpenAPS.Settings.carbRatios)
  601. }
  602. if let originalBGTargets = originalBGTargets {
  603. fileStorage.save(originalBGTargets, as: OpenAPS.Settings.bgTargets)
  604. }
  605. if let originalISFValues = originalISFValues {
  606. fileStorage.save(originalISFValues, as: OpenAPS.Settings.insulinSensitivities)
  607. }
  608. }
  609. @Test(
  610. "Calculate insulin with backdated carbs",
  611. .enabled(if: false, "Flaky test, disabled while investigating")
  612. ) func testHandleBolusCalculationFunction() async throws {
  613. // STEP 1: Setup test scenario
  614. let currentDate = Date()
  615. let backdatedCarbsDate = currentDate.addingTimeInterval(-120 * 60) // 2 hours ago
  616. let carbs: Decimal = 30 // 30g of carbs, backdated 2 hour
  617. let cob: Int16 = 50
  618. // Get the COB value for the backdated carbs
  619. // Use the actual APS Manager to calculate simulated COB for more realistic test
  620. let determination = await apsManager.simulateDetermineBasal(
  621. simulatedCarbsAmount: carbs,
  622. simulatedBolusAmount: 0,
  623. simulatedCarbsDate: backdatedCarbsDate
  624. )
  625. let simulatedCOB = determination?.cob ?? Decimal(cob)
  626. // STEP 2: Calculate results for normal and backdated carbs
  627. let resultBackdated = await calculator.handleBolusCalculation(
  628. carbs: carbs,
  629. useFattyMealCorrection: false,
  630. useSuperBolus: false,
  631. lastLoopDate: Date.now.addingTimeInterval(-5.minutes.timeInterval),
  632. minPredBG: 80,
  633. simulatedCOB: Int16(truncating: NSDecimalNumber(decimal: simulatedCOB)),
  634. isBackdated: true
  635. )
  636. let resultNormalEntry = await calculator.handleBolusCalculation(
  637. carbs: carbs,
  638. useFattyMealCorrection: false,
  639. useSuperBolus: false,
  640. lastLoopDate: Date.now.addingTimeInterval(-5.minutes.timeInterval),
  641. minPredBG: 80,
  642. simulatedCOB: Int16(truncating: NSDecimalNumber(decimal: simulatedCOB)),
  643. isBackdated: false
  644. )
  645. // STEP 3: Compare
  646. // The backdated scenario should recommend less insulin than the current time scenario
  647. #expect(
  648. resultBackdated.insulinCalculated < resultNormalEntry.insulinCalculated,
  649. """
  650. Backdated carbs should result in lower insulin recommendation
  651. Current time: \(resultNormalEntry.insulinCalculated)U
  652. Backdated: \(resultBackdated.insulinCalculated)U
  653. Difference: \(resultNormalEntry.insulinCalculated - resultBackdated.insulinCalculated)U
  654. """
  655. )
  656. }
  657. @Test("Calculate insulin with backdated carbs") func testBackdatedCarbsCalculation() async throws {
  658. // STEP 1: Setup test scenario
  659. let currentDate = Date()
  660. let backdatedCarbsDate = currentDate.addingTimeInterval(-60 * 60) // 1 hour ago
  661. let currentBG: Decimal = 140
  662. let target: Decimal = 100
  663. let isf: Decimal = 40
  664. let carbRatio: Decimal = 10
  665. let iob: Decimal = 0.5
  666. let cob: Int16 = 10 // Existing COB before adding backdated carbs
  667. let carbs: Decimal = 30 // 30g of carbs, backdated 1 hour
  668. // Get the COB value for the backdated carbs
  669. // Use the actual APS Manager to calculate simulated COB for more realistic test
  670. let determination = await apsManager.simulateDetermineBasal(
  671. simulatedCarbsAmount: carbs,
  672. simulatedBolusAmount: 0,
  673. simulatedCarbsDate: backdatedCarbsDate
  674. )
  675. // Fallback to existing COB if determination is nil
  676. let simulatedCOB = determination?.cob ?? Decimal(cob)
  677. // For comparison - same scenario but with current time carbs
  678. let currentTimeInput = CalculationInput(
  679. carbs: carbs, // the newly entered carbs (30g)
  680. currentBG: currentBG,
  681. deltaBG: 0,
  682. target: target,
  683. isf: isf,
  684. carbRatio: carbRatio,
  685. iob: iob,
  686. cob: cob, // the existing cob (10g)
  687. useFattyMealCorrectionFactor: false,
  688. fattyMealFactor: 0.8,
  689. useSuperBolus: false,
  690. sweetMealFactor: 1,
  691. basal: 1.0,
  692. fraction: 1.0,
  693. maxBolus: 10,
  694. maxIOB: 15,
  695. maxCOB: 120,
  696. minPredBG: 80,
  697. lastLoopDate: currentDate
  698. )
  699. // Backdated scenario uses the same input but simulates date in the past
  700. let backdatedInput = CalculationInput(
  701. carbs: 0, // as the carbs are backdated we need to set the (newly entered) carbs to 0
  702. currentBG: currentBG,
  703. deltaBG: 0,
  704. target: target,
  705. isf: isf,
  706. carbRatio: carbRatio,
  707. iob: iob,
  708. cob: Int16(truncating: NSDecimalNumber(decimal: simulatedCOB)), // current COB we got from the simulated Determination
  709. useFattyMealCorrectionFactor: false,
  710. fattyMealFactor: 0.8,
  711. useSuperBolus: false,
  712. sweetMealFactor: 1,
  713. basal: 1.0,
  714. fraction: 1.0,
  715. maxBolus: 10,
  716. maxIOB: 15,
  717. maxCOB: 120,
  718. minPredBG: 80,
  719. lastLoopDate: currentDate
  720. )
  721. // STEP 2: Calculate insulin for both scenarios
  722. let currentTimeResult = await calculator.calculateInsulin(input: currentTimeInput)
  723. let backdatedResult = await calculator.calculateInsulin(input: backdatedInput)
  724. // STEP 3: Verify results
  725. // In the current time scenario, we expect COB to be old COB + current carbs
  726. let expectedCurrentTimeCOB = Decimal(cob) + carbs
  727. #expect(
  728. currentTimeResult.wholeCob == expectedCurrentTimeCOB,
  729. "Current time scenario should have \(expectedCurrentTimeCOB)g COB (\(cob)g existing + \(carbs)g new)"
  730. )
  731. // For backdated scenario, COB should be less than the current time scenario
  732. // because some carbs have already been absorbed
  733. #expect(
  734. backdatedResult.wholeCob < currentTimeResult.wholeCob,
  735. """
  736. Backdated scenario should have less COB than current time scenario
  737. Backdated: \(backdatedResult.wholeCob)g
  738. Current time: \(currentTimeResult.wholeCob)g
  739. Difference: \(currentTimeResult.wholeCob - backdatedResult.wholeCob)g
  740. """
  741. )
  742. // The wholeCobInsulin should reflect the difference in COB
  743. #expect(
  744. backdatedResult.wholeCobInsulin < currentTimeResult.wholeCobInsulin,
  745. """
  746. Backdated scenario should require less insulin for carbs due to partial absorption
  747. Backdated insulin: \(backdatedResult.wholeCobInsulin)U
  748. Current time insulin: \(currentTimeResult.wholeCobInsulin)U
  749. Difference: \(currentTimeResult.wholeCobInsulin - backdatedResult.wholeCobInsulin)U
  750. """
  751. )
  752. // The backdated scenario should recommend less insulin than the current time scenario
  753. #expect(
  754. backdatedResult.insulinCalculated < currentTimeResult.insulinCalculated,
  755. """
  756. Backdated carbs should result in lower insulin recommendation
  757. Current time: \(currentTimeResult.insulinCalculated)U
  758. Backdated: \(backdatedResult.insulinCalculated)U
  759. Difference: \(currentTimeResult.insulinCalculated - backdatedResult.insulinCalculated)U
  760. """
  761. )
  762. }
  763. }
  764. // Copied over from BolusCalculationManager as they are not included in the protocol definition (and I don´t want them to be included)
  765. extension BolusCalculatorTests {
  766. private enum SettingType {
  767. case basal
  768. case carbRatio
  769. case bgTarget
  770. case isf
  771. }
  772. /// Retrieves current settings from the SettingsManager
  773. /// - Returns: Tuple containing units, fraction, fattyMealFactor, sweetMealFactor, and maxCarbs settings
  774. private func getSettings() async -> (
  775. units: GlucoseUnits,
  776. fraction: Decimal,
  777. fattyMealFactor: Decimal,
  778. sweetMealFactor: Decimal,
  779. maxCarbs: Decimal
  780. ) {
  781. return (
  782. units: settingsManager.settings.units,
  783. fraction: settingsManager.settings.overrideFactor,
  784. fattyMealFactor: settingsManager.settings.fattyMealFactor,
  785. sweetMealFactor: settingsManager.settings.sweetMealFactor,
  786. maxCarbs: settingsManager.settings.maxCarbs
  787. )
  788. }
  789. /// Gets the current setting value for a specific setting type based on the time of day
  790. /// - Parameter type: The type of setting to retrieve (basal, carbRatio, bgTarget, or isf)
  791. /// - Returns: The current decimal value for the specified setting type
  792. private func getCurrentSettingValue(for type: SettingType, at date: Date) async -> Decimal {
  793. let calendar = Calendar.current
  794. let midnight = calendar.startOfDay(for: date)
  795. let minutesSinceMidnight = calendar.dateComponents([.minute], from: midnight, to: date).minute ?? 0
  796. switch type {
  797. case .basal:
  798. let profile = await getBasalProfile()
  799. return profile.last { $0.minutes <= minutesSinceMidnight }?.rate ?? 0
  800. case .carbRatio:
  801. let ratios = await getCarbRatios()
  802. return ratios.schedule.last { $0.offset <= minutesSinceMidnight }?.ratio ?? 0
  803. case .bgTarget:
  804. let targets = await getBGTargets()
  805. return targets.targets.last { $0.offset <= minutesSinceMidnight }?.low ?? 0
  806. case .isf:
  807. let sensitivities = await getISFValues()
  808. return sensitivities.sensitivities.last { $0.offset <= minutesSinceMidnight }?.sensitivity ?? 0
  809. }
  810. }
  811. /// Retrieves the pump settings from storage
  812. /// - Returns: PumpSettings object containing pump configuration
  813. private func getPumpSettings() async -> PumpSettings {
  814. await fileStorage.retrieveAsync(OpenAPS.Settings.settings, as: PumpSettings.self)
  815. ?? PumpSettings(from: OpenAPS.defaults(for: OpenAPS.Settings.settings))
  816. ?? PumpSettings(insulinActionCurve: 10, maxBolus: 10, maxBasal: 2)
  817. }
  818. /// Retrieves the basal profile from storage
  819. /// - Returns: Array of BasalProfileEntry objects
  820. private func getBasalProfile() async -> [BasalProfileEntry] {
  821. await fileStorage.retrieveAsync(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self)
  822. ?? [BasalProfileEntry](from: OpenAPS.defaults(for: OpenAPS.Settings.basalProfile))
  823. ?? []
  824. }
  825. /// Retrieves carb ratios from storage
  826. /// - Returns: CarbRatios object containing carb ratio schedule
  827. private func getCarbRatios() async -> CarbRatios {
  828. await fileStorage.retrieveAsync(OpenAPS.Settings.carbRatios, as: CarbRatios.self)
  829. ?? CarbRatios(from: OpenAPS.defaults(for: OpenAPS.Settings.carbRatios))
  830. ?? CarbRatios(units: .grams, schedule: [])
  831. }
  832. /// Retrieves blood glucose targets from storage
  833. /// - Returns: BGTargets object containing target schedule
  834. private func getBGTargets() async -> BGTargets {
  835. await fileStorage.retrieveAsync(OpenAPS.Settings.bgTargets, as: BGTargets.self)
  836. ?? BGTargets(from: OpenAPS.defaults(for: OpenAPS.Settings.bgTargets))
  837. ?? BGTargets(units: .mgdL, userPreferredUnits: .mgdL, targets: [])
  838. }
  839. /// Retrieves insulin sensitivity factors from storage
  840. /// - Returns: InsulinSensitivities object containing sensitivity schedule
  841. private func getISFValues() async -> InsulinSensitivities {
  842. await fileStorage.retrieveAsync(OpenAPS.Settings.insulinSensitivities, as: InsulinSensitivities.self)
  843. ?? InsulinSensitivities(from: OpenAPS.defaults(for: OpenAPS.Settings.insulinSensitivities))
  844. ?? InsulinSensitivities(
  845. units: .mgdL,
  846. userPreferredUnits: .mgdL,
  847. sensitivities: []
  848. )
  849. }
  850. }