File: test_syncobj.py

package info (click to toggle)
pysyncobj 0.3.14-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 476 kB
  • sloc: python: 5,568; makefile: 203; sh: 1
file content (2313 lines) | stat: -rwxr-xr-x 65,786 bytes parent folder | download
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
from __future__ import print_function
import os
import time
import pytest
import random
import threading
import sys
import pysyncobj.pickle as pickle
import pysyncobj.dns_resolver as dns_resolver
import platform

if sys.version_info >= (3, 0):
    xrange = range
from functools import partial
import functools
import struct
import logging
from pysyncobj import SyncObj, SyncObjConf, replicated, FAIL_REASON, _COMMAND_TYPE, \
    createJournal, HAS_CRYPTO, replicated_sync, SyncObjException, SyncObjConsumer, _RAFT_STATE
from pysyncobj.syncobj_admin import executeAdminCommand
from pysyncobj.batteries import ReplCounter, ReplList, ReplDict, ReplSet, ReplLockManager, ReplQueue, ReplPriorityQueue
from pysyncobj.node import TCPNode
from collections import defaultdict

logging.basicConfig(format=u'[%(asctime)s %(filename)s:%(lineno)d %(levelname)s]  %(message)s', level=logging.DEBUG)

_bchr = functools.partial(struct.pack, 'B')


class TEST_TYPE:
    DEFAULT = 0
    COMPACTION_1 = 1
    COMPACTION_2 = 2
    RAND_1 = 3
    JOURNAL_1 = 4
    AUTO_TICK_1 = 5
    WAIT_BIND = 6
    LARGE_COMMAND = 7


class TestObj(SyncObj):

    def __init__(self, selfNodeAddr, otherNodeAddrs,
                 testType=TEST_TYPE.DEFAULT,
                 compactionMinEntries=0,
                 dumpFile=None,
                 journalFile=None,
                 password=None,
                 dynamicMembershipChange=False,
                 useFork=True,
                 testBindAddr=False,
                 consumers=None,
                 onStateChanged=None,
                 leaderFallbackTimeout=None):

        cfg = SyncObjConf(autoTick=False, appendEntriesUseBatch=False)
        cfg.appendEntriesPeriod = 0.1
        cfg.raftMinTimeout = 0.5
        cfg.raftMaxTimeout = 1.0
        cfg.dynamicMembershipChange = dynamicMembershipChange
        cfg.onStateChanged = onStateChanged
        if leaderFallbackTimeout is not None:
            cfg.leaderFallbackTimeout = leaderFallbackTimeout

        if testBindAddr:
            cfg.bindAddress = selfNodeAddr

        if dumpFile is not None:
            cfg.fullDumpFile = dumpFile

        if password is not None:
            cfg.password = password

        cfg.useFork = useFork

        if testType == TEST_TYPE.COMPACTION_1:
            cfg.logCompactionMinEntries = compactionMinEntries
            cfg.logCompactionMinTime = 0.1
            cfg.appendEntriesUseBatch = True

        if testType == TEST_TYPE.COMPACTION_2:
            cfg.logCompactionMinEntries = 99999
            cfg.logCompactionMinTime = 99999
            cfg.fullDumpFile = dumpFile

        if testType == TEST_TYPE.LARGE_COMMAND:
            cfg.connectionTimeout = 15.0
            cfg.logCompactionMinEntries = 99999
            cfg.logCompactionMinTime = 99999
            cfg.fullDumpFile = dumpFile
            cfg.raftMinTimeout = 1.5
            cfg.raftMaxTimeout = 2.5
        # cfg.appendEntriesBatchSizeBytes = 2 ** 13

        if testType == TEST_TYPE.RAND_1:
            cfg.autoTickPeriod = 0.05
            cfg.appendEntriesPeriod = 0.02
            cfg.raftMinTimeout = 0.1
            cfg.raftMaxTimeout = 0.2
            cfg.logCompactionMinTime = 9999999
            cfg.logCompactionMinEntries = 9999999
            cfg.journalFile = journalFile

        if testType == TEST_TYPE.JOURNAL_1:
            cfg.logCompactionMinTime = 999999
            cfg.logCompactionMinEntries = 999999
            cfg.fullDumpFile = dumpFile
            cfg.journalFile = journalFile

        if testType == TEST_TYPE.AUTO_TICK_1:
            cfg.autoTick = True
            cfg.pollerType = 'select'

        if testType == TEST_TYPE.WAIT_BIND:
            cfg.maxBindRetries = 1
            cfg.autoTick = True

        super(TestObj, self).__init__(selfNodeAddr, otherNodeAddrs, cfg, consumers)
        self.__counter = 0
        self.__data = {}

        if testType == TEST_TYPE.RAND_1:
            self._SyncObj__transport._send_random_sleep_duration = 0.03

    @replicated
    def addValue(self, value):
        self.__counter += value
        return self.__counter

    @replicated
    def addKeyValue(self, key, value):
        self.__data[key] = value

    @replicated_sync
    def addValueSync(self, value):
        self.__counter += value
        return self.__counter

    @replicated
    def testMethod(self):
        self.__data['testKey'] = 'valueVer1'

    @replicated(ver=1)
    def testMethod(self):
        self.__data['testKey'] = 'valueVer2'

    def getCounter(self):
        return self.__counter

    def getValue(self, key):
        return self.__data.get(key, None)

    def dumpKeys(self):
        print('keys:', sorted(self.__data.keys()))


def singleTickFunc(o, timeToTick, interval, stopFunc):
    currTime = time.time()
    finishTime = currTime + timeToTick
    while time.time() < finishTime:
        o._onTick(interval)
        if stopFunc is not None:
            if stopFunc():
                break


def utilityTickFunc(args, currRes, key):
    currRes[key] = executeAdminCommand(args)


def doSyncObjAdminTicks(objects, arguments, timeToTick, currRes, interval=0.05, stopFunc=None):
    objThreads = []
    utilityThreads = []
    for o in objects:
        t1 = threading.Thread(target=singleTickFunc, args=(o, timeToTick, interval, stopFunc))
        t1.start()
        objThreads.append(t1)
        if arguments.get(o) is not None:
            t2 = threading.Thread(target=utilityTickFunc, args=(arguments[o], currRes, o))
            t2.start()
            utilityThreads.append(t2)
    for t in objThreads:
        t.join()
    for t in utilityThreads:
        t.join()


def doTicks(objects, timeToTick, interval=0.05, stopFunc=None):
    threads = []
    for o in objects:
        t = threading.Thread(target=singleTickFunc, args=(o, timeToTick, interval, stopFunc))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()


def doAutoTicks(interval=0.05, stopFunc=None):
    deadline = time.time() + interval
    while not stopFunc():
        time.sleep(0.02)
        t2 = time.time()
        if t2 >= deadline:
            break


_g_nextAddress = 6000 + 60 * (int(time.time()) % 600)


def getNextAddr(ipv6=False, isLocalhost=False):
    global _g_nextAddress
    _g_nextAddress += 1
    if ipv6:
        return '::1:%d' % _g_nextAddress
    if isLocalhost:
        return 'localhost:%d' % _g_nextAddress
    return '127.0.0.1:%d' % _g_nextAddress


_g_nextDumpFile = 1
_g_nextJournalFile = 1


def getNextDumpFile():
    global _g_nextDumpFile
    fname = 'dump%d.bin' % _g_nextDumpFile
    _g_nextDumpFile += 1
    return fname


def getNextJournalFile():
    global _g_nextJournalFile
    fname = 'journal%d.bin' % _g_nextJournalFile
    _g_nextJournalFile += 1
    return fname


def test_syncTwoObjects():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]])
    o2 = TestObj(a[1], [a[0]])
    objs = [o1, o2]

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    o1.waitBinded()
    o2.waitBinded()

    o1._printStatus()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._isReady()
    assert o2._isReady()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10.0, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1._isReady()
    assert o2._isReady()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1._destroy()
    o2._destroy()


