Phase 0: mygarmin package — library, importers, dedupe, dashboard, exports, CLI
Generalised from personal scripts: SQLite library with untouched originals, importers for FIT, TCX, GPX, AlpineQuest .trk, Strava and Garmin Connect exports, the Garmin Connect API and a USB watch; cross-source de-duplication; time zones from GPS; data-driven dashboard and GPX/.trk exports. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
84
tests/test_pipeline.py
Normal file
84
tests/test_pipeline.py
Normal file
@@ -0,0 +1,84 @@
|
||||
"""End-to-end test on synthetic data: import every source type, de-duplicate, build the dashboard, export tracks."""
|
||||
import csv, io, json, os, zipfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import pytest
|
||||
from mygarmin import dedupe, export, report, sources
|
||||
from mygarmin.formats import aqtrk, gpx
|
||||
from mygarmin.library import Library
|
||||
|
||||
T0 = datetime(2024, 3, 2, 6, 0, tzinfo=timezone.utc) # 08:00 in Cape Town
|
||||
|
||||
def track(start, minutes, lat=-33.92, lon=18.42, step_s=10, speed=2.8):
|
||||
"""A straight north-going track at `speed` m/s."""
|
||||
n = minutes * 60 // step_s
|
||||
return [{'lat': lat + i * step_s * speed / 111_000, 'lon': lon, 'ele': 100 + (i % 50), 't': start + timedelta(seconds=i * step_s), 'hr': 140}
|
||||
for i in range(n)]
|
||||
|
||||
def tcx(pts, sport='Running'):
|
||||
tp = ''.join(f"<Trackpoint><Time>{p['t']:%Y-%m-%dT%H:%M:%SZ}</Time><Position><LatitudeDegrees>{p['lat']}</LatitudeDegrees>"
|
||||
f"<LongitudeDegrees>{p['lon']}</LongitudeDegrees></Position><AltitudeMeters>{p['ele']}</AltitudeMeters>"
|
||||
f"<HeartRateBpm><Value>{p['hr']}</Value></HeartRateBpm></Trackpoint>" for p in pts)
|
||||
secs = (pts[-1]['t'] - pts[0]['t']).total_seconds()
|
||||
return (f'<?xml version="1.0"?><TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2"><Activities>'
|
||||
f'<Activity Sport="{sport}"><Id>{pts[0]["t"]:%Y-%m-%dT%H:%M:%SZ}</Id><Lap><TotalTimeSeconds>{secs}</TotalTimeSeconds>'
|
||||
f'<DistanceMeters>{secs * 2.8}</DistanceMeters><Calories>300</Calories><Track>{tp}</Track></Lap></Activity></Activities>'
|
||||
f'</TrainingCenterDatabase>').encode()
|
||||
|
||||
def trk(pts, tag):
|
||||
return aqtrk.to_trk([(p['lat'], p['lon'], p['ele'], int(p['t'].timestamp() * 1000)) for p in pts], 'test', tag, 'test', 'test')
|
||||
|
||||
@pytest.fixture
|
||||
def inbox(tmp_path):
|
||||
d = tmp_path / 'inbox'; d.mkdir()
|
||||
run = track(T0, 40)
|
||||
(d / 'old_running.tcx').write_bytes(tcx(run)) # older Garmin watch
|
||||
(d / 'phone.trk').write_bytes(trk(track(T0 + timedelta(minutes=2), 35), 'run')) # same run on the phone: duplicate
|
||||
(d / 'hike.trk').write_bytes(trk(track(T0 + timedelta(days=1), 120, speed=1.2), 'hike'))
|
||||
(d / 'car.trk').write_bytes(trk(track(T0 + timedelta(days=2), 30, speed=25), 'drive')) # transport: flagged
|
||||
(d / 'walk.gpx').write_text(gpx.write(track(T0 + timedelta(days=3), 30, speed=1.4), 'Evening walk', 'walking'))
|
||||
# Strava export: the TCX run again (duplicate) and a ride only Strava has
|
||||
st = d / 'strava'; (st / 'activities').mkdir(parents=True)
|
||||
ride = track(T0 + timedelta(days=4), 60, speed=7)
|
||||
(st / 'activities' / '2.gpx').write_text(gpx.write(ride, 'Morning Ride', 'cycling'))
|
||||
rows = [['Activity ID', 'Activity Date', 'Activity Name', 'Activity Type', 'Elapsed Time', 'Distance', 'Moving Time', 'Max Speed',
|
||||
'Elevation Gain', 'Calories', 'Filename', 'x'],
|
||||
['1', f'{T0:%b %d, %Y, %I:%M:%S %p}', 'Morning Run', 'Run', '2400', '6720', '2400', '3.5', '20', '300', '', ''],
|
||||
['2', f'{ride[0]["t"]:%b %d, %Y, %I:%M:%S %p}', 'Morning Ride', 'Ride', '3600', '25200', '3500', '9', '50', '500', 'activities/2.gpx', '']]
|
||||
buf = io.StringIO(); csv.writer(buf).writerows(rows)
|
||||
(st / 'activities.csv').write_text(buf.getvalue() + '\x00' * 20) # Strava pads its files with NULs
|
||||
# Garmin Connect export, zipped, with two days of health data
|
||||
days = [{'calendarDate': f'2024-03-0{i}', 'restingHeartRate': 50 + i, 'totalSteps': 9000, 'bodyBattery': {'bodyBatteryStatList': [
|
||||
{'bodyBatteryStatType': 'HIGHEST', 'statsValue': 90}, {'bodyBatteryStatType': 'LOWEST', 'statsValue': 20}]}} for i in (2, 3)]
|
||||
sleep = [{'calendarDate': '2024-03-03', 'sleepStartTimestampGMT': '2024-03-02T20:30:00.0', 'sleepEndTimestampGMT': '2024-03-03T04:45:00.0',
|
||||
'deepSleepSeconds': 4000, 'lightSleepSeconds': 16000, 'remSleepSeconds': 6000, 'awakeSleepSeconds': 600, 'sleepScores': {'overallScore': 81}}]
|
||||
bp = [{'bloodPressure': {'systolic': 118, 'diastolic': 72, 'pulse': 55, 'notes': 'Hgb 14.6'}, 'metaData': {'calendarDate': [2024, 3, 3]}}]
|
||||
with zipfile.ZipFile(d / 'garmin_export.zip', 'w') as z:
|
||||
z.writestr('DI_CONNECT/DI-Connect-Aggregator/UDSFile_2024.json', json.dumps(days) + '\x00' * 10)
|
||||
z.writestr('DI_CONNECT/DI-Connect-Wellness/1_sleepData.json', json.dumps(sleep))
|
||||
z.writestr('DI_CONNECT/DI-Connect-Wellness/BloodPressureFile_1.json', json.dumps(bp))
|
||||
return d
|
||||
|
||||
def test_pipeline(tmp_path, inbox):
|
||||
lib = Library.create(str(tmp_path / 'lib'), name='Test', birth_year=1980, sex='F', home_tz='Africa/Johannesburg')
|
||||
st = sources.import_path(lib, str(inbox))
|
||||
assert st['TCX activity'] == 1 and st['AlpineQuest track'] == 3 and st['GPX track'] == 1 and st['Strava activity'] == 2
|
||||
assert sources.import_path(lib, str(inbox))['already imported'] >= 4 # importing again changes nothing
|
||||
assert dedupe.run(lib) == 2 # phone run and Strava run copy the TCX run
|
||||
a = {r['file'].split('/')[-1]: r for r in lib.activities()}
|
||||
assert a['old_running.tcx']['start_local'] == '2024-03-02 08:00:00' # local time from the GPS position
|
||||
assert a['phone.trk']['dup_of'] == a['old_running.tcx']['id']
|
||||
assert a['car.trk']['flag'] == 'transport'
|
||||
assert a['2.gpx']['dup_of'] is None and a['2.gpx']['name'] == 'Morning Ride'
|
||||
days = {d['d']: d for d in lib.days()}
|
||||
assert days['2024-03-03']['rhr'] == 53 and days['2024-03-03']['sleep'] == round(26000 / 3600, 2)
|
||||
assert days['2024-03-03']['bed'] == -1.5 # 22:30 local
|
||||
assert lib.series('bp')[0]['hb'] == 14.6
|
||||
out = report.build(lib, log=lambda *_: None)
|
||||
html = open(out, encoding='utf-8').read()
|
||||
assert '__DATA__' not in html and "Test's activity logbook" in html
|
||||
data = report.data(lib)
|
||||
assert len(data['acts']) == 4 and data['health']['days'] # run, hike, walk, ride
|
||||
assert export.run(lib, log=lambda *_: None) == 4
|
||||
z = zipfile.ZipFile(lib.path('exports', 'tracks_trk.zip'))
|
||||
back = aqtrk.parse_any(z.read([n for n in z.namelist() if 'hiking' in n][0]))
|
||||
assert back['user']['activity'] == 'hike' and len(back['segments'][0]) == 720
|
||||
Reference in New Issue
Block a user