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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
require_relative "../test_helper"
require_relative "../photo_card"
require "digest"
require "fileutils"
require "pathname"
require "tmpdir"
require "hegel"
require "sequel"
require "pro_tacts/store"
require "pro_tacts/vcard"
class StoreTest < Minitest::Test
include Sentry::TestHelper
include SentryMessages
AIDEN = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Aiden\r\nUID:aiden\r\nEND:VCARD\r\n"
# The no-year birthday line as macOS writes it — the shape the
# captured picture cards carry above their PHOTO trio.
APPLE_NO_YEAR = "BDAY;X-APPLE-OMIT-YEAR=1604:1604-01-01" #: String
# UTC ISO 8601 to the millisecond, which is what SQLite is asked for.
TIMESTAMP = /\A\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z\z/
ZED = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Zed\r\nUID:znorth\r\nEND:VCARD\r\n"
# The id a macOS create mints into both the URI and the card's UID.
UUID = "AB12C345-6789-0DEF-1234-567890ABCDEF" #: String
UUID_CARD = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Aiden\r\nUID:#{UUID}\r\nEND:VCARD\r\n" #: String
# A store on disk rather than in memory: WAL, the busy timeout, and
# reopening a database are all part of what is under test.
def with_store(cards = {})
Dir.mktmpdir do |dir|
ProTacts::Store.connect(Pathname.new(dir) / "contacts.db") do |store|
cards.each do |id, card|
store.put(id, vcard(card))
end
yield store
end
end
end
# A write takes the card, not its bytes: the store is handed the
# reading its caller already made (Store#put), and the constants
# here are the bytes a client would submit.
def vcard(bytes) = ProTacts::VCard.new(bytes)
# The store's reports land in the transport this pins for the test;
# teardown clears it so nothing carries into the next one.
def setup
setup_sentry
end
def teardown
teardown_sentry_test
end
## Cards
def test_a_stored_card_comes_back_byte_for_byte
with_store({"aiden" => AIDEN}) do |store|
assert_equal AIDEN, store.contact("aiden").vcard.to_s
end
end
def test_contacts_are_listed_by_id
with_store({"znorth" => ZED, "aiden" => AIDEN}) do |store|
assert_equal %w[aiden znorth], store.contacts.map { it.id }
end
end
def test_an_empty_store_lists_no_contacts
with_store do
assert_empty it.contacts
end
end
def test_a_missing_contact_is_nil
with_store do
assert_nil it.contact("nobody")
end
end
## Pictures
# The sizing case, byte for byte: a photo card is 338 KB — most of
# it the PHOTO property's base64 folds — and the store's verbatim
# design means every fold comes back out exactly as it arrived. The
# memoji shape exercises the one physical line that runs 1,683
# octets.
def test_a_photo_card_round_trips_byte_for_byte
with_store({}) do |store|
store.put("ada", vcard(PhotoCard.photo("ada")))
assert_equal PhotoCard.photo("ada"), store.contact("ada").vcard.to_s
end
end
def test_a_memoji_card_round_trips_byte_for_byte
with_store({}) do |store|
store.put("ada", vcard(PhotoCard.memoji("ada")))
assert_equal PhotoCard.memoji("ada"), store.contact("ada").vcard.to_s
end
end
# The captured writes carry their BDAY above the picture trio, so
# the birthday's move to the model and back is the one difference a
# picture card sees: the PHOTO line, folds and all, is untouched.
def test_a_photo_card_moves_only_its_birthday
submitted = PhotoCard.photo("ada", extra: [APPLE_NO_YEAR])
expected = PhotoCard.photo("ada").sub("END:VCARD\r\n", "#{APPLE_NO_YEAR}\r\nEND:VCARD\r\n")
with_store({}) do |store|
store.put("ada", vcard(submitted))
assert_equal expected, store.contact("ada").vcard.to_s
end
end
## UIDs
# The read behind the no-uid-conflict precondition (RFC 6352 section
# 6.3.2.1).
def test_the_card_holding_a_uid_is_found_by_it
with_store({"aiden" => AIDEN}) do |store|
assert_equal "aiden", store.card_id_with_uid("aiden")
end
end
def test_a_uid_no_card_holds_finds_no_owner
with_store({"aiden" => AIDEN}) do |store|
assert_nil store.card_id_with_uid("znorth")
end
end
# The lookup runs through the index, whose name column ignores case.
def test_a_lowercase_uid_property_is_found
lowercase = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Aiden\r\nuid:aiden\r\nEND:VCARD\r\n"
with_store({"aiden" => lowercase}) do |store|
assert_equal "aiden", store.card_id_with_uid("aiden")
end
end
def test_putting_the_same_id_replaces_the_card
with_store({"aiden" => AIDEN}) do |store|
updated = AIDEN.sub("Aiden", "Aiden Smith")
store.put("aiden", vcard(updated))
assert_equal [updated], store.contacts.map { it.vcard.to_s }
end
end
def test_the_etag_comes_from_the_card
with_store({"aiden" => AIDEN}) do |store|
assert_equal ProTacts::Contact.etag_for(AIDEN), store.contact("aiden").etag
end
end
# Nothing stores an etag beside a card, so there is no second copy to
# fall out of step: change the bytes behind the store's back and the
# etag follows them, because it was never anything but their hash.
def test_an_etag_cannot_drift_from_its_card
with_store({"aiden" => AIDEN}) do |store|
refute_includes database(store)[:cards].columns, :etag
updated = AIDEN.sub("Aiden", "Aiden Smith")
database(store)[:cards].where(id: "aiden").update(vcard: updated)
assert_equal ProTacts::Contact.etag_for(updated), store.contact("aiden").etag
end
end
def test_an_id_that_could_not_be_served_is_refused
with_store do |store|
assert_raises(ArgumentError) { store.put("John Smith", vcard(AIDEN)) }
assert_empty store.contacts
end
end
def test_a_card_survives_reopening_the_database
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
ProTacts::Store.connect(path) do
it.put("aiden", vcard(AIDEN))
end
ProTacts::Store.connect(path) do |store|
assert_equal AIDEN, store.contact("aiden").vcard.to_s
end
end
end
# The store's contract is UTF-8, and the adapter enforces it: the
# sqlite3 gem encodes every bound value to UTF-8, so a binary-flagged
# string with a byte above 7 bits raises at the bind — loudly, at the
# contract violation, rather than being quietly relabelled here. The
# route is where Rack's binary becomes text (Web#write_card).
def test_binary_bytes_above_ascii_raise_at_the_bind
accented = AIDEN.sub("Aiden", "Aiden Åberg")
with_store({"aiden" => AIDEN}) do |store|
assert_raises(Encoding::UndefinedConversionError) do
store.put("aiden".b, vcard(accented.b))
end
# Pure ASCII carries no such byte, so a binary-flagged id still
# finds its row.
assert_equal AIDEN, store.contact("aiden".b).vcard.to_s
end
end
## The collection's content tag
def test_the_ctag_is_stable_across_reads
with_store({"aiden" => AIDEN}) do |store|
assert_equal store.ctag, store.ctag
end
end
def test_the_ctag_moves_with_a_cards_content
with_store({"aiden" => AIDEN}) do |store|
before = store.ctag
store.put("aiden", vcard(AIDEN.sub("Aiden", "Aiden Smith")))
refute_equal before, store.ctag
end
end
# The ctag is the change log's sequence, so it moves forward on a
# removal too. A membership hash would return to an earlier value,
# and a client that saw it would miss the change.
def test_the_ctag_moves_on_a_removal_and_never_returns
with_store({"aiden" => AIDEN}) do |store|
alone = store.ctag
store.put("znorth", vcard(ZED))
refute_equal alone, store.ctag
store.delete("znorth")
refute_equal alone, store.ctag
end
end
## The database a sync token names
def test_the_databases_id_is_the_digest_of_its_first_change
with_store({"aiden" => AIDEN}) do |store|
stamp = database(store)[:changes].where(sequence: 1).sole.fetch(:created_at)
assert_equal Digest::SHA256.hexdigest(stamp)[0, 16], store.database_id
end
end
def test_the_databases_id_survives_reopening
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
ids = Array.new(2) {
ProTacts::Store.connect(path) { |store| store.database_id }
}
assert_equal ids.first, ids.last
end
end
# The digest's entropy is the first write's moment, so two databases
# seeded alike differ by their stamps — a reseed and a restore, both
# moments apart. Two stores in one test can land inside the same
# millisecond, so this seeds a different first card: the digest then
# answers the difference whatever the clock did.
def test_two_databases_answer_different_ids
ids = [AIDEN, ZED].map { |card|
Dir.mktmpdir do |dir|
ProTacts::Store.connect(Pathname.new(dir) / "contacts.db") do |store|
store.put("first", vcard(card))
store.database_id
end
end
}
refute_equal ids.first, ids.last
end
# The empty book's edge: an empty log digests nothing, so its token
# 410s once after the first card lands — a resync of nothing.
def test_an_empty_book_answers_an_id_until_its_first_card_lands
with_store do |store|
empty = store.database_id
assert_match(/\A\h{16}\z/, empty)
store.put("aiden", vcard(AIDEN))
refute_equal empty, store.database_id
end
end
## Timestamps
def test_a_stored_card_is_stamped
with_store({"aiden" => AIDEN}) do |store|
row = card_row(store, "aiden")
assert_match TIMESTAMP, row.fetch(:created_at)
assert_equal row.fetch(:created_at), row.fetch(:updated_at)
end
end
def test_replacing_a_card_moves_updated_at_and_leaves_created_at
with_store({"aiden" => AIDEN}) do |store|
first = card_row(store, "aiden")
sleep 0.002 # the stamp has millisecond resolution
store.put("aiden", vcard(AIDEN.sub("Aiden", "Aiden Smith")))
second = card_row(store, "aiden")
assert_equal first.fetch(:created_at), second.fetch(:created_at)
assert_operator second.fetch(:updated_at), :>, first.fetch(:updated_at)
end
end
# A card written back unchanged is still a write, so it is still
# touched: updated_at is when the store last accepted a card, not when
# the bytes last differed.
def test_storing_the_same_card_again_still_touches_it
with_store({"aiden" => AIDEN}) do |store|
before = card_row(store, "aiden").fetch(:updated_at)
sleep 0.002
store.put("aiden", vcard(AIDEN))
assert_operator card_row(store, "aiden").fetch(:updated_at), :>, before
end
end
def test_contacts_by_recency_orders_newest_first
with_store({"aiden" => AIDEN}) do |store|
sleep 0.002
store.put("znorth", vcard(ZED))
assert_equal %w[znorth aiden], store.contacts_by_recency.map { it.contact.id }
end
end
# The newest few, and the ones a search found, each still newest
# first: the two narrowings the search and the dashboard read.
def test_contacts_by_recency_narrows_to_a_limit_or_to_ids
with_store({"aiden" => AIDEN}) do |store|
sleep 0.002
store.put("znorth", vcard(ZED))
assert_equal %w[znorth], store.contacts_by_recency(limit: 1).map { it.contact.id }
assert_equal %w[aiden], store.contacts_by_recency(["aiden"]).map { it.contact.id }
end
end
def test_contacts_by_recency_carries_the_stamp
with_store({"aiden" => AIDEN}) do |store|
recent = store.contacts_by_recency.fetch(0)
assert_match TIMESTAMP, recent.updated_at
assert_equal card_row(store, "aiden").fetch(:updated_at), recent.updated_at
end
end
def test_a_change_is_stamped_when_it_is_logged
with_store({"aiden" => AIDEN}) do |store|
assert_match TIMESTAMP, store.changes.last.created_at
end
end
## The change log
def test_a_put_records_the_card_and_its_etag
with_store({"aiden" => AIDEN}) do |store|
change = store.changes.last
assert_equal "aiden", change.card_id
assert_equal "put", change.action
assert_equal ProTacts::Contact.etag_for(AIDEN), change.etag
end
end
def test_every_write_is_logged_in_order
with_store({"aiden" => AIDEN}) do |store|
store.put("aiden", vcard(AIDEN.sub("Aiden", "Aiden Smith")))
store.put("znorth", vcard(ZED))
store.delete("aiden")
assert_equal [%w[aiden put], %w[aiden put], %w[znorth put], %w[aiden delete]],
store.changes.map { [it.card_id, it.action] }
assert_equal store.changes.map { it.sequence }.sort, store.changes.map { it.sequence }
end
end
## The editor's write
# save_edit is the store's own editor's path: the bytes land byte for
# byte, the change-log entry carries the composed etag a client
# would download, and the action names the side that wrote it — put
# is a client's submission, edit is the admin's save. The birthday
# passed beside the card is the model's whole new state
# (docs/plans/2026-09-07-web-birthday-editor.md), so the caller
# handing back the current one is the card-only save.
def test_an_edit_stores_the_card_and_logs_the_composed_etag
with_store({"aiden" => AIDEN_BORN}) do |store|
edited = AIDEN.sub("FN:Aiden", "FN:Aiden Smith")
contact = store.save_edit("aiden", vcard(edited), birthday: ProTacts::Birthday.new(year: 1985, month: 4, day: 12))
assert_equal edited, card_row(store, "aiden").fetch(:vcard)
composed = edited.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n")
assert_equal composed, contact.vcard.to_s
assert_equal ProTacts::Contact.etag_for(composed), contact.etag
change = store.changes.last
assert_equal %w[aiden edit], [change.card_id, change.action]
assert_equal ProTacts::Contact.etag_for(composed), change.etag
end
end
# The hazard save_edit exists for: an editor's save carries no BDAY
# line by construction, and put reads exactly that as a birthday the
# client dropped — so running the save through put would delete the
# model row and the contact's birthday with it. save_edit writes the
# birthday it is handed, so the caller passing the current model —
# what a card-only save does — keeps the row.
def test_an_edit_writing_the_current_birthday_keeps_it
with_store({"aiden" => AIDEN_BORN}) do |store|
store.save_edit("aiden", vcard(AIDEN.sub("FN:Aiden", "FN:Aiden Smith")),
birthday: ProTacts::Birthday.new(year: 1985, month: 4, day: 12))
assert_equal ProTacts::Birthday.new(year: 1985, month: 4, day: 12), birthday_row(store, "aiden")
assert_includes store.contact("aiden").vcard.to_s, "BDAY:1985-04-12"
end
end
# A birthday edit is a model write, and the served card moves with
# it: the composed BDAY lands at the new value, the stored bytes do
# not move at all, and the change-log entry carries the new composed
# etag — a client's token has to see what a device would download.
def test_an_edit_with_a_new_birthday_moves_the_served_card_only
with_store({"aiden" => AIDEN_BORN}) do |store|
stored = AIDEN_BORN.sub("BDAY:1985-04-12\r\n", "")
contact = store.save_edit("aiden", vcard(stored), birthday: ProTacts::Birthday.new(month: 4, day: 12))
assert_equal stored, card_row(store, "aiden").fetch(:vcard)
assert_includes contact.vcard.to_s, "BDAY;X-APPLE-OMIT-YEAR=1604:1604-04-12\r\n"
assert_equal ProTacts::Birthday.new(month: 4, day: 12), birthday_row(store, "aiden")
assert_equal contact.etag, store.changes.last.etag
end
end
# Nil is the row's blank-equals-absent: the model row goes, and the
# composed card with it.
def test_an_edit_with_no_birthday_deletes_the_row
with_store({"aiden" => AIDEN_BORN}) do |store|
stored = AIDEN_BORN.sub("BDAY:1985-04-12\r\n", "")
contact = store.save_edit("aiden", vcard(stored), birthday: nil)
assert_nil birthday_row(store, "aiden")
refute_includes contact.vcard.to_s, "BDAY"
end
end
def test_a_delete_leaves_a_tombstone_behind
with_store({"aiden" => AIDEN}) do |store|
assert store.delete("aiden")
assert_nil store.contact("aiden")
tombstone = store.changes.last
assert_equal %w[aiden delete], [tombstone.card_id, tombstone.action]
assert_nil tombstone.etag
end
end
def test_deleting_nothing_logs_nothing
with_store({"aiden" => AIDEN}) do |store|
before = store.changes.length
refute store.delete("nobody")
assert_equal before, store.changes.length
end
end
def test_changes_can_be_read_from_a_sequence_on
with_store({"aiden" => AIDEN}) do |store|
token = store.changes.last.sequence
store.put("znorth", vcard(ZED))
assert_equal %w[znorth], store.changes(after: token).map { it.card_id }
end
end
def test_one_cards_changes_come_back_newest_first
with_store({"aiden" => AIDEN}) do |store|
store.put("znorth", vcard(ZED))
store.delete("aiden")
log = store.changes_of("aiden")
assert_equal %w[delete put], log.map { it.action }
assert_operator log.first.sequence, :>, log.last.sequence
end
end
# The tombstone outlives the card, which is the point of a card id
# rather than a foreign key — and the history stays readable for an
# id the cards table no longer has a row for.
def test_a_deleted_cards_changes_still_read
with_store({"aiden" => AIDEN}) do |store|
store.delete("aiden")
assert_equal %w[delete put], store.changes_of("aiden").map { it.action }
end
end
## Re-id
def test_a_reid_moves_the_contact_onto_a_minted_id
with_store({UUID => UUID_CARD}) do |store|
new_id = store.reid(UUID)
assert ProTacts::ChangeId.minted?(new_id)
assert_nil store.contact(UUID)
assert_equal "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Aiden\r\nUID:#{new_id}\r\nEND:VCARD\r\n",
store.contact(new_id).vcard.to_s
end
end
def test_a_reid_moves_the_birthday_the_memberships_and_the_index
with_store({UUID => "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Aiden\r\nUID:#{UUID}\r\nBDAY:1985-04-12\r\nEND:VCARD\r\n"}) do |store|
group = store.create_group(name: "Booles")
store.add_member(group, UUID)
new_id = store.reid(UUID)
assert_equal ProTacts::Birthday.new(year: 1985, month: 4, day: 12), store.contact(new_id).birthday
assert_equal [new_id], store.group(group).members
assert_equal new_id, store.card_id_with_uid(new_id)
assert database(store)[:card_properties].where(card_id: UUID).empty?
assert_equal [new_id], store.search_keys_by_recency.keys
end
end
def test_a_reid_tells_the_log_what_a_syncing_client_must_hear
with_store({UUID => UUID_CARD}) do |store|
new_id = store.reid(UUID)
# The original put now names the new id, and the delete beside
# the new put is the pair that moves a client off the old href.
assert_equal [[new_id, "put"], [UUID, "delete"], [new_id, "put"]],
store.changes.map { [it.card_id, it.action] }
# An old token's delta: both hrefs, the old one to hear it is gone.
assert_equal [new_id, UUID], store.changes(after: 0).map { it.card_id }.uniq
assert_equal store.contact(new_id).etag, store.changes.last.etag
delete = store.changes.fetch(1)
assert_equal UUID_CARD.lines.map(&:chomp), delete.diff.removed
assert_equal %w[put put], store.changes_of(new_id).map { it.action }
end
end
def test_a_reid_gives_a_card_with_no_uid_line_one
with_store({"aiden" => "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Aiden\r\nEND:VCARD\r\n"}) do |store|
new_id = store.reid("aiden")
assert_equal "UID:#{new_id}", store.contact(new_id).vcard.to_s.lines.fetch(-2).chomp
end
end
def test_reiding_an_unknown_contact_raises
with_store({}) do |store|
assert_raises(Sequel::NoMatchingRow) { store.reid("nope") }
end
end
def test_a_first_write_adds_the_whole_card
with_store({"aiden" => AIDEN}) do |store|
diff = store.changes.last.diff
assert_equal AIDEN.lines.map(&:chomp), diff.added
assert_empty diff.removed
end
end
def test_a_writes_diff_records_the_lines_it_moved
with_store({"aiden" => AIDEN}) do |store|
store.put("aiden", vcard(AIDEN.sub("FN:Aiden", "FN:Aiden Smith")))
diff = store.changes.last.diff
assert_equal ["FN:Aiden Smith"], diff.added
assert_equal ["FN:Aiden"], diff.removed
end
end
# The tombstone is the only record left of a deleted card, the row
# being gone: what it carries away is the whole of what was there.
def test_a_tombstone_carries_the_card_away
with_store({"aiden" => AIDEN}) do |store|
store.delete("aiden")
diff = store.changes.last.diff
assert_equal AIDEN.lines.map(&:chomp), diff.removed
assert_empty diff.added
end
end
# The diff describes the card a client downloads, the same one the
# logged etag hashes — so a birthday that moved to the model, and is
# composed back in on every read, is a line the diff records adding
# even though no stored card carries it.
def test_the_diff_is_of_the_card_as_served
with_store({"aiden" => AIDEN}) do |store|
store.put("aiden", vcard(AIDEN_BORN))
assert_equal ["BDAY:1985-04-12"], store.changes.last.diff.added
end
end
# A group's line is in the served card either side of a member's
# write, so it cancels: what a member's entry records is what the
# member's write did, not what it inherited while doing it.
def test_a_lent_line_is_no_part_of_a_members_diff
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub("FN:Aiden", "FN:Aiden Smith")))
diff = store.changes.last.diff
assert_equal ["FN:Aiden Smith"], diff.added
assert_equal ["FN:Aiden"], diff.removed
end
end
def test_an_unknown_cards_changes_are_empty
with_store({"aiden" => AIDEN}) do |store|
assert_empty store.changes_of("nobody")
end
end
# A sequence number is never reused, so a client holding an old token
# cannot be handed changes numbered below ones it has already seen.
def test_sequence_numbers_are_not_reused_after_a_delete
with_store({"aiden" => AIDEN}) do |store|
highest = store.changes.last.sequence
store.delete("aiden")
store.put("znorth", vcard(ZED))
assert_operator store.changes.last.sequence, :>, highest
end
end
# The whole reason the cards and the log are one database. Both tests
# below fail part way through a write that has already put the card
# row in: if the transaction were dropped, the card would survive and a
# client's sync token would point at a history that never happened.
#
# Refusing a bad id does not test this, however it is named:
# Contact's constructor raises before the transaction opens, so
# nothing was ever attempted.
def test_a_write_that_fails_at_the_log_leaves_no_card
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
FailingLog.connect(path) do |store|
assert_raises(RuntimeError) { store.put("aiden", vcard(AIDEN)) }
end
# Reopened, so this is the file talking and not a cache.
ProTacts::Store.connect(path) do |store|
assert_empty store.contacts
assert_empty store.changes
end
end
end
# A put joins a transaction already open — the group fan-out this
# design needs — so a rollback out there has to take the card, its log
# entry and its index rows with it.
def test_a_put_inside_a_failed_transaction_is_rolled_back_whole
with_store do |store|
assert_raises(RuntimeError) do
database(store).transaction do
store.put("aiden", vcard(AIDEN))
raise "the fan-out failed"
end
end
assert_empty store.contacts
assert_empty store.changes
assert_empty indexed_names(store, "aiden")
end
end
## The index
def test_a_card_is_indexed_by_property
with_store({"aiden" => AIDEN}) do |store|
assert_equal %w[BEGIN VERSION FN UID END], indexed_names(store, "aiden")
end
end
def test_parameters_are_indexed_with_their_property
with_store({"aiden" => AIDEN.sub("FN:Aiden", "TEL;TYPE=work,voice:+1-555-1234\r\nFN:Aiden")}) do |store|
assert_equal [%w[TYPE work], %w[TYPE voice]], indexed_parameters(store, "aiden", "TEL")
end
end
# A card's own values, folded, and nothing its groups lend: a lent
# address is matched as the group's (Admin::Search::Key).
def test_a_card_is_keyed_for_the_search_off_its_own_lines
card = AIDEN.sub("FN:Aiden\r\n", "FN:Áiden\r\nNICKNAME:Ade\r\nTEL:+1 (555) 123-4567\r\nNOTE:Plays chess\r\n")
with_store({"aiden" => card}) do |store|
group = store.create_group(name: "Booles")
store.add_member(group, "aiden")
store.set_group_lines(group, [HOUSEHOLD_ADDRESS])
key = store.search_keys_by_recency.fetch("aiden")
assert_equal ["aiden", "ade", "plays chess"], key.texts
assert_equal ["15551234567"], key.phones
assert_equal ["aiden", "ade"], key.names
end
end
def test_keys_are_listed_newest_first
with_store({"aiden" => AIDEN}) do |store|
sleep 0.002
store.put("znorth", vcard(ZED))
assert_equal %w[znorth aiden], store.search_keys_by_recency.keys
end
end
def test_replacing_a_card_replaces_its_index_rows
with_store({"aiden" => AIDEN}) do |store|
store.put("aiden", vcard(AIDEN.sub("FN:Aiden\r\n", "")))
assert_equal %w[BEGIN VERSION UID END], indexed_names(store, "aiden")
end
end
def test_deleting_a_card_takes_its_index_rows_with_it
with_store({"aiden" => AIDEN}) do |store|
store.delete("aiden")
assert_empty indexed_names(store, "aiden")
assert_empty indexed_parameters(store, "aiden", "FN")
end
end
# The index is derived and nothing else is authoritative in it, so
# throwing it away and deriving it again from the cards alone has to
# land in exactly the same place.
def test_the_index_can_be_rebuilt_from_the_cards_alone
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
before = index_rows(store)
refute_empty before
wreck_the_index(store)
refute_equal before, index_rows(store)
store.rebuild_index
assert_equal before, index_rows(store)
end
end
# Rows, not contacts, so that a rebuild which stamped updated_at would
# be caught: the index is derived, and deriving it again is not a write
# to the card it came from.
def test_rebuilding_the_index_leaves_the_cards_and_the_log_alone
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
cards = database(store)[:cards].order(:id).all
changes = store.changes
sleep 0.002
store.rebuild_index
assert_equal cards, database(store)[:cards].order(:id).all
assert_equal changes, store.changes
end
end
## Cards that will not parse
# Fail open: the bytes are what gets served, so a card the parser
# cannot read is still a contact. Its unreadable lines contribute
# nothing to the index and cost the index nothing else.
def test_an_unparseable_card_is_still_stored_and_served
with_store({"broken" => "this is not a vCard\r\n"}) do |store|
assert_equal "this is not a vCard\r\n", store.contact("broken").vcard.to_s
assert_empty indexed_names(store, "broken")
end
end
# The collection's half of fail open: a card the parser cannot read
# costs the listing nothing, every other contact serves beside it,
# and the ctag moves on its arrival — the broken card is served from
# its bytes like any other, so the tag counts it.
def test_every_other_contact_serves_beside_one_unparseable_card
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
good_cards = store.ctag
store.put("broken", vcard("this is not a vCard\r\n"))
assert_equal %w[aiden broken znorth], store.contacts.map { it.id }
assert_equal AIDEN, store.contact("aiden").vcard.to_s
assert_equal ZED, store.contact("znorth").vcard.to_s
refute_equal good_cards, store.ctag
end
end
# The index is what this server understood, not an all-or-nothing
# verdict on the card.
def test_a_card_is_indexed_by_the_lines_that_read
unreadable = AIDEN.sub("FN:Aiden\r\n", "FN:Aiden\r\nTEL;HOME:+1-555-1234\r\n")
with_store({"aiden" => unreadable}) do |store|
assert_equal %w[BEGIN VERSION FN UID END], indexed_names(store, "aiden")
assert_equal unreadable, store.contact("aiden").vcard.to_s
end
end
## Birthdays
AIDEN_BORN = AIDEN.sub("FN:Aiden\r\n", "FN:Aiden\r\nBDAY:1985-04-12\r\n")
# The stored card carries no BDAY — a partial date has no vCard 3.0
# spelling — and every read composes the birthday back in, so the
# served card is the submitted one with the line back where compose
# puts it.
def test_a_birthday_is_stored_beside_the_card_and_served_within_it
with_store({"aiden" => AIDEN_BORN}) do |store|
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n"), store.contact("aiden").vcard.to_s
end
end
# The composed card is what an etag describes, on a read and in the
# change log alike, so a client's If-Match and its sync token both
# talk about the card it downloads.
def test_the_etag_and_the_log_describe_the_composed_card
with_store({"aiden" => AIDEN_BORN}) do |store|
composed = AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n")
assert_equal ProTacts::Contact.etag_for(composed), store.contact("aiden").etag
assert_equal ProTacts::Contact.etag_for(composed), store.changes.last.etag
end
end
# The ctag follows the composed card too: a birthday moved is a
# change a client must see, even when the stored bytes did not move.
def test_the_ctag_moves_with_a_birthday_alone
with_store({"aiden" => AIDEN}) do |store|
before = store.ctag
store.put("aiden", vcard(AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n")))
refute_equal before, store.ctag
end
end
# iOS writes every birthday with VALUE=date spelled out
# (docs/apple-contacts.md), and the line moves into the model like a
# bare one, served back in the model's spelling.
def test_a_birthday_spelling_out_value_date_moves_into_the_model
with_store({"aiden" => AIDEN}) do |store|
store.put("aiden", vcard(AIDEN.sub("END:VCARD\r\n", "BDAY;value=date:1985-04-12\r\nEND:VCARD\r\n")))
assert_equal ProTacts::Birthday.new(year: 1985, month: 4, day: 12), birthday_row(store, "aiden")
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n"), store.contact("aiden").vcard.to_s
end
end
def test_an_apple_no_year_birthday_round_trips
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "BDAY;X-APPLE-OMIT-YEAR=1604:1604-04-12\r\nEND:VCARD\r\n")}) do |store|
assert_equal ProTacts::Birthday.new(month: 4, day: 12), birthday_row(store, "aiden")
end
end
# A submitted card with no BDAY deletes the birthday — the client
# was served one and sent its card back without it, which on a
# read-modify-write client is the user removing it.
def test_a_card_put_back_without_its_served_birthday_loses_it
with_store({"aiden" => AIDEN_BORN}) do |store|
store.put("aiden", vcard(AIDEN))
assert_nil birthday_row(store, "aiden")
assert_equal AIDEN, store.contact("aiden").vcard.to_s
end
end
# A birthday no client can see — year alone, month alone, day alone,
# year and month — survives a round trip the client never saw a
# birthday in.
def test_a_birthday_no_client_can_see_survives_a_card_without_one
with_store({"aiden" => AIDEN}) do |store|
database(store)[:birthdays].insert(card_id: "aiden", year: 1985)
store.put("aiden", vcard(AIDEN.sub("FN:Aiden", "FN:Aiden Smith")))
assert_equal ProTacts::Birthday.new(year: 1985), birthday_row(store, "aiden")
assert_equal AIDEN.sub("FN:Aiden", "FN:Aiden Smith"), store.contact("aiden").vcard.to_s
end
end
# The card's own line speaks for itself, and nothing composes a
# second one beside it. A fold travels with its line, byte for byte.
def test_an_unmodeled_bday_stays_in_the_card_and_empties_the_model
["BDAY:1985-13", "BDAY:1985-\r\n 13\r\n", "BDAY:1985-04-12\r\nBDAY:1986-04-12\r\n"].each do |bday|
unmodeled = AIDEN.sub("END:VCARD\r\n", "#{bday}END:VCARD\r\n")
with_store({"aiden" => AIDEN_BORN}) do |store|
store.put("aiden", vcard(unmodeled))
assert_equal unmodeled, store.contact("aiden").vcard.to_s, bday
assert_nil birthday_row(store, "aiden"), bday
end
end
end
# A bare CR packs two content lines into one physical line, a shape
# the parser is built to assume macOS never sends, so the line is
# never read. The store says nothing about it: a value it never read
# is not a value it failed to recognize, and reporting it as an odd
# BDAY would send anyone reading the message looking in the wrong
# place. WebTest holds the report worth making, at the arrival.
def test_a_bday_sharing_its_line_arrives_whole_and_unreported
shared = AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\rNOTE:b\r\nEND:VCARD\r\n")
with_store({"aiden" => AIDEN_BORN}) do |store|
store.put("aiden", vcard(shared))
messages = sentry_messages
assert_equal shared, store.contact("aiden").vcard.to_s
assert_nil birthday_row(store, "aiden")
assert_empty messages
end
end
# The four shapes no client displays go into the model and are never
# sent, so a card sent back without them has not deleted them.
def test_a_birthday_no_client_is_sent_survives_a_rewrite
{
"BDAY:1985-04" => ProTacts::Birthday.new(year: 1985, month: 4),
"BDAY:1985" => ProTacts::Birthday.new(year: 1985),
"BDAY:--04" => ProTacts::Birthday.new(month: 4),
"BDAY:---12" => ProTacts::Birthday.new(day: 12),
}.each do |line, birthday|
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "#{line}\r\nEND:VCARD\r\n")}) do |store|
assert_equal AIDEN, store.contact("aiden").vcard.to_s, line
edited = AIDEN.sub("FN:Aiden", "FN:Aiden Smith")
store.put("aiden", vcard(edited))
assert_equal edited, store.contact("aiden").vcard.to_s, line
assert_equal birthday, birthday_row(store, "aiden"), line
end
end
end
# A month and day goes out as the sentinel whatever spelling it came
# in, including the extended one iOS misreads as a year-2 date and the
# parameterless 1604 iOS writes back.
def test_a_month_and_day_in_any_spelling_goes_out_as_the_sentinel
["BDAY:--11-27", "BDAY:--1127", "BDAY;value=date:1604-11-27"].each do |line|
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "#{line}\r\nEND:VCARD\r\n")}) do |store|
assert_equal ProTacts::Birthday.new(month: 11, day: 27), birthday_row(store, "aiden"), line
assert_equal AIDEN.sub("END:VCARD\r\n", "BDAY;X-APPLE-OMIT-YEAR=1604:1604-11-27\r\nEND:VCARD\r\n"),
store.contact("aiden").vcard.to_s, line
end
end
end
# --0412 goes out as the sentinel, so a rewrite without it removed a
# birthday the client was sent, and the deletion is honored.
def test_a_birthday_a_client_renders_is_deleted_by_a_rewrite_without_it
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "BDAY:--0412\r\nEND:VCARD\r\n")}) do |store|
store.put("aiden", vcard(AIDEN))
assert_equal AIDEN, store.contact("aiden").vcard.to_s
assert_nil birthday_row(store, "aiden")
end
end
# A shared line never reaches the model, so it stays in the stored
# card, and a rewrite dropping it is reported rather than silent.
def test_a_rewrite_dropping_a_shared_bday_line_is_reported
shared = AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04\rNOTE:b\r\nEND:VCARD\r\n")
edited = AIDEN.sub("FN:Aiden", "FN:Aiden Smith")
with_store({"aiden" => shared}) do |store|
store.put("aiden", vcard(edited))
messages = sentry_messages
assert_equal edited, store.contact("aiden").vcard.to_s
assert_equal 1, messages.length
end
end
# A submission carrying any BDAY replaces what was there, a birthday
# no client was sent included: PUT is a whole-card replace.
def test_a_submitted_birthday_replaces_one_no_client_was_sent
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04\r\nEND:VCARD\r\n")}) do |store|
born = AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n")
store.put("aiden", vcard(born))
assert_equal ProTacts::Birthday.new(year: 1985, month: 4, day: 12), birthday_row(store, "aiden")
assert_equal born, store.contact("aiden").vcard.to_s
end
end
# The loss report, the rewrite's half of the arrival one: a stored
# BDAY the model did not take is about to be dropped, and nobody
# would know.
def test_a_rewrite_dropping_an_unrecognized_bday_is_reported
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "BDAY:1985-13\r\nEND:VCARD\r\n")}) do |store|
# The seed's own arrival report is not this test's subject.
clear_sentry_events
store.put("aiden", vcard(AIDEN.sub("FN:Aiden", "FN:Aiden Smith")))
messages = sentry_messages
assert_equal 1, messages.length
assert_match(/BDAY/, messages.fetch(0))
end
end
# A rewrite over birthdays the model holds has no line to drop.
def test_a_rewrite_over_known_bdays_stays_quiet
["BDAY:--0412", "BDAY:1985-04"].each do |line|
with_store({"aiden" => AIDEN.sub("END:VCARD\r\n", "#{line}\r\nEND:VCARD\r\n")}) do |store|
store.put("aiden", vcard(AIDEN.sub("FN:Aiden", "FN:Aiden Smith")))
assert_empty sentry_messages, line
end
end
end
# Both ways a BDAY misses the reader, and the one that is neither: a
# component out of range (month 13, day 32), a spelling its grammar
# does not take (undashed, unpadded — see Birthday's patterns), and a
# BDAY the card hangs off a property group. Why it reports rather
# than stores quietly is EditedContact#report_unrecognized_bday_line.
def test_an_unrecognized_bday_arriving_is_reported
["BDAY:1985-13", "BDAY:--0432", "BDAY:19850412", "BDAY:1985-4", "item1.BDAY:1985-04-12"].each do |line|
with_store({}) do |store|
clear_sentry_events
store.put("aiden", vcard(AIDEN.sub("END:VCARD\r\n", "#{line}\r\nEND:VCARD\r\n")))
assert_equal 1, sentry_messages.length, line
end
end
end
def test_a_bday_the_server_knows_arrives_quietly
["BDAY:1985-04-12", "BDAY:1985-04-12T23:10:00Z", "BDAY;X-APPLE-OMIT-YEAR=1604:1604-04-12",
"BDAY:--0412", "BDAY:--04-12", "BDAY:1985-04", "BDAY:1985", "BDAY:--04", "BDAY:---12",
"BDAY;value=date:1985-04-12"].each do |line|
with_store({}) do |store|
store.put("aiden", vcard(AIDEN.sub("END:VCARD\r\n", "#{line}\r\nEND:VCARD\r\n")))
assert_empty sentry_messages, line
end
end
end
# A contact has one birthday, so several BDAY lines are reported even
# when each would read on its own.
def test_several_bday_lines_are_reported_whatever_they_hold
with_store({}) do |store|
store.put("aiden", vcard(AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nBDAY:1986-04-12\r\nEND:VCARD\r\n")))
messages = sentry_messages
assert_equal 1, messages.length
assert_match "2 BDAY lines", messages.fetch(0)
end
end
## The change log
def test_a_stored_card_is_never_indexed_with_a_bday
with_store({"aiden" => AIDEN_BORN}) do |store|
assert_equal %w[BEGIN VERSION FN UID END], indexed_names(store, "aiden")
end
end
def test_deleting_a_card_takes_its_birthday_with_it
with_store({"aiden" => AIDEN_BORN}) do |store|
store.delete("aiden")
assert_empty database(store)[:birthdays].all
end
end
## Upcoming birthdays
NO_YEAR = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:No Year\r\n" \
"BDAY;X-APPLE-OMIT-YEAR=1604:1604-06-15\r\nUID:noyear\r\nEND:VCARD\r\n"
# Arrival order is the coming year's, not the calendar's: a
# birthday already passed this year wraps onto next year and sorts
# after one still ahead, and one already here today is first.
def test_upcoming_birthdays_arrive_in_order_across_the_year_wrap
september = Date.new(2026, 9, 3)
ahead = AIDEN.sub("FN:Aiden\r\n", "FN:Aiden\r\nBDAY:1985-09-04\r\n")
passed = ZED.sub("FN:Zed\r\n", "FN:Zed\r\nBDAY:1990-03-15\r\n")
today = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Today\r\nBDAY:2000-09-03\r\nUID:today\r\nEND:VCARD\r\n"
with_store({"aiden" => ahead, "znorth" => passed, "today" => today}) do |store|
upcoming = store.upcoming_birthdays(10, today: september)
assert_equal %w[today aiden znorth], upcoming.map { it.contact.id }
assert_equal Date.new(2026, 9, 3), upcoming.fetch(0).occurs_on
assert_equal Date.new(2026, 9, 4), upcoming.fetch(1).occurs_on
assert_equal Date.new(2027, 3, 15), upcoming.fetch(2).occurs_on
end
end
def test_upcoming_birthdays_take_the_first_n
september = Date.new(2026, 9, 3)
cards = (1..3).to_h { |n|
["c#{n}", "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Contact #{n}\r\nBDAY:1990-09-0#{n + 4}\r\nUID:c#{n}\r\nEND:VCARD\r\n"]
}
with_store(cards) do |store|
assert_equal %w[c1 c2], store.upcoming_birthdays(2, today: september).map { it.contact.id }
end
end
# The age is the view's question, not the query's.
def test_a_birthday_without_a_year_is_upcoming
september = Date.new(2026, 9, 3)
with_store({"noyear" => NO_YEAR}) do |store|
upcoming = store.upcoming_birthdays(10, today: september)
assert_equal 1, upcoming.length
assert_equal "noyear", upcoming.fetch(0).contact.id
assert_equal Date.new(2027, 6, 15), upcoming.fetch(0).occurs_on
end
end
def test_birthdays_on_no_calendar_day_are_left_out
september = Date.new(2026, 9, 3)
with_store({"aiden" => AIDEN_BORN, "noyear" => NO_YEAR, "znorth" => ZED}) do |store|
database(store)[:birthdays].where(card_id: "noyear").update(year: 1990, month: 6, day: nil)
database(store)[:birthdays].insert(card_id: "znorth", year: 1990)
assert_equal %w[aiden], store.upcoming_birthdays(10, today: september).map { it.contact.id }
end
end
# The transaction the whole design turns on, birthdays included: a
# birthday must not survive a write whose log entry failed.
def test_a_failed_birthday_write_leaves_no_birthday
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
FailingLog.connect(path) do |store|
assert_raises(RuntimeError) { store.put("aiden", vcard(AIDEN_BORN)) }
end
ProTacts::Store.connect(path) do |store|
assert_empty store.contacts
assert_empty database(store)[:birthdays].all
end
end
end
## Groups
HOUSEHOLD_ADDRESS = "ADR;TYPE=home:;;7 Calculus Close;London;England;NW1 1AB;United Kingdom" #: String
HOUSEHOLD_NOTE = "NOTE:Gate code 1854." #: String
# What a group lends now, in the order it lends it — the rows a
# propagated edit rewrites.
def lent_lines(store, group)
database(store)[:group_properties].where(group_id: group).order(:position).map { it[:line] }
end
# A member's served card is the stored one with the group's lines
# composed in, and the birthday composed after them — every read,
# single or listed, hands out the same composed card. A lent note
# composes as a section of the one NOTE, headed by the group's
# label — its id, this group being nameless
# (docs/plans/2026-09-25-one-note-per-contact.md).
def test_a_member_serves_the_group_lines_composed_in
born = AIDEN.sub("FN:Aiden\r\n", "FN:Aiden\r\nBDAY:1985-12-10\r\n")
with_store({"aiden" => born, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS, HOUSEHOLD_NOTE])
composed = AIDEN.sub(
"END:VCARD\r\n",
"#{HOUSEHOLD_ADDRESS}\r\nNOTE:Shared · #{id}:\\nGate code 1854.\r\nBDAY:1985-12-10\r\nEND:VCARD\r\n",
)
assert_equal composed, store.contact("aiden").vcard.to_s
assert_equal composed, store.contacts.find { it.id == "aiden" }.vcard.to_s
listed = store.contacts_by_recency.find { it.contact.id == "aiden" }.contact
assert_equal store.contact("aiden").addresses.map(&:street), listed.addresses.map(&:street)
assert_equal store.contact("aiden").notes.map(&:value), listed.notes.map(&:value)
end
end
# A listed contact is the index's reading of the card, and reads the
# same as the contact itself does: names, a labelled phone, quoted
# and repeated parameters, an email, the birthday, and whether there
# is a picture, without the picture's payload.
def test_a_listed_contact_reads_as_the_contact_does
card = PhotoCard.photo("aiden", bytes: 64).sub(
"END:VCARD\r\n",
"N:North;Aiden;;;\r\nNICKNAME:Ade\r\nORG:Calculus\\, Ltd\r\n" \
"item1.TEL;TYPE=CELL;TYPE=pref:+44 20 7946 0000\r\nitem1.X-ABLabel:_$!<Mobile>!$_\r\n" \
"EMAIL;TYPE=\"work,internet\":a@example.com\r\nBDAY:1985-12-10\r\nEND:VCARD\r\n",
)
with_store({"aiden" => card, "znorth" => ZED}) do |store|
contact = store.contact("aiden")
listed = store.listed_contacts(["aiden"]).fetch(0)
%i[id name name_components nickname organization company? birthday photo?].each do |reading|
assert_equal contact.public_send(reading), listed.public_send(reading), reading
end
assert_equal contact.phones.map { [it.value, it.label, it.types] }, listed.phones.map { [it.value, it.label, it.types] }
assert_equal contact.emails.map { [it.value, it.types] }, listed.emails.map { [it.value, it.types] }
assert_predicate listed, :photo?
refute_predicate store.listed_contacts(["znorth"]).fetch(0), :photo?
assert_equal %w[aiden znorth], store.listed_contacts.map(&:id)
end
end
# A contact in no group serves the stored bytes with the etag it
# always had — the byte-identity the whole fixture replay stands on.
def test_a_contact_in_no_group_serves_unchanged_bytes_and_etag
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
before = store.contact("aiden")
FixtureData.seed_group(store, members: ["znorth"], lines: [HOUSEHOLD_ADDRESS])
after = store.contact("aiden")
assert_equal AIDEN, after.vcard.to_s
assert_equal before.etag, after.etag
end
end
# Membership is the only lever: a contact that leaves the group
# serves its own bytes again, at the etag it had before any of the
# group's lines reached it.
def test_leaving_a_group_restores_the_stored_bytes
with_store({"aiden" => AIDEN}) do |store|
before = store.contact("aiden").etag
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
refute_equal before, store.contact("aiden").etag
database(store)[:group_members].where(card_id: "aiden").delete
assert_equal AIDEN, store.contact("aiden").vcard.to_s
assert_equal before, store.contact("aiden").etag
end
end
# Two groups' sections compose in group-id order, then position —
# the order is a fact of the schema, not of whichever join SQLite
# returns first, so the composed bytes never move between reads. The
# ids are minted rather than chosen, so the expectation is sorted by
# them: which group leads is the ids' business, that the id decides
# it rather than the creation order is this test's. Both groups are
# nameless, so each section is headed by the id that ordered it.
def test_two_groups_compose_in_a_fixed_order
with_store({"aiden" => AIDEN}) do |store|
lent = [HOUSEHOLD_NOTE, "NOTE:Second note."].to_h { |line|
[FixtureData.seed_group(store, members: ["aiden"], lines: [line]), line]
}
first, second = lent.keys.sort
text = -> gid { lent.fetch(gid).split(":", 2).fetch(1) }
value = "Shared · #{first}:\n#{text.(first)}\n\nShared · #{second}:\n#{text.(second)}"
composed = AIDEN.sub(
"END:VCARD\r\n",
"NOTE:#{ProTacts::VCard.escape(value)}\r\nEND:VCARD\r\n",
)
assert_equal composed, store.contact("aiden").vcard.to_s
end
end
# The index projects the stored cards, and no stored card carries an
# inherited line: the group's address is in the served card and in
# no index row, and rebuilding the index leaves it that way.
def test_the_index_holds_nothing_the_group_composes_in
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
assert_includes store.contact("aiden").vcard.to_s, HOUSEHOLD_ADDRESS
assert_includes indexed_names(store, "aiden"), "FN"
refute_includes indexed_names(store, "aiden"), "ADR"
store.rebuild_index
refute_includes indexed_names(store, "aiden"), "ADR"
end
end
# A PUT and an editor's save both hand back the composed contact —
# the etag each records in the change log is the composed card's, so
# a client's token describes what there is to download. The first
# entry is with_store's own seed put, logged before the group existed.
#
# The PUT submits the served card, as a client does: a submission
# missing the lent line is that member deleting it, which is a
# different test's subject.
def test_writes_log_the_composed_etag_for_a_member
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
put = store.put("aiden", vcard(store.contact("aiden").vcard.to_s))
edit = store.save_edit("aiden", vcard(AIDEN), birthday: nil)
logged = database(store)[:changes].where(card_id: "aiden").order(:sequence).all
assert_equal [put.etag, edit.etag], logged.last(2).map { it[:etag] }
assert_includes put.vcard.to_s, HOUSEHOLD_ADDRESS
end
end
# The note-bearing member's round trip, the one the one-note shape
# exists for: a client PUTs back the served card and the member's
# own note is what is stored — the group's section gone, nothing
# propagated, the composed etag standing — so a client that changed
# nothing hears of nothing (docs/plans/2026-09-25-one-note-per-
# contact.md).
def test_a_note_bearing_members_served_card_round_trips
stored = AIDEN.sub("END:VCARD\r\n", "NOTE:Own note.\r\nEND:VCARD\r\n")
with_store({"aiden" => stored}) do |store|
id = FixtureData.seed_group(store, name: "Booles", members: ["aiden"], lines: [HOUSEHOLD_NOTE])
served = store.contact("aiden")
put = store.put("aiden", vcard(served.vcard.to_s))
change = store.changes_of("aiden").first
assert_includes put.vcard.to_s, "NOTE:Own note.\\n\\nShared · Booles:\\nGate code 1854.\r\n"
assert_equal stored, put.stored.to_s
assert_equal [HOUSEHOLD_NOTE], store.group(id).lines
assert_equal served.etag, change.etag
assert_empty change.diff.added
assert_empty change.diff.removed
end
end
# Every inherited line carries the group lending it, whole, on the
# single read and on the listing read that composes a whole
# collection — a screen tags a row as the household's from either.
def test_an_inherited_line_carries_its_group
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, name: "Household", members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
listed = store.contacts.find { it.id == "aiden" }
[store.contact("aiden"), listed].each do |contact|
assert_equal store.group(id), contact.addresses.fetch(0).lent_by
end
end
end
# Membership is a read of its own: every group a contact is in,
# under the label a screen shows it by — the name, or the id where
# there is no name — ordered by id so a rename never moves a tag. A
# group that lends nothing is a membership like any other; it is the
# inherited reads, not this one, that have nothing of it to carry.
def test_the_groups_a_contact_is_in_are_read_with_their_labels
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
named = FixtureData.seed_group(store, name: "Booles", members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
nameless = FixtureData.seed_group(store, members: ["aiden"], lines: [])
FixtureData.seed_group(store, name: "Neighbours", members: [], lines: [HOUSEHOLD_NOTE])
expected = {named => "Booles", nameless => nameless}.sort.map { it.last }
assert_equal expected, store.groups_of("aiden").map(&:label)
assert_empty store.groups_of("znorth")
end
end
def test_a_group_read_with_its_members_lists_them_in_order
with_store({"znorth" => ZED, "aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, name: "Booles", members: ["znorth", "aiden"])
assert_equal [%w[aiden znorth]], store.listed_groups_of("znorth", first: 5).map { it.first_members.map(&:id) }
assert_equal [%w[aiden znorth]], store.all_listed_groups(store.listed_contacts, first: 5).map { it.first_members.map(&:id) }
assert_instance_of ProTacts::Group, store.groups_of("znorth").fetch(0)
assert_instance_of ProTacts::Group, store.all_groups.fetch(0)
end
end
# A tag lists only a group's first few, the contact's read taking
# them off the sort keys and the whole list's off the listing it
# sorted: the two agree with each other and with Contact#<=> — a
# family name first, FN for a card with no N, the id behind both —
# and every member is still counted.
def test_a_group_read_for_a_tag_lists_its_first_few_in_a_lists_order
cards = {
"znorth" => ZED,
"aiden" => AIDEN,
"boole" => "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Boole;Mary;;;\r\nFN:Mary Boole\r\nUID:boole\r\nEND:VCARD\r\n",
"boole2" => "BEGIN:VCARD\r\nVERSION:3.0\r\nN:boole;George;;;\r\nFN:George Boole\r\nUID:boole2\r\nEND:VCARD\r\n",
}
with_store(cards) do |store|
FixtureData.seed_group(store, name: "Everyone", members: cards.keys)
expected = store.listed_contacts.sort.first(3).map(&:id)
assert_equal %w[aiden boole boole2], expected
[store.listed_groups_of("znorth", first: 3), store.all_listed_groups(store.listed_contacts, first: 3)].each do |groups|
assert_equal 1, groups.length
group = groups.fetch(0)
assert_equal expected, group.first_members.map(&:id)
assert_equal 4, group.members.length
end
end
end
# A card's sort key follows its name: a rename moves it in a tag's
# first few as it moves in a list.
def test_a_rename_moves_a_card_among_a_groups_first_few
with_store({"znorth" => ZED, "aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, name: "Booles", members: %w[znorth aiden])
store.put("znorth", ProTacts::VCard.new(ZED.sub("FN:Zed", "FN:Abe")))
assert_equal %w[znorth], store.listed_groups_of("aiden", first: 1).fetch(0).first_members.map(&:id)
end
end
def test_a_group_inspects_to_its_label_and_member_count
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, name: "Household", members: %w[znorth aiden])
nameless = store.create_group
assert_equal %(#<ProTacts::Group id="#{id}" label="Household" members=2>), store.group(id).inspect
assert_equal %(#<ProTacts::Group id="#{nameless}" label="#{nameless}" members=0>), store.group(nameless).inspect
end
end
# The schema is the gate on what a group may hold
# (Store#set_group_lines), so what it admits is worth pinning: an
# address or a note, bare or parameterized, in whatever case the
# author spelled the name. Everything else is refused — a phone or an
# email reaches a person rather than a household, and a grouped ADR is
# half of a labeled property whose other half no group may hold.
def test_a_group_holds_only_addresses_and_notes
with_store({"aiden" => AIDEN}) do |store|
properties = database(store)[:group_properties]
group_id = store.create_group(name: "Household")
admitted = [HOUSEHOLD_ADDRESS, HOUSEHOLD_NOTE, "ADR:;;1 Long Road;;;;", "note:lowercase is the same name"]
admitted.each.with_index do |line, position|
properties.insert(group_id:, position:, line:)
end
assert_equal admitted, properties.order(:position).map { it.fetch(:line) }
["TEL;TYPE=home:+44 20 5555 0100", "EMAIL:boole@example.com", "item1.ADR:;;1 Long Road;;;;"].each do |line|
assert_raises(Sequel::ConstraintViolation) do
properties.insert(group_id:, position: admitted.size, line:)
end
end
end
end
# An id is minted, never chosen, in the shape jj spells a change id:
# four letters from k to z, drawn independently, so that two creates
# in a row are two groups.
def test_a_created_group_takes_a_change_id
with_store do |store|
ids = Array.new(8) { store.create_group }
ids.each { assert_match(/\A[k-z]{4}\z/, it) }
assert_equal ids.size, ids.uniq.size
end
end
# The schema is the gate on the id's shape, the way it is the gate on
# what a group may hold: nothing else stops a hand-written row from
# taking a word, a hash, or a change id's letters in the wrong case.
def test_the_schema_refuses_an_id_that_is_not_a_change_id
with_store do |store|
["household", "abcd", "kxs", "kxsvv", "KXSV", "kx s"].each do |id|
assert_raises(Sequel::ConstraintViolation) do
database(store)[:groups].insert(id:, name: "Household")
end
end
end
end
# A group may have no name — NULL, the one spelling of it. The empty
# string is the other spelling the column would otherwise admit, and
# it renders as a mark with nothing in it, so the schema refuses it.
def test_a_group_may_be_nameless_but_not_named_nothing
with_store do |store|
id = store.create_group
assert_nil database(store)[:groups].where(id:).sole.fetch(:name)
assert_raises(Sequel::ConstraintViolation) { store.create_group(name: "") }
end
end
# The fourth action value is the fan-out's (Store#fan_out); this pins
# that the schema admits it, apart from anything the store writes.
def test_the_change_log_admits_the_group_action
with_store({"aiden" => AIDEN}) do |store|
database(store)[:changes]
.insert(card_id: "aiden", action: "group", etag: "\"x\"", diff: diff_json(added: ["NOTE:Gate code."]))
change = store.changes.last
assert_equal "group", change.action
assert_equal ["NOTE:Gate code."], change.diff.added
end
end
## Authoring a group
def test_a_group_reads_whole
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, name: "Household", members: %w[znorth aiden], lines: [HOUSEHOLD_ADDRESS, HOUSEHOLD_NOTE])
group = store.group(id)
assert_equal "Household", group.label
assert_equal [HOUSEHOLD_ADDRESS, HOUSEHOLD_NOTE], group.lines
assert_equal %w[aiden znorth], group.members
assert_nil store.group("zzzz")
end
end
def test_every_group_is_listed_by_id_under_its_label
with_store do |store|
named = store.create_group(name: "Household")
nameless = store.create_group
assert_equal({named => "Household", nameless => nameless}.sort.to_h,
store.all_groups.to_h { [it.id, it.label] })
end
end
# The pickers' read: id, name and the same coalesced label a tag
# shows, and how many are in a group rather than who — a nameless
# group is its id here as everywhere, and one nobody is in counts
# nought rather than going missing from the list.
def test_group_choices_carry_the_label_and_a_member_count
with_store({"aiden" => UUID_CARD}) do |store|
named = store.create_group(name: "Household")
nameless = store.create_group
store.add_member(named, "aiden")
assert_equal({named => ["Household", "Household", 1], nameless => [nil, nameless, 0]}.sort.to_h,
store.group_choices.to_h { [it.id, [it.name, it.label, it.member_count]] })
end
end
# What a group lends is what every member serves, so setting it logs
# a `group` entry on each (docs/plans/2026-09-09-group-edits-propagate.md,
# "The fan-out").
def test_setting_a_groups_lines_reaches_every_member
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, members: %w[aiden znorth], lines: [HOUSEHOLD_ADDRESS])
store.set_group_lines(id, [EDITED_ADDRESS, HOUSEHOLD_NOTE])
%w[aiden znorth].each do |member|
assert_includes store.contact(member).vcard.to_s, EDITED_ADDRESS
change = store.changes_of(member).first
assert_equal "group", change.action
assert_equal store.contact(member).etag, change.etag
assert_equal [EDITED_ADDRESS, "NOTE:Shared · #{id}:\\nGate code 1854."], change.diff.added
end
end
end
# The one-note invariant's raise: lines this server built carrying
# two NOTEs are a bug, and the raise reaches Sentry with the request
# (docs/plans/2026-09-25-one-note-per-contact.md, "The invariant").
def test_a_group_may_not_hold_two_notes
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, members: ["aiden"])
error = assert_raises(RuntimeError) {
store.set_group_lines(id, [HOUSEHOLD_NOTE, "NOTE:Second."])
}
assert_equal "a group was given 2 NOTE lines", error.message
end
end
# The same raise over an editor's save — foreign input joins on its
# way in (EditedContact, Import::Merge), so two NOTEs here can only
# be a path this server built.
def test_an_editors_save_may_not_store_two_notes
with_store({"aiden" => AIDEN}) do |store|
two = AIDEN.sub("END:VCARD\r\n", "NOTE:First.\r\nNOTE:Second.\r\nEND:VCARD\r\n")
error = assert_raises(RuntimeError) { store.save_edit("aiden", vcard(two), birthday: nil) }
assert_equal "a stored card was built with 2 NOTE lines", error.message
end
end
def test_a_joining_member_serves_the_group_and_is_logged
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, members: [], lines: [HOUSEHOLD_ADDRESS])
store.add_member(id, "aiden")
store.add_member(id, "aiden")
assert_includes store.contact("aiden").vcard.to_s, HOUSEHOLD_ADDRESS
assert_equal %w[group put], store.changes_of("aiden").map(&:action)
assert_equal [HOUSEHOLD_ADDRESS], store.changes_of("aiden").first.diff.added
end
end
def test_a_leaving_member_stops_serving_the_group_and_is_logged
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
store.remove_member(id, "aiden")
assert_equal AIDEN, store.contact("aiden").vcard.to_s
assert_equal [HOUSEHOLD_ADDRESS], store.changes_of("aiden").first.diff.removed
end
end
def test_a_deleted_group_takes_its_membership_and_lent_lines_away
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, members: %w[aiden znorth], lines: [HOUSEHOLD_ADDRESS])
assert store.delete_group(id)
assert_nil store.group(id)
%w[aiden znorth].each do |member|
assert_equal [], store.groups_of(member).map(&:id)
change = store.changes_of(member).first
assert_equal "group", change.action
assert_equal store.contact(member).etag, change.etag
assert_equal [HOUSEHOLD_ADDRESS], change.diff.removed
end
end
end
def test_deleting_a_sync_group_logs_its_members_whatever_their_bytes
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, name: "sync:Alpha Chen", members: ["aiden"])
store.delete_group(id)
assert_equal %w[group put], store.changes_of("aiden").map(&:action)
end
end
def test_deleting_a_group_that_lends_nothing_logs_no_member
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, members: ["aiden"])
store.delete_group(id)
assert_equal %w[put], store.changes_of("aiden").map(&:action)
end
end
def test_everyones_book_is_not_a_group_to_delete
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, name: ProTacts::Group::EVERYONE, members: ["aiden"])
assert_raises(ProTacts::Store::EveryonesBookName) { store.delete_group(id) }
assert_equal [id], store.groups_of("aiden").map(&:id)
assert_equal %w[put], store.changes_of("aiden").map(&:action)
end
end
def test_deleting_a_group_nobody_has_is_no_delete
with_store({"aiden" => AIDEN}) do |store|
refute store.delete_group("nobody")
end
end
JPEG = ProTacts::Contact.photo_of("\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\xFF".b) #: ProTacts::Contact::Photo
PNG = ProTacts::Contact.photo_of("\x89PNG\r\n\x1A\n\x00\x00\xFF".b) #: ProTacts::Contact::Photo
# A group's photo is the page's alone: it reads back byte for byte
# under its sniffed type, and no member's card moves for it.
def test_a_group_photo_reads_back_and_reaches_no_card
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, members: ["aiden"])
store.set_group_photo(id, JPEG)
assert store.group(id).photo
assert_equal JPEG, store.group_photo(id)
assert_equal AIDEN, store.contact("aiden").vcard.to_s
assert_equal %w[put], store.changes_of("aiden").map(&:action)
end
end
def test_a_group_photo_is_replaced_and_removed
with_store do |store|
id = FixtureData.seed_group(store, members: [])
store.set_group_photo(id, JPEG)
store.set_group_photo(id, PNG)
assert_equal PNG, store.group_photo(id)
store.remove_group_photo(id)
refute store.group(id).photo
assert_nil store.group_photo(id)
end
end
def test_a_deleted_group_takes_its_photo_away
with_store do |store|
id = FixtureData.seed_group(store, members: [])
store.set_group_photo(id, JPEG)
store.delete_group(id)
assert_nil store.group_photo(id)
end
end
def test_a_regroup_leaves_and_joins
with_store({"aiden" => AIDEN}) do |store|
left = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
joined = FixtureData.seed_group(store, members: [])
store.regroup("aiden", join: [joined], leave: [left])
assert_equal [joined], store.groups_of("aiden").map(&:id)
assert_equal AIDEN, store.contact("aiden").vcard.to_s
end
end
def test_a_regroup_creates_the_groups_it_names_and_joins_them
with_store({"aiden" => AIDEN}) do |store|
store.regroup("aiden", join: [], leave: [], create: ["Clarks", "Booles"])
assert_equal ["Booles", "Clarks"], store.groups_of("aiden").map(&:label).sort
end
end
# Nothing a client downloads moved, so nothing is logged: a group
# that lends nothing composes nothing into a new member, and a name
# is on no card.
def test_writes_that_move_no_served_card_log_nothing
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, members: [], lines: [])
store.add_member(id, "aiden")
store.rename_group(id, name: "Household")
store.rename_group(id, name: " ")
assert_equal ["put"], store.changes_of("aiden").map(&:action)
assert_equal id, store.group(id).label
end
end
## The group change log
# Every primitive, in the order a hand would write them, ending in
# a delete whose tombstone carries the whole group — the card
# tombstone's bargain, the entry being the only record left of what
# was here.
def test_every_group_write_is_logged
with_store({"aiden" => AIDEN}) do |store|
id = store.create_group(name: "Booles")
store.set_group_lines(id, [HOUSEHOLD_ADDRESS])
store.add_member(id, "aiden")
store.rename_group(id, name: "The Booles")
store.remove_member(id, "aiden")
store.delete_group(id)
entries = store.group_changes_of(id)
assert_equal %w[delete leave rename join lines create], entries.map(&:action)
assert_equal({"name" => "Booles"}, entries.fetch(5).detail)
assert_equal [HOUSEHOLD_ADDRESS], entries.fetch(4).detail.fetch("added")
assert_equal [], entries.fetch(4).detail.fetch("removed")
assert_equal "aiden", entries.fetch(3).detail.fetch("card")
assert_equal({"was" => "Booles", "name" => "The Booles"}, entries.fetch(2).detail)
assert_equal "aiden", entries.fetch(1).detail.fetch("card")
assert_equal(
{"name" => "The Booles", "lines" => [HOUSEHOLD_ADDRESS], "members" => []},
entries.fetch(0).detail,
)
end
end
def test_a_group_change_is_stamped_when_it_is_logged
with_store do |store|
store.create_group
assert_match TIMESTAMP, store.group_changes_of(store.all_groups.fetch(0).id).fetch(0).created_at
end
end
# The log records what happened, not that a save was asked
# (docs/plans/2026-09-23-group-change-log.md, "One entry per
# primitive") — the cards' log's own opposite bargain, nothing
# syncing from this one to miss a change.
def test_writes_that_move_nothing_of_the_group_log_nothing
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = store.create_group(name: "Booles")
store.set_group_lines(id, [HOUSEHOLD_ADDRESS])
store.add_member(id, "aiden")
logged = store.group_changes_of(id).length
store.rename_group(id, name: "Booles")
store.set_group_lines(id, [HOUSEHOLD_ADDRESS])
store.add_member(id, "aiden")
store.remove_member(id, "znorth")
store.edit_group(id, name: "Booles", lines: [HOUSEHOLD_ADDRESS])
store.edit_members(id, join: [], leave: ["znorth"])
assert_equal logged, store.group_changes_of(id).length
end
end
# A pure reorder moved every member's composed card — the fan-out
# logs them — so it is a real entry, though the multiset difference
# sees no line move at all.
def test_a_reorder_of_a_groups_lines_is_an_entry_with_an_empty_diff
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, lines: [HOUSEHOLD_ADDRESS, HOUSEHOLD_NOTE])
store.set_group_lines(id, [HOUSEHOLD_NOTE, HOUSEHOLD_ADDRESS])
entry = store.group_changes_of(id).first
assert_equal "lines", entry.action
assert_equal [], entry.detail.fetch("added")
assert_equal [], entry.detail.fetch("removed")
end
end
# The composites log as the primitives they run, in the order the
# transaction made them — an editor save read in the history as
# exactly the moves it made.
def test_an_edit_groups_save_logs_each_move_in_the_order_it_made_them
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, name: "Booles", members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
store.edit_group(id, name: "The Booles", lines: [HOUSEHOLD_NOTE])
store.edit_members(id, join: ["znorth"], leave: ["aiden"])
assert_equal %w[join leave lines rename create], store.group_changes_of(id).map(&:action)
end
end
def test_a_rename_to_nameless_is_logged_with_a_null_name
with_store do |store|
id = store.create_group(name: "Booles")
store.rename_group(id, name: " ")
assert_equal({"was" => "Booles", "name" => nil}, store.group_changes_of(id).first.detail)
end
end
# A group id and not a foreign key, the card log's reason: the
# history outlives the group and ends in its tombstone.
def test_a_deleted_groups_changes_still_read
with_store do |store|
id = store.create_group(name: "Booles")
store.delete_group(id)
assert_equal %w[delete create], store.group_changes_of(id).map(&:action)
end
end
## Books
YUKI = AIDEN.sub("FN:Aiden", "FN:Yuki").sub("UID:aiden", "UID:yuki") #: String
# A card in `sync:*` is everyone's, one in `sync:<name>` that user's
# alone, and one in any other group nobody's
# (docs/plans/2026-09-12-per-user-books.md).
def test_a_book_is_everyones_cards_and_the_users_own
with_store({"aiden" => AIDEN, "znorth" => ZED, "yuki" => YUKI}) do |store|
FixtureData.seed_group(store, name: "sync:*", members: ["aiden"])
FixtureData.seed_group(store, name: "sync:Alpha Chen", members: %w[aiden znorth])
FixtureData.seed_group(store, name: "Household", members: ["yuki"])
assert_equal Set["aiden", "znorth"], store.book_cards("Alpha Chen")
assert_equal Set["aiden"], store.book_cards("Zoë Chen")
end
end
# A case variant, or the prefix spelled another way, is some other
# group.
def test_a_book_matches_its_group_name_exactly
with_store({"aiden" => AIDEN, "znorth" => ZED, "yuki" => YUKI}) do |store|
FixtureData.seed_group(store, name: "sync:Alpha Chen", members: ["aiden"])
FixtureData.seed_group(store, name: "sync:alpha chen", members: ["znorth"])
FixtureData.seed_group(store, name: "SYNC:Alpha Chen", members: ["yuki"])
assert_equal Set["aiden"], store.book_cards("Alpha Chen")
end
end
# A named book is the named group's, and the login's own group moves
# to the name with its members logged, so a client hears of nothing
# but the rename (docs/plans/2026-09-16-book-names.md).
def test_a_named_book_takes_its_group_along
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, name: "sync:alpha@example.com", members: ["aiden"])
store.name_book("alpha@example.com", "Alpha Chen")
assert_equal "sync:Alpha Chen", store.group(id).name
assert_equal "Alpha Chen", store.book_name("alpha@example.com")
assert_equal Set["aiden"], store.book_cards("alpha@example.com")
assert_equal %w[group put], store.changes_of("aiden").map(&:action)
store.name_book("alpha@example.com", " ")
assert_equal "sync:alpha@example.com", store.group(id).name
assert_equal "alpha@example.com", store.book_name("alpha@example.com")
assert_equal Set["aiden"], store.book_cards("alpha@example.com")
end
end
def test_a_book_is_named_before_its_group_exists
with_store({"aiden" => AIDEN}) do |store|
store.name_book("alpha@example.com", "Alpha Chen")
FixtureData.seed_group(store, name: "sync:Alpha Chen", members: ["aiden"])
assert_equal Set["aiden"], store.book_cards("alpha@example.com")
end
end
# Another login's name would share a book, and `*` is everyone's.
def test_a_book_name_is_one_logins
with_store do |store|
store.name_book("alpha@example.com", "Alpha Chen")
store.name_book("alpha@example.com", "Alpha Chen")
assert_raises(Sequel::UniqueConstraintViolation) { store.name_book("zoe@example.com", "Alpha Chen") }
assert_raises(ProTacts::Store::EveryonesBookName) { store.name_book("zoe@example.com", "*") }
assert_equal "zoe@example.com", store.book_name("zoe@example.com")
end
end
# The put's own entry is the card's arrival in every book, so the join
# logs nothing beside it.
def test_a_client_create_joins_everyones_book
with_store do |store|
store.put("aiden", vcard(AIDEN), client: true)
store.put("znorth", vcard(ZED), client: true)
assert_equal Set["aiden", "znorth"], store.book_cards("Zoë Chen")
assert_equal ["sync:*"], store.all_groups.map(&:name)
assert_equal ["put"], store.changes_of("aiden").map(&:action)
end
end
def test_a_client_rewrite_joins_nothing
with_store({"aiden" => AIDEN}) do |store|
store.put("aiden", vcard(AIDEN), client: true)
assert_empty store.book_cards("Alpha Chen")
end
end
# A `sync:` group can lend lines like any other, and the logged etag
# is the card as the book serves it.
def test_a_client_create_is_logged_as_its_book_serves_it
with_store do |store|
FixtureData.seed_group(store, name: "sync:*", lines: [HOUSEHOLD_NOTE])
contact = store.put("aiden", vcard(AIDEN), client: true)
assert_includes contact.vcard.to_s, "NOTE:Shared · sync:*:\\nGate code 1854."
assert_equal store.contact("aiden").etag, store.changes_of("aiden").first.etag
end
end
# Joining or leaving moves no bytes when the group lends nothing, but
# it moves the card between books, which a sync token hears of only
# through the log. Joining twice is still joining once.
def test_joining_and_leaving_a_sync_group_is_logged
with_store({"aiden" => AIDEN}) do |store|
id = FixtureData.seed_group(store, name: "sync:Alpha Chen")
store.add_member(id, "aiden")
store.add_member(id, "aiden")
store.remove_member(id, "aiden")
store.remove_member(id, "aiden")
assert_equal %w[group group put], store.changes_of("aiden").map(&:action)
end
end
# Into a book by a rename, and between books by #name_book, the one
# way a book's group is renamed.
def test_a_rename_into_or_between_books_logs_every_member
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
id = FixtureData.seed_group(store, name: "Household", members: %w[aiden znorth])
store.rename_group(id, name: "sync:alpha@example.com")
store.rename_group(id, name: "sync:alpha@example.com")
store.name_book("alpha@example.com", "Alpha Chen")
%w[aiden znorth].each do
assert_equal %w[group group put], store.changes_of(it).map(&:action)
end
end
end
# A book's group keeps its name: out of `sync:` or between two such
# names, and everyone's book above all, which would tell every
# client to drop every card.
def test_a_books_group_refuses_a_rename
with_store({"aiden" => AIDEN}) do |store|
everyone = FixtureData.seed_group(store, name: ProTacts::Group::EVERYONE, members: %w[aiden])
alpha = store.create_group(name: "sync:Alpha Chen")
assert_raises(ProTacts::Store::SyncGroupRename) { store.rename_group(everyone, name: "Everyone") }
assert_raises(ProTacts::Store::SyncGroupRename) { store.rename_group(everyone, name: " ") }
assert_raises(ProTacts::Store::SyncGroupRename) { store.rename_group(alpha, name: "sync:Zoë Chen") }
assert_raises(ProTacts::Store::SyncGroupRename) do
store.edit_group(everyone, name: "Everyone", lines: [])
end
assert_equal ProTacts::Group::EVERYONE, store.group(everyone).name
assert_equal "sync:Alpha Chen", store.group(alpha).name
assert_equal %w[put], store.changes_of("aiden").map(&:action)
end
end
# Keeping the name it has is no rename, which every group edit does.
def test_a_books_group_keeps_its_name_through_an_edit
with_store({"aiden" => AIDEN}) do |store|
everyone = FixtureData.seed_group(store, name: ProTacts::Group::EVERYONE, members: %w[aiden])
store.edit_group(everyone, name: ProTacts::Group::EVERYONE, lines: [HOUSEHOLD_NOTE])
assert_equal ProTacts::Group::EVERYONE, store.group(everyone).name
assert_equal [HOUSEHOLD_NOTE], store.group(everyone).lines
end
end
# A name is one group's (db/migrations/008_group_names.rb). Nameless
# groups are the exception, and a group keeping the name it has is no
# collision with itself — every group edit rewrites the name it found
# (#edit_group).
def test_a_name_is_one_groups_and_nameless_groups_are_any_number
with_store do |store|
household = store.create_group(name: "Household")
store.create_group(name: "sync:Alpha Chen")
store.create_group
other = store.create_group
assert_raises(Sequel::UniqueConstraintViolation) { store.create_group(name: "Household") }
assert_raises(Sequel::UniqueConstraintViolation) { store.rename_group(other, name: "sync:Alpha Chen") }
assert_nil store.group(other).name
store.rename_group(household, name: "Household")
assert_equal "Household", store.group(household).name
end
end
## Subtracting what a group lends
# The member's own address, deliberately unlike the group's so a
# stored line and a lent one are told apart by their bytes.
OWN_ADDRESS = "ADR:;;1 Long Road;;;;" #: String
# The group's address as a client sends it back changed — one digit,
# so nothing but the value moved.
EDITED_ADDRESS = HOUSEHOLD_ADDRESS.sub("7 Calculus", "8 Calculus") #: String
# The group's lines as macOS returns them on a card whose address and
# note nobody edited: the parameter name lowercased, its value
# uppercased, `pref` filled in, an unmodeled parameter dropped, and
# every value byte-identical (docs/apple-contacts.md, "The client
# rewrites every card it touches" and "An annotation survives only on
# its own line").
RESERIALIZED_ADDRESS = HOUSEHOLD_ADDRESS.sub("ADR;TYPE=home:", "ADR;type=HOME;type=pref:") #: String
# The same address lent with no type on it, which is a shape the
# round trip leaves alone.
UNTYPED_ADDRESS = HOUSEHOLD_ADDRESS.sub("ADR;TYPE=home:", "ADR:") #: String
TAGGED_NOTE = HOUSEHOLD_NOTE.sub("NOTE:", "NOTE;LANGUAGE=en:") #: String
# The round trip the whole composition rests on: a member PUTs back
# what it downloaded, and what is stored is the card it was composed
# from — the group's lines in the served card, in the index nowhere
# (docs/plans/2026-08-24-vcard-storage-and-groups.md).
def test_a_members_put_of_its_served_card_stores_what_it_started_with
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS, HOUSEHOLD_NOTE])
served = store.contact("aiden").vcard.to_s
contact = store.put("aiden", vcard(served))
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal served, contact.vcard.to_s
refute_includes indexed_names(store, "aiden"), "ADR"
end
end
# Both subtractions in one write, and the composition puts them back
# in the order it always does: the group's lines, then the birthday.
def test_a_put_subtracts_the_birthday_and_the_lent_lines_together
born = AIDEN.sub("FN:Aiden\r\n", "FN:Aiden\r\nBDAY:1985-12-10\r\n")
with_store({"aiden" => born}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served))
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal served, store.contact("aiden").vcard.to_s
end
end
# A member's own line of the name its group lends keeps its place in
# the card: the subtraction takes the lent copy and moves nothing
# else, which is what lets the round trip hold for a member that
# carries an address of its own.
def test_a_members_own_line_survives_the_subtraction_in_place
own = AIDEN.sub("FN:Aiden\r\n", "#{OWN_ADDRESS}\r\nFN:Aiden\r\n")
with_store({"aiden" => own}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served))
assert_equal own, card_row(store, "aiden").fetch(:vcard)
assert_equal served, store.contact("aiden").vcard.to_s
end
end
# An edit to a shared value is an edit to the group's line: the row
# takes the new bytes, the member stores none of them, and the served
# card carries one copy rather than the member's beside the group's
# (docs/plans/2026-09-09-group-edits-propagate.md).
def test_an_edited_lent_line_becomes_the_groups_line
with_store({"aiden" => AIDEN}) do |store|
group = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, EDITED_ADDRESS)))
assert_equal [EDITED_ADDRESS], lent_lines(store, group)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
composed = store.contact("aiden").vcard.to_s
assert_includes composed, EDITED_ADDRESS
refute_includes composed, HOUSEHOLD_ADDRESS
assert_empty sentry_messages
end
end
# The round trip as a real client makes it: macOS re-serializes every
# line of every card it touches, so the group's address comes back
# spelled its way on an address nobody edited. Matching bytes would
# call that an edit and materialize the group's line into the
# member's own card, which is what the composition exists to prevent.
def test_a_reserialized_lent_line_is_still_the_groups
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, RESERIALIZED_ADDRESS)))
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal served, store.contact("aiden").vcard.to_s
assert_empty sentry_messages
end
end
# The same for a note, whose re-serialization is a parameter the
# client does not model going missing.
def test_a_lent_note_stripped_of_its_parameter_is_still_the_groups
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [TAGGED_NOTE])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(TAGGED_NOTE, HOUSEHOLD_NOTE)))
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal served, store.contact("aiden").vcard.to_s
assert_empty sentry_messages
end
end
# Relabelling a shared address is an edit to the shared line, and the
# label travels with the value: the group takes the line as the
# client spelled it, because re-rendering under the group's old
# header would propagate the address and drop the relabel (the plan's
# "What a propagated edit stores").
def test_a_relabeled_lent_line_relabels_the_groups_line
relabeled = HOUSEHOLD_ADDRESS.sub("ADR;TYPE=home:", "ADR;type=WORK;type=pref:")
with_store({"aiden" => AIDEN}) do |store|
group = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, relabeled)))
assert_equal [relabeled], lent_lines(store, group)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_includes store.contact("aiden").vcard.to_s, relabeled
assert_empty sentry_messages
end
end
# An untyped line comes back untyped: the client invents no type to
# fill the gap (docs/apple-contacts.md, "An address type the client
# cannot model becomes a custom label").
def test_an_untyped_lent_line_comes_back_untyped
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [UNTYPED_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served))
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal served, store.contact("aiden").vcard.to_s
assert_empty sentry_messages
end
end
# Which is what makes labelling one an edit like any other relabel:
# the type it arrives with is the member's, nobody else having put
# one there.
def test_a_label_on_an_untyped_lent_line_labels_the_groups_line
labeled = UNTYPED_ADDRESS.sub("ADR:", "ADR;type=HOME;type=pref:")
with_store({"aiden" => AIDEN}) do |store|
group = FixtureData.seed_group(store, members: ["aiden"], lines: [UNTYPED_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(UNTYPED_ADDRESS, labeled)))
assert_equal [labeled], lent_lines(store, group)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_includes store.contact("aiden").vcard.to_s, labeled
assert_empty sentry_messages
end
end
# The label goes with the line it was made from: left behind, it
# would be a label in the member's card naming nothing.
def test_a_lent_type_the_client_made_a_label_of_comes_back_unedited
domestic = HOUSEHOLD_ADDRESS.sub("ADR;TYPE=home:", "ADR;TYPE=dom:")
labeled = domestic.sub("ADR;TYPE=dom:", "item1.ADR:") + "\r\nitem1.X-ABLabel:dom"
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
group = FixtureData.seed_group(store, members: %w[aiden znorth], lines: [domestic])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(domestic, labeled)))
assert_equal [domestic], lent_lines(store, group)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal ["put"], store.changes_of("znorth").map(&:action)
assert_empty sentry_messages
end
end
# An edit still reads as one through the re-serialization it arrives
# wrapped in: the value moved, and the spelling around it is what the
# comparison sees past.
def test_an_edit_survives_the_reserialization_it_arrives_in
edited = RESERIALIZED_ADDRESS.sub("7 Calculus", "8 Calculus")
with_store({"aiden" => AIDEN}) do |store|
group = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, edited)))
assert_equal [edited], lent_lines(store, group)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_includes store.contact("aiden").vcard.to_s, edited
assert_empty sentry_messages
end
end
# A deletion leaves the group: the row goes, so the next read
# composes nothing back in and the member serves what it stores.
# Consistent with an edit, and the plan's open question decided —
# a member either inherits or does not, negative overrides included
# (docs/plans/2026-09-09-group-edits-propagate.md, "The open
# question, decided").
def test_a_deleted_lent_line_leaves_the_group
with_store({"aiden" => AIDEN}) do |store|
group = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub("#{HOUSEHOLD_ADDRESS}\r\n", "")))
assert_empty lent_lines(store, group)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal AIDEN, store.contact("aiden").vcard.to_s
assert_empty sentry_messages
end
end
## The fan-out
# The whole point of propagating: one member's edit is what every
# other member serves, and each of them is told so. The writer gets
# no `group` entry — its own `put` entry already carries the
# composition (docs/plans/2026-09-09-group-edits-propagate.md, "The
# fan-out").
def test_an_edit_reaches_every_other_member
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
FixtureData.seed_group(store, members: %w[aiden znorth], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, EDITED_ADDRESS)))
assert_includes store.contact("znorth").vcard.to_s, EDITED_ADDRESS
fanned = store.changes_of("znorth").first
assert_equal "group", fanned.action
assert_equal store.contact("znorth").etag, fanned.etag
assert_equal [EDITED_ADDRESS], fanned.diff.added
assert_equal [HOUSEHOLD_ADDRESS], fanned.diff.removed
assert_equal "put", store.changes_of("aiden").first.action
end
end
# A deletion fans out the same way, its diff the line every other
# member just lost.
def test_a_deletion_reaches_every_other_member
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
FixtureData.seed_group(store, members: %w[aiden znorth], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub("#{HOUSEHOLD_ADDRESS}\r\n", "")))
assert_equal ZED, store.contact("znorth").vcard.to_s
fanned = store.changes_of("znorth").first
assert_equal "group", fanned.action
assert_equal [HOUSEHOLD_ADDRESS], fanned.diff.removed
assert_empty fanned.diff.added
end
end
# A member returning what it downloaded moves no group line, so
# nobody else is told anything: an entry per member of the group
# rather than per member the edit moved would have every client
# re-fetch a card that reads the same.
def test_an_unchanged_round_trip_fans_out_nothing
with_store({"aiden" => AIDEN, "znorth" => ZED}) do |store|
FixtureData.seed_group(store, members: %w[aiden znorth], lines: [HOUSEHOLD_ADDRESS])
store.put("aiden", vcard(store.contact("aiden").vcard.to_s))
assert_equal ["put"], store.changes_of("znorth").map(&:action)
end
end
# Both halves land together or neither does: the group's row is
# rewritten inside the transaction the member's own write opens, so a
# log that will not take an entry leaves the group holding what it
# lent. The card row and the group row are two tables, and a client's
# sync token counts on the entry that ties them.
def test_a_propagated_edit_rolls_back_with_the_members_write
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
group = ProTacts::Store.connect(path) do |store|
store.put("aiden", vcard(AIDEN))
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
end
ProTacts::Store.connect(path) do |store|
served = store.contact("aiden").vcard.to_s
submitted = vcard(served.sub(HOUSEHOLD_ADDRESS, EDITED_ADDRESS))
assert_raises(RuntimeError) { FailingLog.new(database(store)).put("aiden", submitted) }
assert_equal [HOUSEHOLD_ADDRESS], lent_lines(store, group)
assert_equal served, store.contact("aiden").vcard.to_s
end
end
end
## What propagation refuses
# An edit into a shape no group may hold stays on the member: an
# address type Contacts cannot model comes back as a property group
# with its label beside it, which reads as an edit and which
# group_properties refuses. Propagating it would be an exception on
# an ordinary sync, so the member keeps the line — serving it twice,
# which is what the report is for
# (docs/plans/2026-09-09-group-edits-propagate.md, "The line a group
# cannot hold").
def test_an_edit_the_group_cannot_hold_stays_on_the_member
labeled = HOUSEHOLD_ADDRESS.sub("ADR;TYPE=home:", "item1.ADR:") + "\r\nitem1.X-ABLabel:dom"
with_store({"aiden" => AIDEN}) do |store|
group = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, labeled)))
assert_equal [HOUSEHOLD_ADDRESS], lent_lines(store, group)
assert_includes card_row(store, "aiden").fetch(:vcard), labeled
assert_equal 1, sentry_messages.length
end
end
# One group's untouched line must not be attributed to another
# group's lent line. A member of two groups that each lend an
# address, editing one of them, submits one edited line and one
# untouched: attributed in a single pass, whichever group came first
# would take the other's line as its own edit and the other would
# read a deletion.
def test_a_lent_line_is_not_attributed_anothers_untouched_line
with_store({"aiden" => AIDEN}) do |store|
household = FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
other = FixtureData.seed_group(store, members: ["aiden"], lines: [OWN_ADDRESS])
served = store.contact("aiden").vcard.to_s
store.put("aiden", vcard(served.sub(HOUSEHOLD_ADDRESS, EDITED_ADDRESS)))
assert_equal [EDITED_ADDRESS], lent_lines(store, household)
assert_equal [OWN_ADDRESS], lent_lines(store, other)
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_empty sentry_messages
end
end
# Two lines of the lent name, neither of them its bytes: the edit
# cannot be told from the addition, so the card is stored as it
# arrived and the ambiguity is reported rather than guessed at.
def test_two_candidates_for_one_lent_line_are_stored_and_reported
with_store({"aiden" => AIDEN}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
submitted = served.sub(HOUSEHOLD_ADDRESS, "#{EDITED_ADDRESS}\r\n#{OWN_ADDRESS}")
store.put("aiden", vcard(submitted))
assert_equal submitted, card_row(store, "aiden").fetch(:vcard)
assert_equal 1, sentry_messages.length
end
end
# A member whose own card spells a line exactly as its group does
# keeps one copy of it: the stored lines are struck against the
# submission before anything is attributed to a group, so what is
# left over is the lent copy and only that one goes.
def test_a_line_the_member_and_its_group_both_spell_keeps_one_copy
own = AIDEN.sub("END:VCARD\r\n", "#{HOUSEHOLD_ADDRESS}\r\nEND:VCARD\r\n")
with_store({"aiden" => own}) do |store|
FixtureData.seed_group(store, members: ["aiden"], lines: [HOUSEHOLD_ADDRESS])
served = store.contact("aiden").vcard.to_s
assert_equal 2, served.scan(HOUSEHOLD_ADDRESS).length
store.put("aiden", vcard(served))
assert_equal own, card_row(store, "aiden").fetch(:vcard)
assert_equal served, store.contact("aiden").vcard.to_s
end
end
## The migration
# A database from before the diff column loses its log to 006, which
# is what that migration trades for a column that is never null: an
# entry written then has no diff and no way to be given one. The
# sequence restarts with it, and the widened action vocabulary is
# still there on the other side.
def test_the_diff_migration_drops_the_change_log
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
Sequel.connect("sqlite://#{path}") do |db|
Sequel::Migrator.run(db, ProTacts::Store::MIGRATIONS.to_s, target: 2)
db[:changes].insert(card_id: "aiden", action: "put", etag: '"a1"')
db[:changes].insert(card_id: "aiden", action: "delete", etag: nil)
end
ProTacts::Store.connect(path) do |store|
assert_empty store.changes
store.put("aiden", vcard(AIDEN))
store.save_edit("aiden", vcard(AIDEN.sub("FN:Aiden", "FN:Aiden Smith")), birthday: nil)
change = store.changes.last
assert_equal %w[aiden edit], [change.card_id, change.action]
assert_equal 2, change.sequence
end
end
end
# The group rebuild carries all three tables, and the hazard it is
# written around is this one: dropping the old groups table with
# foreign keys on runs an implicit DELETE FROM, and the members and
# the properties would cascade away behind it. So the members and
# the properties are asserted across the upgrade, and both cascades
# asserted still to fire on the far side — a rebuild that forgot to
# redeclare them would pass the first half of this alone.
def test_the_migration_carries_a_group_with_its_members_and_properties
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
Sequel.connect("sqlite://#{path}") do |db|
Sequel::Migrator.run(db, ProTacts::Store::MIGRATIONS.to_s, target: 4)
db[:cards].insert(id: "aiden", vcard: AIDEN)
db[:groups].insert(id: "nous", name: "Booles")
db[:group_properties].insert(group_id: "nous", position: 0, line: HOUSEHOLD_ADDRESS)
db[:group_members].insert(group_id: "nous", card_id: "aiden")
end
ProTacts::Store.connect(path) do |store|
contact = store.contact("aiden")
assert_includes contact.vcard.to_s, HOUSEHOLD_ADDRESS
assert_equal "nous", contact.addresses.fetch(0).lent_by&.id
database(store)[:cards].where(id: "aiden").delete
assert_empty database(store)[:group_members].all
database(store)[:groups].where(id: "nous").delete
assert_empty database(store)[:group_properties].all
end
end
end
# A database at the old shape — BDAY in the card, no birthdays table
# — is carried over by the same subtraction a write makes: modeled
# forms move, unmodeled forms stay put.
def test_the_migration_moves_a_modeled_bday_out_of_the_cards
shared = ZED.sub("UID:znorth", "UID:xavi").sub("END:VCARD\r\n", "BDAY:1985-04-12\rNOTE:b\r\nEND:VCARD\r\n")
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
Sequel.connect("sqlite://#{path}") do |db|
Sequel::Migrator.run(db, ProTacts::Store::MIGRATIONS.to_s, target: 1)
db[:cards].insert(id: "aiden", vcard: AIDEN_BORN)
db[:cards].insert(id: "znorth", vcard: ZED.sub("END:VCARD\r\n", "BDAY:19850412\r\nEND:VCARD\r\n"))
db[:cards].insert(id: "xavi", vcard: shared)
end
ProTacts::Store.connect(path) do |store|
assert_equal AIDEN, card_row(store, "aiden").fetch(:vcard)
assert_equal ProTacts::Birthday.new(year: 1985, month: 4, day: 12), birthday_row(store, "aiden")
assert_equal AIDEN.sub("END:VCARD\r\n", "BDAY:1985-04-12\r\nEND:VCARD\r\n"), store.contact("aiden").vcard.to_s
# Unmodeled: byte-identical, no birthday row beside it.
assert_equal ZED.sub("END:VCARD\r\n", "BDAY:19850412\r\nEND:VCARD\r\n"), store.contact("znorth").vcard.to_s
assert_nil birthday_row(store, "znorth")
# A BDAY sharing its line's bytes stays put: the line moves as
# one or not at all, where the first property alone would have
# moved the birthday and dropped the NOTE unwitnessed.
assert_equal shared, store.contact("xavi").vcard.to_s
assert_nil birthday_row(store, "xavi")
end
end
end
# A database from before the one-note invariant is joined onto it:
# a card's several NOTEs become one value, a group's several NOTE
# rows become the one row a member's edit writes back to, and a
# card holding one note all along keeps its bytes. The member
# serves the group's joined note as one section, the shape every
# write composes from here
# (docs/plans/2026-09-25-one-note-per-contact.md).
# The cards already stored are keyed as the table lands, so a search
# finds them before any is written again.
def test_the_migration_keys_the_cards_already_stored
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
Sequel.connect("sqlite://#{path}") do |db|
Sequel::Migrator.run(db, ProTacts::Store::MIGRATIONS.to_s, target: 13)
db[:cards].insert(id: "aiden", vcard: AIDEN)
db[:cards].insert(id: "znorth", vcard: ZED)
end
ProTacts::Store.connect(path) do |store|
assert_equal({"aiden" => ["aiden"], "znorth" => ["zed"]}, store.search_keys_by_recency.transform_values(&:names))
end
end
end
def test_the_migration_joins_several_notes_into_one
two_notes = AIDEN.sub("END:VCARD\r\n", "NOTE:First.\r\nNOTE:Second.\r\nEND:VCARD\r\n")
Dir.mktmpdir do |dir|
path = Pathname.new(dir) / "contacts.db"
Sequel.connect("sqlite://#{path}") do |db|
Sequel::Migrator.run(db, ProTacts::Store::MIGRATIONS.to_s, target: 11)
db[:cards].insert(id: "aiden", vcard: two_notes)
db[:cards].insert(id: "znorth", vcard: ZED.sub("END:VCARD\r\n", "NOTE:One only.\r\nEND:VCARD\r\n"))
db[:groups].insert(id: "nous", name: "Booles")
db[:group_properties].insert(group_id: "nous", position: 0, line: HOUSEHOLD_ADDRESS)
db[:group_properties].insert(group_id: "nous", position: 1, line: "NOTE:Gate code 1854.")
db[:group_properties].insert(group_id: "nous", position: 2, line: "NOTE:Bins on Tuesday.")
db[:group_members].insert(group_id: "nous", card_id: "znorth")
end
ProTacts::Store.connect(path) do |store|
joined = AIDEN.sub("END:VCARD\r\n", "NOTE:First.\\n\\nSecond.\r\nEND:VCARD\r\n")
assert_equal joined, store.contact("aiden").vcard.to_s
assert_equal(
[HOUSEHOLD_ADDRESS, "NOTE:Gate code 1854.\\n\\nBins on Tuesday."],
store.group("nous").lines,
)
served = ZED.sub(
"END:VCARD\r\n",
"NOTE:One only.\\n\\nShared · Booles:\\nGate code 1854.\\n\\nBins on Tuesday.\r\n" \
"#{HOUSEHOLD_ADDRESS}\r\nEND:VCARD\r\n",
)
assert_equal served, store.contact("znorth").vcard.to_s
end
end
end
def test_a_snapshot_holds_the_stored_state
with_store({"aiden" => AIDEN_BORN}) do |store|
group = store.create_group(name: "Booles")
store.add_member(group, "aiden")
store.name_book("alpha@example.com", "Alpha Chen")
snapshot = store.snapshot
assert_equal({"aiden" => AIDEN}, snapshot.cards)
assert_equal({"aiden" => ProTacts::Birthday.new(year: 1985, month: 4, day: 12)}, snapshot.birthdays)
assert_equal [["Booles", ["aiden"]]], snapshot.groups.map { [it.name, it.members] }
assert_equal({"alpha@example.com" => "Alpha Chen"}, snapshot.books)
end
end
## The change log, driven
# Clients' writes and the admin's in any order, against the two
# promises the change log makes (Store's class comment, and #put):
# a client holding any token it was ever handed catches up to the
# book by applying what #changes hands it, and a card's history,
# its diffs replayed oldest first, rebuilds the card it ends in.
class ChangeLogMachine < Hegel::StateMachine
# A few ids, so writes land on cards that exist as often as not.
IDS = %w[ada bob cy].freeze #: Array[String]
def initialize(store, tc)
@store = store
# A token with the book its client held when it took it: the
# first is a client that has never synced.
@tokens = Hegel::Stateful::Pool.new(tc)
@tokens.add([0, {}])
end
# A card a write might carry: any name, and a TEL or two that may
# repeat, which a diff counts rather than sets. Any name but one
# holding a NUL, which is not text a card can be made of
# (VCard.text?).
def card(tc, id)
name = ProTacts::VCard.escape(tc.draw(text(max_size: 10, min_codepoint: 1)))
phones = tc.draw(arrays(sampled_from(["TEL:+1 555 0100\r\n", "TEL:+1 555 0199\r\n"]), max_size: 3))
ProTacts::VCard.new("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:#{name}\r\n#{phones.join}UID:#{id}\r\nEND:VCARD\r\n")
end
# What a client downloading the whole book now would hold: each
# card's etag, by id.
def book = @store.contacts.to_h { [it.id, it.etag] }
rule(:put) do |tc|
id = tc.draw(sampled_from(IDS))
@store.put(id, card(tc, id), client: tc.draw(booleans))
end
rule(:edit) do |tc|
id = tc.draw(sampled_from(IDS))
tc.assume(@store.contact(id))
@store.save_edit(id, card(tc, id), birthday: nil)
end
rule(:delete) do |tc|
@store.delete(tc.draw(sampled_from(IDS)))
end
rule(:sync) do
@tokens.add([@store.latest_sequence, book])
end
# A client's sync-collection report (RFC 6578 section 3.2): the
# entries after its token, applied in order to what it held.
rule(:catch_up) do |tc|
sequence, held = tc.draw(@tokens.values_reusable)
caught_up = @store.changes(after: sequence).each_with_object(held.dup) { |change, cards|
if change.action == ProTacts::Store::Action::DELETE
cards.delete(change.card_id)
else
cards[change.card_id] = change.etag
end
}
raise "a client at #{sequence} caught up to #{caught_up}, not #{book}" unless caught_up == book
end
rule(:read_history) do |tc|
id = tc.draw(sampled_from(IDS))
rebuilt = Hash.new(0)
@store.changes_of(id).reverse_each do |change|
change.diff.removed.each { rebuilt[it] -= 1 }
change.diff.added.each { rebuilt[it] += 1 }
end
lines = @store.contact(id)&.vcard&.lines&.map(&:content)&.reject(&:empty?) || []
raise "#{id}'s history rebuilds #{rebuilt}, not #{lines}" unless rebuilt.reject { |_, count| count.zero? } == lines.tally
end
invariant(:the_ctag_is_the_last_entry) do
raise "the ctag is #{@store.ctag}" unless @store.ctag == (@store.changes.last&.sequence || 0).to_s
end
end
# Each run starts from a copy of one migrated database rather than
# migrating its own, which is most of what opening a store costs.
def test_the_change_log_keeps_its_promises_whatever_the_writes
Dir.mktmpdir do |dir|
template = Pathname.new(dir) / "template.db"
ProTacts::Store.connect(template) {}
runs = 0
Hegel.test(test_cases: 100, stateful_step_count: 20) do |tc|
path = Pathname.new(dir) / "#{runs += 1}.db"
FileUtils.cp(template, path)
ProTacts::Store.connect(path) { |store| Hegel::Stateful.run(ChangeLogMachine.new(store, tc), tc) }
end
end
end
private
# A store whose change-log write fails, after Store#put has already put
# the card row in. Minitest 6 ships no stubbing, and a subclass says
# what is being broken more plainly than a stub would.
class FailingLog < ProTacts::Store
private
def record(card_id, action:, etag:, diff:)
raise "the change log is unavailable"
end
end
# The index is queried directly on purpose: it exists to be queried,
# and a test that went back through the store would not show that it
# can be.
def database(store)
store.instance_variable_get(:@database)
end
# A diff column's value, for a row inserted around the store.
def diff_json(added: [], removed: [])
ProTacts::CardDiff.new(added:, removed:).to_json
end
def card_row(store, id)
database(store)[:cards].where(id:).sole
end
def indexed_names(store, card_id)
database(store)[:card_properties].where(card_id:).order(:position).select_map(:name)
end
def indexed_parameters(store, card_id, name)
parameter = Sequel[:card_parameters]
database(store)[:card_parameters]
.join(:card_properties, [:card_id, :position])
.where(parameter[:card_id] => card_id, Sequel[:card_properties][:name] => name)
.order(parameter[:rowid])
.select_map([parameter[:name], parameter[:value]])
end
def index_rows(store)
[
database(store)[:card_properties].order(:card_id, :position).all,
database(store)[:card_parameters].order(:card_id, :position, :name, :value).all,
database(store)[:search_keys].order(:card_id).all,
database(store)[:sort_keys].order(:card_id).all,
]
end
# The birthday row read through the store's own model, so a test sees
# the shape it holds and not the columns it came from.
def birthday_row(store, id)
birthday = database(store)[:birthdays].where(card_id: id).first
birthday && ProTacts::Birthday.new(year: birthday[:year], month: birthday[:month], day: birthday[:day])
end
def wreck_the_index(store)
database(store)[:card_parameters].delete
database(store)[:card_properties].update(value: "wrong")
database(store)[:search_keys].delete
database(store)[:sort_keys].delete
end
end