def test_hasQuorum():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]])
    o2 = TestObj(a[1], [a[0]])
    objs = [o1, o2]

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    o1.waitBinded()
    o2.waitBinded()

    o1._printStatus()
    assert o1.hasQuorum

    # Stop the second node in the cluster
    o2._destroy()
    doTicks(objs, 10.0, stopFunc=lambda: not o1.hasQuorum)

    assert not o1.hasQuorum

    o1._destroy()


def test_singleObject():
    random.seed(42)

    a = [getNextAddr(), ]

    o1 = TestObj(a[0], [])
    objs = [o1, ]

    assert not o1._isReady()

    doTicks(objs, 3.0, stopFunc=lambda: o1._isReady())

    o1._printStatus()

    assert o1._getLeader().address in a
    assert o1._isReady()

    o1.addValue(150)
    o1.addValue(200)

    doTicks(objs, 3.0, stopFunc=lambda: o1.getCounter() == 350)

    assert o1._isReady()

    assert o1.getCounter() == 350

    o1._destroy()


def test_syncThreeObjectsLeaderFail():
    random.seed(12)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    states = defaultdict(list)

    o1 = TestObj(a[0], [a[1], a[2]], testBindAddr=True, onStateChanged=lambda old, new: states[a[0]].append(new))
    o2 = TestObj(a[1], [a[2], a[0]], testBindAddr=True, onStateChanged=lambda old, new: states[a[1]].append(new))
    o3 = TestObj(a[2], [a[0], a[1]], testBindAddr=True, onStateChanged=lambda old, new: states[a[2]].append(new))
    objs = [o1, o2, o3]

    assert not o1._isReady()
    assert not o2._isReady()
    assert not o3._isReady()

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._getLeader() == o3._getLeader()

    assert _RAFT_STATE.LEADER in states[o1._getLeader().address]

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10.0, stopFunc=lambda: o3.getCounter() == 350)

    assert o3.getCounter() == 350

    prevLeader = o1._getLeader()

    newObjs = [o for o in objs if o._SyncObj__selfNode != prevLeader]

    assert len(newObjs) == 2

    doTicks(newObjs, 10.0, stopFunc=lambda: newObjs[0]._getLeader() != prevLeader and \
                                            newObjs[0]._getLeader() is not None and \
                                            newObjs[0]._getLeader().address in a and \
                                            newObjs[0]._getLeader() == newObjs[1]._getLeader())

    assert newObjs[0]._getLeader() != prevLeader
    assert newObjs[0]._getLeader().address in a
    assert newObjs[0]._getLeader() == newObjs[1]._getLeader()

    assert _RAFT_STATE.LEADER in states[newObjs[0]._getLeader().address]

    newObjs[1].addValue(50)

    doTicks(newObjs, 10, stopFunc=lambda: newObjs[0].getCounter() == 400)

    assert newObjs[0].getCounter() == 400

    doTicks(objs, 10.0, stopFunc=lambda: sum([int(o.getCounter() == 400) for o in objs]) == len(objs))

    for o in objs:
        assert o.getCounter() == 400

    o1._destroy()
    o2._destroy()
    o3._destroy()


def test_manyActionsLogCompaction():
    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]], TEST_TYPE.COMPACTION_1, compactionMinEntries=100)
    o2 = TestObj(a[1], [a[2], a[0]], TEST_TYPE.COMPACTION_1, compactionMinEntries=100)
    o3 = TestObj(a[2], [a[0], a[1]], TEST_TYPE.COMPACTION_1, compactionMinEntries=100)
    objs = [o1, o2, o3]

    assert not o1._isReady()
    assert not o2._isReady()
    assert not o3._isReady()

    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._getLeader() == o3._getLeader()

    for i in xrange(0, 500):
        o1.addValue(1)
        o2.addValue(1)

    doTicks(objs, 10, stopFunc=lambda:
        o1.getCounter() == 1000 and
        o2.getCounter() == 1000 and
        o3.getCounter() == 1000 and
        o1._getRaftLogSize() <= 100 and
        o2._getRaftLogSize() <= 100 and
        o3._getRaftLogSize() <= 100
    )

    assert o1.getCounter() == 1000
    assert o2.getCounter() == 1000
    assert o3.getCounter() == 1000

    assert o1._getRaftLogSize() <= 100
    assert o2._getRaftLogSize() <= 100
    assert o3._getRaftLogSize() <= 100

    newObjs = [o1, o2]
    doTicks(newObjs, 10, stopFunc=lambda: o3._getLeader() is None)

    for i in xrange(0, 500):
        o1.addValue(1)
        o2.addValue(1)

    doTicks(newObjs, 10, stopFunc=lambda:
        o1.getCounter() == 2000 and
        o2.getCounter() == 2000 and
        o1._getRaftLogSize() <= 100 and
        o2._getRaftLogSize() <= 100 and
        o3._getRaftLogSize() <= 100
    )

    assert o1.getCounter() == 2000
    assert o2.getCounter() == 2000
    assert o3.getCounter() != 2000

    doTicks(objs, 10, stopFunc=lambda: o3.getCounter() == 2000)

    assert o3.getCounter() == 2000

    assert o1._getRaftLogSize() <= 100
    assert o2._getRaftLogSize() <= 100
    assert o3._getRaftLogSize() <= 100

    o1._destroy()
    o2._destroy()
    o3._destroy()


def onAddValue(res, err, info):
    assert res == 3
    assert err == FAIL_REASON.SUCCESS
    info['callback'] = True


def test_checkCallbacksSimple():
    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]])
    o2 = TestObj(a[1], [a[2], a[0]])
    o3 = TestObj(a[2], [a[0], a[1]])
    objs = [o1, o2, o3]

    assert not o1._isReady()
    assert not o2._isReady()
    assert not o3._isReady()

    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._getLeader() == o3._getLeader()

    callbackInfo = {
        'callback': False
    }
    o1.addValue(3, callback=partial(onAddValue, info=callbackInfo))

    doTicks(objs, 10, stopFunc=lambda: o2.getCounter() == 3 and callbackInfo['callback'] == True)

    assert o2.getCounter() == 3
    assert callbackInfo['callback'] == True

    o1._destroy()
    o2._destroy()
    o3._destroy()


def removeFiles(files):
    for f in (files):
        if os.path.isfile(f):
            for i in xrange(0, 15):
                try:
                    if os.path.isfile(f):
                        os.remove(f)
                        break
                    else:
                        break
                except:
                    time.sleep(1.0)


def checkDumpToFile(useFork):
    dumpFiles = [getNextDumpFile(), getNextDumpFile()]
    removeFiles(dumpFiles)

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0], useFork=useFork)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1], useFork=useFork)
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1._forceLogCompaction()
    o2._forceLogCompaction()

    doTicks(objs, 1.5)

    o1._destroy()
    o2._destroy()

    a = [getNextAddr(), getNextAddr()]
    o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0], useFork=useFork)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1], useFork=useFork)
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())
    assert o1._isReady()
    assert o2._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1._destroy()
    o2._destroy()

    removeFiles(dumpFiles)


def test_checkDumpToFile():
    if hasattr(os, 'fork'):
        checkDumpToFile(True)
    checkDumpToFile(False)


def getRandStr():
    return '%0100000x' % random.randrange(16 ** 100000)


