"""Offline batches use synthetic coordinates and an isolated database/cloud stub.""" import hashlib import json import time import unittest from unittest.mock import patch import test_phone_locations as fixtures app=fixtures.app class LocationSyncTests(unittest.TestCase): setUp=fixtures.PhoneLocationTests.setUp stop_server=fixtures.PhoneLocationTests.stop_server phone=fixtures.PhoneLocationTests.phone configure=fixtures.PhoneLocationTests.configure def enabled(self, **options): phone=self.phone('离线测试成员') self.configure(phone,viewerIds=[self.owner['id']],historyEnabled=True,historyConsent=True,**options) result=app.LOCATIONS.native(phone['token'],dict(action='start',consent=True,receipt=phone['receipt'],bufferedHistory=True)) phone.update(result) return phone def body(self,phone,count=2,at=None,batch='a'*32): at=at or phone['collectionStartedAt'] points=[dict(id=f'{i:032x}',position=dict(latitude=36.61,longitude=117.1,accuracy=8,at=at+i)) for i in range(count)] raw=json.dumps(dict(version=1,collectionId=phone['collectionId'],points=points),separators=(',',':')) return dict(action='history-batch',batchId=batch,sha256=hashlib.sha256(raw.encode()).hexdigest(),payload=raw) def send(self,phone,body=None):return app.LOCATIONS.native(phone['token'],body or self.body(phone)) def file(self):return dict(app.DB.execute('SELECT * FROM location_history_files').fetchone()) def verify_cloud(self): with patch.object(app.BAIDU,'upload',return_value={'fs_id':123}),patch.object(app.BAIDU,'verify_file'): app.HISTORY.process(self.file()) def test_acceptance_is_not_cloud_confirmation(self): phone=self.enabled();body=self.body(phone);reply=self.send(phone,body) self.assertEqual(reply['state'],'accepted');self.assertEqual(reply['count'],2);self.assertEqual(reply['sha256'],body['sha256']) self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],2) self.verify_cloud();reply=self.send(phone,body) self.assertEqual(reply['state'],'verified');self.assertEqual(reply['batchId'],body['batchId']) self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],0) def test_repeated_batches_before_and_after_cloud_are_idempotent(self): phone=self.enabled();body=self.body(phone) for _ in range(3):self.send(phone,body) self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],1) self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],2) self.verify_cloud() for _ in range(3):self.assertEqual(self.send(phone,body)['state'],'verified') self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],1) def test_network_and_cloud_verification_failures_never_acknowledge(self): phone=self.enabled();self.send(phone) for operation in ('upload','verify_file'): with patch.object(app.BAIDU,'upload',return_value={'fs_id':123}),patch.object(app.BAIDU,operation,side_effect=OSError('offline')):app.HISTORY.process(self.file()) self.assertEqual(self.send(phone)['state'],'accepted') self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_points').fetchone()[0],2) def test_old_points_accepted_after_three_days_without_becoming_live_position(self): phone=self.enabled(intervalSeconds=3*86400);body=self.body(phone);later=time.time()+3*86400 with patch('location_sync.time.time',return_value=later):self.assertEqual(self.send(phone,body)['state'],'accepted') self.assertIsNone(app.LOCATIONS.latest[phone['sid']]['fix']) def test_expired_still_bound_phone_can_only_finish_prior_collection(self): phone=self.enabled();body=self.body(phone) with patch('location_sync.time.time',return_value=phone['expires']+86400): self.assertEqual(self.send(phone,body)['state'],'accepted') with self.assertRaises(app.Problem):app.LOCATIONS.native(phone['token'],dict(action='start',consent=True,receipt=phone['receipt'])) def test_wrong_digest_different_payload_and_duplicate_points_rejected(self): phone=self.enabled();body=self.body(phone) for changed in (dict(body,sha256='f'*64),dict(body,payload='{}')): with self.assertRaises(app.Problem):self.send(phone,changed) self.send(phone,body) with self.assertRaises(app.Problem):self.send(phone,self.body(phone,count=1)) raw=json.loads(body['payload']);raw['points'][1]['id']=raw['points'][0]['id'];serialized=json.dumps(raw) with self.assertRaises(app.Problem):self.send(phone,dict(body,batchId='b'*32,payload=serialized,sha256=hashlib.sha256(serialized.encode()).hexdigest())) def test_batch_is_atomic_for_bad_coordinates_or_time(self): phone=self.enabled() for at in (phone['collectionStartedAt']-60,phone['expires']+100): with self.assertRaises(app.Problem):self.send(phone,self.body(phone,at=at)) body=self.body(phone);raw=json.loads(body['payload']);raw['points'][1]['position']['latitude']=float('nan');serialized=json.dumps(raw) with self.assertRaises(app.Problem):self.send(phone,dict(body,payload=serialized,sha256=hashlib.sha256(serialized.encode()).hexdigest())) self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],0) def test_other_phone_cannot_submit_or_confirm_ones_batch(self): phone=self.enabled();other=self.phone('其他手机');body=self.body(phone);self.send(phone,body) with self.assertRaises(app.Problem):self.send(other,body) def test_stop_allows_previously_collected_but_not_later_points(self): phone=self.enabled();body=self.body(phone,count=1) app.LOCATIONS.native(phone['token'],dict(action='stop')) self.assertEqual(self.send(phone,body)['state'],'accepted') with self.assertRaises(app.Problem):self.send(phone,self.body(phone,count=1,at=time.time()+30,batch='b'*32)) def test_revocation_blocks_even_existing_receipts(self): phone=self.enabled();body=self.body(phone);self.send(phone,body) app.LOCATIONS.native(phone['token'],dict(action='revoke')) with self.assertRaises(app.Problem):self.send(phone,body) def test_new_viewer_does_not_get_old_offline_points(self): phone=self.enabled();body=self.body(phone,count=1);viewer=self.phone('新增查看人') self.configure(phone,phoneIds=[viewer['sid']],historyEnabled=True,historyConsent=True) app.LOCATIONS.native(phone['token'],dict(action='start',consent=True,receipt=phone['receipt'])) self.send(phone,body) result=app.HISTORY.native(viewer['token'],dict(action='history-list',memberId=phone['member']['id'],period='life',date='2026-10-19')) self.assertEqual(result['points'],[]) def test_deleted_history_cannot_be_recreated_by_offline_retry(self): phone=self.enabled();body=self.body(phone,count=1);self.send(phone,body) app.HISTORY.native(phone['token'],dict(action='history-delete',confirm=True)) with self.assertRaises(app.Problem):self.send(phone,body) with patch.object(app.BAIDU,'delete_history_file'):app.HISTORY.process(self.file()) with self.assertRaises(app.Problem):self.send(phone,body) def test_capacity_rejects_without_accepting_or_losing_phone_receipt(self): phone=self.enabled() with patch('location_history.LIMIT',0),self.assertRaises(app.Problem):self.send(phone) self.assertEqual(app.DB.execute('SELECT count(*) FROM location_history_files').fetchone()[0],0) def test_payload_is_encrypted_at_rest(self): phone=self.enabled();self.send(phone) dump='\n'.join(app.DB.iterdump()) self.assertNotIn('latitude',dump);self.assertNotIn(phone['token'],dump) def test_long_periods_and_independent_sampling(self): phone=self.phone('周期测试') for seconds in (3600,7200,10800,14400,18000,23*3600,86400,172800,259200,30*86400): reply=self.configure(phone,viewerIds=[self.owner['id']],intervalSeconds=seconds,sampleIntervalSeconds=60) self.assertEqual(reply['intervalSeconds'],seconds);self.assertEqual(reply['sampleIntervalSeconds'],60) for invalid in (True,3601,31*86400,3600.0,'3600'): with self.assertRaises(app.Problem):self.configure(phone,viewerIds=[self.owner['id']],intervalSeconds=invalid) def test_long_period_wait_does_not_trigger_stale_alarm(self): phone=self.enabled(intervalSeconds=86400);started=phone['collectionStartedAt'] with patch('member_locations.time.time',return_value=started+3600): row=app.LOCATIONS.listing(self.aid,user=self.owner)[0];self.assertEqual(row['status'],'scheduled');self.assertIsNone(row['position']) with patch('member_locations.time.time',return_value=started+86400+901):self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'stale') def test_schedule_survives_server_memory_reset(self): phone=self.enabled(intervalSeconds=3*86400);started=phone['collectionStartedAt'];app.LOCATIONS.latest.clear() with patch('member_locations.time.time',return_value=started+86400):self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'scheduled') def test_custom_sampling_roundtrips_independently_and_limits_one_day(self): phone=self.phone('自定义采集') for sample in (10,30,120,420,900,1800,3600,7200,10800,14400,18000,25200,43200,86400): response=self.configure(phone,viewerIds=[self.owner['id']],intervalSeconds=300,sampleIntervalSeconds=sample) self.assertEqual(response['sampleIntervalSeconds'],sample) self.assertEqual(response['intervalSeconds'],300) settings=app.LOCATIONS.native(phone['token'],dict(action='settings')) self.assertEqual(settings['sampleIntervalSeconds'],sample) for invalid in (True,0,9,86401,7*86400,3600.0,'3600',None): with self.assertRaises(app.Problem):self.configure(phone,viewerIds=[self.owner['id']],sampleIntervalSeconds=invalid) def test_daily_sampling_wait_and_overdue_are_distinct_from_upload(self): phone=self.enabled(intervalSeconds=300,sampleIntervalSeconds=86400);started=phone['collectionStartedAt'] with patch('member_locations.time.time',return_value=started+3600): row=app.LOCATIONS.listing(self.aid,user=self.owner)[0] self.assertEqual(row['status'],'scheduled');self.assertEqual(row['scheduleReason'],'sampling') self.assertEqual(row['nextSampleAt'],started+86400);self.assertIsNone(row['position']) # Heartbeats must not postpone the next scheduled collection indefinitely. app.LOCATIONS.latest[phone['sid']]['seen']=started+86400+901 with patch('member_locations.time.time',return_value=started+86400+901): self.assertEqual(app.LOCATIONS.listing(self.aid,user=self.owner)[0]['status'],'stale') def test_last_sample_schedule_survives_restart_without_persisting_coordinates(self): phone=self.enabled(intervalSeconds=300,sampleIntervalSeconds=86400);started=phone['collectionStartedAt'] with app.DB:app.LOCATIONS.sync.seen(phone['sid'],started,started+86400,started+86400) app.LOCATIONS.latest.clear() with patch('member_locations.time.time',return_value=started+86400+3600): row=app.LOCATIONS.listing(self.aid,user=self.owner)[0];self.assertEqual(row['status'],'scheduled') self.assertEqual(row['nextSampleAt'],started+2*86400);self.assertIsNone(row['position']) def test_upload_timing_migration_preserves_existing_schedule(self): with app.DB: app.DB.execute('DROP TABLE location_upload_timing') app.DB.execute('CREATE TABLE location_upload_timing (share_id TEXT PRIMARY KEY,started REAL,last_received REAL)') app.DB.execute('INSERT INTO location_upload_timing VALUES (?,?,?)',('old-phone',100,200)) app.LOCATIONS.sync.initialize();app.LOCATIONS.sync.initialize() self.assertEqual(app.LOCATIONS.sync.timing('old-phone'),dict(started=100,seen=200,sampleAt=0)) if __name__=='__main__':unittest.main()