Repository navigation
Expand file tree
/
Copy pathtest_sync.py
More file actions
3332 lines (2784 loc) · 127 KB
/
Copy pathtest_sync.py
File metadata and controls
3332 lines (2784 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import hashlib
import json
import os
import plistlib
import shutil
import sqlite3
import subprocess
import uuid
from pathlib import Path
import pytest
import browser_bookmark_sync as sync_module
import safari_adapter
from browser_bookmark_sync import (
App,
AutomationRunLock,
ProfileMapping,
alphabetize_bookmarks,
automation_readiness,
catalog_backup_sets,
close_browser_processes,
compare_backup_sets,
deduplicate_bookmarks,
discover_firefox_profiles,
discover_profiles,
export_html,
iter_urls,
load_automation_config,
load_profile_mappings,
main,
merge_bookmarks,
normalized_url,
parse_args,
prepare_merged_data,
prune_backups,
read_firefox_bookmarks,
restore_firefox_backup,
restore_json_backup,
run_automation,
running_browser_processes,
save_profile_mapping,
synchronize,
transactional_firefox_write,
validate_backup_manifest,
validate_unique_guids,
verify_firefox_backup,
verify_json_backup,
write_launchd_plist,
write_task_scheduler_script,
)
def safari_document(version: int = 1) -> dict:
return {
"WebBookmarkFileVersion": version,
"Children": [
{
"WebBookmarkType": "WebBookmarkTypeList",
"WebBookmarkIdentifier": "BookmarksBar",
"Title": "Favorites",
"Children": [
{
"WebBookmarkType": "WebBookmarkTypeList",
"Title": "Nested",
"Children": [
{
"WebBookmarkType": "WebBookmarkTypeLeaf",
"URLString": "https://safari.test/path",
"URIDictionary": {"title": "Private Safari title"},
}
],
}
],
},
{
"WebBookmarkType": "WebBookmarkTypeList",
"WebBookmarkIdentifier": "com.apple.ReadingList",
"Title": "Reading List",
"Children": [
{
"WebBookmarkType": "WebBookmarkTypeLeaf",
"URLString": "https://reading-list.test",
"URIDictionary": {"title": "Never export"},
}
],
},
],
}
def write_safari_plist(path: Path, document: dict | None = None) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb") as stream:
plistlib.dump(document or safari_document(), stream, fmt=plistlib.FMT_BINARY)
return path
@pytest.fixture(autouse=True)
def windows_platform(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(sync_module, "is_macos", lambda: False)
def data(*urls: str) -> dict:
children = [{"type": "url", "id": str(i + 10), "name": url, "url": url} for i, url in enumerate(urls)]
return {"roots": {"bookmark_bar": {"type": "folder", "id": "1", "name": "Bookmarks bar", "children": children}, "other": {"type": "folder", "id": "2", "name": "Other bookmarks", "children": []}}, "version": 1, "checksum": "old"}
def firefox_profile(tmp_path: Path, *urls: str) -> Path:
profile = tmp_path / "Firefox" / "Profiles" / "test.default-release"
profile.mkdir(parents=True)
connection = sqlite3.connect(profile / "places.sqlite")
connection.execute("PRAGMA journal_mode=WAL")
connection.executescript(
"""
CREATE TABLE moz_places (
id INTEGER PRIMARY KEY,
url TEXT UNIQUE,
url_hash INTEGER NOT NULL,
title TEXT,
rev_host TEXT NOT NULL DEFAULT '',
hidden INTEGER NOT NULL DEFAULT 0,
typed INTEGER NOT NULL DEFAULT 0,
frecency INTEGER NOT NULL DEFAULT -1,
guid TEXT UNIQUE NOT NULL,
foreign_count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE moz_bookmarks (
id INTEGER PRIMARY KEY,
type INTEGER NOT NULL,
fk INTEGER,
parent INTEGER NOT NULL,
position INTEGER NOT NULL,
title TEXT,
dateAdded INTEGER NOT NULL DEFAULT 0,
lastModified INTEGER NOT NULL DEFAULT 0,
guid TEXT UNIQUE NOT NULL,
syncStatus INTEGER NOT NULL DEFAULT 0,
syncChangeCounter INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE moz_keywords (place_id INTEGER);
INSERT INTO moz_bookmarks (id, type, parent, position, title, guid)
VALUES
(1, 2, 0, 0, '', 'root________'),
(2, 2, 1, 0, 'Bookmarks Menu', 'menu________'),
(3, 2, 1, 1, 'Bookmarks Toolbar', 'toolbar_____'),
(4, 2, 1, 2, 'Other Bookmarks', 'unfiled_____'),
(5, 2, 1, 3, 'Mobile Bookmarks', 'mobile______');
"""
)
for index, url in enumerate(urls, start=1):
place_id = 100 + index
connection.execute(
"INSERT INTO moz_places (id, url, url_hash, title, rev_host, guid, foreign_count) VALUES (?, ?, ?, ?, '', ?, 1)",
(place_id, url, sync_module.places_url_hash(url), url, f"placeguid{index:03d}"),
)
connection.execute(
"INSERT INTO moz_bookmarks (id, type, fk, parent, position, title, guid) VALUES (?, 1, ?, 3, ?, ?, ?)",
(200 + index, place_id, index - 1, url, f"bookmark{index:03d}"),
)
connection.commit()
connection.close()
return profile
@pytest.fixture(autouse=True)
def no_running_browsers(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(sync_module, "running_browser_processes", lambda: [])
monkeypatch.setattr(sync_module, "running_firefox_processes", lambda: [])
def test_merge_deduplicates_and_retains_unique_links():
merged, added = merge_bookmarks(
data("https://a.test/", "https://b.test"),
data("https://a.test", "https://c.test"),
duplicate_mode="aggressive",
)
urls = [node["url"] for root in merged["roots"].values() for node in iter_urls(root)]
assert added == 1
assert urls.count("https://c.test") == 1
assert "checksum" not in merged
def test_merge_regenerates_imported_guids_and_preserves_primary_guids():
primary = data("https://chrome.test")
primary["roots"]["bookmark_bar"]["guid"] = "00000000-0000-4000-a000-000000000002"
primary["roots"]["bookmark_bar"]["children"][0]["guid"] = "11111111-1111-4111-8111-111111111111"
primary["roots"]["other"]["guid"] = "00000000-0000-4000-a000-000000000003"
secondary = data()
secondary["roots"]["bookmark_bar"]["children"] = [
{
"type": "folder",
"id": "20",
"guid": "22222222-2222-4222-8222-222222222222",
"name": "Edge folder",
"children": [
{
"type": "url",
"id": "21",
"guid": "33333333-3333-4333-8333-333333333333",
"name": "Edge link",
"url": "https://edge.test",
}
],
}
]
merged, added = merge_bookmarks(primary, secondary)
guids = [
node["guid"]
for root in merged["roots"].values()
for node in sync_module.walk_nodes(root)
if node.get("guid")
]
assert added == 1
assert "11111111-1111-4111-8111-111111111111" in guids
assert "22222222-2222-4222-8222-222222222222" not in guids
assert "33333333-3333-4333-8333-333333333333" not in guids
assert len(guids) == len(set(guid.casefold() for guid in guids))
for guid in guids:
uuid.UUID(guid)
def test_guid_validation_rejects_duplicates():
bookmarks = data("https://one.test", "https://two.test")
for child in bookmarks["roots"]["bookmark_bar"]["children"]:
child["guid"] = "11111111-1111-4111-8111-111111111111"
with pytest.raises(RuntimeError, match="duplicate GUID values"):
validate_unique_guids(bookmarks)
def test_export_html(tmp_path: Path):
destination = tmp_path / "bookmarks.html"
count = export_html(data("https://example.test/?a=1&b=2"), destination)
assert count == 1
assert "NETSCAPE-Bookmark-file-1" in destination.read_text()
assert "&" in destination.read_text()
def test_firefox_profile_discovery_uses_explicit_profiles_ini(tmp_path: Path):
source_profile = firefox_profile(tmp_path / "source", "https://firefox.test")
firefox_root = tmp_path / "Mozilla" / "Firefox"
relative_profile = firefox_root / "Profiles" / "default-release"
absolute_profile = tmp_path / "absolute-profile"
shutil.copytree(source_profile, relative_profile)
shutil.copytree(source_profile, absolute_profile)
profiles_ini = firefox_root / "profiles.ini"
profiles_ini.write_text(
"[Profile0]\nName=Default\nIsRelative=1\nPath=Profiles/default-release\nDefault=1\n\n"
f"[Profile1]\nName=Absolute\nIsRelative=0\nPath={absolute_profile.as_posix()}\n"
)
assert discover_firefox_profiles(profiles_ini) == [relative_profile.resolve(), absolute_profile.resolve()]
def test_macos_discovers_standard_chromium_and_firefox_profiles(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setattr(sync_module, "is_macos", lambda: True)
monkeypatch.setattr(sync_module.Path, "home", lambda: tmp_path)
application_support = tmp_path / "Library" / "Application Support"
chrome = application_support / "Google" / "Chrome" / "Default"
edge = application_support / "Microsoft Edge" / "Profile 1"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data()))
(edge / "Bookmarks").write_text(json.dumps(data()))
firefox_root = application_support / "Firefox"
firefox = firefox_root / "Profiles" / "test.default-release"
firefox.mkdir(parents=True)
(firefox / "places.sqlite").touch()
(firefox_root / "profiles.ini").write_text(
"[Profile0]\nName=default-release\nIsRelative=1\nPath=Profiles/test.default-release\nDefault=1\n"
)
assert discover_profiles("Chrome") == [chrome]
assert discover_profiles("Edge") == [edge]
assert discover_firefox_profiles() == [firefox.resolve()]
def test_firefox_import_uses_selected_duplicate_mode(tmp_path: Path, capsys: pytest.CaptureFixture[str]):
profile = firefox_profile(tmp_path, "https://EXAMPLE.test/Path/")
firefox = read_firefox_bookmarks(profile)
conservative, conservative_preview = prepare_merged_data(
data("https://example.test/path"),
data(),
duplicate_mode="conservative",
firefox=firefox,
)
aggressive, aggressive_preview = prepare_merged_data(
data("https://example.test/path"),
data(),
duplicate_mode="aggressive",
firefox=firefox,
)
assert len([node for root in conservative["roots"].values() for node in iter_urls(root)]) == 2
assert len([node for root in aggressive["roots"].values() for node in iter_urls(root)]) == 1
assert conservative_preview.firefox_count == aggressive_preview.firefox_count == 1
assert conservative_preview.firefox_enabled and aggressive_preview.firefox_enabled
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data("https://chrome.test")))
(edge / "Bookmarks").write_text(json.dumps(data("https://edge.test")))
assert main(
[
"--dry-run",
"--chrome-profile",
str(chrome),
"--edge-profile",
str(edge),
"--firefox-profile",
str(profile),
]
) == 0
assert "Firefox bookmarks: 1" in capsys.readouterr().out
def test_firefox_can_be_disabled_without_entering_firefox_code(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data("https://chrome.test")))
(edge / "Bookmarks").write_text(json.dumps(data("https://edge.test")))
monkeypatch.setattr(sync_module, "read_firefox_bookmarks", lambda _profile: pytest.fail("Firefox was read"))
result = synchronize(chrome, edge, tmp_path / "backups", write=False)
assert result.firefox_count == 0
assert not list((tmp_path / "backups").glob("Firefox_*.sqlite"))
assert "firefox_count" not in json.loads(result.manifest_path.read_text())["summary"]
assert "firefox_count" not in result.log_path.read_text()
assert result.preview.render() == prepare_merged_data(data("https://chrome.test"), data("https://edge.test"))[1].render()
def test_firefox_export_backs_up_before_write_and_adds_missing_bookmarks(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data("https://chrome.test")))
(edge / "Bookmarks").write_text(json.dumps(data("https://edge.test")))
firefox = firefox_profile(tmp_path, "https://firefox.test")
backup_dir = tmp_path / "backups"
original_checkpoint = sync_module.checkpoint_firefox_database
def assert_backup_precedes_write(path: Path):
firefox_backups = list(backup_dir.glob("Firefox_*.sqlite"))
manifests = list(backup_dir.glob("Manifest_*.json"))
assert len(firefox_backups) == len(manifests) == 1
validate_backup_manifest(manifests[0])
assert firefox_backups[0].name in {
entry["name"] for entry in json.loads(manifests[0].read_text())["files"]
}
original_checkpoint(path)
monkeypatch.setattr(sync_module, "checkpoint_firefox_database", assert_backup_precedes_write)
result = synchronize(
chrome,
edge,
backup_dir,
write=True,
firefox_profile=firefox,
firefox_export=True,
)
assert result.firefox_added == 2
assert {node["url"] for root in read_firefox_bookmarks(firefox)["roots"].values() for node in iter_urls(root)} == {
"https://chrome.test",
"https://edge.test",
"https://firefox.test",
}
firefox_backups = list(backup_dir.glob("Firefox_*.sqlite"))
assert len(firefox_backups) == 1
manifest = json.loads(result.manifest_path.read_text())
assert firefox_backups[0].name in {entry["name"] for entry in manifest["files"]}
validate_backup_manifest(result.manifest_path)
assert not list(firefox.glob("places.pending.*"))
def test_firefox_running_blocks_export_after_backups(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data("https://chrome.test")))
(edge / "Bookmarks").write_text(json.dumps(data("https://edge.test")))
firefox = firefox_profile(tmp_path, "https://firefox.test")
backup_dir = tmp_path / "backups"
monkeypatch.setattr(sync_module, "running_firefox_processes", lambda: ["firefox.exe"])
with pytest.raises(RuntimeError, match="firefox.exe"):
synchronize(
chrome,
edge,
backup_dir,
write=True,
firefox_profile=firefox,
firefox_export=True,
)
assert len(list(backup_dir.glob("Firefox_*.sqlite"))) == 1
assert len(list(backup_dir.glob("Manifest_*.json"))) == 1
def test_firefox_replacement_failure_restores_chrome_and_edge(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_file = chrome / "Bookmarks"
edge_file = edge / "Bookmarks"
chrome_original = data("https://chrome.test")
edge_original = data("https://edge.test")
chrome_file.write_text(json.dumps(chrome_original))
edge_file.write_text(json.dumps(edge_original))
firefox = firefox_profile(tmp_path, "https://firefox.test")
firefox_file = firefox / "places.sqlite"
firefox_staged = firefox / "places.pending.sqlite"
shutil.copy2(firefox_file, firefox_staged)
original_replace = sync_module.os.replace
def fail_firefox(source: Path | str, destination: Path | str):
if Path(destination) == firefox_file:
raise OSError("simulated Firefox replacement failure")
return original_replace(source, destination)
monkeypatch.setattr(sync_module.os, "replace", fail_firefox)
with pytest.raises(RuntimeError, match="Chrome and Edge were restored automatically"):
transactional_firefox_write(chrome_file, edge_file, firefox_file, data("https://merged.test"), firefox_staged)
assert json.loads(chrome_file.read_text()) == chrome_original
assert json.loads(edge_file.read_text()) == edge_original
def test_deduplicate_bookmarks_removes_normalized_urls_across_folders():
bookmarks = data("https://first.test", "https://duplicate.test/")
bookmarks["roots"]["other"]["children"] = [
{
"type": "folder",
"id": "20",
"name": "Nested",
"children": [
{"type": "url", "id": "21", "name": "Duplicate", "url": "https://duplicate.test"},
{"type": "url", "id": "22", "name": "Unique", "url": "https://unique.test"},
],
}
]
removed = deduplicate_bookmarks(bookmarks, mode="aggressive")
urls = [node["url"] for root in bookmarks["roots"].values() for node in iter_urls(root)]
assert removed == 1
assert urls == ["https://first.test", "https://duplicate.test/", "https://unique.test"]
def test_alphabetize_bookmarks_sorts_folders_first_and_recursively():
bookmarks = data()
bookmarks["roots"]["bookmark_bar"]["children"] = [
{"type": "url", "id": "10", "name": "Zulu", "url": "https://zulu.test"},
{
"type": "folder",
"id": "11",
"name": "beta folder",
"children": [
{"type": "url", "id": "12", "name": "Zulu", "url": "https://nested-zulu.test"},
{"type": "url", "id": "13", "name": "Alpha", "url": "https://nested-alpha.test"},
],
},
{"type": "url", "id": "14", "name": "alpha", "url": "https://alpha.test"},
{"type": "folder", "id": "15", "name": "Alpha folder", "children": []},
]
alphabetize_bookmarks(bookmarks)
children = bookmarks["roots"]["bookmark_bar"]["children"]
assert [child["name"] for child in children] == ["Alpha folder", "beta folder", "alpha", "Zulu"]
assert [child["name"] for child in children[1]["children"]] == ["Alpha", "Zulu"]
def test_organization_options_are_disabled_by_default():
args = parse_args([])
assert args.keep == 50
assert not args.deduplicate
assert not args.alphabetize
assert not args.force
assert not args.close_browsers
def test_conservative_url_matching_preserves_potentially_distinct_urls():
assert normalized_url(" HTTPS://Example.Test/Path?Value=One ") == "https://example.test/Path?Value=One"
assert normalized_url("https://example.test/Path") != normalized_url("https://example.test/path")
assert normalized_url("https://example.test/") != normalized_url("https://example.test")
assert normalized_url("https://example.test/Path/", mode="aggressive") == normalized_url(
"https://example.test/path",
mode="aggressive",
)
def test_sync_and_dry_run_are_mutually_exclusive():
with pytest.raises(SystemExit):
parse_args(["--sync", "--dry-run"])
def test_backup_retention_rejects_values_above_50():
with pytest.raises(SystemExit):
parse_args(["--keep", "51"])
def test_backup_retention_keeps_at_most_50_html_backups(tmp_path: Path):
for index in range(51):
path = tmp_path / f"Bookmarks_2026-08-07_12-00-00_{index:06}.html"
path.write_text(str(index))
os.utime(path, (index + 1, index + 1))
prune_backups(tmp_path, 50)
backups = sorted(tmp_path.glob("Bookmarks_*.html"))
assert len(backups) == 50
assert not (tmp_path / "Bookmarks_2026-08-07_12-00-00_000000.html").exists()
def test_backup_retention_uses_filename_timestamp_instead_of_file_mtime(tmp_path: Path):
older = tmp_path / "Chrome_2026-08-07_12-00-00_000001.json"
newer = tmp_path / "Chrome_2026-08-07_12-00-00_000002.json"
older.write_text("older")
newer.write_text("newer")
os.utime(older, (200, 200))
os.utime(newer, (100, 100))
prune_backups(tmp_path, 1)
assert not older.exists()
assert newer.exists()
def test_backup_retention_ignores_unrecognized_files_and_directories(tmp_path: Path):
unrelated = [
tmp_path / "Chrome_notes.json",
tmp_path / "Edge_backup.json",
tmp_path / "Bookmarks_readme.html",
]
for path in unrelated:
path.write_text("keep")
directory = tmp_path / "Chrome_2026-08-07_12-00-00_000001.json"
directory.mkdir()
prune_backups(tmp_path, 1)
assert all(path.exists() for path in unrelated)
assert directory.is_dir()
def test_backup_retention_prunes_old_manifests(tmp_path: Path):
older = tmp_path / "Manifest_2026-08-07_12-00-00_000001.json"
newer = tmp_path / "Manifest_2026-08-07_12-00-00_000002.json"
older.write_text("{}")
newer.write_text("{}")
prune_backups(tmp_path, 1)
assert not older.exists()
assert newer.exists()
def test_force_and_close_browsers_are_mutually_exclusive():
assert parse_args(["--close-browsers"]).close_browsers
with pytest.raises(SystemExit):
parse_args(["--force", "--close-browsers"])
def test_synchronize_backs_up_and_writes_both(tmp_path: Path):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data("https://chrome.test")))
(edge / "Bookmarks").write_text(json.dumps(data("https://edge.test")))
result = synchronize(chrome, edge, tmp_path / "backups", keep=10, write=True)
assert result.merged_count == 2
assert json.loads((chrome / "Bookmarks").read_text()) == json.loads((edge / "Bookmarks").read_text())
assert len(list((tmp_path / "backups").glob("Chrome_*.json"))) == 1
assert len(list((tmp_path / "backups").glob("Edge_*.json"))) == 1
assert result.manifest_path.exists()
assert result.html_path.exists()
def test_synchronize_applies_optional_deduplication_and_alphabetizing(tmp_path: Path):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(
json.dumps(data("https://zulu.test", "https://alpha.test/", "https://alpha.test"))
)
(edge / "Bookmarks").write_text(json.dumps(data("https://bravo.test")))
result = synchronize(
chrome,
edge,
tmp_path / "backups",
write=True,
deduplicate=True,
alphabetize=True,
duplicate_mode="aggressive",
)
written = json.loads((chrome / "Bookmarks").read_text())
bookmark_bar = written["roots"]["bookmark_bar"]["children"]
imported = written["roots"]["other"]["children"][0]["children"]
assert result.duplicates_removed == 1
assert result.alphabetized
assert [child["name"] for child in bookmark_bar] == ["https://alpha.test/", "https://zulu.test"]
assert [child["name"] for child in imported] == ["https://bravo.test"]
assert written == json.loads((edge / "Bookmarks").read_text())
def test_repeated_synchronization_preserves_unique_guids(tmp_path: Path):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_data = data("https://chrome.test")
edge_data = data("https://edge.test")
chrome_data["roots"]["bookmark_bar"]["guid"] = "00000000-0000-4000-a000-000000000002"
chrome_data["roots"]["other"]["guid"] = "00000000-0000-4000-a000-000000000003"
chrome_data["roots"]["bookmark_bar"]["children"][0]["guid"] = "11111111-1111-4111-8111-111111111111"
edge_data["roots"]["bookmark_bar"]["guid"] = "00000000-0000-4000-a000-000000000002"
edge_data["roots"]["other"]["guid"] = "00000000-0000-4000-a000-000000000003"
edge_data["roots"]["bookmark_bar"]["children"][0]["guid"] = "22222222-2222-4222-8222-222222222222"
(chrome / "Bookmarks").write_text(json.dumps(chrome_data))
(edge / "Bookmarks").write_text(json.dumps(edge_data))
synchronize(chrome, edge, tmp_path / "backups", write=True)
first = json.loads((chrome / "Bookmarks").read_text())
first_guids = [
node["guid"]
for root in first["roots"].values()
for node in sync_module.walk_nodes(root)
if node.get("guid")
]
synchronize(chrome, edge, tmp_path / "backups", write=True)
second = json.loads((chrome / "Bookmarks").read_text())
second_guids = [
node["guid"]
for root in second["roots"].values()
for node in sync_module.walk_nodes(root)
if node.get("guid")
]
assert second == json.loads((edge / "Bookmarks").read_text())
assert second_guids == first_guids
assert len(second_guids) == len(set(guid.casefold() for guid in second_guids))
assert json.dumps(second).count("Imported from other browser") == 1
def test_synchronize_first_write_failure_changes_neither_browser(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_original = json.dumps(data("https://chrome.test"))
edge_original = json.dumps(data("https://edge.test"))
chrome_path.write_text(chrome_original)
edge_path.write_text(edge_original)
real_replace = os.replace
def fail_chrome_replace(source: str | Path, destination: str | Path) -> None:
if Path(source).name.startswith("Bookmarks.pending.") and Path(destination) == chrome_path:
raise OSError("simulated Chrome replacement failure")
real_replace(source, destination)
monkeypatch.setattr(sync_module.os, "replace", fail_chrome_replace)
with pytest.raises(RuntimeError, match="Neither browser was changed"):
synchronize(chrome, edge, tmp_path / "backups", write=True)
assert chrome_path.read_text() == chrome_original
assert edge_path.read_text() == edge_original
assert not list(chrome.glob("Bookmarks.pending.*"))
assert not list(edge.glob("Bookmarks.pending.*"))
assert not list(chrome.glob("Bookmarks.rollback.*"))
def test_synchronize_second_write_failure_restores_chrome(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_original = json.dumps(data("https://chrome.test"))
edge_original = json.dumps(data("https://edge.test"))
chrome_path.write_text(chrome_original)
edge_path.write_text(edge_original)
real_replace = os.replace
def fail_edge_replace(source: str | Path, destination: str | Path) -> None:
if Path(source).name.startswith("Bookmarks.pending.") and Path(destination) == edge_path:
raise OSError("simulated Edge replacement failure")
real_replace(source, destination)
monkeypatch.setattr(sync_module.os, "replace", fail_edge_replace)
with pytest.raises(RuntimeError, match="Chrome was restored automatically"):
synchronize(chrome, edge, tmp_path / "backups", write=True)
assert chrome_path.read_text() == chrome_original
assert edge_path.read_text() == edge_original
assert not list(chrome.glob("Bookmarks.pending.*"))
assert not list(edge.glob("Bookmarks.pending.*"))
assert not list(chrome.glob("Bookmarks.rollback.*"))
def test_running_browser_processes_detects_chrome_and_edge(monkeypatch: pytest.MonkeyPatch):
output = (
'"chrome.exe","100","Console","1","10,000 K"\n'
'"unrelated.exe","200","Console","1","10,000 K"\n'
'"msedge.exe","300","Console","1","10,000 K"\n'
'"chrome.exe","400","Console","1","10,000 K"\n'
)
completed = sync_module.subprocess.CompletedProcess([], 0, stdout=output, stderr="")
monkeypatch.setattr(sync_module.subprocess, "run", lambda *args, **kwargs: completed)
assert running_browser_processes() == ["chrome.exe", "msedge.exe"]
def test_macos_process_detection_uses_executable_names(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(sync_module, "is_macos", lambda: True)
output = (
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome\n"
"/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper\n"
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge\n"
"/Applications/Firefox.app/Contents/MacOS/firefox\n"
)
completed = sync_module.subprocess.CompletedProcess([], 0, stdout=output, stderr="")
monkeypatch.setattr(sync_module.subprocess, "run", lambda *args, **kwargs: completed)
assert running_browser_processes() == ["Google Chrome", "Microsoft Edge"]
assert sync_module.running_macos_processes(("firefox",), "Firefox") == ["firefox"]
@pytest.mark.parametrize(
"processes",
[["chrome.exe"], ["msedge.exe"], ["chrome.exe", "msedge.exe"]],
ids=["chrome-running", "edge-running", "both-running"],
)
def test_synchronize_blocks_running_browsers_after_export(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
processes: list[str],
):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
backup_dir = tmp_path / "backups"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_original = json.dumps(data("https://chrome.test"))
edge_original = json.dumps(data("https://edge.test"))
chrome_path.write_text(chrome_original)
edge_path.write_text(edge_original)
monkeypatch.setattr(sync_module, "running_browser_processes", lambda: processes)
with pytest.raises(RuntimeError) as error:
synchronize(chrome, edge, backup_dir, write=True)
assert all(process in str(error.value) for process in processes)
assert chrome_path.read_text() == chrome_original
assert edge_path.read_text() == edge_original
assert len(list(backup_dir.glob("Chrome_*.json"))) == 1
assert len(list(backup_dir.glob("Edge_*.json"))) == 1
assert len(list(backup_dir.glob("Manifest_*.json"))) == 1
assert len(list(backup_dir.glob("*.html"))) == 1
def test_export_only_ignores_running_browsers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_original = json.dumps(data("https://chrome.test"))
edge_original = json.dumps(data("https://edge.test"))
chrome_path.write_text(chrome_original)
edge_path.write_text(edge_original)
def unexpected_detection() -> list[str]:
raise AssertionError("Export-only mode must not check browser processes")
monkeypatch.setattr(sync_module, "running_browser_processes", unexpected_detection)
result = synchronize(chrome, edge, tmp_path / "backups", write=False, close_browsers=True)
assert result.html_path.exists()
assert chrome_path.read_text() == chrome_original
assert edge_path.read_text() == edge_original
def test_rapid_exports_create_distinct_html_backups(tmp_path: Path):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
backup_dir = tmp_path / "backups"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
(chrome / "Bookmarks").write_text(json.dumps(data("https://chrome.test")))
(edge / "Bookmarks").write_text(json.dumps(data("https://edge.test")))
first = synchronize(chrome, edge, backup_dir, write=False)
second = synchronize(chrome, edge, backup_dir, write=False)
assert first.html_path != second.html_path
assert len(list(backup_dir.glob("Bookmarks_*.html"))) == 2
assert len(list(backup_dir.glob("Chrome_*.json"))) == 2
assert len(list(backup_dir.glob("Edge_*.json"))) == 2
assert len(list(backup_dir.glob("Manifest_*.json"))) == 2
def test_force_synchronizes_without_process_detection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_path.write_text(json.dumps(data("https://chrome.test")))
edge_path.write_text(json.dumps(data("https://edge.test")))
def unexpected_detection() -> list[str]:
raise AssertionError("Forced synchronization must bypass process detection")
monkeypatch.setattr(sync_module, "running_browser_processes", unexpected_detection)
synchronize(chrome, edge, tmp_path / "backups", write=True, force=True)
assert json.loads(chrome_path.read_text()) == json.loads(edge_path.read_text())
def test_edge_wins_uses_edge_as_primary_structure():
chrome = data("https://chrome.test")
edge = data("https://edge.test")
merged, preview = prepare_merged_data(chrome, edge, merge_strategy="edge-wins")
bookmark_bar_urls = [node["url"] for node in iter_urls(merged["roots"]["bookmark_bar"])]
imported_urls = [node["url"] for node in iter_urls(merged["roots"]["other"])]
assert bookmark_bar_urls == ["https://edge.test"]
assert imported_urls == ["https://chrome.test"]
assert merged["roots"]["other"]["children"][0]["name"] == "Imported from Chrome"
assert preview.merge_strategy == "edge-wins"
def test_merge_folders_reports_no_new_wrapper_folder():
chrome = data()
edge = data()
chrome["roots"]["bookmark_bar"]["children"] = [
{
"type": "folder",
"id": "10",
"name": "Shared",
"children": [{"type": "url", "id": "11", "name": "Chrome", "url": "https://chrome.test"}],
}
]
edge["roots"]["bookmark_bar"]["children"] = [
{
"type": "folder",
"id": "20",
"name": "shared",
"children": [{"type": "url", "id": "21", "name": "Edge", "url": "https://edge.test"}],
}
]
merged, preview = prepare_merged_data(chrome, edge, merge_strategy="merge-folders")
shared = merged["roots"]["bookmark_bar"]["children"][0]
assert [node["url"] for node in iter_urls(shared)] == ["https://chrome.test", "https://edge.test"]
assert not merged["roots"]["other"]["children"]
assert preview.folders_added == 0
def test_cli_dry_run_does_not_create_backups_or_write_profiles(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
backup_dir = tmp_path / "backups"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_original = json.dumps(data("https://chrome.test"))
edge_original = json.dumps(data("https://edge.test"))
chrome_path.write_text(chrome_original)
edge_path.write_text(edge_original)
exit_code = main(
[
"--dry-run",
"--chrome-profile",
str(chrome),
"--edge-profile",
str(edge),
"--backup-dir",
str(backup_dir),
]
)
assert exit_code == 0
assert "Strategy: chrome-wins" in capsys.readouterr().out
assert chrome_path.read_text() == chrome_original
assert edge_path.read_text() == edge_original
assert not backup_dir.exists()
def test_close_browsers_terminates_detected_processes_then_synchronizes(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_path.write_text(json.dumps(data("https://chrome.test")))
edge_path.write_text(json.dumps(data("https://edge.test")))
detections = iter([["chrome.exe", "msedge.exe"], []])
closed: list[str] = []
monkeypatch.setattr(sync_module, "running_browser_processes", lambda: next(detections))
monkeypatch.setattr(sync_module, "close_browser_processes", lambda processes: closed.extend(processes))
result = synchronize(chrome, edge, tmp_path / "backups", write=True, close_browsers=True)
assert closed == ["chrome.exe", "msedge.exe"]
assert result.closed_processes == ("chrome.exe", "msedge.exe")
assert json.loads(chrome_path.read_text()) == json.loads(edge_path.read_text())
def test_close_browsers_blocks_when_processes_remain(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
chrome = tmp_path / "Chrome" / "Default"
edge = tmp_path / "Edge" / "Default"
backup_dir = tmp_path / "backups"
chrome.mkdir(parents=True)
edge.mkdir(parents=True)
chrome_path = chrome / "Bookmarks"
edge_path = edge / "Bookmarks"
chrome_original = json.dumps(data("https://chrome.test"))
edge_original = json.dumps(data("https://edge.test"))
chrome_path.write_text(chrome_original)
edge_path.write_text(edge_original)
monkeypatch.setattr(sync_module, "running_browser_processes", lambda: ["chrome.exe"])
monkeypatch.setattr(sync_module, "close_browser_processes", lambda processes: None)
monkeypatch.setattr(sync_module, "wait_for_browsers_to_close", lambda: ["chrome.exe"])
with pytest.raises(RuntimeError, match="Could not close these browser processes: chrome.exe"):
synchronize(chrome, edge, backup_dir, write=True, close_browsers=True)
assert chrome_path.read_text() == chrome_original
assert edge_path.read_text() == edge_original
assert len(list(backup_dir.glob("Bookmarks_*.html"))) == 1
def test_close_browser_processes_uses_forceful_taskkill(monkeypatch: pytest.MonkeyPatch):
commands: list[list[str]] = []
completed = sync_module.subprocess.CompletedProcess([], 0, stdout="", stderr="")
def record_run(command, **kwargs):
commands.append(command)
return completed
monkeypatch.setattr(sync_module.subprocess, "run", record_run)
close_browser_processes(["chrome.exe", "msedge.exe", "notepad.exe"])
assert commands == [
["taskkill", "/IM", "chrome.exe", "/T", "/F"],
["taskkill", "/IM", "msedge.exe", "/T", "/F"],
]
def test_close_browser_processes_uses_exact_macos_names(monkeypatch: pytest.MonkeyPatch):