def test_checkBigStorage():
    dumpFiles = [getNextDumpFile(), getNextDumpFile()]
    removeFiles(dumpFiles)

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1])
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    # Store ~50Mb data.
    testRandStr = getRandStr()
    for i in xrange(0, 500):
        o1.addKeyValue(i, getRandStr())
    o1.addKeyValue('test', testRandStr)

    # Wait for replication.
    doTicks(objs, 60, stopFunc=lambda: o1.getValue('test') == testRandStr and \
                                       o2.getValue('test') == testRandStr)

    assert o1.getValue('test') == testRandStr

    o1._forceLogCompaction()
    o2._forceLogCompaction()

    # Wait for disk dump
    doTicks(objs, 8.0)

    o1._destroy()
    o2._destroy()

    a = [getNextAddr(), getNextAddr()]
    o1 = TestObj(a[0], [a[1]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[0])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.COMPACTION_2, dumpFile=dumpFiles[1])
    objs = [o1, o2]
    # Wait for disk load, election and replication
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    assert o1.getValue('test') == testRandStr
    assert o2.getValue('test') == testRandStr

    o1._destroy()
    o2._destroy()

    removeFiles(dumpFiles)

@pytest.mark.skipif(sys.platform == "win32" or platform.python_implementation() != 'CPython', reason="does not run on windows or pypy")
def test_encryptionCorrectPassword():
    assert HAS_CRYPTO

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], password='asd')
    o2 = TestObj(a[1], [a[0]], password='asd')
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    for conn in list(o1._SyncObj__transport._connections.values()) + list(o2._SyncObj__transport._connections.values()):
        conn.disconnect()

    doTicks(objs, 10)

    o1.addValue(100)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 450 and o2.getCounter() == 450)

    assert o1.getCounter() == 450
    assert o2.getCounter() == 450

    o1._destroy()
    o2._destroy()

@pytest.mark.skipif(platform.python_implementation() != 'CPython', reason="does not have crypto on pypy")
def test_encryptionWrongPassword():
    assert HAS_CRYPTO

    random.seed(12)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]], password='asd')
    o2 = TestObj(a[1], [a[2], a[0]], password='asd')
    o3 = TestObj(a[2], [a[0], a[1]], password='qwe')
    objs = [o1, o2, o3]

    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    doTicks(objs, 1.0)
    assert o3._getLeader() is None

    o1._destroy()
    o2._destroy()
    o3._destroy()


def _checkSameLeader(objs):
    for obj1 in objs:
        l1 = obj1._getLeader()
        if l1 != obj1._SyncObj__selfNode:
            continue
        t1 = obj1._getTerm()
        for obj2 in objs:
            l2 = obj2._getLeader()
            if l2 != obj2._SyncObj__selfNode:
                continue
            if obj2._getTerm() != t1:
                continue
            if l2 != l1:
                obj1._printStatus()
                obj2._printStatus()
                return False
    return True


def _checkSameLeader2(objs):
    for obj1 in objs:
        l1 = obj1._getLeader()
        if l1 is None:
            continue
        t1 = obj1._getTerm()
        for obj2 in objs:
            l2 = obj2._getLeader()
            if l2 is None:
                continue
            if obj2._getTerm() != t1:
                continue
            if l2 != l1:
                obj1._printStatus()
                obj2._printStatus()
                return False
    return True


def test_randomTest1():
    journalFiles = [getNextJournalFile(), getNextJournalFile(), getNextJournalFile()]
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])

    random.seed(12)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]], TEST_TYPE.RAND_1, journalFile=journalFiles[0])
    o2 = TestObj(a[1], [a[2], a[0]], TEST_TYPE.RAND_1, journalFile=journalFiles[1])
    o3 = TestObj(a[2], [a[0], a[1]], TEST_TYPE.RAND_1, journalFile=journalFiles[2])
    objs = [o1, o2, o3]

    raft_commit_indices = [0, 0, 0]

    st = time.time()
    while time.time() - st < 120.0:
        doTicks(objs, random.random() * 0.3, interval=0.05)

        for i in range(3):
            new_commit_idx = objs[i]._SyncObj__raftCommitIndex
            assert new_commit_idx >= raft_commit_indices[i]
            raft_commit_indices[i] = new_commit_idx

        assert _checkSameLeader(objs)
        assert _checkSameLeader2(objs)
        for i in xrange(0, random.randint(0, 2)):
            random.choice(objs).addValue(random.randint(0, 10))
        newObjs = list(objs)
        newObjs.pop(random.randint(0, len(newObjs) - 1))
        doTicks(newObjs, random.random() * 0.3, interval=0.05)

        for i in range(3):
            new_commit_idx = objs[i]._SyncObj__raftCommitIndex
            assert new_commit_idx >= raft_commit_indices[i]
            raft_commit_indices[i] = new_commit_idx

        assert _checkSameLeader(objs)
        assert _checkSameLeader2(objs)
        for i in xrange(0, random.randint(0, 2)):
            random.choice(objs).addValue(random.randint(0, 10))

    if not (o1.getCounter() == o2.getCounter() == o3.getCounter()):
        print(time.time(), 'counters:', o1.getCounter(), o2.getCounter(), o3.getCounter())

        # disable send delays to make test finish faster
        for obj in objs:
            obj._SyncObj__transport._send_random_sleep_duration = 0.00

    st = time.time()
    while not (o1.getCounter() == o2.getCounter() == o3.getCounter()):
        doTicks(objs, 2.0, interval=0.05)
        if time.time() - st > 30:
            break

    if not (o1.getCounter() == o2.getCounter() == o3.getCounter()):
        o1._printStatus()
        o2._printStatus()
        o3._printStatus()
        print('Logs same:', o1._SyncObj__raftLog == o2._SyncObj__raftLog == o3._SyncObj__raftLog)
        print(time.time(), 'counters:', o1.getCounter(), o2.getCounter(), o3.getCounter())
        raise AssertionError('Values not equal')

    counter = o1.getCounter()
    o1._destroy()
    o2._destroy()
    o3._destroy()
    del o1
    del o2
    del o3
    time.sleep(0.1)

    o1 = TestObj(a[0], [a[1], a[2]], TEST_TYPE.RAND_1, journalFile=journalFiles[0])
    o2 = TestObj(a[1], [a[2], a[0]], TEST_TYPE.RAND_1, journalFile=journalFiles[1])
    o3 = TestObj(a[2], [a[0], a[1]], TEST_TYPE.RAND_1, journalFile=journalFiles[2])
    objs = [o1, o2, o3]

    st = time.time()
    while not (o1.getCounter() == o2.getCounter() == o3.getCounter() == counter):
        doTicks(objs, 2.0, interval=0.05)
        if time.time() - st > 30:
            break

    if not (o1.getCounter() == o2.getCounter() == o3.getCounter() >= counter):
        o1._printStatus()
        o2._printStatus()
        o3._printStatus()
        print('Logs same:', o1._SyncObj__raftLog == o2._SyncObj__raftLog == o3._SyncObj__raftLog)
        print(time.time(), 'counters:', o1.getCounter(), o2.getCounter(), o3.getCounter(), counter)
        raise AssertionError('Values not equal')

    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])


# Ensure that raftLog after serialization is the same as in serialized data
def test_logCompactionRegressionTest1():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]])
    o2 = TestObj(a[1], [a[0]])
    objs = [o1, o2]

    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    o1._forceLogCompaction()
    doTicks(objs, 0.5)
    assert o1._SyncObj__forceLogCompaction == False
    logAfterCompaction = o1._SyncObj__raftLog
    o1._SyncObj__loadDumpFile(True)
    logAfterDeserialize = o1._SyncObj__raftLog
    assert logAfterCompaction == logAfterDeserialize
    o1._destroy()
    o2._destroy()


def test_logCompactionRegressionTest2():
    dumpFiles = [getNextDumpFile(), getNextDumpFile(), getNextDumpFile()]
    removeFiles(dumpFiles)

    random.seed(12)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]], dumpFile=dumpFiles[0])
    o2 = TestObj(a[1], [a[2], a[0]], dumpFile=dumpFiles[1])
    o3 = TestObj(a[2], [a[0], a[1]], dumpFile=dumpFiles[2])
    objs = [o1, o2]

    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    objs = [o1, o2, o3]
    o1.addValue(2)
    o1.addValue(3)
    doTicks(objs, 10, stopFunc=lambda: o3.getCounter() == 5)

    o3._forceLogCompaction()
    doTicks(objs, 0.5)

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader() == o3._getLeader()

    o3._destroy()

    objs = [o1, o2]

    o1.addValue(2)
    o1.addValue(3)

    doTicks(objs, 0.5)
    o1._forceLogCompaction()
    o2._forceLogCompaction()
    doTicks(objs, 0.5)

    o3 = TestObj(a[2], [a[0], a[1]], dumpFile=dumpFiles[2])
    objs = [o1, o2, o3]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    o1._destroy()
    o2._destroy()
    o3._destroy()

    removeFiles(dumpFiles)


