-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathLoopDataManagerDosingTests.swift
663 lines (575 loc) · 30.5 KB
/
LoopDataManagerDosingTests.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//
// LoopDataManagerDosingTests.swift
// LoopTests
//
// Created by Anna Quinlan on 10/19/22.
// Copyright © 2022 LoopKit Authors. All rights reserved.
//
import XCTest
import HealthKit
import LoopKit
@testable import LoopCore
@testable import Loop
class MockDelegate: LoopDataManagerDelegate {
let pumpManager = MockPumpManager()
var bolusUnits: Double?
func loopDataManager(_ manager: Loop.LoopDataManager, estimateBolusDuration units: Double) -> TimeInterval? {
self.bolusUnits = units
return pumpManager.estimatedDuration(toBolus: units)
}
var recommendation: AutomaticDoseRecommendation?
var error: LoopError?
func loopDataManager(_ manager: LoopDataManager, didRecommend automaticDose: (recommendation: AutomaticDoseRecommendation, date: Date), completion: @escaping (LoopError?) -> Void) {
self.recommendation = automaticDose.recommendation
completion(error)
}
func roundBasalRate(unitsPerHour: Double) -> Double { Double(Int(unitsPerHour / 0.05)) * 0.05 }
func roundBolusVolume(units: Double) -> Double { Double(Int(units / 0.05)) * 0.05 }
var pumpManagerStatus: PumpManagerStatus?
var cgmManagerStatus: CGMManagerStatus?
var pumpStatusHighlight: DeviceStatusHighlight?
}
class LoopDataManagerDosingTests: LoopDataManagerTests {
// MARK: Functions to load fixtures
func loadLocalDateGlucoseEffect(_ name: String) -> [GlucoseEffect] {
let fixture: [JSONDictionary] = loadFixture(name)
let localDateFormatter = ISO8601DateFormatter.localTimeDate()
return fixture.map {
return GlucoseEffect(startDate: localDateFormatter.date(from: $0["date"] as! String)!, quantity: HKQuantity(unit: HKUnit(from: $0["unit"] as! String), doubleValue:$0["amount"] as! Double))
}
}
func loadPredictedGlucoseFixture(_ name: String) -> [PredictedGlucoseValue] {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let url = bundle.url(forResource: name, withExtension: "json")!
return try! decoder.decode([PredictedGlucoseValue].self, from: try! Data(contentsOf: url))
}
// MARK: Tests
func testForecastFromLiveCaptureInputData() {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let url = bundle.url(forResource: "live_capture_input", withExtension: "json")!
let predictionInput = try! decoder.decode(LoopPredictionInput.self, from: try! Data(contentsOf: url))
// Therapy settings in the "live capture" input only have one value, so we can fake some schedules
// from the first entry of each therapy setting's history.
let basalRateSchedule = BasalRateSchedule(dailyItems: [
RepeatingScheduleValue(startTime: 0, value: predictionInput.settings.basal.first!.value)
])
let insulinSensitivitySchedule = InsulinSensitivitySchedule(
unit: .milligramsPerDeciliter,
dailyItems: [
RepeatingScheduleValue(startTime: 0, value: predictionInput.settings.sensitivity.first!.value.doubleValue(for: .milligramsPerDeciliter))
],
timeZone: .utcTimeZone
)!
let carbRatioSchedule = CarbRatioSchedule(
unit: .gram(),
dailyItems: [
RepeatingScheduleValue(startTime: 0.0, value: predictionInput.settings.carbRatio.first!.value)
],
timeZone: .utcTimeZone
)!
let settings = LoopSettings(
dosingEnabled: false,
glucoseTargetRangeSchedule: glucoseTargetRangeSchedule,
insulinSensitivitySchedule: insulinSensitivitySchedule,
basalRateSchedule: basalRateSchedule,
carbRatioSchedule: carbRatioSchedule,
maximumBasalRatePerHour: 10,
maximumBolus: 5,
suspendThreshold: predictionInput.settings.suspendThreshold,
automaticDosingStrategy: .automaticBolus
)
let glucoseStore = MockGlucoseStore()
glucoseStore.storedGlucose = predictionInput.glucoseHistory
let currentDate = glucoseStore.latestGlucose!.startDate
now = currentDate
let doseStore = MockDoseStore()
doseStore.basalProfile = basalRateSchedule
doseStore.basalProfileApplyingOverrideHistory = doseStore.basalProfile
doseStore.sensitivitySchedule = insulinSensitivitySchedule
doseStore.doseHistory = predictionInput.doses
doseStore.lastAddedPumpData = predictionInput.doses.last!.startDate
let carbStore = MockCarbStore()
carbStore.insulinSensitivityScheduleApplyingOverrideHistory = insulinSensitivitySchedule
carbStore.carbRatioSchedule = carbRatioSchedule
carbStore.carbRatioScheduleApplyingOverrideHistory = carbRatioSchedule
carbStore.carbHistory = predictionInput.carbEntries
dosingDecisionStore = MockDosingDecisionStore()
automaticDosingStatus = AutomaticDosingStatus(automaticDosingEnabled: true, isAutomaticDosingAllowed: true)
loopDataManager = LoopDataManager(
lastLoopCompleted: currentDate,
basalDeliveryState: .active(currentDate),
settings: settings,
overrideHistory: TemporaryScheduleOverrideHistory(),
analyticsServicesManager: AnalyticsServicesManager(),
localCacheDuration: .days(1),
doseStore: doseStore,
glucoseStore: glucoseStore,
carbStore: carbStore,
dosingDecisionStore: dosingDecisionStore,
latestStoredSettingsProvider: MockLatestStoredSettingsProvider(),
now: { currentDate },
pumpInsulinType: .novolog,
automaticDosingStatus: automaticDosingStatus,
trustedTimeOffset: { 0 }
)
let expectedPredictedGlucose = loadPredictedGlucoseFixture("live_capture_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedBasal: TempBasalRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucoseIncludingPendingInsulin
recommendedBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(expectedPredictedGlucose.count, predictedGlucose!.count)
for (expected, calculated) in zip(expectedPredictedGlucose, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
}
func testFlatAndStable() {
setUp(for: .flatAndStable)
let predictedGlucoseOutput = loadLocalDateGlucoseEffect("flat_and_stable_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedDose: AutomaticDoseRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucose
recommendedDose = state.recommendedAutomaticDose?.recommendation
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(predictedGlucoseOutput.count, predictedGlucose!.count)
for (expected, calculated) in zip(predictedGlucoseOutput, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
let recommendedTempBasal = recommendedDose?.basalAdjustment
XCTAssertEqual(1.40, recommendedTempBasal!.unitsPerHour, accuracy: defaultAccuracy)
}
func testHighAndStable() {
setUp(for: .highAndStable)
let predictedGlucoseOutput = loadLocalDateGlucoseEffect("high_and_stable_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedBasal: TempBasalRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucose
recommendedBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(predictedGlucoseOutput.count, predictedGlucose!.count)
for (expected, calculated) in zip(predictedGlucoseOutput, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
XCTAssertEqual(4.63, recommendedBasal!.unitsPerHour, accuracy: defaultAccuracy)
}
func testHighAndFalling() {
setUp(for: .highAndFalling)
let predictedGlucoseOutput = loadLocalDateGlucoseEffect("high_and_falling_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedTempBasal: TempBasalRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucose
recommendedTempBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(predictedGlucoseOutput.count, predictedGlucose!.count)
for (expected, calculated) in zip(predictedGlucoseOutput, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
XCTAssertEqual(0, recommendedTempBasal!.unitsPerHour, accuracy: defaultAccuracy)
}
func testHighAndRisingWithCOB() {
setUp(for: .highAndRisingWithCOB)
let predictedGlucoseOutput = loadLocalDateGlucoseEffect("high_and_rising_with_cob_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedBolus: ManualBolusRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucose
recommendedBolus = try? state.recommendBolus(consideringPotentialCarbEntry: nil, replacingCarbEntry: nil, considerPositiveVelocityAndRC: true)
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(predictedGlucoseOutput.count, predictedGlucose!.count)
for (expected, calculated) in zip(predictedGlucoseOutput, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
XCTAssertEqual(1.6, recommendedBolus!.amount, accuracy: defaultAccuracy)
}
func testLowAndFallingWithCOB() {
setUp(for: .lowAndFallingWithCOB)
let predictedGlucoseOutput = loadLocalDateGlucoseEffect("low_and_falling_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedTempBasal: TempBasalRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucose
recommendedTempBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(predictedGlucoseOutput.count, predictedGlucose!.count)
for (expected, calculated) in zip(predictedGlucoseOutput, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
XCTAssertEqual(0, recommendedTempBasal!.unitsPerHour, accuracy: defaultAccuracy)
}
func testLowWithLowTreatment() {
setUp(for: .lowWithLowTreatment)
let predictedGlucoseOutput = loadLocalDateGlucoseEffect("low_with_low_treatment_predicted_glucose")
let updateGroup = DispatchGroup()
updateGroup.enter()
var predictedGlucose: [PredictedGlucoseValue]?
var recommendedTempBasal: TempBasalRecommendation?
self.loopDataManager.getLoopState { _, state in
predictedGlucose = state.predictedGlucose
recommendedTempBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
// We need to wait until the task completes to get outputs
updateGroup.wait()
XCTAssertNotNil(predictedGlucose)
XCTAssertEqual(predictedGlucoseOutput.count, predictedGlucose!.count)
for (expected, calculated) in zip(predictedGlucoseOutput, predictedGlucose!) {
XCTAssertEqual(expected.startDate, calculated.startDate)
XCTAssertEqual(expected.quantity.doubleValue(for: .milligramsPerDeciliter), calculated.quantity.doubleValue(for: .milligramsPerDeciliter), accuracy: defaultAccuracy)
}
XCTAssertEqual(0, recommendedTempBasal!.unitsPerHour, accuracy: defaultAccuracy)
}
func waitOnDataQueue(timeout: TimeInterval = 1.0) {
let e = expectation(description: "dataQueue")
loopDataManager.getLoopState { _, _ in
e.fulfill()
}
wait(for: [e], timeout: timeout)
}
func testValidateMaxTempBasalDoesntCancelTempBasalIfHigher() {
let dose = DoseEntry(type: .tempBasal, startDate: Date(), endDate: nil, value: 3.0, unit: .unitsPerHour, deliveredUnits: nil, description: nil, syncIdentifier: nil, scheduledBasalRate: nil)
setUp(for: .highAndStable, basalDeliveryState: .tempBasal(dose))
// This wait is working around the issue presented by LoopDataManager.init(). It cancels the temp basal if
// `isClosedLoop` is false (which it is from `setUp` above). When that happens, it races with
// `maxTempBasalSavePreflight` below. This ensures only one happens at a time.
waitOnDataQueue()
let delegate = MockDelegate()
loopDataManager.delegate = delegate
var error: Error?
let exp = expectation(description: #function)
XCTAssertNil(delegate.recommendation)
loopDataManager.maxTempBasalSavePreflight(unitsPerHour: 5.0) {
error = $0
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
XCTAssertNil(error)
XCTAssertNil(delegate.recommendation)
XCTAssertTrue(dosingDecisionStore.dosingDecisions.isEmpty)
}
func testValidateMaxTempBasalCancelsTempBasalIfLower() {
let dose = DoseEntry(type: .tempBasal, startDate: Date(), endDate: nil, value: 5.0, unit: .unitsPerHour, deliveredUnits: nil, description: nil, syncIdentifier: nil, scheduledBasalRate: nil)
setUp(for: .highAndStable, basalDeliveryState: .tempBasal(dose))
// This wait is working around the issue presented by LoopDataManager.init(). It cancels the temp basal if
// `isClosedLoop` is false (which it is from `setUp` above). When that happens, it races with
// `maxTempBasalSavePreflight` below. This ensures only one happens at a time.
waitOnDataQueue()
let delegate = MockDelegate()
loopDataManager.delegate = delegate
var error: Error?
let exp = expectation(description: #function)
XCTAssertNil(delegate.recommendation)
loopDataManager.maxTempBasalSavePreflight(unitsPerHour: 3.0) {
error = $0
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
XCTAssertNil(error)
XCTAssertEqual(delegate.recommendation, AutomaticDoseRecommendation(basalAdjustment: .cancel))
XCTAssertEqual(dosingDecisionStore.dosingDecisions.count, 1)
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].reason, "maximumBasalRateChanged")
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].automaticDoseRecommendation, AutomaticDoseRecommendation(basalAdjustment: .cancel))
}
func testChangingMaxBasalUpdatesLoopData() {
setUp(for: .highAndStable)
waitOnDataQueue()
var loopDataUpdated = false
let exp = expectation(description: #function)
let observer = NotificationCenter.default.addObserver(forName: .LoopDataUpdated, object: nil, queue: nil) { _ in
loopDataUpdated = true
exp.fulfill()
}
XCTAssertFalse(loopDataUpdated)
loopDataManager.mutateSettings { $0.maximumBasalRatePerHour = 2.0 }
wait(for: [exp], timeout: 1.0)
XCTAssertTrue(loopDataUpdated)
NotificationCenter.default.removeObserver(observer)
}
func testOpenLoopCancelsTempBasal() {
let dose = DoseEntry(type: .tempBasal, startDate: Date(), value: 1.0, unit: .unitsPerHour)
setUp(for: .highAndStable, basalDeliveryState: .tempBasal(dose))
waitOnDataQueue()
let delegate = MockDelegate()
loopDataManager.delegate = delegate
let exp = expectation(description: #function)
let observer = NotificationCenter.default.addObserver(forName: .LoopDataUpdated, object: nil, queue: nil) { _ in
exp.fulfill()
}
automaticDosingStatus.automaticDosingEnabled = false
wait(for: [exp], timeout: 1.0)
let expectedAutomaticDoseRecommendation = AutomaticDoseRecommendation(basalAdjustment: .cancel)
XCTAssertEqual(delegate.recommendation, expectedAutomaticDoseRecommendation)
XCTAssertEqual(dosingDecisionStore.dosingDecisions.count, 1)
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].reason, "automaticDosingDisabled")
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].automaticDoseRecommendation, expectedAutomaticDoseRecommendation)
NotificationCenter.default.removeObserver(observer)
}
func testReceivedUnreliableCGMReadingCancelsTempBasal() {
let dose = DoseEntry(type: .tempBasal, startDate: Date(), value: 5.0, unit: .unitsPerHour)
setUp(for: .highAndStable, basalDeliveryState: .tempBasal(dose))
waitOnDataQueue()
let delegate = MockDelegate()
loopDataManager.delegate = delegate
let exp = expectation(description: #function)
let observer = NotificationCenter.default.addObserver(forName: .LoopDataUpdated, object: nil, queue: nil) { _ in
exp.fulfill()
}
loopDataManager.receivedUnreliableCGMReading()
wait(for: [exp], timeout: 1.0)
let expectedAutomaticDoseRecommendation = AutomaticDoseRecommendation(basalAdjustment: .cancel)
XCTAssertEqual(delegate.recommendation, expectedAutomaticDoseRecommendation)
XCTAssertEqual(dosingDecisionStore.dosingDecisions.count, 1)
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].reason, "unreliableCGMData")
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].automaticDoseRecommendation, expectedAutomaticDoseRecommendation)
NotificationCenter.default.removeObserver(observer)
}
func testLoopEnactsTempBasalWithoutManualBolusRecommendation() {
setUp(for: .highAndStable)
waitOnDataQueue()
let delegate = MockDelegate()
loopDataManager.delegate = delegate
let exp = expectation(description: #function)
let observer = NotificationCenter.default.addObserver(forName: .LoopCompleted, object: nil, queue: nil) { _ in
exp.fulfill()
}
loopDataManager.loop()
wait(for: [exp], timeout: 1.0)
let expectedAutomaticDoseRecommendation = AutomaticDoseRecommendation(basalAdjustment: TempBasalRecommendation(unitsPerHour: 4.55, duration: .minutes(30)))
XCTAssertEqual(delegate.recommendation, expectedAutomaticDoseRecommendation)
XCTAssertEqual(dosingDecisionStore.dosingDecisions.count, 1)
if dosingDecisionStore.dosingDecisions.count == 1 {
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].reason, "loop")
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].automaticDoseRecommendation, expectedAutomaticDoseRecommendation)
XCTAssertNil(dosingDecisionStore.dosingDecisions[0].manualBolusRecommendation)
XCTAssertNil(dosingDecisionStore.dosingDecisions[0].manualBolusRequested)
}
NotificationCenter.default.removeObserver(observer)
}
func testLoopRecommendsTempBasalWithoutEnactingIfOpenLoop() {
setUp(for: .highAndStable)
automaticDosingStatus.automaticDosingEnabled = false
waitOnDataQueue()
let delegate = MockDelegate()
loopDataManager.delegate = delegate
let exp = expectation(description: #function)
let observer = NotificationCenter.default.addObserver(forName: .LoopCompleted, object: nil, queue: nil) { _ in
exp.fulfill()
}
loopDataManager.loop()
wait(for: [exp], timeout: 1.0)
let expectedAutomaticDoseRecommendation = AutomaticDoseRecommendation(basalAdjustment: TempBasalRecommendation(unitsPerHour: 4.55, duration: .minutes(30)))
XCTAssertNil(delegate.recommendation)
XCTAssertEqual(dosingDecisionStore.dosingDecisions.count, 1)
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].reason, "loop")
XCTAssertEqual(dosingDecisionStore.dosingDecisions[0].automaticDoseRecommendation, expectedAutomaticDoseRecommendation)
XCTAssertNil(dosingDecisionStore.dosingDecisions[0].manualBolusRecommendation)
XCTAssertNil(dosingDecisionStore.dosingDecisions[0].manualBolusRequested)
NotificationCenter.default.removeObserver(observer)
}
func testLoopGetStateRecommendsManualBolus() {
setUp(for: .highAndStable)
let exp = expectation(description: #function)
var recommendedBolus: ManualBolusRecommendation?
loopDataManager.getLoopState { (_, loopState) in
recommendedBolus = try? loopState.recommendBolus(consideringPotentialCarbEntry: nil, replacingCarbEntry: nil, considerPositiveVelocityAndRC: true)
exp.fulfill()
}
wait(for: [exp], timeout: 100000.0)
XCTAssertEqual(recommendedBolus!.amount, 1.82, accuracy: 0.01)
}
func testLoopGetStateRecommendsManualBolusForCarbEntry() {
setUp(for: .highAndStable, predictGlucose: true)
let exp = expectation(description: #function)
var recommendedBolus: ManualBolusRecommendation?
let carbEntry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 5.0), startDate: now, foodType: nil, absorptionTime: TimeInterval(hours: 1.0))
loopDataManager.getLoopState { (_, loopState) in
recommendedBolus = try? loopState.recommendBolus(consideringPotentialCarbEntry: carbEntry, replacingCarbEntry: nil, considerPositiveVelocityAndRC: false)
exp.fulfill()
}
wait(for: [exp], timeout: 100000.0)
XCTAssertEqual(recommendedBolus!.correctionAmount!, 1.82, accuracy: 0.01)
XCTAssertEqual(recommendedBolus!.carbsAmount!, 0.5, accuracy: 0.01)
}
func testLoopGetStateRecommendsManualBolusWithMomentum() {
setUp(for: .highAndRisingWithCOB)
let exp = expectation(description: #function)
var recommendedBolus: ManualBolusRecommendation?
loopDataManager.getLoopState { (_, loopState) in
recommendedBolus = try? loopState.recommendBolus(consideringPotentialCarbEntry: nil, replacingCarbEntry: nil, considerPositiveVelocityAndRC: true)
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
XCTAssertEqual(recommendedBolus!.amount, 1.62, accuracy: 0.01)
}
func testLoopGetStateRecommendsManualBolusWithoutMomentum() {
setUp(for: .highAndRisingWithCOB)
let exp = expectation(description: #function)
var recommendedBolus: ManualBolusRecommendation?
loopDataManager.getLoopState { (_, loopState) in
recommendedBolus = try? loopState.recommendBolus(consideringPotentialCarbEntry: nil, replacingCarbEntry: nil, considerPositiveVelocityAndRC: false)
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
XCTAssertEqual(recommendedBolus!.amount, 1.52, accuracy: 0.01)
}
func testIsClosedLoopAvoidsTriggeringTempBasalCancelOnCreation() {
let settings = LoopSettings(
dosingEnabled: false,
glucoseTargetRangeSchedule: glucoseTargetRangeSchedule,
maximumBasalRatePerHour: 5,
maximumBolus: 10,
suspendThreshold: suspendThreshold
)
let doseStore = MockDoseStore()
let glucoseStore = MockGlucoseStore(for: .flatAndStable)
let carbStore = MockCarbStore()
let currentDate = Date()
dosingDecisionStore = MockDosingDecisionStore()
automaticDosingStatus = AutomaticDosingStatus(automaticDosingEnabled: false, isAutomaticDosingAllowed: true)
let existingTempBasal = DoseEntry(
type: .tempBasal,
startDate: currentDate.addingTimeInterval(-.minutes(2)),
endDate: currentDate.addingTimeInterval(.minutes(28)),
value: 1.0,
unit: .unitsPerHour,
deliveredUnits: nil,
description: "Mock Temp Basal",
syncIdentifier: "asdf",
scheduledBasalRate: nil,
insulinType: .novolog,
automatic: true,
manuallyEntered: false,
isMutable: true)
loopDataManager = LoopDataManager(
lastLoopCompleted: currentDate.addingTimeInterval(-.minutes(5)),
basalDeliveryState: .tempBasal(existingTempBasal),
settings: settings,
overrideHistory: TemporaryScheduleOverrideHistory(),
analyticsServicesManager: AnalyticsServicesManager(),
localCacheDuration: .days(1),
doseStore: doseStore,
glucoseStore: glucoseStore,
carbStore: carbStore,
dosingDecisionStore: dosingDecisionStore,
latestStoredSettingsProvider: MockLatestStoredSettingsProvider(),
now: { currentDate },
pumpInsulinType: .novolog,
automaticDosingStatus: automaticDosingStatus,
trustedTimeOffset: { 0 }
)
let mockDelegate = MockDelegate()
loopDataManager.delegate = mockDelegate
// Dose enacting happens asynchronously, as does receiving isClosedLoop signals
waitOnMain(timeout: 5)
XCTAssertNil(mockDelegate.recommendation)
}
func testAutoBolusMaxIOBClamping() {
/// `maxBolus` is set to clamp the automatic dose
/// Autobolus without clamping: 0.65 U. Clamped recommendation: 0.2 U.
setUp(for: .highAndRisingWithCOB, maxBolus: 5, dosingStrategy: .automaticBolus)
// This sets up dose rounding
let delegate = MockDelegate()
loopDataManager.delegate = delegate
let updateGroup = DispatchGroup()
updateGroup.enter()
var insulinOnBoard: InsulinValue?
var recommendedBolus: Double?
self.loopDataManager.getLoopState { _, state in
insulinOnBoard = state.insulinOnBoard
recommendedBolus = state.recommendedAutomaticDose?.recommendation.bolusUnits
updateGroup.leave()
}
updateGroup.wait()
XCTAssertEqual(recommendedBolus!, 0.5, accuracy: 0.01)
XCTAssertEqual(insulinOnBoard?.value, 9.5)
/// Set the `maximumBolus` to 10U so there's no clamping
updateGroup.enter()
self.loopDataManager.mutateSettings { settings in settings.maximumBolus = 10 }
self.loopDataManager.getLoopState { _, state in
insulinOnBoard = state.insulinOnBoard
recommendedBolus = state.recommendedAutomaticDose?.recommendation.bolusUnits
updateGroup.leave()
}
updateGroup.wait()
XCTAssertEqual(recommendedBolus!, 0.65, accuracy: 0.01)
XCTAssertEqual(insulinOnBoard?.value, 9.5)
}
func testTempBasalMaxIOBClamping() {
/// `maximumBolus` is set to 5U to clamp max IOB at 10U
/// Without clamping: 4.25 U/hr. Clamped recommendation: 2.0 U/hr.
setUp(for: .highAndRisingWithCOB, maxBolus: 5)
// This sets up dose rounding
let delegate = MockDelegate()
loopDataManager.delegate = delegate
let updateGroup = DispatchGroup()
updateGroup.enter()
var insulinOnBoard: InsulinValue?
var recommendedBasal: TempBasalRecommendation?
self.loopDataManager.getLoopState { _, state in
insulinOnBoard = state.insulinOnBoard
recommendedBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
updateGroup.wait()
XCTAssertEqual(recommendedBasal!.unitsPerHour, 2.0, accuracy: 0.01)
XCTAssertEqual(insulinOnBoard?.value, 9.5)
/// Set the `maximumBolus` to 10U so there's no clamping
updateGroup.enter()
self.loopDataManager.mutateSettings { settings in settings.maximumBolus = 10 }
self.loopDataManager.getLoopState { _, state in
insulinOnBoard = state.insulinOnBoard
recommendedBasal = state.recommendedAutomaticDose?.recommendation.basalAdjustment
updateGroup.leave()
}
updateGroup.wait()
XCTAssertEqual(recommendedBasal!.unitsPerHour, 4.25, accuracy: 0.01)
XCTAssertEqual(insulinOnBoard?.value, 9.5)
}
}