ImportTests.swift (29701B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import XCTest 3 import GitLite 4 import GitTestSupport 5 import SQLite3 6 @testable import SubsurfaceLog 7 8 final class ImportTests: XCTestCase { 9 /// 32-byte PNF record. 10 private func record(_ type: UInt8, _ fill: (inout [UInt8]) -> Void) -> [UInt8] { 11 var bytes = [UInt8](repeating: 0, count: 32) 12 bytes[0] = type 13 fill(&bytes) 14 return bytes 15 } 16 17 private func put16(_ bytes: inout [UInt8], _ offset: Int, _ value: Int) { 18 bytes[offset] = UInt8(value >> 8) 19 bytes[offset + 1] = UInt8(value & 255) 20 } 21 22 /// Made-up log: 6 samples every 10 s, one gas change, one stop. 23 private func syntheticLog(imperial: Bool = false) -> [UInt8] { 24 var log = [UInt8]() 25 log += record(0x10) { $0[4] = 45; $0[5] = 95; $0[8] = imperial ? 1 : 0 } 26 log += record(0x11) { self.put16(&$0, 16, 1013) } 27 log += record(0x13) { self.put16(&$0, 3, 1025) } 28 log += record(0x15) { self.put16(&$0, 23, 10_000) } 29 let samples: [(depth: Int, temp: Int8, stop: Int, time: Int, tts: Int, o2: Int, psi2: Int, cns: Int)] = [ 30 (52, 20, 0, 99, 1, 32, 1450, 0), (150, 18, 0, 60, 2, 32, 1440, 1), (305, 12, 0, 12, 4, 32, 0, 1), 31 (300, 12, 3, 2, 6, 32, 1300, 2), (60, 14, 0, 99, 1, 50, 1250, 2), (10, 19, 0, 99, 0, 50, 0xFFFF, 2), 32 ] 33 for s in samples { 34 log += record(0x01) { 35 self.put16(&$0, 1, s.depth) 36 self.put16(&$0, 3, s.stop) 37 self.put16(&$0, 5, s.tts) 38 $0[8] = UInt8(s.o2) 39 $0[10] = UInt8(s.time) 40 $0[12] = 0x10 41 $0[14] = UInt8(bitPattern: s.temp) 42 $0[23] = UInt8(s.cns) 43 self.put16(&$0, 28, s.psi2) 44 self.put16(&$0, 20, 0xFFFF) 45 } 46 } 47 log += record(0xFF) { _ in } 48 return log 49 } 50 51 /// Database with the schema of the Shearwater Cloud export, reduced to the columns that are read. 52 private func makeDatabase(log: [UInt8]) throws -> [UInt8] { 53 let url = try LocalGit.temporaryDirectory("sw").appendingPathComponent("dive_data.db") 54 var db: OpaquePointer? 55 XCTAssertEqual(sqlite3_open(url.path, &db), SQLITE_OK) 56 defer { sqlite3_close(db) } 57 let schema = """ 58 create table log_data(log_id varchar primary key, file_name varchar, format varchar, data_bytes_1 blob); 59 create table dive_details(DiveId varchar primary key, DiveDate datetime, DiveLengthTime varchar, Site varchar, Location varchar, 60 Buddy varchar, Notes varchar, SerialNumber varchar); 61 insert into dive_details values('42', '2025-09-06 11:27:54', '55', 'Carrière du Nord', '', 'Sam', 'Belle "visi"', 'ABCD1234'); 62 """ 63 XCTAssertEqual(sqlite3_exec(db, schema, nil, nil, nil), SQLITE_OK) 64 var statement: OpaquePointer? 65 XCTAssertEqual(sqlite3_prepare_v2(db, "insert into log_data values('42', 'Petrel 3[ABCD1234]#9 2025-9-6 11-27-54.swlogzp', 'sw-pnf', ?)", -1, &statement, nil), SQLITE_OK) 66 let blob = [UInt8(0), 0, 0, 0] + Inflate.gzip(log) 67 blob.withUnsafeBufferPointer { _ = sqlite3_bind_blob(statement, 1, $0.baseAddress, Int32($0.count), unsafeBitCast(-1, to: sqlite3_destructor_type.self)) } 68 XCTAssertEqual(sqlite3_step(statement), SQLITE_DONE) 69 sqlite3_finalize(statement) 70 sqlite3_close(db) 71 db = nil 72 return Array(try Data(contentsOf: url)) 73 } 74 75 func testGzipAndZip() throws { 76 let payload = Array("hello ".utf8) + [UInt8](repeating: 7, count: 100_000) 77 XCTAssertEqual(try Inflate.decompress(Inflate.gzip(payload), format: .gzip), payload) 78 79 let directory = try LocalGit.temporaryDirectory("zip") 80 try Data(payload).write(to: directory.appendingPathComponent("dive_data.db")) 81 try Data("x".utf8).write(to: directory.appendingPathComponent("SyncReport.txt")) 82 let process = Process() 83 process.executableURL = URL(fileURLWithPath: "/usr/bin/zip") 84 process.arguments = ["-q", "export.zip", "SyncReport.txt", "dive_data.db"] 85 process.currentDirectoryURL = directory 86 try process.run() 87 process.waitUntilExit() 88 let archive = try ZipArchive(Array(try Data(contentsOf: directory.appendingPathComponent("export.zip")))) 89 XCTAssertEqual(archive.entries.map(\.name), ["SyncReport.txt", "dive_data.db"]) 90 XCTAssertEqual(try archive.contents(named: "dive_data.db"), payload) 91 XCTAssertNil(try archive.contents(named: "absent")) 92 } 93 94 func testShearwaterImport() throws { 95 let dives = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog())) 96 XCTAssertEqual(dives.count, 1) 97 let dive = dives[0] 98 XCTAssertEqual(dive.when, Fixture.when(2025, 9, 6, 11, 27, 54)) 99 XCTAssertEqual(dive.durationSeconds, 55) 100 XCTAssertEqual(dive.model, "Shearwater Petrel 3") 101 XCTAssertEqual(dive.serial, "ABCD1234") 102 XCTAssertEqual(dive.site, "Carrière du Nord") 103 XCTAssertEqual(dive.buddy, "Sam") 104 XCTAssertEqual(dive.decoModel, "GF 45/95") 105 XCTAssertEqual(dive.surfacePressureBar, 1.013) 106 XCTAssertEqual(dive.salinity, 1025) 107 XCTAssertEqual(dive.samples.map(\.time), [10, 20, 30, 40, 50, 60]) 108 XCTAssertEqual(dive.samples.map(\.depth), [5.2, 15, 30.5, 30, 6, 1]) 109 XCTAssertEqual(dive.samples.map(\.temperature), [20, 18, 12, 12, 14, 19]) 110 XCTAssertEqual(dive.samples[0].pressure1, 199.9) // 1450 × 2 psi 111 XCTAssertNil(dive.samples[2].pressure1) // no reading 112 XCTAssertNil(dive.samples[5].pressure1) // silent transmitter 113 XCTAssertNil(dive.samples[0].pressure2) 114 XCTAssertEqual(dive.samples[3].stopDepth, 3) 115 XCTAssertEqual(dive.samples[3].decoTime, 120) 116 XCTAssertEqual(dive.samples[1].decoTime, 3600) 117 XCTAssertEqual(dive.gases.map(\.label), ["EAN32", "EAN50"]) 118 XCTAssertEqual(dive.maxDepth, 30.5) 119 120 // Imperial units: feet and °F converted. 121 let imperial = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog(imperial: true)))[0] 122 XCTAssertEqual(imperial.samples[2].depth, 30.5 * 0.3048, accuracy: 0.001) 123 XCTAssertEqual(try XCTUnwrap(imperial.samples[0].temperature), (20.0 - 32) * 5 / 9, accuracy: 0.001) 124 125 XCTAssertThrowsError(try DiveImporter.dives(from: Array("not a database".utf8))) { 126 XCTAssertEqual($0 as? ImportError, .unknownFormat) 127 } 128 } 129 130 /// Database of the Dive Shearwater app (WatermelonDB): logs in base64, sites and buddies in separate tables. 131 func testDiveShearwaterAppDatabase() throws { 132 let url = try LocalGit.temporaryDirectory("dsw").appendingPathComponent("watermelon.db") 133 var db: OpaquePointer? 134 XCTAssertEqual(sqlite3_open(url.path, &db), SQLITE_OK) 135 let log = Data([UInt8(0), 0, 0, 0] + Inflate.gzip(syntheticLog())).base64EncodedString() 136 let schema = """ 137 create table dive_log_data(id primary key, format, data_bytes_1); 138 create table dive_details(id primary key, date_timestamp, dive_buddy_ids, notes, dive_location); 139 create table calculated_dive_log_samples(id primary key, duration_sec, dive_computer_serial, dive_computer_product); 140 create table geo_site(id primary key, common_name, latitude, longitude); 141 create table dive_buddy(id primary key, name); 142 insert into dive_log_data values('1203799431757158074', 'sw-pnf', '\(log)'); 143 insert into dive_details values('1203799431757158074', 1757158020, '["b1","b2"]', 'Free flow', 's1'); 144 insert into calculated_dive_log_samples values('1203799431757158074', 55, 'ABCD1234', 'Petrel 3'); 145 insert into geo_site values('s1', 'Forest', 45.25007, -81.66647); 146 insert into dive_buddy values('b1', 'Sam'); 147 insert into dive_buddy values('b2', 'Alex'); 148 insert into dive_log_data values('1203799431757160635', 'sw-pnf', '\(log)'); 149 """ 150 XCTAssertEqual(sqlite3_exec(db, schema, nil, nil, nil), SQLITE_OK) 151 sqlite3_close(db) 152 let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: url))) 153 XCTAssertEqual(dives.count, 2) 154 let dive = try XCTUnwrap(dives.last) 155 XCTAssertEqual(dive.when, Fixture.when(2025, 9, 6, 11, 27, 54)) // the exact time comes from the identifier 156 XCTAssertEqual(dive.durationSeconds, 55) 157 XCTAssertEqual(dive.model, "Shearwater Petrel 3") 158 XCTAssertEqual(dive.serial, "ABCD1234") 159 XCTAssertEqual(dive.site, "Forest") 160 XCTAssertEqual(dive.latitude, 45.25007) 161 XCTAssertEqual(dive.longitude, -81.66647) 162 XCTAssertEqual(dive.buddy, "Sam, Alex") 163 XCTAssertEqual(dive.notes, "Free flow") 164 XCTAssertEqual(dive.samples.map(\.depth), [5.2, 15, 30.5, 30, 6, 1]) 165 // Log without a details record: imported anyway, dated from its identifier. 166 XCTAssertEqual(dives[0].when, 1_757_160_635) 167 XCTAssertEqual(dives[0].site, "") 168 XCTAssertEqual(dives[0].durationSeconds, 60) 169 } 170 171 /// The imported dive enters the logbook, goes to the server and reads back identically. 172 func testImportedDiveRoundTrip() async throws { 173 let (remote, _) = try Fixture.makeRemote() 174 let transport = LocalProcessTransport(repository: remote.directory) 175 let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: Fixture.branch, 176 authorName: "DiveLog", authorEmail: Fixture.branch) 177 _ = try await repo.sync(transport: transport) 178 let imported = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog()))[0] 179 var log = try await repo.enqueue(.importDive(imported, number: 44, siteUUID: 0x7f3a1b2c)) 180 XCTAssertEqual(log.dives.count, 4) 181 182 // The same dive twice: rejected. 183 do { 184 try await repo.enqueue(.importDive(imported, number: 45, siteUUID: nil)) 185 XCTFail("should have failed") 186 } catch let error as ChangeError { 187 XCTAssertEqual(error, .diveAlreadyExists(imported.when)) 188 } 189 190 let report = try await repo.sync(transport: transport) 191 XCTAssertEqual(report.sent.count, 1) 192 try remote.git(["fsck", "--strict"]) 193 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):2025/09/06-Sat-11=27=54/Dive-44"]), 194 "duration 0:55 min\ndivesiteid 7f3a1b2c\nbuddy \"Sam\"\nnotes \"Belle \\\"visi\\\"\"\ncylinder o2=32.0% start=199.9bar end=172.4bar\ncylinder o2=50.0%") 195 let computerText = try remote.text(["show", "\(Fixture.branch):2025/09/06-Sat-11=27=54/Divecomputer"]) 196 XCTAssertEqual(computerText, """ 197 model "Shearwater Petrel 3" 198 maxdepth 30.5m 199 meandepth 14.617m 200 watertemp 12.0°C 201 surfacepressure 1.013bar 202 salinity 1025g/l 203 keyvalue "Serial" "ABCD1234" 204 keyvalue "Deco model" "GF 45/95" 205 event 0:00 type=25 flags=1 name="gaschange" cylinder=0 o2=32.0% 206 event 0:50 type=25 flags=2 name="gaschange" cylinder=1 o2=50.0% 207 0:10 5.2m 20.0°C 199.9bar:0 ndl=99:00 tts=1:00 208 0:20 15.0m 18.0°C 198.6bar:0 ndl=60:00 tts=2:00 cns=1% 209 0:30 30.5m 12.0°C ndl=12:00 tts=4:00 210 0:40 30.0m 179.3bar:0 ndl=0:00 tts=6:00 in_deco=1 stoptime=2:00 stopdepth=3.0m cns=2% 211 0:50 6.0m 14.0°C 172.4bar:0 ndl=99:00 tts=1:00 in_deco=0 stoptime=0:00 stopdepth=0.0m 212 1:00 1.0m 19.0°C tts=0:00 213 """) 214 215 log = try await repo.logbook() 216 let dive = try XCTUnwrap(log.dive(when: imported.when)) 217 XCTAssertEqual(dive.number, 44) 218 XCTAssertEqual(log.site(of: dive)?.name, "Carrière Morrison") 219 XCTAssertEqual(dive.cylinders.map(\.gas.label), ["EAN32", "EAN50"]) 220 XCTAssertEqual(dive.maxDepth, 30.5) 221 XCTAssertEqual(dive.waterTemperature, 12) 222 let computers = try await repo.profile(of: dive) 223 let computer = try XCTUnwrap(computers.first) 224 XCTAssertEqual(computer.samples.map(\.depth), imported.samples.map(\.depth)) 225 XCTAssertEqual(computer.samples.map(\.temperature), imported.samples.map(\.temperature)) 226 XCTAssertEqual(computer.samples[3].stopDepth, 3) 227 XCTAssertTrue(computer.samples[3].inDeco) 228 XCTAssertFalse(computer.samples[4].inDeco) 229 XCTAssertEqual(computer.samples[1].ndl, 3600) 230 XCTAssertEqual(computer.events.filter(\.isGasChange).map { $0.gas?.label }, ["EAN32", "EAN50"]) 231 XCTAssertEqual(computer.extra.first, KeyValue(key: "Serial", value: "ABCD1234")) 232 } 233 234 /// Real Shearwater Cloud export (SHEARWATER_EXPORT = path of the .zip or of dive_data.db), kept outside the repository. 235 func testRealShearwaterExport() throws { 236 guard let path = ProcessInfo.processInfo.environment["SHEARWATER_EXPORT"] else { throw XCTSkip("SHEARWATER_EXPORT not set") } 237 let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path)))) 238 XCTAssertGreaterThan(dives.count, 0) 239 for dive in dives { 240 let c = NaiveTime.components(dive.when) 241 let pressures = dive.samples.compactMap(\.pressure1) 242 print("IMPORT \(c.year!)-\(c.month!)-\(c.day!) \(c.hour!):\(c.minute!) \(dive.model) duration=\(dive.durationSeconds) max=\(dive.maxDepth) mean=\(String(format: "%.2f", dive.meanDepth)) tmin=\(dive.minTemperature ?? -99) gases=\(dive.gases.map(\.label)) \(dive.decoModel ?? "") surf=\(dive.surfacePressureBar ?? 0) sal=\(dive.salinity ?? 0) samples=\(dive.samples.count) step=\(dive.samples.first?.time ?? 0) bar=\(pressures.first ?? 0)→\(pressures.last ?? 0) stops=\(Set(dive.samples.map(\.stopDepth)).sorted()) site=\(dive.site.count) buddy=\(dive.buddy.isEmpty ? 0 : 1)") 243 XCTAssertGreaterThan(dive.maxDepth, 3) 244 XCTAssertLessThan(dive.maxDepth, 80) 245 XCTAssertGreaterThan(dive.samples.count, 50) 246 XCTAssertFalse(LogEditor.computerFile(dive).isEmpty) 247 } 248 } 249 250 /// Merging dives by hand leaves no hole in the numbering, and what was merged is not offered again. 251 func testManualMergeClosesTheNumbering() async throws { 252 let (remote, _) = try Fixture.makeRemote() 253 let transport = LocalProcessTransport(repository: remote.directory) 254 let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: Fixture.branch, 255 authorName: "DiveLog", authorEmail: Fixture.branch) 256 _ = try await repo.sync(transport: transport) 257 func immersion(_ id: String, at when: Int) -> ImportedDive { 258 var dive = ImportedDive(when: when, durationSeconds: 600) 259 dive.sourceID = id 260 dive.model = "Shearwater Petrel 3" 261 dive.serial = "1a2b3c4d" 262 dive.samples = stride(from: 60, through: 600, by: 60).map { ImportedDive.Sample(time: $0, depth: 9) } 263 return dive 264 } 265 let start = 1_781_619_660 266 let parts = [immersion("a", at: start), immersion("b", at: start + 1500), immersion("c", at: start + 3000)] 267 let later = immersion("d", at: start + 9000) 268 _ = try await repo.importDives(parts + [later]) 269 var log = try await repo.logbook() 270 let first = try XCTUnwrap(log.dives.first { $0.when == start }).number 271 XCTAssertEqual(log.dives.first { $0.when == start + 9000 }?.number, first + 3) 272 273 log = try await repo.mergeDives(log.dives.filter { $0.when >= start && $0.when <= start + 3000 }) 274 XCTAssertEqual(log.dives.first { $0.when == start }?.number, first) 275 XCTAssertEqual(log.dives.first { $0.when == start + 9000 }?.number, first + 1) 276 XCTAssertEqual(Set(log.dives.map(\.number)).count, log.dives.count) 277 278 // The three immersions are still known, each one inside the merged dive. 279 let found = try await repo.dispositions(of: parts) 280 for part in parts { 281 guard case .duplicate(let existing)? = found[part.id] else { return XCTFail("\(part.id) should be known") } 282 XCTAssertEqual(existing.number, first) 283 } 284 _ = try await repo.sync(transport: transport) 285 try remote.git(["fsck", "--strict"]) 286 } 287 288 /// UDDF: a document written by another program is read, and the logbook written as UDDF reads back the same. 289 func testUDDF() async throws { 290 let document = """ 291 <?xml version="1.0" encoding="UTF-8"?> 292 <uddf xmlns="http://www.streit.cc/uddf/3.2/" version="3.2.1"> 293 <generator><name>Other Logbook</name><version>1.0</version></generator> 294 <diver> 295 <owner id="me"><personal><firstname>Sam</firstname><lastname>Diver</lastname></personal></owner> 296 <buddy id="b1"><personal><firstname>Alex</firstname><lastname>Martin</lastname></personal></buddy> 297 </diver> 298 <divesite><site id="s1"><name>North Quarry</name><geography><latitude>45.5</latitude><longitude>-73.6</longitude></geography></site></divesite> 299 <gasdefinitions> 300 <mix id="air"><name>Air</name><o2>0.21</o2><n2>0.79</n2><he>0</he></mix> 301 <mix id="ean50"><name>EAN50</name><o2>0.5</o2><n2>0.5</n2><he>0</he></mix> 302 </gasdefinitions> 303 <profiledata><repetitiongroup id="rg1"> 304 <dive id="d1"> 305 <informationbeforedive><link ref="s1"/><link ref="b1"/><divenumber>7</divenumber><datetime>2026-07-18T10:30:00</datetime> 306 <atmosphericpressure>101300</atmosphericpressure></informationbeforedive> 307 <tankdata><link ref="air"/><tankvolume>0.012</tankvolume><tankpressurebegin>20000000</tankpressurebegin></tankdata> 308 <samples> 309 <waypoint><depth>0.0</depth><divetime>0</divetime><switchmix ref="air"/></waypoint> 310 <waypoint><depth>20.4</depth><divetime>120</divetime><temperature>285.15</temperature><tankpressure>19000000</tankpressure></waypoint> 311 <waypoint><depth>6.0</depth><divetime>1800</divetime><switchmix ref="ean50"/><decostop kind="mandatory" decodepth="6" duration="120"/></waypoint> 312 <waypoint><depth>0.0</depth><divetime>2400</divetime></waypoint> 313 </samples> 314 <informationafterdive><greatestdepth>20.4</greatestdepth><diveduration>2400</diveduration> 315 <notes><para>Clear water & a pike.</para><para>Second line.</para></notes></informationafterdive> 316 </dive> 317 <dive id="d2"><informationbeforedive><datetime>2026-07-19T14:00:00Z</datetime></informationbeforedive> 318 <samples><waypoint><depth>5</depth><divetime>60</divetime></waypoint><waypoint><depth>0</depth><divetime>600</divetime></waypoint></samples> 319 <informationafterdive><diveduration>600</diveduration></informationafterdive></dive> 320 </repetitiongroup></profiledata> 321 </uddf> 322 """ 323 XCTAssertTrue(UDDF.isUDDF(Array(document.utf8))) 324 let dives = try UDDF.dives(from: Array(document.utf8), timeZone: TimeZone(secondsFromGMT: -4 * 3600)!) 325 XCTAssertEqual(dives.count, 2) 326 let first = dives[0] 327 XCTAssertEqual(first.when, NaiveTime.timestamp(year: 2026, month: 7, day: 18, hour: 10, minute: 30)) 328 XCTAssertEqual(first.durationSeconds, 2400) 329 XCTAssertEqual(first.site, "North Quarry") 330 XCTAssertEqual(first.latitude, 45.5) 331 XCTAssertEqual(first.buddy, "Alex Martin") 332 XCTAssertEqual(first.notes, "Clear water & a pike.\nSecond line.") 333 XCTAssertEqual(first.model, "Other Logbook") 334 XCTAssertEqual(first.surfacePressureBar, 1.013) 335 XCTAssertEqual(first.samples.map(\.depth), [0, 20.4, 6, 0]) 336 XCTAssertEqual(first.samples[1].temperature, 12) 337 XCTAssertEqual(first.samples[1].pressure1, 190) 338 XCTAssertEqual(first.samples.map(\.o2), [21, 21, 50, 50]) 339 XCTAssertEqual(first.samples[2].stopDepth, 6) 340 // A universal time ("Z") is brought back to the local time of the reader: 14:00 UTC is 10:00 at UTC-4. 341 XCTAssertEqual(dives[1].when, NaiveTime.timestamp(year: 2026, month: 7, day: 19, hour: 10, minute: 0)) 342 XCTAssertEqual(try DiveImporter.dives(from: Array(document.utf8)).count, 2) 343 344 // The fixture logbook, written as UDDF, reads back with the same dives. 345 let (remote, _) = try Fixture.makeRemote() 346 let transport = LocalProcessTransport(repository: remote.directory) 347 let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: Fixture.branch, 348 authorName: "DiveLog", authorEmail: Fixture.branch) 349 _ = try await repo.sync(transport: transport) 350 let log = try await repo.logbook() 351 let written = try await repo.uddf(generator: "DiveLog", version: "1.0") 352 XCTAssertTrue(written.contains("<uddf ")) 353 let back = try UDDF.dives(from: Array(written.utf8)) 354 XCTAssertEqual(back.map(\.when).sorted(), log.dives.map(\.when).sorted()) 355 for dive in log.dives { 356 let read = try XCTUnwrap(back.first { $0.when == dive.when }) 357 XCTAssertEqual(read.durationSeconds, dive.durationSeconds) 358 XCTAssertEqual(read.site, log.site(of: dive)?.name ?? "") 359 XCTAssertEqual(read.notes, dive.notes.split(separator: "\n", omittingEmptySubsequences: true).joined(separator: "\n")) 360 let profile = try await repo.profile(of: dive).first 361 XCTAssertEqual(read.samples.count, profile?.samples.count ?? 0) 362 if let deepest = profile?.samples.map(\.depth).max() { XCTAssertEqual(read.maxDepth, deepest, accuracy: 0.01) } 363 } 364 // And it is well-formed for the system's own XML tool. 365 let file = try LocalGit.temporaryDirectory("uddf").appendingPathComponent("logbook.uddf") 366 try written.write(to: file, atomically: true, encoding: .utf8) 367 let lint = Process() 368 lint.executableURL = URL(fileURLWithPath: "/usr/bin/xmllint") 369 lint.arguments = ["--noout", file.path] 370 try lint.run() 371 lint.waitUntilExit() 372 XCTAssertEqual(lint.terminationStatus, 0) 373 } 374 375 /// Dive dropped by Open Rémora (JSON of RemoraDeco's `DiveLog`, sorted keys, ISO 8601 dates). 376 func testOpenRemoraDive() throws { 377 let json = """ 378 {"computerModel":"Open Rémora","events":[{"time":600,"warning":"ascentFast"},{"time":1260,"warning":"ceilingViolated"}], 379 "gas":{"o2":0.32},"gradientFactors":{"high":0.7,"low":0.3},"id":"6F1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D","latitude":45.2503,"longitude":-81.6017, 380 "notes":"Première sortie","number":3,"site":"Niagara II","source":"remora","start":"2026-07-04T14:30:00Z","surfaceIntervalBefore":null, 381 "surfacePressure":1.012,"tissuesAfter":{"n2":[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]},"water":"fresh", 382 "samples":[{"ceiling":0,"depth":0.4,"noDecompressionLimit":null,"temperature":18.24,"time":2}, 383 {"ceiling":0,"depth":12.04,"noDecompressionLimit":45,"temperature":12,"time":60}, 384 {"ceiling":3,"depth":30.26,"noDecompressionLimit":0,"stopDepth":3,"stopMinutes":4,"temperature":8,"time":1200}, 385 {"ceiling":0,"depth":5,"noDecompressionLimit":120.4,"temperature":14,"time":1500}, 386 {"ceiling":0,"depth":0,"noDecompressionLimit":null,"time":1560}]} 387 """ 388 let montreal = try XCTUnwrap(TimeZone(identifier: "America/Toronto")) 389 let dive = try RemoraImport.dive(fromJSON: Data(json.utf8), timeZone: montreal) 390 XCTAssertEqual(dive.when, Fixture.when(2026, 7, 4, 10, 30, 0)) // 14:30 UTC = 10:30 in Montreal in summer 391 XCTAssertEqual(dive.durationSeconds, 1560) 392 XCTAssertEqual(dive.model, "Open Rémora") 393 XCTAssertEqual(dive.sourceID, "6F1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D") 394 XCTAssertEqual(dive.site, "Niagara II") 395 XCTAssertEqual(dive.latitude, 45.2503) 396 XCTAssertEqual(dive.salinity, 1000) 397 XCTAssertEqual(dive.surfacePressureBar, 1.012) 398 XCTAssertEqual(dive.decoModel, "GF 30/70") 399 XCTAssertEqual(dive.gases.map(\.label), ["EAN32"]) 400 XCTAssertEqual(dive.samples.map(\.time), [2, 60, 1200, 1500, 1560]) 401 XCTAssertEqual(dive.samples.map(\.depth), [0.4, 12, 30.3, 5, 0]) 402 XCTAssertEqual(dive.samples.map(\.temperature), [18.2, 12, 8, 14, nil]) 403 XCTAssertEqual(dive.samples.map(\.decoTime), [99 * 60, 45 * 60, 4 * 60, 99 * 60, 99 * 60]) 404 XCTAssertEqual(dive.samples.map(\.stopDepth), [0, 0, 3, 0, 0]) 405 // Default alarm labels are English. 406 XCTAssertEqual(dive.notes, "Première sortie\nAlarms: 10:00 fast ascent, 21:00 ceiling violated") 407 XCTAssertTrue(LogEditor.computerFile(dive).contains("in_deco=1 stoptime=4:00 stopdepth=3.0m")) 408 409 // The app passes its own localized labels and prefix; a warning missing from the dictionary is written as is. 410 let localized = try RemoraImport.dive(fromJSON: Data(json.utf8), timeZone: montreal, 411 alarmLabels: ["ascentFast": "remontée rapide"], alarmsPrefix: "Alarmes : ") 412 XCTAssertEqual(localized.notes, "Première sortie\nAlarmes : 10:00 remontée rapide, 21:00 ceilingViolated") 413 XCTAssertEqual(RemoraImport.defaultAlarmLabels.keys.sorted(), 414 ["ascentFast", "ascentTooFast", "ceilingViolated", "missedSafetyStop", "ppO2Critical", "ppO2High"]) 415 416 // Points marked by the diver with the Action button of the watch go into the notes too. 417 let marked = json.replacingOccurrences(of: "\"number\":3", with: "\"number\":3,\"marks\":[{\"time\":605,\"depth\":18.24,\"heading\":237.4},{\"time\":900,\"depth\":25}]") 418 XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(marked.utf8), timeZone: montreal, marksPrefix: "Repères : ").notes, 419 "Première sortie\nAlarms: 10:00 fast ascent, 21:00 ceiling violated\nRepères : 10:05 18.2 m 237°, 15:00 25.0 m") 420 421 // Open Mérou drops the same JSON in its own folder of the same app group, with its own model name. 422 XCTAssertEqual(SharedDiveSource.all.map(\.folder), ["OpenRemora/Plongees", "OpenMerou/Dives"]) 423 XCTAssertEqual(RemoraImport.folder, "OpenRemora/Plongees") 424 let merouJSON = json.replacingOccurrences(of: "\"computerModel\":\"Open Rémora\"", with: "\"computerModel\":\"Open Mérou\"") 425 XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(merouJSON.utf8), timeZone: montreal).model, "Open Mérou") 426 let unnamed = json.replacingOccurrences(of: "\"computerModel\":\"Open Rémora\",", with: "") 427 XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(unnamed.utf8), timeZone: montreal, defaultModel: SharedDiveSource.openMerou.name).model, "Open Mérou") 428 XCTAssertEqual(try RemoraImport.dive(fromJSON: Data(unnamed.utf8), timeZone: montreal).model, "Open Rémora") 429 XCTAssertThrowsError(try RemoraImport.dive(fromJSON: Data(merouJSON.replacingOccurrences(of: "\"source\":\"remora\"", with: "\"source\":\"simulation\"").utf8))) 430 431 // A demo dive must never enter the logbook. 432 XCTAssertThrowsError(try RemoraImport.dive(fromJSON: Data(json.replacingOccurrences(of: "\"source\":\"remora\"", with: "\"source\":\"simulation\"").utf8))) 433 434 // Shared folder: only the JSON files are pending; consuming also removes the UDDF. 435 let folder = try LocalGit.temporaryDirectory("shared") 436 try Data(json.utf8).write(to: folder.appendingPathComponent("a.json")) 437 try Data("<uddf/>".utf8).write(to: folder.appendingPathComponent("a.uddf")) 438 let pending = RemoraImport.pendingFiles(in: folder) 439 XCTAssertEqual(pending.map(\.lastPathComponent), ["a.json"]) 440 RemoraImport.consume(pending[0]) 441 XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: folder.path), []) 442 } 443 444 func testCloudAccountReplies() { 445 XCTAssertEqual(CloudAccount.status(fromReply: "[VERIFY]"), .needsPIN) 446 XCTAssertEqual(CloudAccount.status(fromReply: "[VERIFIED]\n"), .verified) 447 XCTAssertEqual(CloudAccount.status(fromReply: "[OK]"), .verified) 448 XCTAssertEqual(CloudAccount.status(fromReply: "Invalid PIN"), .invalidPIN) 449 XCTAssertEqual(CloudAccount.status(fromReply: "Invalid request format"), .rejected("Invalid request format")) 450 XCTAssertTrue(CloudAccount.isValid(email: "jean.test+plongee@example.com")) 451 XCTAssertFalse(CloudAccount.isValid(email: "jean@example")) 452 XCTAssertFalse(CloudAccount.isValid(email: "jean example@example.com")) 453 XCTAssertTrue(CloudAccount.isValid(password: "Abc123@.+_-")) 454 XCTAssertFalse(CloudAccount.isValid(password: "pass word")) 455 XCTAssertFalse(CloudAccount.isValid(password: "été2026!")) 456 XCTAssertFalse(CloudAccount.isValid(password: "")) 457 458 let create = CloudAccount.request(email: " Jean@Example.com", password: "secret1", pin: nil, userAgent: "test") 459 XCTAssertEqual(create.url?.absoluteString, "https://cloud.subsurface-divelog.org/storage") 460 XCTAssertEqual(create.httpBody.map { String(decoding: $0, as: UTF8.self) }, "jean@example.com secret1") 461 let verify = CloudAccount.request(email: "jean@example.com", password: "secret1", pin: "1234", userAgent: "test") 462 XCTAssertEqual(verify.url?.absoluteString, "https://cloud.subsurface-divelog.org/verify") 463 XCTAssertEqual(verify.httpBody.map { String(decoding: $0, as: UTF8.self) }, "jean@example.com secret1 1234") 464 } 465 }