def __checkParnerNodeExists(obj, nodeAddr, shouldExist=True):
    nodeAddrSet = {node.address for node in obj._SyncObj__otherNodes}
    return (
                   nodeAddr in nodeAddrSet) == shouldExist  # either nodeAddr is in nodeAddrSet and shouldExist is True, or nodeAddr isn't in the set and shouldExist is False


def test_doChangeClusterUT1():
    dumpFiles = [getNextDumpFile()]
    removeFiles(dumpFiles)

    baseAddr = getNextAddr()
    oterAddr = getNextAddr()

    o1 = TestObj(baseAddr, ['localhost:1235', oterAddr], dumpFile=dumpFiles[0], dynamicMembershipChange=True)
    __checkParnerNodeExists(o1, 'localhost:1238', False)
    __checkParnerNodeExists(o1, 'localhost:1239', False)
    __checkParnerNodeExists(o1, 'localhost:1235', True)

    noop = _bchr(_COMMAND_TYPE.NO_OP)
    member = _bchr(_COMMAND_TYPE.MEMBERSHIP)

    # Check regular configuration change - adding
    o1._SyncObj__onMessageReceived(TCPNode('localhost:12345'), {
        'type': 'append_entries',
        'term': 1,
        'prevLogIdx': 1,
        'prevLogTerm': 0,
        'commit_index': 2,
        'entries': [(noop, 2, 1), (noop, 3, 1), (member + pickle.dumps(['add', 'localhost:1238']), 4, 1)]
    })
    __checkParnerNodeExists(o1, 'localhost:1238', True)
    __checkParnerNodeExists(o1, 'localhost:1239', False)

    # Check rollback adding
    o1._SyncObj__onMessageReceived(TCPNode('localhost:1236'), {
        'type': 'append_entries',
        'term': 2,
        'prevLogIdx': 2,
        'prevLogTerm': 1,
        'commit_index': 3,
        'entries': [(noop, 3, 2), (member + pickle.dumps(['add', 'localhost:1239']), 4, 2)]
    })
    __checkParnerNodeExists(o1, 'localhost:1238', False)
    __checkParnerNodeExists(o1, 'localhost:1239', True)
    __checkParnerNodeExists(o1, oterAddr, True)

    # Check regular configuration change - removing
    o1._SyncObj__onMessageReceived(TCPNode('localhost:1236'), {
        'type': 'append_entries',
        'term': 2,
        'prevLogIdx': 4,
        'prevLogTerm': 2,
        'commit_index': 4,
        'entries': [(member + pickle.dumps(['rem', 'localhost:1235']), 5, 2)]
    })

    __checkParnerNodeExists(o1, 'localhost:1238', False)
    __checkParnerNodeExists(o1, 'localhost:1239', True)
    __checkParnerNodeExists(o1, 'localhost:1235', False)

    # Check log compaction
    o1._forceLogCompaction()
    doTicks([o1], 0.5)
    o1._destroy()

    o2 = TestObj(oterAddr, [baseAddr, 'localhost:1236'], dumpFile='dump1.bin', dynamicMembershipChange=True)
    doTicks([o2], 0.5)

    __checkParnerNodeExists(o2, oterAddr, False)
    __checkParnerNodeExists(o2, baseAddr, True)
    __checkParnerNodeExists(o2, 'localhost:1238', False)
    __checkParnerNodeExists(o2, 'localhost:1239', True)
    __checkParnerNodeExists(o2, 'localhost:1235', False)
    o2._destroy()

    removeFiles(dumpFiles)


def test_doChangeClusterUT2():
    a = [getNextAddr(), getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]], dynamicMembershipChange=True)
    o2 = TestObj(a[1], [a[2], a[0]], dynamicMembershipChange=True)
    o3 = TestObj(a[2], [a[0], a[1]], dynamicMembershipChange=True)

    doTicks([o1, o2, o3], 10, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady() == o2._isReady() == o3._isReady() == True
    o3.addValue(50)
    o2.addNodeToCluster(a[3])

    success = False
    for i in xrange(10):
        doTicks([o1, o2, o3], 0.5)
        res = True
        res &= __checkParnerNodeExists(o1, a[3], True)
        res &= __checkParnerNodeExists(o2, a[3], True)
        res &= __checkParnerNodeExists(o3, a[3], True)
        if res:
            success = True
            break
        o2.addNodeToCluster(a[3])

    assert success

    o4 = TestObj(a[3], [a[0], a[1], a[2]], dynamicMembershipChange=True)
    doTicks([o1, o2, o3, o4], 10, stopFunc=lambda: o4._isReady())
    o1.addValue(450)
    doTicks([o1, o2, o3, o4], 10, stopFunc=lambda: o4.getCounter() == 500)
    assert o4.getCounter() == 500

    o1._destroy()
    o2._destroy()
    o3._destroy()
    o4._destroy()


def test_journalTest1():
    dumpFiles = [getNextDumpFile(), getNextDumpFile()]
    journalFiles = [getNextJournalFile(), getNextJournalFile()]
    removeFiles(dumpFiles)
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[1], journalFile=journalFiles[1])
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1._destroy()
    o2._destroy()

    a = [getNextAddr(), getNextAddr()]
    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[1], journalFile=journalFiles[1])
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and \
                                       o1.getCounter() == 350 and o2.getCounter() == 350)
    assert o1._isReady()
    assert o2._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1.addValue(100)
    o2.addValue(150)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 600 and o2.getCounter() == 600)

    assert o1.getCounter() == 600
    assert o2.getCounter() == 600

    o1._forceLogCompaction()
    o2._forceLogCompaction()

    doTicks(objs, 0.5)

    o1.addValue(150)
    o2.addValue(150)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 900 and o2.getCounter() == 900)

    assert o1.getCounter() == 900
    assert o2.getCounter() == 900

    o1._destroy()
    o2._destroy()

    a = [getNextAddr(), getNextAddr()]
    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[1], journalFile=journalFiles[1])
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady() and \
                                       o1.getCounter() == 900 and o2.getCounter() == 900)
    assert o1._isReady()
    assert o2._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    assert o1.getCounter() == 900
    assert o2.getCounter() == 900

    o1._destroy()
    o2._destroy()

    removeFiles(dumpFiles)
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])


def test_journalTest2():
    journalFiles = [getNextJournalFile()]
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])

    removeFiles(journalFiles)
    journal = createJournal(journalFiles[0])
    journal.add(b'cmd1', 1, 0)
    journal.add(b'cmd2', 2, 0)
    journal.add(b'cmd3', 3, 0)
    journal._destroy()

    journal = createJournal(journalFiles[0])
    assert len(journal) == 3
    assert journal[0] == (b'cmd1', 1, 0)
    assert journal[-1] == (b'cmd3', 3, 0)
    journal.deleteEntriesFrom(2)
    journal._destroy()

    journal = createJournal(journalFiles[0])
    assert len(journal) == 2
    assert journal[0] == (b'cmd1', 1, 0)
    assert journal[-1] == (b'cmd2', 2, 0)
    journal.deleteEntriesTo(1)
    journal._destroy()

    journal = createJournal(journalFiles[0])
    assert len(journal) == 1
    assert journal[0] == (b'cmd2', 2, 0)
    journal._destroy()
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])


