open-merou

Open Mérou, a free iOS app for the Oceanic+ underwater iPhone housing
git clone https://git.schurger.org/open-merou.git
Log | Files | Refs | README | LICENSE

DiveSessionTests.swift (10324B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import RemoraDeco
      4 import Testing
      5 @testable import OpenMerou
      6 
      7 /// The optional dive computer: off, nothing is computed, recorded or shared; on, a real dive is recorded
      8 /// and handed over to Sub Rascasse; a simulated one never is.
      9 @MainActor
     10 struct DiveSessionTests {
     11     /// Wall clock of the tests: thirds of a second counted as integers, so that times are exact.
     12     final class Clock {
     13         var ticks = 0
     14         var offset = 0.0
     15         var date: Date { Date(timeIntervalSinceReferenceDate: 800_000_000 + offset + Double(ticks) / 3) }
     16     }
     17 
     18     let clock = Clock()
     19     let folder = FileManager.default.temporaryDirectory.appendingPathComponent("merou-tests-\(UUID().uuidString)")
     20     let surfacePa = 99_400.0
     21     /// Pa per metre in the default water of the computer (EN 13319).
     22     let perMetre = 10_002.783
     23 
     24     func session(enabled: Bool, termsAccepted: Bool = true, shared: URL? = nil) -> DiveSession {
     25         let name = "merou-tests-\(UUID().uuidString)"
     26         let defaults = UserDefaults(suiteName: name)!
     27         defaults.removePersistentDomain(forName: name)
     28         defaults.set(enabled, forKey: DiveSession.enabledKey)
     29         if termsAccepted { defaults.set(DiveSession.terms.version, forKey: DiveSession.terms.acceptedKey) }
     30         let clock = clock
     31         return DiveSession(store: DiveStore(folder: folder, sharedContainer: shared), defaults: defaults, now: { clock.date })
     32     }
     33 
     34     /// `seconds` at `depth`, three samples per second as the housing sends them.
     35     func stay(_ session: DiveSession, at depth: Double, seconds: Int, simulated: Bool = false) {
     36         for _ in 0..<(seconds * 3) {
     37             session.pressure(pa: surfacePa + depth * perMetre, time: clock.date.timeIntervalSinceReferenceDate, simulated: simulated)
     38             clock.ticks += 1
     39         }
     40     }
     41 
     42     func files(in url: URL) -> [String] {
     43         ((try? FileManager.default.contentsOfDirectory(atPath: url.path)) ?? []).sorted()
     44     }
     45 
     46     @Test func offByDefault() {
     47         let name = "merou-tests-\(UUID().uuidString)"
     48         let defaults = UserDefaults(suiteName: name)!
     49         defaults.removePersistentDomain(forName: name)
     50         let fresh = DiveSession(store: DiveStore(folder: folder, sharedContainer: nil), defaults: defaults)
     51         #expect(!fresh.enabled)
     52         #expect(!fresh.isActive)
     53     }
     54 
     55     @Test func offNothingIsComputedRecordedOrShared() {
     56         let s = session(enabled: false)
     57         stay(s, at: 0, seconds: 3)
     58         stay(s, at: 8, seconds: 120)
     59         // Basic information only: an estimated depth and a dive time.
     60         #expect(abs((s.depth ?? 0) - 8.16) < 0.01)                   // fresh water estimate
     61         #expect(s.diveStart != nil)
     62         #expect(!s.monitor.isDiving)
     63         #expect(s.monitor.status == nil)
     64         #expect(!s.isComputing)
     65         stay(s, at: 0, seconds: 70)
     66         #expect(s.diveStart == nil)
     67         #expect(s.store.logbook.dives.isEmpty)
     68         #expect(s.store.pending == 0)
     69         #expect(files(in: s.store.outbox).isEmpty)
     70         #expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("logbook.json").path))
     71     }
     72 
     73     @Test func turnedOnWithoutAcceptedTermsIsStillOff() {
     74         let s = session(enabled: true, termsAccepted: false)
     75         #expect(!s.isActive)
     76         stay(s, at: 0, seconds: 3)
     77         stay(s, at: 8, seconds: 30)
     78         #expect(!s.monitor.isDiving)
     79         s.acceptTerms()
     80         #expect(s.isActive)
     81     }
     82 
     83     @Test func onARealDiveIsRecordedAndHandedOver() throws {
     84         let s = session(enabled: true)
     85         var ended: [(DiveLog?, Bool)] = []
     86         s.onDiveEnded = { ended.append(($0, $1)) }
     87         stay(s, at: 0, seconds: 3)
     88         stay(s, at: 8, seconds: 120)
     89         #expect(s.isComputing)
     90         #expect(abs((s.depth ?? 0) - 8) < 0.01)                      // the computer's depth, in its water setting
     91         stay(s, at: 0, seconds: 62)
     92         #expect(!s.monitor.isDiving)
     93 
     94         let dive = try #require(s.store.logbook.dives.first)
     95         #expect(dive.computerModel == "Open Mérou")
     96         #expect(dive.source == .remora)
     97         #expect(abs(dive.maxDepth - 8) < 0.01)
     98         // 1626 is the temperature inside the housing: it is not recorded as the water temperature.
     99         #expect(dive.minTemperature == nil)
    100         #expect(ended.count == 1)
    101         #expect(ended.first?.0?.id == dive.id)
    102         #expect(ended.first?.1 == false)
    103 
    104         // Without the app group, the pair of files stays in the app's Documents.
    105         #expect(!s.store.sharedFolderAvailable)
    106         #expect(s.store.outbox == folder.appendingPathComponent("Dives", isDirectory: true))
    107         #expect(files(in: s.store.outbox) == ["\(dive.id.uuidString).json", "\(dive.id.uuidString).uddf"])
    108         #expect(s.store.pending == 1)
    109         let json = try Data(contentsOf: s.store.outbox.appendingPathComponent("\(dive.id.uuidString).json"))
    110         #expect(try DiveStore.decoder.decode(DiveLog.self, from: json) == dive)
    111         let uddf = try String(contentsOf: s.store.outbox.appendingPathComponent("\(dive.id.uuidString).uddf"), encoding: .utf8)
    112         #expect(uddf.contains("<name>Open Mérou</name>"))
    113 
    114         // The logbook survives a relaunch (tissues for a repetitive dive).
    115         let again = DiveStore(folder: folder, sharedContainer: nil)
    116         #expect(again.logbook.dives.map(\.id) == [dive.id])
    117         #expect(again.lastDive?.tissuesAfter != nil)
    118     }
    119 
    120     @Test func divesGoToTheSharedFolderWhenItExists() throws {
    121         // A dive kept in Documents while the app group was missing…
    122         let first = session(enabled: true)
    123         stay(first, at: 0, seconds: 3)
    124         stay(first, at: 6, seconds: 60)
    125         stay(first, at: 0, seconds: 62)
    126         #expect(files(in: folder.appendingPathComponent("Dives")).count == 2)
    127 
    128         // …moves to the shared folder once the group is there, and new dives go straight to it.
    129         let group = FileManager.default.temporaryDirectory.appendingPathComponent("merou-group-\(UUID().uuidString)")
    130         let s = session(enabled: true, shared: group)
    131         let outbox = group.appendingPathComponent("OpenMerou/Dives", isDirectory: true)
    132         #expect(s.store.sharedFolderAvailable)
    133         #expect(s.store.outbox == outbox)
    134         #expect(files(in: outbox).count == 2)
    135         #expect(files(in: folder.appendingPathComponent("Dives")).isEmpty)
    136         clock.offset += 3 * 3600
    137         stay(s, at: 0, seconds: 3)
    138         stay(s, at: 6, seconds: 60)
    139         stay(s, at: 0, seconds: 62)
    140         #expect(files(in: outbox).count == 4)
    141         #expect(s.store.pending == 2)
    142         #expect(s.store.logbook.dives.count == 2)
    143         #expect(s.store.logbook.dives.last?.surfaceIntervalBefore != nil)   // repetitive dive: tissues carried over
    144     }
    145 
    146     @Test func aSimulatedDiveIsNeverSavedNorShared() {
    147         let s = session(enabled: true)
    148         var ended: [(DiveLog?, Bool)] = []
    149         s.onDiveEnded = { ended.append(($0, $1)) }
    150         stay(s, at: 0, seconds: 3, simulated: true)
    151         stay(s, at: 8, seconds: 120, simulated: true)
    152         #expect(s.isComputing)                                       // the simulation does show the computer
    153         stay(s, at: 0, seconds: 62, simulated: true)
    154         #expect(!s.monitor.isDiving)
    155         #expect(ended.count == 1)
    156         #expect(ended.first?.0?.source == .simulation)
    157         #expect(ended.first?.1 == true)
    158         #expect(s.store.logbook.dives.isEmpty)
    159         #expect(files(in: s.store.outbox).isEmpty)
    160         #expect(s.store.pending == 0)
    161     }
    162 
    163     @Test func linkLostUnderwaterMakesTheDepthUnknownUntilTheHousingIsBack() {
    164         let s = session(enabled: true)
    165         var cues: [DiveCue] = []
    166         s.onCue = { cues.append($0) }
    167         stay(s, at: 0, seconds: 3)
    168         stay(s, at: 15, seconds: 60)
    169         #expect(!s.monitor.isAlarming)
    170         s.linkLost()
    171         #expect(s.monitor.depthUnknown)
    172         #expect(s.monitor.isAlarming)
    173         #expect(cues.contains(.depthLost))
    174         #expect(abs((s.monitor.status?.depth ?? 0) - 15) < 0.01)     // last known depth held
    175         #expect(s.monitor.isDiving)
    176         stay(s, at: 14, seconds: 2)
    177         #expect(!s.monitor.depthUnknown)
    178     }
    179 
    180     @Test func linkLostWithTheComputerOffDoesNothing() {
    181         let s = session(enabled: false)
    182         stay(s, at: 0, seconds: 3)
    183         stay(s, at: 15, seconds: 10)
    184         s.linkLost()
    185         #expect(!s.monitor.isDiving)
    186         #expect(!s.monitor.depthUnknown)
    187     }
    188 
    189     @Test func depthLimitWarningIsAtFortyMetres() {
    190         let s = session(enabled: true)
    191         stay(s, at: 0, seconds: 3)
    192         stay(s, at: 39, seconds: 5)
    193         #expect(!s.monitor.warnings.contains(.depthLimit))           // the watch warns at 38 m
    194         stay(s, at: 40.2, seconds: 5)
    195         #expect(s.monitor.warnings.contains(.depthLimit))
    196     }
    197 
    198     @Test func implausibleSensorNeverStartsADive() {
    199         let s = session(enabled: true)
    200         for value in [0.0, 12.0, 9_940, 3_000_000] {
    201             s.pressure(pa: value, time: clock.date.timeIntervalSinceReferenceDate, simulated: false)
    202             clock.ticks += 3
    203         }
    204         #expect(s.sensorImplausible)
    205         #expect(!s.monitor.isDiving)
    206         #expect(s.depth == nil)
    207     }
    208 
    209     @Test func aNewHousingSessionEndsTheDiveAndMeasuresTheSurfaceAgain() {
    210         let s = session(enabled: true)
    211         stay(s, at: 0, seconds: 3)
    212         stay(s, at: 8, seconds: 60)
    213         s.reset()
    214         #expect(!s.monitor.isDiving)
    215         #expect(s.source.surfacePa == nil)
    216         #expect(s.store.logbook.dives.count == 1)                    // what was dived is kept
    217     }
    218 
    219     @Test func shotCommentCarriesTheBasicDiveInformation() {
    220         let off = session(enabled: false)
    221         stay(off, at: 0, seconds: 3)
    222         #expect(off.shotComment(housingTemperature: 21) == nil)       // at the surface: nothing to write
    223         stay(off, at: 8, seconds: 65)
    224         #expect(off.shotComment(housingTemperature: 21.26)
    225                 == "Open Mérou: depth 8.2 m (estimated), dive time 1:05, temperature inside the housing 21.3 °C")
    226 
    227         let on = session(enabled: true)
    228         stay(on, at: 0, seconds: 3)
    229         stay(on, at: 8, seconds: 65)
    230         #expect(on.shotComment(housingTemperature: nil) == "Open Mérou: depth 8.0 m, dive time 1:05")
    231     }
    232 }