SubsurfaceLogTests.swift (32545B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import XCTest 3 import GitLite 4 import GitTestSupport 5 @testable import SubsurfaceLog 6 7 final class SubsurfaceLogTests: XCTestCase { 8 private func repository(_ name: String = "local") throws -> LogRepository { 9 try LogRepository(directory: try LocalGit.temporaryDirectory(name), branch: Fixture.branch, 10 authorName: "DiveLog", authorEmail: Fixture.branch) 11 } 12 13 // MARK: Format 14 15 func testQuoteRoundTrip() { 16 for value in ["simple", "with \"quotes\" and a \\ backslash", "line 1\nline 2", "a\n\nb\n\n\nc", "end\n", "accents éàü 🐚"] { 17 let line = Array(("notes " + LogFormat.quote(value) + "\n").utf8) 18 let parsed = LogFormat.lines(line) 19 XCTAssertEqual(parsed.count, 1, value) 20 XCTAssertEqual(parsed.first?.strings, [value]) 21 } 22 XCTAssertEqual(LogFormat.quote("a\nb"), "\"a\n\tb\"") 23 } 24 25 func testNumbers() { 26 XCTAssertEqual(LogFormat.milli(12500), "12.5") 27 XCTAssertEqual(LogFormat.milli(3000), "3.0") 28 XCTAssertEqual(LogFormat.milli(33998), "33.998") 29 XCTAssertEqual(LogFormat.milli(-1500), "-1.5") 30 XCTAssertEqual(LogFormat.number("24.5°C"), 24.5) 31 XCTAssertEqual(LogFormat.number("-75.916667"), -75.916667) 32 XCTAssertEqual(LogFormat.duration("45:30 min"), 2730) 33 XCTAssertEqual(LogFormat.minutes(2730), "45:30") 34 } 35 36 func testDiveDirectoryNames() { 37 XCTAssertEqual(LogWalker.diveTime(name: "13-Sat-10=15=30", year: 2024, month: 7), Fixture.when(2024, 7, 13, 10, 15, 30)) 38 XCTAssertEqual(LogWalker.diveTime(name: "13-Sat-10:15:30", year: 2024, month: 7), Fixture.when(2024, 7, 13, 10, 15, 30)) 39 XCTAssertEqual(LogWalker.diveTime(name: "09-01-Sun-08=30=00~abcdef1", year: 2024, month: 8), Fixture.when(2024, 9, 1, 8, 30, 0)) 40 XCTAssertEqual(LogWalker.diveTime(name: "2025-01-02-Thu-08=30=00", year: 2024, month: 12), Fixture.when(2025, 1, 2, 8, 30, 0)) 41 XCTAssertNil(LogWalker.diveTime(name: "02-Bonaire~1a2b3c4", year: 2024, month: 8)) 42 XCTAssertNil(LogWalker.diveTime(name: "Pictures", year: 2024, month: 8)) 43 XCTAssertEqual(LogEditor.divePath(when: Fixture.when(2024, 7, 13, 10, 15, 30)), ["2024", "07", "13-Sat-10=15=30"]) 44 XCTAssertEqual(LogWalker.diveNumber(fileName: "Dive-41"), 41) 45 XCTAssertEqual(LogWalker.diveNumber(fileName: "Dive-41~abc1234"), 41) 46 XCTAssertEqual(LogWalker.diveNumber(fileName: "Dive"), 0) 47 XCTAssertNil(LogWalker.diveNumber(fileName: "Divecomputer-001")) 48 } 49 50 // MARK: Reading 51 52 func testLoadLogbook() async throws { 53 let (remote, _) = try Fixture.makeRemote() 54 let repo = try repository() 55 let report = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory)) 56 XCTAssertTrue(report.downloaded) 57 let log = try await repo.logbook() 58 XCTAssertEqual(log.warnings, []) 59 XCTAssertEqual(log.dives.map(\.number), [43, 42, 41]) 60 XCTAssertEqual(log.settings.units, "METRIC") 61 XCTAssertTrue(log.settings.autogroup) 62 63 let dive = try XCTUnwrap(log.dives.last) 64 XCTAssertEqual(dive.when, Fixture.when(2024, 7, 13, 10, 15, 30)) 65 XCTAssertEqual(dive.durationSeconds, 2730) 66 XCTAssertEqual(dive.rating, 4) 67 XCTAssertEqual(dive.visibility, 3) 68 XCTAssertEqual(dive.tags, ["bateau", "épave"]) 69 XCTAssertEqual(dive.divemaster, "Alex") 70 XCTAssertEqual(dive.buddy, "Sam, Max") 71 XCTAssertEqual(dive.suit, "7 mm") 72 XCTAssertEqual(dive.notes, "Belle plongée.\nTortue \"verte\" au palier.\n\nFin.") 73 XCTAssertEqual(dive.cylinders.count, 2) 74 XCTAssertEqual(dive.cylinders[0].description, "AL80") 75 XCTAssertEqual(dive.cylinders[0].volumeLiters, 11.1) 76 XCTAssertEqual(dive.cylinders[0].gas.label, "EAN32") 77 XCTAssertEqual(dive.cylinders[0].startBar, 200) 78 XCTAssertEqual(dive.cylinders[0].endBar, 60) 79 XCTAssertEqual(dive.cylinders[1].use, "not used") 80 XCTAssertEqual(dive.weights.first?.kilograms, 6) 81 XCTAssertEqual(dive.waterTemperature, 24.5) 82 XCTAssertEqual(dive.airTemperature, 28) 83 XCTAssertEqual(dive.maxDepth, 30.5) 84 XCTAssertEqual(dive.computerModel, "Shearwater Petrel 3") 85 XCTAssertNil(dive.tripID) 86 XCTAssertEqual(try XCTUnwrap(dive.sac), 11.1 * 140 / 45.5 / 2.62, accuracy: 0.01) 87 88 let site = try XCTUnwrap(log.site(of: dive)) 89 XCTAssertEqual(site.name, "Carrière Morrison") 90 XCTAssertEqual(site.notes, "Accès par le quai\nPlateformes à 6 m et 12 m") 91 XCTAssertEqual(site.latitude, 45.65) 92 XCTAssertEqual(site.longitude, -75.916667) 93 XCTAssertEqual(site.country, "Canada") 94 95 let tripped = log.dives[0] 96 XCTAssertEqual(tripped.when, Fixture.when(2024, 9, 1, 8, 30, 0)) 97 XCTAssertEqual(log.trip(of: tripped)?.location, "Bonaire") 98 XCTAssertEqual(log.trip(of: tripped)?.notes, "Semaine de plongée du bord") 99 XCTAssertEqual(tripped.computers.map(\.model), ["Shearwater Petrel 3", "Suunto D5"]) 100 XCTAssertEqual(tripped.maxDepth, 21.9) 101 XCTAssertEqual(log.dives[1].tripID, tripped.tripID) 102 XCTAssertEqual(log.nextNumber, 44) 103 } 104 105 func testProfile() async throws { 106 let (remote, _) = try Fixture.makeRemote() 107 let repo = try repository() 108 _ = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory)) 109 let log = try await repo.logbook() 110 let dive = try XCTUnwrap(log.dive(when: Fixture.when(2024, 7, 13, 10, 15, 30))) 111 XCTAssertEqual(dive.computers.first?.samples.count, 0) // summary only 112 let computers = try await repo.profile(of: dive) 113 let dc = try XCTUnwrap(computers.first) 114 XCTAssertEqual(dc.samples.count, 6) 115 XCTAssertEqual(dc.samples.map(\.time), [0, 10, 60, 1200, 1800, 2730]) 116 XCTAssertEqual(dc.samples.map(\.depth), [0, 3.2, 12, 30.5, 15, 0]) 117 XCTAssertEqual(dc.samples[1].temperature, 26) // carried over 118 XCTAssertEqual(dc.samples[2].temperature, 25) 119 XCTAssertEqual(dc.samples[0].pressures, [SensorPressure(sensor: 0, bar: 200)]) 120 XCTAssertEqual(dc.samples[1].pressures, []) // not carried over: interpolated 121 XCTAssertEqual(dc.samples[2].ndl, 2700) 122 XCTAssertEqual(dc.samples[2].cns, 1) 123 XCTAssertTrue(dc.samples[3].inDeco) 124 XCTAssertEqual(dc.samples[3].stopDepth, 3) 125 XCTAssertEqual(dc.samples[3].tts, 480) 126 XCTAssertFalse(dc.samples[4].inDeco) 127 XCTAssertEqual(dc.events.count, 2) 128 XCTAssertTrue(dc.events[0].isGasChange) 129 XCTAssertEqual(dc.events[0].gas?.label, "EAN32") 130 XCTAssertEqual(dc.events[0].cylinder, 0) 131 XCTAssertEqual(dc.events[1].name, "ascent") 132 XCTAssertEqual(dc.events[1].time, 730) 133 XCTAssertEqual(dc.extra, [KeyValue(key: "Serial", value: "1234")]) 134 XCTAssertEqual(dc.salinity, 1025) 135 } 136 137 // MARK: Editing 138 139 func testPatchKeepsEverythingElse() { 140 let original = Array(Fixture.dive41.utf8) 141 let patched = LogEditor.patch(diveFile: original, fields: [.buddy: "Léa", .rating: "5"]) 142 let expected = Fixture.dive41 143 .replacingOccurrences(of: "rating 4", with: "rating 5") 144 .replacingOccurrences(of: "buddy \"Sam, Max\"", with: "buddy \"Léa\"") 145 XCTAssertEqual(String(decoding: patched, as: UTF8.self), expected) 146 147 // Nothing to change: identical byte for byte. 148 XCTAssertEqual(LogEditor.patch(diveFile: original, fields: [:]), original) 149 XCTAssertEqual(LogEditor.patch(diveFile: original, fields: [.buddy: "Sam, Max", .notes: "Belle plongée.\nTortue \"verte\" au palier.\n\nFin."]), original) 150 151 // Emptied field: the line disappears (an existing text line is kept as `""`). Missing field: inserted at its canonical place. 152 let minimal = Array("duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n".utf8) 153 let edited = LogEditor.patch(diveFile: minimal, fields: [.buddy: "", .notes: "ok", .rating: "3", .site: "7f3a1b2c", .tags: "nuit, épave"]) 154 XCTAssertEqual(String(decoding: edited, as: UTF8.self), 155 "duration 50:00 min\nrating 3\ntags \"nuit\", \"épave\"\ndivesiteid 7f3a1b2c\nbuddy \"\"\nnotes \"ok\"\ncylinder vol=11.1l\n") 156 XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: minimal, fields: [.rating: "0", .suit: ""]), as: UTF8.self), 157 "duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n") 158 } 159 160 /// A logbook kept without an account: exported, zipped, read back, then sent to an account that gets one. 161 func testLocalLogbookBackupAndConnect() async throws { 162 let (remote, _) = try Fixture.makeRemote() 163 let transport = LocalProcessTransport(repository: remote.directory) 164 let source = try LogRepository(directory: try LocalGit.temporaryDirectory("source"), branch: Fixture.branch, 165 authorName: "DiveLog", authorEmail: Fixture.branch) 166 _ = try await source.sync(transport: transport) 167 let original = try await source.logbook() 168 let files = try await source.exportFiles() 169 XCTAssertNotNil(files["00-Subsurface"]) 170 XCTAssertGreaterThan(files.count, original.dives.count) 171 172 // Zip round trip, with names in sub-folders and an empty file. 173 let archive = ZipArchive.archive(files.sorted { $0.key < $1.key }.map { ($0.key, Array($0.value.utf8)) } + [("empty", [])]) 174 XCTAssertTrue(ZipArchive.isZip(archive)) 175 let read = try ZipArchive(archive) 176 XCTAssertEqual(read.entries.count, files.count + 1) 177 var restored = [String: String]() 178 for entry in read.entries where entry.name != "empty" { 179 restored[entry.name] = String(decoding: try read.contents(of: entry), as: UTF8.self) 180 } 181 XCTAssertEqual(restored, files) 182 183 // A logbook without a server: the backup comes back, a change is committed locally. 184 let local = try LogRepository(directory: try LocalGit.temporaryDirectory("alone"), branch: "local", 185 authorName: "DiveLog", authorEmail: "local") 186 try await local.importTree(files: restored) 187 var log = try await local.logbook() 188 XCTAssertEqual(log.dives.map(\.when), original.dives.map(\.when)) 189 let first = try XCTUnwrap(log.dives.first) 190 log = try await local.enqueue(.editDive(when: first.when, number: first.number, fields: ["buddy": "Kept offline"])) 191 try await local.commitPendingLocally() 192 let stillPending = await local.pending 193 XCTAssertTrue(stillPending.isEmpty) 194 let kept = try await local.logbook() 195 XCTAssertEqual(kept.dives.first?.buddy, "Kept offline") 196 197 // The day an account is connected: the whole logbook goes up, on top of what the account held. 198 let cloud = try LogRepository(directory: try LocalGit.temporaryDirectory("cloud"), branch: Fixture.branch, 199 authorName: "DiveLog", authorEmail: Fixture.branch) 200 _ = try await cloud.sync(transport: transport) 201 let localFiles = try await local.exportFiles() 202 try await cloud.replaceRemote(files: localFiles, transport: transport) 203 try remote.git(["fsck", "--strict"]) 204 let sent = try await cloud.logbook() 205 XCTAssertEqual(sent.dives.first?.buddy, "Kept offline") 206 let again = try LogRepository(directory: try LocalGit.temporaryDirectory("again"), branch: Fixture.branch, 207 authorName: "DiveLog", authorEmail: Fixture.branch) 208 _ = try await again.sync(transport: transport) 209 let fetched = try await again.logbook() 210 XCTAssertEqual(fetched.dives.first?.buddy, "Kept offline") 211 let fetchedFiles = try await again.exportFiles() 212 XCTAssertEqual(fetchedFiles, localFiles) 213 _ = try await cloud.sync(transport: transport) 214 } 215 216 /// Editing the equipment rewrites the lines that changed and nothing else. 217 func testEquipmentPatch() { 218 let file = """ 219 duration 45:00 min 220 buddy "Sam" 221 cylinder vol=11.1l workpressure=207.0bar description="AL80" o2=32.0% start=200.0bar end=60.0bar depth=33.998m 222 cylinder vol=5.7l description="AL40" o2=50.0% use="not used" 223 weightsystem weight=6.0kg description="ceinture" 224 watertemp 12.0°C 225 226 """ 227 var first = Cylinder() 228 first.description = "ignored: this line is kept as it is" 229 var second = Cylinder() 230 second.description = "AL40" 231 second.volumeLiters = 5.7 232 second.gas = GasMix(o2Permille: 800) 233 second.startBar = 190 234 second.endBar = 150 235 var third = Cylinder() 236 third.description = "D12" 237 third.gas = GasMix(o2Permille: 180, hePermille: 450) 238 var belt = WeightSystem() 239 belt.kilograms = 4.5 240 belt.description = "belt" 241 var pockets = WeightSystem() 242 pockets.kilograms = 2 243 pockets.description = "pockets" 244 let patched = String(decoding: LogEditor.patch(diveFile: Array(file.utf8), cylinders: [first, second, third], 245 unchangedCylinders: [0], weights: [belt, pockets]), as: UTF8.self) 246 XCTAssertEqual(patched, """ 247 duration 45:00 min 248 buddy "Sam" 249 cylinder vol=11.1l workpressure=207.0bar description="AL80" o2=32.0% start=200.0bar end=60.0bar depth=33.998m 250 cylinder vol=5.7l description="AL40" o2=80.0% start=190.0bar end=150.0bar 251 cylinder description="D12" o2=18.0% he=45.0% 252 weightsystem weight=4.5kg description="belt" 253 weightsystem weight=2.0kg description="pockets" 254 watertemp 12.0°C 255 256 """) 257 // No equipment at all yet: the lines land at their place in the file. 258 let bare = "duration 30:00 min\nnotes \"x\"\nwatertemp 9.0°C\n" 259 XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: Array(bare.utf8), cylinders: [third], unchangedCylinders: [], weights: [belt]), as: UTF8.self), 260 "duration 30:00 min\nnotes \"x\"\ncylinder description=\"D12\" o2=18.0% he=45.0%\nweightsystem weight=4.5kg description=\"belt\"\nwatertemp 9.0°C\n") 261 // Weights removed, cylinders left alone. 262 XCTAssertFalse(String(decoding: LogEditor.patch(diveFile: Array(file.utf8), cylinders: nil, unchangedCylinders: [], weights: []), as: UTF8.self).contains("weightsystem")) 263 } 264 265 func testSyncEditsAndPush() async throws { 266 let (remote, _) = try Fixture.makeRemote() 267 let transport = LocalProcessTransport(repository: remote.directory) 268 let repo = try repository() 269 _ = try await repo.sync(transport: transport) 270 let when41 = Fixture.when(2024, 7, 13, 10, 15, 30) 271 let when43 = Fixture.when(2024, 9, 1, 8, 30, 0) 272 273 // Offline changes: visible right away, not sent yet. 274 var log = try await repo.enqueue(.editDive(when: when41, number: 41, fields: ["buddy": "Léa", "notes": "Nouvelles notes\nsur deux lignes"])) 275 XCTAssertEqual(log.dive(when: when41)?.buddy, "Léa") 276 log = try await repo.enqueue(.editDive(when: when43, number: 43, fields: ["rating": "5"])) 277 XCTAssertEqual(log.dive(when: when43)?.rating, 5) 278 log = try await repo.enqueue(.addSite(uuid: 0x1234abcd, name: "Épave du \"Lord\"", latitude: 12.1, longitude: -68.25)) 279 var added = NewDive(when: Fixture.when(2024, 10, 5, 14, 0, 0), number: log.nextNumber, durationSeconds: 2400, maxDepth: 18) 280 added.siteUUID = 0x1234abcd 281 added.buddy = "Sam" 282 added.waterTemperature = 12.5 283 log = try await repo.enqueue(.addDive(added)) 284 XCTAssertEqual(log.dives.count, 4) 285 XCTAssertEqual(log.dives[0].number, 44) 286 XCTAssertEqual(try remote.text(["log", "--format=%s", Fixture.branch]), "carnet de test") 287 288 // Another instance reopens the same local copy: the queue survived. 289 let reopened = try LogRepository(directory: repo.directory, branch: Fixture.branch, authorName: "DiveLog", authorEmail: Fixture.branch) 290 let pendingCount = await reopened.pending.count 291 XCTAssertEqual(pendingCount, 4) 292 293 let report = try await reopened.sync(transport: transport) 294 XCTAssertEqual(report.sent.count, 4) 295 XCTAssertEqual(report.dropped, []) 296 let stillPending = await reopened.pending.count 297 XCTAssertEqual(stillPending, 0) 298 299 // The real git sees a healthy repository, with one more commit and the right files. 300 try remote.git(["fsck", "--strict"]) 301 XCTAssertEqual(try remote.text(["rev-list", "--count", Fixture.branch]), "2") 302 XCTAssertEqual(try remote.text(["rev-parse", Fixture.branch]), report.head?.hex) 303 let expected41 = Fixture.dive41 304 .replacingOccurrences(of: "buddy \"Sam, Max\"", with: "buddy \"Léa\"") 305 .replacingOccurrences(of: "notes \"Belle plongée.\n\tTortue \\\"verte\\\" au palier.\n\n\tFin.\"", with: "notes \"Nouvelles notes\n\tsur deux lignes\"") 306 XCTAssertEqual(String(decoding: try remote.git(["show", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Dive-41"]), as: UTF8.self), expected41) 307 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):2024/08/02-Bonaire~1a2b3c4/09-01-Sun-08=30=00~abcdef1/Dive-43"]), 308 "duration 50:00 min\nrating 5\nbuddy \"Max\"") 309 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):2024/10/05-Sat-14=00=00/Dive-44"]), 310 "duration 40:00 min\ndivesiteid 1234abcd\nbuddy \"Sam\"\nwatertemp 12.5°C") 311 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):2024/10/05-Sat-14=00=00/Divecomputer"]), 312 "model \"manually added dive\"\nmaxdepth 18.0m\nmeandepth 17.325m\n 0:00 0.0m\n 1:00 18.0m\n 38:00 18.0m\n 40:00 0.0m") 313 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):01-Divesites/Site-1234abcd"]), 314 "name \"Épave du \\\"Lord\\\"\"\ngps 12.100000 -68.250000") 315 // The untouched files are the same objects as before. 316 XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Divecomputer"]), 317 try remote.text(["rev-parse", "\(Fixture.branch)~1:2024/07/13-Sat-10=15=30/Divecomputer"])) 318 XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):00-Subsurface"]), 319 try remote.text(["rev-parse", "\(Fixture.branch)~1:00-Subsurface"])) 320 321 // A second device starts from scratch and sees everything. 322 let other = try repository("other") 323 _ = try await other.sync(transport: transport) 324 let seen = try await other.logbook() 325 XCTAssertEqual(seen.dives.map(\.number), [44, 43, 42, 41]) 326 XCTAssertEqual(seen.dives[0].maxDepth, 18) 327 XCTAssertTrue(seen.dives[0].isManual) 328 XCTAssertEqual(seen.site(of: seen.dives[0])?.name, "Épave du \"Lord\"") 329 XCTAssertEqual(seen.dive(when: when41)?.notes, "Nouvelles notes\nsur deux lignes") 330 331 // Nothing new: the next sync neither downloads nor sends anything. 332 let idle = try await reopened.sync(transport: transport) 333 XCTAssertFalse(idle.downloaded) 334 XCTAssertEqual(idle.sent, []) 335 } 336 337 /// Another device (desktop Subsurface) pushed in the meantime: our changes are replayed on top. 338 func testPendingEditsReplayOverRemoteChanges() async throws { 339 let (remote, work) = try Fixture.makeRemote() 340 let transport = LocalProcessTransport(repository: remote.directory) 341 let repo = try repository() 342 _ = try await repo.sync(transport: transport) 343 let when41 = Fixture.when(2024, 7, 13, 10, 15, 30) 344 let when42 = Fixture.when(2024, 8, 2, 9, 0, 0) 345 346 try await repo.enqueue(.editDive(when: when41, number: 41, fields: ["suit": "étanche"])) 347 try await repo.enqueue(.editDive(when: when42, number: 42, fields: ["notes": "sera perdue"])) 348 try await repo.enqueue(.deleteDive(when: Fixture.when(2024, 9, 1, 8, 30, 0), number: 43)) 349 350 // Meanwhile, the desktop renumbers dive 41 to 141, changes its buddy and deletes dive 42. 351 try work.git(["mv", "2024/07/13-Sat-10=15=30/Dive-41", "2024/07/13-Sat-10=15=30/Dive-141"]) 352 try work.write("2024/07/13-Sat-10=15=30/Dive-141", Fixture.dive41.replacingOccurrences(of: "buddy \"Sam, Max\"", with: "buddy \"Bureau\"")) 353 try work.git(["rm", "-rq", "2024/08/02-Bonaire~1a2b3c4/02-Fri-09=00=00"]) 354 try work.commitAll("desktop changes") 355 try work.git(["push", "-q", "origin", "main:refs/heads/\(Fixture.branch)"]) 356 357 let report = try await repo.sync(transport: transport) 358 XCTAssertTrue(report.downloaded) 359 XCTAssertEqual(report.sent.count, 2) 360 XCTAssertEqual(report.dropped.count, 1) 361 try remote.git(["fsck", "--strict"]) 362 XCTAssertEqual(try remote.text(["rev-list", "--count", Fixture.branch]), "3") 363 364 let log = try await repo.logbook() 365 XCTAssertEqual(log.dives.map(\.number), [141]) 366 XCTAssertEqual(log.dives[0].buddy, "Bureau") // the desktop's change 367 XCTAssertEqual(log.dives[0].suit, "étanche") // and ours 368 // The trip emptied of its dives keeps its record, as in Subsurface. 369 XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2024/08/02-Bonaire~1a2b3c4"]), "00-Trip") 370 } 371 372 func testRejectsChangesThatDoNotApply() async throws { 373 let (remote, _) = try Fixture.makeRemote() 374 let repo = try repository() 375 _ = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory)) 376 do { 377 try await repo.enqueue(.editDive(when: 12345, number: 1, fields: ["buddy": "x"])) 378 XCTFail("should have failed") 379 } catch let error as ChangeError { 380 XCTAssertEqual(error, .diveNotFound(12345)) 381 } 382 let duplicate = NewDive(when: Fixture.when(2024, 7, 13, 10, 15, 30), number: 99, durationSeconds: 600, maxDepth: 5) 383 do { 384 try await repo.enqueue(.addDive(duplicate)) 385 XCTFail("should have failed") 386 } catch let error as ChangeError { 387 XCTAssertEqual(error, .diveAlreadyExists(duplicate.when)) 388 } 389 let pending = await repo.pending.count 390 XCTAssertEqual(pending, 0) 391 } 392 393 /// Brand-new account: no branch on the server; the first dive creates it. 394 func testEmptyAccount() async throws { 395 let remote = try LocalGit.create(bare: true, name: "empty") 396 let transport = LocalProcessTransport(repository: remote.directory) 397 let repo = try repository() 398 let first = try await repo.sync(transport: transport) 399 XCTAssertNil(first.head) 400 let empty = try await repo.logbook() 401 XCTAssertEqual(empty.dives.count, 0) 402 403 try await repo.enqueue(.addDive(NewDive(when: Fixture.when(2025, 1, 2, 3, 4, 5), number: 1, durationSeconds: 1800, maxDepth: 6))) 404 let report = try await repo.sync(transport: transport) 405 XCTAssertEqual(report.sent.count, 1) 406 try remote.git(["fsck", "--strict"]) 407 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):00-Subsurface"]), "version 3") 408 XCTAssertEqual(try remote.text(["ls-tree", "-r", "--name-only", Fixture.branch]), 409 "00-Subsurface\n2025/01/02-Thu-03=04=05/Dive-1\n2025/01/02-Thu-03=04=05/Divecomputer") 410 } 411 412 /// Validation against a real logbook: SUBSURFACE_TREE = directory laid out like the git tree (00-Subsurface, 01-Divesites, yyyy/…). 413 func testExternalTree() async throws { 414 guard let path = ProcessInfo.processInfo.environment["SUBSURFACE_TREE"] else { 415 throw XCTSkip("SUBSURFACE_TREE not set") 416 } 417 let work = try LocalGit.create(name: "external") 418 _ = try LocalGit.run(["-c", "core.quotepath=off", "init", "-q"], in: work.directory) 419 let process = Process() 420 process.executableURL = URL(fileURLWithPath: "/bin/cp") 421 process.arguments = ["-R", path + "/.", work.directory.path] 422 try process.run() 423 process.waitUntilExit() 424 try work.commitAll("external logbook") 425 let remote = try LocalGit.create(bare: true, name: "remote") 426 try work.git(["push", "-q", remote.directory.path, "main:refs/heads/\(Fixture.branch)"]) 427 let repo = try repository() 428 _ = try await repo.sync(transport: LocalProcessTransport(repository: remote.directory)) 429 let log = try await repo.logbook() 430 XCTAssertEqual(log.warnings, []) 431 XCTAssertGreaterThan(log.dives.count, 0) 432 var samples = 0 433 for dive in log.dives { 434 let computers = try await repo.profile(of: dive) 435 samples += computers.reduce(0) { $0 + $1.samples.count } 436 let site = log.site(of: dive)?.name ?? "-" 437 print("#\(dive.number) \(dive.date) \(dive.durationSeconds / 60) min \(dive.maxDepth) m \(dive.waterTemperature.map { "\($0) °C" } ?? "-") [\(site)] \(dive.computers.map(\.model)) cylinders=\(dive.cylinders.map { $0.gas.label }) buddy=\(dive.buddy) samples=\(computers.map(\.samples.count)) events=\(computers.map(\.events.count))") 438 // Rewriting a dive with its own values must not change a single byte. 439 let original = try repo.store.blob(try XCTUnwrap(dive.diveBlob)) 440 var same: [DiveField: String] = [.buddy: dive.buddy, .divemaster: dive.divemaster, .suit: dive.suit, .notes: dive.notes, 441 .rating: String(dive.rating), .visibility: String(dive.visibility), 442 .tags: dive.tags.joined(separator: ",")] 443 if let uuid = dive.siteUUID, original.count > 0, String(decoding: original, as: UTF8.self).contains("divesiteid") { 444 same[.site] = String(uuid, radix: 16) 445 } 446 XCTAssertEqual(String(decoding: LogEditor.patch(diveFile: original, fields: same), as: UTF8.self), 447 String(decoding: original, as: UTF8.self), "dive \(dive.number)") 448 } 449 print("\(log.dives.count) dives, \(log.sites.count) sites, \(log.trips.count) trips, \(samples) samples") 450 } 451 452 /// A single request to the real cloud, with an account that does not exist (CLOUD_TEST=1): it must refuse cleanly. 453 func testCloudRejectsUnknownAccount() async throws { 454 guard ProcessInfo.processInfo.environment["CLOUD_TEST"] == "1" else { throw XCTSkip("CLOUD_TEST not set") } 455 let transport = SubsurfaceCloud.transport(email: "nobody@example.com", password: "invalid") 456 do { 457 _ = try await GitClient(transport: transport, store: MemoryObjectStore()).refs() 458 XCTFail("the cloud should have refused") 459 } catch let error as GitError { 460 XCTAssertEqual(error, .unauthorized) 461 } 462 } 463 464 /// Account created by Subsurface but never filled: a commit whose tree is empty. The settings file gets added. 465 func testEmptyTreeAccountGetsSettingsFile() async throws { 466 let remote = try LocalGit.create(bare: true, name: "empty") 467 let work = try LocalGit.create(name: "work") 468 try work.commitAll("Initial commit to create empty repo.") 469 try work.git(["push", "-q", remote.directory.path, "main:refs/heads/\(Fixture.branch)"]) 470 let transport = LocalProcessTransport(repository: remote.directory) 471 let repo = try repository() 472 _ = try await repo.sync(transport: transport) 473 try await repo.enqueue(.addDive(NewDive(when: Fixture.when(2025, 1, 2, 3, 4, 5), number: 1, durationSeconds: 1800, maxDepth: 6))) 474 _ = try await repo.sync(transport: transport) 475 try remote.git(["fsck", "--strict"]) 476 XCTAssertEqual(try remote.text(["ls-tree", "-r", "--name-only", Fixture.branch]), 477 "00-Subsurface\n2025/01/02-Thu-03=04=05/Dive-1\n2025/01/02-Thu-03=04=05/Divecomputer") 478 XCTAssertEqual(try remote.text(["rev-list", "--count", Fixture.branch]), "2") 479 // Nothing to do when the file already exists: no additional commit. 480 try await repo.enqueue(.ensureSettings) 481 let idle = try await repo.sync(transport: transport) 482 XCTAssertEqual(idle.sent, []) 483 XCTAssertEqual(try remote.text(["rev-list", "--count", Fixture.branch]), "2") 484 } 485 486 func testRenumberAndPaperDive() async throws { 487 let (remote, _) = try Fixture.makeRemote() 488 let transport = LocalProcessTransport(repository: remote.directory) 489 let repo = try repository() 490 _ = try await repo.sync(transport: transport) 491 try await repo.enqueue(.renumberDive(when: Fixture.when(2024, 7, 13, 10, 15, 30), number: 41, newNumber: 188)) 492 var paper = NewDive(when: Fixture.when(2021, 8, 16, 10, 0, 0), number: 101, durationSeconds: 67 * 60, maxDepth: 17) 493 paper.tank = "Acier 130 PC" 494 paper.o2Percent = 32 495 paper.startBar = 207 496 paper.endBar = 50 497 paper.weightKg = 13.6 498 paper.suit = "Dry" 499 paper.waterTemperature = 10 500 paper.notes = "Tunnels" 501 let log = try await repo.enqueue(.addDive(paper)) 502 XCTAssertEqual(log.dives.map(\.number), [43, 42, 188, 101]) 503 XCTAssertEqual(log.dives[2].buddy, "Sam, Max") // the content of the renumbered dive has not changed 504 _ = try await repo.sync(transport: transport) 505 try remote.git(["fsck", "--strict"]) 506 XCTAssertEqual(try remote.text(["ls-tree", "--name-only", "\(Fixture.branch):2024/07/13-Sat-10=15=30"]), "Dive-188\nDivecomputer") 507 XCTAssertEqual(try remote.text(["rev-parse", "\(Fixture.branch):2024/07/13-Sat-10=15=30/Dive-188"]), 508 try remote.text(["rev-parse", "\(Fixture.branch)~1:2024/07/13-Sat-10=15=30/Dive-41"])) 509 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):2021/08/16-Mon-10=00=00/Dive-101"]), 510 "duration 67:00 min\nsuit \"Dry\"\nnotes \"Tunnels\"\ncylinder description=\"Acier 130 PC\" o2=32.0% start=207.0bar end=50.0bar\nweightsystem weight=13.6kg description=\"lest\"\nwatertemp 10.0°C") 511 let reread = try await repo.logbook() 512 let dive = try XCTUnwrap(reread.dive(when: paper.when)) 513 XCTAssertEqual(dive.cylinders.first?.description, "Acier 130 PC") 514 XCTAssertEqual(dive.cylinders.first?.gas.label, "EAN32") 515 XCTAssertEqual(dive.totalWeight, 13.6) 516 XCTAssertEqual(dive.maxDepth, 17) 517 } 518 519 func testLocateSite() async throws { 520 let (remote, _) = try Fixture.makeRemote() 521 let transport = LocalProcessTransport(repository: remote.directory) 522 let repo = try repository() 523 _ = try await repo.sync(transport: transport) 524 try await repo.enqueue(.addSite(uuid: 0xabc, name: "Tugs", latitude: nil, longitude: nil)) 525 try await repo.enqueue(.locateSite(uuid: 0xabc, latitude: 45.26166, longitude: -81.66015)) 526 let log = try await repo.enqueue(.locateSite(uuid: 0x7f3a1b2c, latitude: 45.5, longitude: -75.5)) 527 XCTAssertEqual(log.sites[0xabc]?.latitude, 45.26166) 528 // A site that is no longer used can be removed; the others stay. 529 try await repo.enqueue(.addSite(uuid: 0xdef, name: "En trop", latitude: nil, longitude: nil)) 530 let trimmed = try await repo.enqueue(.removeSite(uuid: 0xdef)) 531 XCTAssertNil(trimmed.sites[0xdef]) 532 XCTAssertNotNil(trimmed.sites[0xabc]) 533 XCTAssertEqual(log.sites[0x7f3a1b2c]?.longitude, -75.5) 534 _ = try await repo.sync(transport: transport) 535 try remote.git(["fsck", "--strict"]) 536 XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):01-Divesites/Site-00000abc"]), "name \"Tugs\"\ngps 45.261660 -81.660150") 537 XCTAssertEqual(String(decoding: try remote.git(["show", "\(Fixture.branch):01-Divesites/Site-7f3a1b2c"]), as: UTF8.self), 538 Fixture.site.replacingOccurrences(of: "gps 45.650000 -75.916667", with: "gps 45.500000 -75.500000")) 539 } 540 541 func testCloudAddresses() { 542 XCTAssertEqual(SubsurfaceCloud.sanitize(email: " Jean.Test+plongee@Example.com\n"), "jean.test+plongee@example.com") 543 XCTAssertEqual(SubsurfaceCloud.repositoryURL(email: "Jean@Example.com").absoluteString, 544 "https://cloud.subsurface-divelog.org/git/jean@example.com") 545 } 546 }