def test_applyJournalAfterRestart():
    dumpFiles = [getNextDumpFile(), getNextDumpFile()]
    journalFiles = [getNextJournalFile(), getNextJournalFile()]
    removeFiles(dumpFiles)
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[1], journalFile=journalFiles[1])
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350
    doTicks(objs, 2)

    o1._destroy()
    o2._destroy()

    removeFiles(dumpFiles)

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0])
    objs = [o1]
    doTicks(objs, 10, o1.getCounter() == 350)

    assert o1.getCounter() == 350

    removeFiles(dumpFiles)
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])


def test_autoTick1():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.AUTO_TICK_1)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.AUTO_TICK_1)

    assert not o1._isReady()
    assert not o2._isReady()

    time.sleep(4.5)
    assert o1._isReady()
    assert o2._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._isReady()
    assert o2._isReady()

    o1.addValue(150)
    o2.addValue(200)

    time.sleep(1.5)

    assert o1._isReady()
    assert o2._isReady()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    assert o2.addValueSync(10) == 360
    assert o1.addValueSync(20) == 380

    o1._destroy()
    o2._destroy()
    time.sleep(0.5)


def test_largeCommands():
    dumpFiles = [getNextDumpFile(), getNextDumpFile()]
    removeFiles(dumpFiles)

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.LARGE_COMMAND, dumpFile=dumpFiles[0], leaderFallbackTimeout=60.0)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.LARGE_COMMAND, dumpFile=dumpFiles[1], leaderFallbackTimeout=60.0)
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    # Generate ~20Mb data.
    testRandStr = getRandStr()
    bigStr = ''
    for i in xrange(0, 200):
        bigStr += getRandStr()
    o1.addKeyValue('big', bigStr)
    o1.addKeyValue('test', testRandStr)

    # Wait for replication.
    doTicks(objs, 60, stopFunc=lambda: o1.getValue('test') == testRandStr and \
                                       o2.getValue('test') == testRandStr and \
                                       o1.getValue('big') == bigStr and \
                                       o2.getValue('big') == bigStr)

    assert o1.getValue('test') == testRandStr
    assert o2.getValue('big') == bigStr

    o1._forceLogCompaction()
    o2._forceLogCompaction()

    # Wait for disk dump
    doTicks(objs, 8.0)

    o1._destroy()
    o2._destroy()

    a = [getNextAddr(), getNextAddr()]
    o1 = TestObj(a[0], [a[1]], TEST_TYPE.LARGE_COMMAND, dumpFile=dumpFiles[0], leaderFallbackTimeout=60.0)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.LARGE_COMMAND, dumpFile=dumpFiles[1], leaderFallbackTimeout=60.0)
    objs = [o1, o2]
    # Wait for disk load, election and replication

    doTicks(objs, 60, stopFunc=lambda: o1.getValue('test') == testRandStr and \
                                       o2.getValue('test') == testRandStr and \
                                       o1.getValue('big') == bigStr and \
                                       o2.getValue('big') == bigStr and \
                                       o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    assert o1.getValue('test') == testRandStr
    assert o2.getValue('big') == bigStr
    assert o1.getValue('test') == testRandStr
    assert o2.getValue('big') == bigStr

    o1._destroy()
    o2._destroy()

    removeFiles(dumpFiles)

@pytest.mark.skipif(platform.python_implementation() != 'CPython', reason="does not have crypto on pypy")
def test_readOnlyNodes():
    random.seed(12)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[2]], password='123')
    o2 = TestObj(a[1], [a[2], a[0]], password='123')
    o3 = TestObj(a[2], [a[0], a[1]], password='123')
    objs = [o1, o2, o3]

    b1 = TestObj(None, [a[0], a[1], a[2]], password='123')
    b2 = TestObj(None, [a[0], a[1], a[2]], password='123')

    roObjs = [b1, b2]

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10.0, stopFunc=lambda: o3.getCounter() == 350)

    doTicks(objs + roObjs, 4.0, stopFunc=lambda: b1.getCounter() == 350 and b2.getCounter() == 350)

    assert b1.getCounter() == b2.getCounter() == 350
    assert o1._getLeader() == b1._getLeader() == o2._getLeader() == b2._getLeader()
    assert b1._getLeader().address in a

    prevLeader = o1._getLeader()

    newObjs = [o for o in objs if o._SyncObj__selfNode != prevLeader]

    assert len(newObjs) == 2

    doTicks(newObjs + roObjs, 10.0, stopFunc=lambda: newObjs[0]._getLeader() != prevLeader and \
                                                     newObjs[0]._getLeader() is not None and \
                                                     newObjs[0]._getLeader().address in a and \
                                                     newObjs[0]._getLeader() == newObjs[1]._getLeader())

    assert newObjs[0]._getLeader() != prevLeader
    assert newObjs[0]._getLeader().address in a
    assert newObjs[0]._getLeader() == newObjs[1]._getLeader()

    newObjs[1].addValue(50)

    doTicks(newObjs + roObjs, 10.0, stopFunc=lambda: newObjs[0].getCounter() == 400 and b1.getCounter() == 400)

    o1._printStatus()
    o2._printStatus()
    o3._printStatus()

    b1._printStatus()

    assert newObjs[0].getCounter() == 400
    assert b1.getCounter() == 400

    doTicks(objs + roObjs, 10.0,
            stopFunc=lambda: sum([int(o.getCounter() == 400) for o in objs + roObjs]) == len(objs + roObjs))

    for o in objs + roObjs:
        assert o.getCounter() == 400

    currRes = {}

    def onAdd(res, err):
        currRes[0] = err

    b1.addValue(50, callback=onAdd)

    doTicks(objs + roObjs, 5.0, stopFunc=lambda: o1.getCounter() == 450 and \
                                                 b1.getCounter() == 450 and \
                                                 b2.getCounter() == 450 and
                                                 currRes.get(0) == FAIL_REASON.SUCCESS)
    assert o1.getCounter() == 450
    assert b1.getCounter() == 450
    assert b2.getCounter() == 450
    assert currRes.get(0) == FAIL_REASON.SUCCESS


    # check that all objects have 2 readonly nodes
    assert all(map(lambda o: o.getStatus()['readonly_nodes_count'] == 2, objs))

    # disconnect readonly node
    b1._destroy()
    doTicks(objs, 2.0)

    assert all(map(lambda o: o.getStatus()['readonly_nodes_count'] == 1, objs))



    o1._destroy()
    o2._destroy()
    o3._destroy()

    b1._destroy()
    b2._destroy()


@pytest.mark.skipif(platform.python_implementation() != 'CPython', reason="does not have crypto on pypy")
def test_syncobjAdminStatus():
    assert HAS_CRYPTO

    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], password='123')
    o2 = TestObj(a[1], [a[0]], password='123')

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._isReady()
    assert o2._isReady()

    status1 = o1.getStatus()
    status2 = o2.getStatus()

    assert 'version' in status1
    assert 'log_len' in status2

    trueRes = {
        o1: '\n'.join('%s: %s' % (k, v) for k, v in sorted(status1.items())),
        o2: '\n'.join('%s: %s' % (k, v) for k, v in sorted(status2.items())),
    }

    currRes = {
    }
    args = {
        o1: ['-conn', a[0], '-pass', '123', '-status'],
        o2: ['-conn', a[1], '-pass', '123', '-status'],
    }
    doSyncObjAdminTicks([o1, o2], args, 10.0, currRes,
                        stopFunc=lambda: currRes.get(o1) is not None and currRes.get(o2) is not None)

    assert len(currRes[o1]) == len(trueRes[o1])
    assert len(currRes[o2]) == len(trueRes[o2])

    o1._destroy()
    o2._destroy()


def test_syncobjAdminAddRemove():
    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], dynamicMembershipChange=True)
    o2 = TestObj(a[1], [a[0]], dynamicMembershipChange=True)

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._isReady()
    assert o2._isReady()

    trueRes = 'SUCCESS ADD ' + a[2]

    currRes = {}

    args = {
        o1: ['-conn', a[0], '-add', a[2]],
    }

    doSyncObjAdminTicks([o1, o2], args, 10.0, currRes, stopFunc=lambda: currRes.get(o1) is not None)

    assert currRes[o1] == trueRes

    o3 = TestObj(a[2], [a[1], a[0]], dynamicMembershipChange=True)

    doTicks([o1, o2, o3], 10.0, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    trueRes = 'SUCCESS REMOVE ' + a[2]
    args[o1] = None
    args[o2] = ['-conn', a[1], '-remove', a[2]]

    doSyncObjAdminTicks([o1, o2, o3], args, 10.0, currRes, stopFunc=lambda: currRes.get(o2) is not None)

    assert currRes[o2] == trueRes

    o3._destroy()

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._isReady()
    assert o2._isReady()

    o1._destroy()
    o2._destroy()


def test_journalWithAddNodes():
    dumpFiles = [getNextDumpFile(), getNextDumpFile(), getNextDumpFile()]
    journalFiles = [getNextJournalFile(), getNextJournalFile(), getNextJournalFile()]
    removeFiles(dumpFiles)
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])

    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0], dynamicMembershipChange=True)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[1], journalFile=journalFiles[1], dynamicMembershipChange=True)
    objs = [o1, o2]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350
    doTicks(objs, 2)


    trueRes = 'SUCCESS ADD ' + a[2]
    currRes = {}
    args = {
        o1: ['-conn', a[0], '-add', a[2]],
    }
    doSyncObjAdminTicks([o1, o2], args, 10.0, currRes, stopFunc=lambda: currRes.get(o1) is not None)

    assert currRes[o1] == trueRes

    o3 = TestObj(a[2], [a[1], a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[2], journalFile=journalFiles[2], dynamicMembershipChange=True)

    doTicks([o1, o2, o3], 10.0, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    assert o3.getCounter() == 350

    doTicks(objs, 2)


    o1._destroy()
    o2._destroy()
    o3._destroy()

    removeFiles(dumpFiles)

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[0], journalFile=journalFiles[0], dynamicMembershipChange=True)
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[1], journalFile=journalFiles[1], dynamicMembershipChange=True)
    o3 = TestObj(a[2], [a[1], a[0]], TEST_TYPE.JOURNAL_1, dumpFile=dumpFiles[2], journalFile=journalFiles[2], dynamicMembershipChange=True)

    objs = [o1, o2, o3]
    doTicks(objs, 10, stopFunc=lambda: o1._isReady() and o1.getCounter() == 350 and o3._isReady() and o3.getCounter() == 350)

    assert o1._isReady()
    assert o3._isReady()

    assert o1.getCounter() == 350
    assert o3.getCounter() == 350

    o2.addValue(200)

    doTicks(objs, 10, stopFunc=lambda: o1.getCounter() == 550 and o3.getCounter() == 550)

    assert o1.getCounter() == 550
    assert o3.getCounter() == 550

    o1._destroy()
    o2._destroy()
    o3._destroy()

    removeFiles(dumpFiles)
    removeFiles(journalFiles)
    removeFiles([e + '.meta' for e in journalFiles])


def test_syncobjAdminSetVersion():
    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], dynamicMembershipChange=True)
    o2 = TestObj(a[1], [a[0]], dynamicMembershipChange=True)

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._isReady()
    assert o2._isReady()

    assert o1.getCodeVersion() == 0
    assert o2.getCodeVersion() == 0

    o2.testMethod()

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1.getValue('testKey') == 'valueVer1' and \
                                             o2.getValue('testKey') == 'valueVer1')

    assert o1.getValue('testKey') == 'valueVer1'
    assert o2.getValue('testKey') == 'valueVer1'

    trueRes = 'SUCCESS SET_VERSION 1'

    currRes = {}

    args = {
        o1: ['-conn', a[0], '-set_version', '1'],
    }

    doSyncObjAdminTicks([o1, o2], args, 10.0, currRes, stopFunc=lambda: currRes.get(o1) is not None)

    assert currRes[o1] == trueRes

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1.getCodeVersion() == 1 and o2.getCodeVersion() == 1)

    assert o1.getCodeVersion() == 1
    assert o2.getCodeVersion() == 1

    o2.testMethod()

    doTicks([o1, o2], 10.0, stopFunc=lambda: o1.getValue('testKey') == 'valueVer2' and \
                                             o2.getValue('testKey') == 'valueVer2')

    assert o1.getValue('testKey') == 'valueVer2'
    assert o2.getValue('testKey') == 'valueVer2'

    o1._destroy()
    o2._destroy()


@pytest.mark.skipif(os.name == 'nt', reason='temporary disabled for windows')
def test_syncobjWaitBinded():
    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], testType=TEST_TYPE.WAIT_BIND)
    o2 = TestObj(a[1], [a[0]], testType=TEST_TYPE.WAIT_BIND)

    o1.waitBinded()
    o2.waitBinded()

    o3 = TestObj(a[1], [a[0]], testType=TEST_TYPE.WAIT_BIND)
    with pytest.raises(SyncObjException):
        o3.waitBinded()

    o1.destroy()
    o2.destroy()
    o3.destroy()


@pytest.mark.skipif(os.name == 'nt', reason='temporary disabled for windows')
def test_unpickle():
    data = {'foo': 'bar', 'command': b'\xfa', 'entries': [b'\xfb', b'\xfc']}
    python2_cpickle = b'\x80\x02}q\x01(U\x03fooq\x02U\x03barq\x03U\x07commandq\x04U\x01\xfaU\x07entriesq\x05]q\x06(U\x01\xfbU\x01\xfceu.'
    python2_pickle = b'\x80\x02}q\x00(U\x03fooq\x01U\x03barq\x02U\x07commandq\x03U\x01\xfaq\x04U\x07entriesq\x05]q\x06(U\x01\xfbq\x07U\x01\xfcq\x08eu.'
    python3_pickle = b'\x80\x02}q\x00(X\x03\x00\x00\x00fooq\x01X\x03\x00\x00\x00barq\x02X\x07\x00\x00\x00commandq\x03c_codecs\nencode\nq\x04X\x02\x00\x00\x00\xc3\xbaq\x05X\x06\x00\x00\x00latin1q\x06\x86q\x07Rq\x08X\x07\x00\x00\x00entriesq\t]q\n(h\x04X\x02\x00\x00\x00\xc3\xbbq\x0bh\x06\x86q\x0cRq\rh\x04X\x02\x00\x00\x00\xc3\xbcq\x0eh\x06\x86q\x0fRq\x10eu.'

    python2_cpickle_data = pickle.loads(python2_cpickle)
    assert data == python2_cpickle_data, 'Failed to unpickle data pickled by python2 cPickle'

    python2_pickle_data = pickle.loads(python2_pickle)
    assert data == python2_pickle_data, 'Failed to unpickle data pickled by python2 pickle'

    python3_pickle_data = pickle.loads(python3_pickle)
    assert data == python3_pickle_data, 'Failed to unpickle data pickled by python3 pickle'


class TestConsumer1(SyncObjConsumer):
    def __init__(self):
        super(TestConsumer1, self).__init__()
        self.__counter = 0

    @replicated
    def add(self, value):
        self.__counter += value

    @replicated
    def set(self, value):
        self.__counter = value

    def get(self):
        return self.__counter


class TestConsumer2(SyncObjConsumer):
    def __init__(self):
        super(TestConsumer2, self).__init__()
        self.__values = {}

    @replicated
    def set(self, key, value):
        self.__values[key] = value

    def get(self, key):
        return self.__values.get(key)


def test_consumers():
    random.seed(42)

    a = [getNextAddr(), getNextAddr(), getNextAddr()]

    c11 = TestConsumer1()
    c12 = TestConsumer1()
    c13 = TestConsumer2()

    c21 = TestConsumer1()
    c22 = TestConsumer1()
    c23 = TestConsumer2()

    c31 = TestConsumer1()
    c32 = TestConsumer1()
    c33 = TestConsumer2()

    o1 = TestObj(a[0], [a[1], a[2]], consumers=[c11, c12, c13])
    o2 = TestObj(a[1], [a[0], a[2]], consumers=[c21, c22, c23])
    o3 = TestObj(a[2], [a[0], a[1]], consumers=[c31, c32, c33])
    objs = [o1, o2]

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._isReady()
    assert o2._isReady()

    c11.set(42)
    c11.add(10)
    c12.add(15)
    c13.set('testKey', 'testValue')
    doTicks(objs, 10.0, stopFunc=lambda: c21.get() == 52 and c22.get() == 15 and c23.get('testKey') == 'testValue')

    assert c21.get() == 52
    assert c22.get() == 15
    assert c23.get('testKey') == 'testValue'

    o1.forceLogCompaction()
    o2.forceLogCompaction()
    doTicks(objs, 0.5)
    objs = [o1, o2, o3]

    doTicks(objs, 10.0, stopFunc=lambda: c31.get() == 52 and c32.get() == 15 and c33.get('testKey') == 'testValue')

    assert c31.get() == 52
    assert c32.get() == 15
    assert c33.get('testKey') == 'testValue'

    o1.destroy()
    o2.destroy()
    o3.destroy()


def test_batteriesCommon():
    d1 = ReplDict()
    l1 = ReplLockManager(autoUnlockTime=30.0)

    d2 = ReplDict()
    l2 = ReplLockManager(autoUnlockTime=30.0)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], TEST_TYPE.AUTO_TICK_1, consumers=[d1, l1])
    o2 = TestObj(a[1], [a[0]], TEST_TYPE.AUTO_TICK_1, consumers=[d2, l2])

    doAutoTicks(10.0, stopFunc=lambda: o1.isReady() and o2.isReady())

    assert o1.isReady() and o2.isReady()

    d1.set('testKey', 'testValue', sync=True)
    doAutoTicks(3.0, stopFunc=lambda: d2.get('testKey') == 'testValue')

    assert d2['testKey'] == 'testValue'

    d2.pop('testKey', sync=True)
    doAutoTicks(3.0, stopFunc=lambda: d1.get('testKey') == None)

    assert d1.get('testKey') == None

    assert l1.tryAcquire('test.lock1', sync=True) == True
    assert l2.tryAcquire('test.lock1', sync=True) == False
    assert l2.isAcquired('test.lock1') == False

    l1id = l1._ReplLockManager__selfID
    l1._ReplLockManager__lockImpl.prolongate(l1id, 0, _doApply=True)

    l1.release('test.lock1', sync=True)
    assert l2.tryAcquire('test.lock1', sync=True) == True

    assert d1.setdefault('keyA', 'valueA', sync=True) == 'valueA'
    assert d2.setdefault('keyA', 'valueB', sync=True) == 'valueA'
    d2.pop('keyA', sync=True)
    assert d2.setdefault('keyA', 'valueB', sync=True) == 'valueB'

    o1.destroy()
    o2.destroy()

    l1.destroy()
    l2.destroy()


def test_ReplCounter():
    c = ReplCounter()
    c.set(42, _doApply=True)
    assert c.get() == 42
    c.add(10, _doApply=True)
    assert c.get() == 52
    c.sub(20, _doApply=True)
    assert c.get() == 32
    c.inc(_doApply=True)
    assert c.get() == 33


def test_ReplList():
    l = ReplList()
    l.reset([1, 2, 3], _doApply=True)
    assert l.rawData() == [1, 2, 3]
    l.set(1, 10, _doApply=True)
    assert l.rawData() == [1, 10, 3]
    l.append(42, _doApply=True)
    assert l.rawData() == [1, 10, 3, 42]
    l.extend([5, 6], _doApply=True)
    assert l.rawData() == [1, 10, 3, 42, 5, 6]
    l.insert(2, 66, _doApply=True)
    assert l.rawData() == [1, 10, 66, 3, 42, 5, 6]
    l.remove(66, _doApply=True)
    assert l.rawData() == [1, 10, 3, 42, 5, 6]
    l.pop(1, _doApply=True)
    assert l.rawData() == [1, 3, 42, 5, 6]
    l.sort(reverse=True, _doApply=True)
    assert l.rawData() == [42, 6, 5, 3, 1]
    assert l.index(6) == 1
    assert l.count(42) == 1
    assert l.get(2) == 5
    assert l[4] == 1
    assert len(l) == 5
    l.__setitem__(0, 43, _doApply=True)
    assert l[0] == 43


def test_ReplDict():
    d = ReplDict()

    d.reset({
        1: 1,
        2: 22,
    }, _doApply=True)
    assert d.rawData() == {
        1: 1,
        2: 22,
    }

    d.__setitem__(1, 10, _doApply=True)
    assert d.rawData() == {
        1: 10,
        2: 22,
    }

    d.set(1, 20, _doApply=True)
    assert d.rawData() == {
        1: 20,
        2: 22,
    }

    assert d.setdefault(1, 50, _doApply=True) == 20
    assert d.setdefault(3, 50, _doApply=True) == 50

    d.update({
        5: 5,
        6: 7,
    }, _doApply=True)

    assert d.rawData() == {
        1: 20,
        2: 22,
        3: 50,
        5: 5,
        6: 7,
    }

    assert d.pop(3, _doApply=True) == 50
    assert d.pop(6, _doApply=True) == 7
    assert d.pop(6, _doApply=True) == None
    assert d.pop(6, 0, _doApply=True) == 0

    assert d.rawData() == {
        1: 20,
        2: 22,
        5: 5,
    }

    assert d[1] == 20
    assert d.get(2) == 22
    assert d.get(22) == None
    assert d.get(22, 10) == 10
    assert len(d) == 3
    assert 2 in d
    assert 22 not in d
    assert sorted(d.keys()) == [1, 2, 5]
    assert sorted(d.values()) == [5, 20, 22]
    assert d.items() == d.rawData().items()

    d.clear(_doApply=True)
    assert len(d) == 0


def test_ReplSet():
    s = ReplSet()
    s.reset({1, 4}, _doApply=True)
    assert s.rawData() == {1, 4}

    s.add(10, _doApply=True)
    assert s.rawData() == {1, 4, 10}

    s.remove(1, _doApply=True)
    s.discard(10, _doApply=True)
    assert s.rawData() == {4}

    assert s.pop(_doApply=True) == 4

    s.add(48, _doApply=True)
    s.update({9, 2, 3}, _doApply=True)

    assert s.rawData() == {9, 2, 3, 48}

    assert len(s) == 4
    assert 9 in s
    assert 42 not in s

    s.clear(_doApply=True)
    assert len(s) == 0
    assert 9 not in s


def test_ReplQueue():
    q = ReplQueue()
    q.put(42, _doApply=True)
    q.put(33, _doApply=True)
    q.put(14, _doApply=True)

    assert q.get(_doApply=True) == 42

    assert q.qsize() == 2
    assert len(q) == 2

    assert q.empty() == False

    assert q.get(_doApply=True) == 33
    assert q.get(-1, _doApply=True) == 14
    assert q.get(_doApply=True) == None
    assert q.get(-1, _doApply=True) == -1
    assert q.empty()

    q = ReplQueue(3)
    q.put(42, _doApply=True)
    q.put(33, _doApply=True)
    assert q.full() == False
    assert q.put(14, _doApply=True) == True
    assert q.full() == True
    assert q.put(19, _doApply=True) == False
    assert q.get(_doApply=True) == 42


def test_ReplPriorityQueue():
    q = ReplPriorityQueue()
    q.put(42, _doApply=True)
    q.put(14, _doApply=True)
    q.put(33, _doApply=True)

    assert q.get(_doApply=True) == 14

    assert q.qsize() == 2
    assert len(q) == 2

    assert q.empty() == False

    assert q.get(_doApply=True) == 33
    assert q.get(-1, _doApply=True) == 42
    assert q.get(_doApply=True) == None
    assert q.get(-1, _doApply=True) == -1
    assert q.empty()

    q = ReplPriorityQueue(3)
    q.put(42, _doApply=True)
    q.put(33, _doApply=True)
    assert q.full() == False
    assert q.put(14, _doApply=True) == True
    assert q.full() == True
    assert q.put(19, _doApply=True) == False
    assert q.get(_doApply=True) == 14


# https://github.com/travis-ci/travis-ci/issues/8695
@pytest.mark.skipif(os.name == 'nt' or os.environ.get('TRAVIS') == 'true', reason='temporary disabled for windows')
def test_ipv6():
    random.seed(42)

    a = [getNextAddr(ipv6=True), getNextAddr(ipv6=True)]

    o1 = TestObj(a[0], [a[1]])
    o2 = TestObj(a[1], [a[0]])
    objs = [o1, o2]

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    assert o1._isReady()
    assert o2._isReady()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._isReady()
    assert o2._isReady()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10.0, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1._isReady()
    assert o2._isReady()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1._destroy()
    o2._destroy()


def test_localhost():
    random.seed(42)

    a = [getNextAddr(isLocalhost=True), getNextAddr(isLocalhost=True)]

    o1 = TestObj(a[0], [a[1]])
    o2 = TestObj(a[1], [a[0]])
    objs = [o1, o2]

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks(objs, 3.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    o1.waitBinded()
    o2.waitBinded()

    o1._printStatus()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._isReady()
    assert o2._isReady()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10.0, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350)

    assert o1._isReady()
    assert o2._isReady()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350

    o1._destroy()
    o2._destroy()


def test_leaderFallback():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]], leaderFallbackTimeout=30.0)
    o2 = TestObj(a[1], [a[0]], leaderFallbackTimeout=30.0)
    objs = [o1, o2]

    assert not o1._isReady()
    assert not o2._isReady()

    doTicks(objs, 5.0, stopFunc=lambda: o1._isReady() and o2._isReady())

    o1._SyncObj__conf.leaderFallbackTimeout = 3.0
    o2._SyncObj__conf.leaderFallbackTimeout = 3.0

    doTicks([o for o in objs if o._isLeader()], 2.0)

    assert o1._isLeader() or o2._isLeader()

    doTicks([o for o in objs if o._isLeader()], 2.0)

    assert not o1._isLeader() and not o2._isLeader()


class ZeroDeployConsumerAlpha(SyncObjConsumer):
    @replicated(ver=1)
    def someMethod(self):
        pass

    @replicated
    def methodTwo(self):
        pass


class ZeroDeployConsumerBravo(SyncObjConsumer):
    @replicated
    def alphaMethod(self):
        pass

    @replicated(ver=3)
    def methodTwo(self):
        pass


class ZeroDeployTestObj(SyncObj):
    def __init__(self, selfAddr, otherAddrs, consumers):
        cfg = SyncObjConf(autoTick=False)
        super(ZeroDeployTestObj, self).__init__(selfAddr, otherAddrs, cfg, consumers=consumers)

    @replicated
    def someMethod(self):
        pass

    @replicated
    def otherMethod(self):
        pass

    @replicated(ver=1)
    def thirdMethod(self):
        pass

    @replicated(ver=2)
    def lastMethod(self):
        pass

    @replicated(ver=3)
    def lastMethod(self):
        pass


def test_zeroDeployVersions():
    random.seed(42)

    a = [getNextAddr()]

    cAlpha = ZeroDeployConsumerAlpha()
    cBravo = ZeroDeployConsumerBravo()

    o1 = ZeroDeployTestObj(a[0], [], [cAlpha, cBravo])

    assert hasattr(o1, 'otherMethod_v0') == True
    assert hasattr(o1, 'lastMethod_v2') == True
    assert hasattr(o1, 'lastMethod_v3') == True
    assert hasattr(o1, 'lastMethod_v4') == False
    assert hasattr(cAlpha, 'methodTwo_v0') == True
    assert hasattr(cBravo, 'methodTwo_v3') == True

    assert o1._methodToID['lastMethod_v2'] > o1._methodToID['otherMethod_v0']
    assert o1._methodToID['lastMethod_v3'] > o1._methodToID['lastMethod_v2']
    assert o1._methodToID['lastMethod_v3'] > o1._methodToID['someMethod_v0']
    assert o1._methodToID['thirdMethod_v1'] > o1._methodToID['someMethod_v0']

    assert o1._methodToID['lastMethod_v2'] > o1._methodToID[(id(cAlpha), 'methodTwo_v0')]
    assert o1._methodToID[id(cBravo), 'methodTwo_v3'] > o1._methodToID['lastMethod_v2']

    assert 'someMethod' not in o1._methodToID
    assert 'thirdMethod' not in o1._methodToID
    assert 'lastMethod' not in o1._methodToID


def test_dnsResolverBug(monkeypatch):
    monkeypatch.setattr(dns_resolver, "monotonicTime", lambda: 0.0)
    resolver = dns_resolver.DnsCachingResolver(600, 30)
    ip = resolver.resolve('localhost')
    assert ip == '127.0.0.1'

class MockSocket(object):
    def __init__(self, socket, numSuccessSends):
        self.socket = socket
        self.numSuccessSends = numSuccessSends
    def send(self, data):
        self.numSuccessSends -= 1
        if self.numSuccessSends <= 0:
            return -100500
        return self.socket.send(data)
    def close(self):
        return self.socket.close()
    def getsockopt(self, *args, **kwargs):
        return self.socket.getsockopt(*args, **kwargs)
    def recv(self, *args, **kwargs):
        return self.socket.recv(*args, **kwargs)

def setMockSocket(o, numSuccess = 0):
    for readonlyNode in o._SyncObj__readonlyNodes:
        for node, conn in o._SyncObj__transport._connections.items():
            if node == readonlyNode:
                origSocket = conn._TcpConnection__socket
                conn._TcpConnection__socket = MockSocket(origSocket, numSuccess)
                #origSend = origSocket.send
                #origSocket.send = lambda x: mockSend(origSend, x)
                #print("Set mock send")

def test_readOnlyDrop():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1]])
    o2 = TestObj(a[1], [a[0]])
    o3 = TestObj(None, [a[0], a[1]])
    objs = [o1, o2, o3]

    assert not o1._isReady()
    assert not o2._isReady()
    assert not o3._isReady()

    doTicks(objs, 10.0, stopFunc=lambda: o1._isReady() and o2._isReady() and o3._isReady())

    o1.waitBinded()
    o2.waitBinded()

    o1._printStatus()

    assert o1._getLeader().address in a
    assert o1._getLeader() == o2._getLeader()
    assert o1._isReady()
    assert o2._isReady()
    assert o3._isReady()

    o1.addValue(150)
    o2.addValue(200)

    doTicks(objs, 10.0, stopFunc=lambda: o1.getCounter() == 350 and o2.getCounter() == 350 and o3.getCounter() == 350)

    assert o1._isReady()
    assert o2._isReady()

    assert o1.getCounter() == 350
    assert o2.getCounter() == 350
    assert o3.getCounter() == 350

    setMockSocket(o1, 1)
    setMockSocket(o2, 1)

    global _g_numSuccessSends
    _g_numSuccessSends = 0

    for i in range(150):
        o1.addValue(1)
    for i in range(200):
        o2.addValue(1)

    doTicks(objs, 10.0, stopFunc=lambda: o1.getCounter() == 700 and o2.getCounter() == 700)

    assert o1.getCounter() == 700
    assert o2.getCounter() == 700

    o1._destroy()
    o2._destroy()
    o3._destroy()


def test_filterParners():
    random.seed(42)

    a = [getNextAddr(), getNextAddr()]

    o1 = TestObj(a[0], [a[1], a[0]])
    assert len(o1._SyncObj__otherNodes) == 1