This file is indexed.

/usr/lib/python3/dist-packages/dbf/tests.py is in python3-dbf 0.96.005-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
import codecs
import os
import sys
import unittest
import tempfile
import shutil
import datetime
import traceback

py_ver = sys.version_info[:2]
module = globals()

import dbf
from dbf.api import *

if py_ver < (3, 0):
    EOF = '\x1a'
    MISC = ''.join([chr(i) for i in range(256)])
    PHOTO = ''.join(reversed([chr(i) for i in range(256)]))
else:
    unicode = str
    xrange = range
    dbf.LatinByte.export_to(module)
    MISC = ''.join([chr(i) for i in range(256)]).encode('latin-1')
    PHOTO = ''.join(reversed([chr(i) for i in range(256)])).encode('latin-1')


print("\nTesting dbf version %d.%02d.%03d on %s with Python %s\n" % (
    dbf.version + (sys.platform, sys.version) ))


# Walker in Leaves -- by Scot Noel -- http://www.scienceandfantasyfiction.com/sciencefiction/Walker-in-Leaves/walker-in-leaves.htm

words = """
Soft rains, given time, have rounded the angles of great towers. Generation after generation, wind borne seeds have brought down cities amid the gentle tangle of their roots. All statues of stone have been worn away.
Still one statue, not of stone, holds its lines against the passing years.
Sunlight, fading autumn light, warms the sculpture as best it can, almost penetrating to its dreaming core. The figure is that of a woman, once the fair sex of a species now untroubled and long unseen. Man sleeps the sleep of extinction. This one statue remains. Behind the grace of its ivory brow and gentle, unseeing eyes, the statue dreams.
A susurrus of voices, a flutter of images, and the dream tumbles down through the long morning. Suspended. Floating on the stream that brings from the heart of time the wandering self. Maya  for that is the statue s name-- is buoyed by the sensation, rising within the cage of consciousness, but asleep. She has been this way for months: the unmoving figure of a woman caught in mid stride across the glade. The warmth of sunlight on her face makes her wonder if she will ever wake again.
Even at the end, there was no proper word for what Maya has become. Robot. Cybernetic Organism. Android. These are as appropriate to her condition as calling the stars campfires of the night sky and equally precise. It is enough to know that her motive energies are no longer sun and sustenance, and though Maya was once a living woman, a scientist, now she inhabits a form of ageless attraction. It is a form whose energies are flagging.
With great determination, Maya moves toward wakefulness. Flex a finger. Move a hand. Think of the lemurs, their tongues reaching out in stroke after stroke for the drip of the honeyed thorns. Though there is little time left to save her charges, Maya s only choice is the patience of the trees. On the day her energies return, it is autumn of the year following the morning her sleep began. Maya opens her eyes. The woman, the frozen machine --that which is both-- moves once more.
Two lemur cubs tumbling near the edge of the glade take notice. One rushes forward to touch Maya s knee and laugh. Maya reaches out with an arthritic hand, cold in its sculpted smoothness, but the lemur darts away. Leaves swirl about its retreat, making a crisp sound. The cub displays a playfulness Maya s fevered mind cannot match. The second cub rolls between her moss covered feet, laughing. The lemurs are her charges, and she is failing them. Still, it is good to be awake.
Sugar maples and sumacs shoulder brilliant robes. In the low sun, their orange and purple hues startle the heart. Of course, Maya has no beating organ, no heart. Her life energies are transmitted from deep underground. Nor are the cubs truly lemurs, nor the sugar maples the trees of old. The names have carried for ten million seasons, but the species have changed. Once the lemurs inhabited an island off the southeast coast of a place called Africa. Now they are here, much changed, in the great forests of the northern climes.
The young lemurs seem hale, and it speaks well for their consanguine fellows. But their true fate lies in the story of DNA, of a few strands in the matriarchal line, of a sequence code-named "hope." No doubt a once clever acronym, today Maya s clouded mind holds nothing of the ancient codes. She knows only that a poet once spoke of hope as "the thing with feathers that perches in the soul." Emily Dickinson. A strange name, and so unlike the agnomen of the lemurs. What has become of Giver-of-Corn?
Having no reason to alarm the cubs, Maya moves with her hands high, so that any movement will be down as leaves fall. Though anxious about Giver-of-Corn, she ambles on to finish the mission begun six months earlier. Ahead, the shadow of a mound rises up beneath a great oak. A door awaits. Somewhere below the forest, the engine that gives her life weakens. Held in sway to its faltering beat her mind and body froze, sending her into an abyss of dreams. She has been striding toward that door for half a year, unknowing if she would ever wake again.
Vines lose their toughened grip as the door responds to Maya s approach. Regretfully, a tree root snaps, but the door shudders to a halt before its whine of power can cross the glade. Suddenly, an opening has been made into the earth, and Maya steps lightly on its downward slope. Without breathing, she catches a scent of mold and of deep, uncirculated water. A flutter like the sound of wings echoes from the hollow. Her vision adjusts as she descends. In spots, lights attempt to greet her, but it is a basement she enters, flickering and ancient, where the footfalls of millipedes wear tracks in grime older than the forest above. After a long descent, she steps into water.
How long ago was it that the floor was dry? The exactitude of such time, vast time, escapes her.
Once this place sustained great scholars, scientists. Now sightless fish skip through broken walls, retreating as Maya wades their private corridors, finding with each step that she remembers the labyrinthine path to the heart of power. A heart that flutters like dark wings. And with it, she flutters too. The closer she comes to the vault in which the great engine is housed, the less hopeful she becomes.
The vault housing the engine rests beneath a silvered arch. Its mirrored surface denies age, even as a new generation of snails rise up out of the dark pool, mounting first the dais of pearled stone left by their ancestors, the discarded shells of millions, then higher to where the overhang drips, layered in egg sacs bright as coral.
Maya has no need to set the vault door in motion, to break the dance of the snails. The state of things tells her all she needs to know. There shall be no repairs, no rescue; the engine will die, and she with it. Still, it is impossible not to check. At her touch, a breath of firefly lights coalesces within the patient dampness of the room. They confirm. The heart is simply too tired to go on. Its last reserves wield processes of great weight and care, banking the fires of its blood, dimming the furnace into safe resolve. Perhaps a month or two in cooling, then the last fire kindled by man shall die.
For the figure standing knee deep in water the issues are more immediate. The powers that allow her to live will be the first to fade. It is amazing, even now, that she remains cognizant.
For a moment, Maya stands transfixed by her own reflection. The silvered arch holds it as moonlight does a ghost. She is a sculpted thing with shoulders of white marble. Lips of stone. A child s face. No, the grace of a woman resides in the features, as though eternity can neither deny the sage nor touch the youth. Demeter. The Earth Mother.
Maya smiles at the Greek metaphor. She has never before thought of herself as divine, nor monumental. When the energies of the base are withdrawn entirely, she will become immobile. Once a goddess, then a statue to be worn away by endless time, the crumbling remnant of something the self has ceased to be. Maya trembles at the thought. The last conscious reserve of man will soon fade forever from the halls of time.
As if hewn of irresolute marble, Maya begins to shake; were she still human there would be sobs; there would be tears to moisten her grief and add to the dark waters at her feet.
In time, Maya breaks the spell. She sets aside her grief to work cold fingers over the dim firefly controls, giving what priorities remain to her survival. In response, the great engine promises little, but does what it can.
While life remains, Maya determines to learn what she can of the lemurs, of their progress, and the fate of the matriarchal line. There will be time enough for dreams. Dreams. The one that tumbled down through the long morning comes to her and she pauses to consider it. There was a big table. Indistinct voices gathered around it, but the energy of a family gathering filled the space. The warmth of the room curled about her, perfumed by the smell of cooking. An ancient memory, from a time before the shedding of the flesh. Outside, children laughed. A hand took hers in its own, bringing her to a table filled with colorful dishes and surrounded by relatives and friends. Thanksgiving?
They re calling me home, Maya thinks. If indeed her ancestors could reach across time and into a form not of the flesh, perhaps that was the meaning of the dream. I am the last human consciousness, and I am being called home.
With a flutter, Maya is outside, and the trees all but bare of leaves. Something has happened. Weeks have passed and she struggles to take in her situation. This time she has neither dreamed nor stood immobile, but she has been active without memory.
Her arms cradle a lemur, sheltering the pubescent female against the wind. They sit atop a ridge that separates the valley from the forest to the west, and Walker-in-Leaves has been gone too long. That much Maya remembers. The female lemur sighs. It is a rumbling, mournful noise, and she buries her head tighter against Maya. This is Giver-of-Corn, and Walker is her love.
With her free hand, Maya works at a stiff knitting of pine boughs, the blanket which covers their legs. She pulls it up to better shelter Giver-of-Corn. Beside them, on a shell of bark, a sliver of fish has gone bad from inattention.
They wait through the long afternoon, but Walker does not return. When it is warmest and Giver sleeps, Maya rises in stages, gently separating herself from the lemur. She covers her charge well. Soon it will snow.
There are few memories after reaching the vault, only flashes, and that she has been active in a semi-consciousness state frightens Maya. She stumbles away, shaking, but there is no comfort to seek. She does not know if her diminished abilities endanger the lemurs, and considers locking herself beneath the earth. But the sun is warm, and for the moment every thought is a cloudless sky. Memories descend from the past like a lost tribe wandering for home.
To the east lie once powerful lands and remembered sepulchers. The life of the gods, the pulse of kings, it has all vanished and gone. Maya thinks back to the days of man. There was no disaster at the end. Just time. Civilization did not fail, it succumbed to endless seasons. Each vast stretch of years drawn on by the next saw the conquest of earth and stars, then went on, unheeding, until man dwindled and his monuments frayed.
To the west rise groves of oaks and grassland plains, beyond them, mountains that shrugged off civilization more easily than the rest.
Where is the voyager in those leaves?
A flash of time and Maya finds herself deep in the forests to the west. A lemur call escapes her throat, and suddenly she realizes she is searching for Walker-in-Leaves. The season is the same. Though the air is crisp, the trees are not yet unburdened of their color.
"Walker!" she calls out. "Your love is dying. She mourns your absence."
At the crest of a rise, Maya finds another like herself, but one long devoid of life. This sculpted form startles her at first. It has been almost wholly absorbed into the trunk of a great tree. The knee and calf of one leg escape the surrounding wood, as does a shoulder, the curve of a breast, a mournful face. A single hand reaches out from the tree toward the valley below.
In the distance, Maya sees the remnants of a fallen orbiter. Its power nacelle lies buried deep beneath the river that cushioned its fall. Earth and water, which once heaved at the impact, have worn down impenetrable metals and grown a forest over forgotten technologies.
Had the watcher in the tree come to see the fall, or to stand vigil over the corpse? Maya knows only that she must go on before the hills and the trees conspire to bury her. She moves on, continuing to call for Walker-in-Leaves.
In the night, a coyote finally answers Maya, its frenetic howls awakening responses from many cousins, hunting packs holding court up and down the valley.
Giver-of-Corn holds the spark of her generation. It is not much. A gene here and there, a deep manipulation of the flesh. The consciousness that was man is not easy to engender. Far easier to make an eye than a mind to see. Along a path of endless complication, today Giver-of-Corn mourns the absence of her mate. That Giver may die of such stubborn love before passing on her genes forces Maya deeper into the forest, using the last of her strength to call endlessly into the night.
Maya is dreaming. It s Thanksgiving, but the table is cold. The chairs are empty, and no one answers her call. As she walks from room to room, the lights dim and it begins to rain within the once familiar walls.
When Maya opens her eyes, it is to see Giver-of-Corm sleeping beneath a blanket of pine boughs, the young lemur s bushy tail twitching to the rhythm of sorrowful dreams. Maya is awake once more, but unaware of how much time has passed, or why she decided to return. Her most frightening thought is that she may already have found Walker-in-Leaves, or what the coyotes left behind.
Up from the valley, two older lemurs walk arm in arm, supporting one another along the rise. They bring with them a twig basket and a pouch made of hide. The former holds squash, its hollowed interior brimming with water, the latter a corn mash favored by the tribe. They are not without skills, these lemurs. Nor is language unknown to them. They have known Maya forever and treat her, not as a god, but as a force of nature.
With a few brief howls, by clicks, chatters, and the sweeping gestures of their tails, the lemurs make clear their plea. Their words all but rhyme. Giver-of-Corn will not eat for them. Will she eat for Maya?
Thus has the mission to found a new race come down to this: with her last strength, Maya shall spoon feed a grieving female. The thought strikes her as both funny and sad, while beyond her thoughts, the lemurs continue to chatter.
Scouts have been sent, the elders assure Maya, brave sires skilled in tracking. They hope to find Walker before the winter snows. Their voices stir Giver, and she howls in petty anguish at her benefactors, then disappears beneath the blanket. The elders bow their heads and turn to go, oblivious of Maya s failures.
Days pass upon the ridge in a thickness of clouds. Growing. Advancing. Dimmed by the mountainous billows above, the sun gives way to snow, and Maya watches Giver focus ever more intently on the line to the west. As the lemur s strength fails, her determination to await Walker s return seems to grow stronger still.
Walker-in-Leaves holds a spark of his own. He alone ventures west after the harvest. He has done it before, always returning with a colored stone, a bit of metal, or a flower never before seen by the tribe. It is as if some mad vision compels him, for the journey s end brings a collection of smooth and colored booty to be arranged in a crescent beneath a small monolith Walker himself toiled to raise. Large stones and small, the lemur has broken two fingers of its left hand doing this. To Maya, it seems the ambition of butterflies and falling leaves, of no consequence beyond a motion in the sun. The only importance now is to keep the genes within Giver alive.
Long ago, an ambition rose among the last generation of men, of what had once been men: to cultivate a new consciousness upon the Earth. Maya neither led nor knew the masters of the effort, but she was there when the first prosimians arrived, fresh from their land of orchids and baobabs. Men gathered lemurs and said to them "we shall make you men." Long years followed in the work of the genes, gentling the generations forward. Yet with each passing season, the cultivators grew fewer and their skills less true. So while the men died of age, or boredom, or despair, the lemurs prospered in their youth.
To warm the starving lemur, Maya builds a fire. For this feat the tribe has little skill, nor do they know zero, nor that a lever can move the world. She holds Giver close and pulls the rough blanket of boughs about them both.
All this time, Maya s thoughts remain clear, and the giving of comfort comforts her as well.
The snow begins to cover the monument Walker-in-Leaves has built upon the ridge. As Maya stares on and on into the fire, watching it absorb the snow, watching the snow conquer the cold stones and the grasses already bowed under a cloak of white, she drifts into a flutter of reverie, a weakening of consciousness. The gate to the end is closing, and she shall never know  never know.
"I ll take it easy like, an  stay around de house this winter," her father said. "There s carpenter work for me to do."
Other voices joined in around a table upon which a vast meal had been set. Thanksgiving. At the call of their names, the children rushed in from outside, their laughter quick as sunlight, their jackets smelling of autumn and leaves. Her mother made them wash and bow their heads in prayer. Those already seated joined in.
Grandmother passed the potatoes and called Maya her little kolache, rattling on in a series of endearments and concerns Maya s ear could not follow. Her mother passed on the sense of it and reminded Maya of the Czech for Thank you, Grandma.
It s good to be home, she thinks at first, then: where is the walker in those leaves?
A hand on which two fingers lay curled by the power of an old wound touches Maya. It shakes her, then gently moves her arms so that its owner can pull back the warm pine boughs hiding Giver-of Corn. Eyes first, then smile to tail, Giver opens herself to the returning wanderer. Walker-in-Leaves has returned, and the silence of their embrace brings the whole of the ridge alive in a glitter of sun-bright snow. Maya too comes awake, though this time neither word nor movement prevails entirely upon the fog of sleep.
When the answering howls come to the ridge, those who follow help Maya to stand. She follows them back to the shelter of the valley, and though she stumbles, there is satisfaction in the hurried gait, in the growing pace of the many as they gather to celebrate the return of the one. Songs of rejoicing join the undisciplined and cacophonous barks of youth. Food is brought, from the deep stores, from the caves and their recesses. Someone heats fish over coals they have kept sheltered and going for months. The thought of this ingenuity heartens Maya.
A delicacy of honeyed thorns is offered with great ceremony to Giver-of-Corn, and she tastes at last something beyond the bitterness of loss.
Though Walker-in-Leaves hesitates to leave the side of his love, the others demand stories, persuading him to the center where he begins a cacophonous song of his own.
Maya hopes to see what stones Walker has brought from the west this time, but though she tries to speak, the sounds are forgotten. The engine fades. The last flicker of man s fire is done, and with it the effort of her desires overcome her. She is gone.
Around a table suited for the Queen of queens, a thousand and a thousand sit. Mother to daughter, side-by-side, generation after generation of lemurs share in the feast. Maya is there, hearing the excited voices and the stern warnings to prayer. To her left and her right, each daughter speaks freely. Then the rhythms change, rising along one side to the cadence of Shakespeare and falling along the other to howls the forest first knew.
Unable to contain herself, Maya rises. She pushes on toward the head of a table she cannot see, beginning at last to run. What is the height her charges have reached? How far have they advanced? Lemur faces turn to laugh, their wide eyes joyous and amused. As the generations pass, she sees herself reflected in spectacles, hears the jangle of bracelets and burnished metal, watches matrons laugh behind scarves of silk. Then at last, someone with sculpted hands directs her outside, where the other children are at play in the leaves, now and forever.
THE END""".split()

# data
numbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541]
floats = []
last = 1
for number in numbers:
    floats.append(float(number ** 2 / last))
    last = number

def permutate(Xs, N):
    if N <= 0:
        yield []
        return
    for x in Xs:
        for sub in permutate(Xs, N-1):
            result = [x]+sub                    # don't allow duplicates
            for item in result:
                if result.count(item) > 1:
                    break
            else:
                yield result

def combinate(Xs, N):
    """Generate combinations of N items from list Xs"""
    if N == 0:
        yield []
        return
    for i in xrange(len(Xs)-N+1):
        for r in combinate(Xs[i+1:], N-1):
            yield [Xs[i]] + r

def index(sequence):
    "returns integers 0 - len(sequence)"
    for i in xrange(len(sequence)):
        yield i

# tests
def active(rec):
    if is_deleted(rec):
        return DoNotIndex
    return dbf.recno(rec)
def inactive(rec):
    if is_deleted(rec):
        return recno(rec)
    return DoNotIndex

class TestChar(unittest.TestCase):
    def test_exceptions(self):
        "exceptions"
        self.assertRaises(ValueError, Char, 7)
        self.assertRaises(ValueError, Char, ['nope'])
        self.assertRaises(ValueError, Char, True)
        self.assertRaises(ValueError, Char, False)
        self.assertRaises(ValueError, Char, type)
        self.assertRaises(ValueError, Char, str)
        self.assertRaises(ValueError, Char, None)
    def test_bools_and_none(self):
        "booleans and None"
        empty = Char()
        self.assertFalse(bool(empty))
        one = Char(' ')
        self.assertFalse(bool(one))
        actual = Char('1')
        self.assertTrue(bool(actual))
    def test_equality(self):
        "equality"
        a1 = Char('a')
        a2 = 'a '
        self.assertEqual(a1, a2)
        self.assertEqual(a2, a1)
        a3 = 'a '
        a4 = Char('a ')
        self.assertEqual(a3, a4)
        self.assertEqual(a4, a3)
    def test_inequality(self):
        "inequality"
        a1 = Char('ab ')
        a2 = 'a b'
        self.assertNotEqual(a1, a2)
        self.assertNotEqual(a2, a1)
        a3 = 'ab '
        a4 = Char('a b')
        self.assertNotEqual(a3, a4)
        self.assertNotEqual(a4, a3)
    def test_less_than(self):
        "less-than"
        a1 = Char('a')
        a2 = 'a '
        self.assertFalse(a1 < a2)
        self.assertFalse(a2 < a1)
        a3 = 'a '
        a4 = Char('a ')
        self.assertFalse(a3 < a4)
        self.assertFalse(a4 < a3)
        a5 = 'abcd'
        a6 = 'abce'
        self.assertTrue(a5 < a6)
        self.assertFalse(a6 < a5)
    def test_less_than_equal(self):
        "less-than or equal"
        a1 = Char('a')
        a2 = 'a '
        self.assertTrue(a1 <= a2)
        self.assertTrue(a2 <= a1)
        a3 = 'a '
        a4 = Char('a ')
        self.assertTrue(a3 <= a4)
        self.assertTrue(a4 <= a3)
        a5 = 'abcd'
        a6 = 'abce'
        self.assertTrue(a5 <= a6)
        self.assertFalse(a6 <= a5)
    def test_greater_than(self):
        "greater-than or equal"
        a1 = Char('a')
        a2 = 'a '
        self.assertTrue(a1 >= a2)
        self.assertTrue(a2 >= a1)
        a3 = 'a '
        a4 = Char('a ')
        self.assertTrue(a3 >= a4)
        self.assertTrue(a4 >= a3)
        a5 = 'abcd'
        a6 = 'abce'
        self.assertFalse(a5 >= a6)
        self.assertTrue(a6 >= a5)
    def test_greater_than_equal(self):
        "greater-than"
        a1 = Char('a')
        a2 = 'a '
        self.assertFalse(a1 > a2)
        self.assertFalse(a2 > a1)
        a3 = 'a '
        a4 = Char('a ')
        self.assertFalse(a3 > a4)
        self.assertFalse(a4 > a3)
        a5 = 'abcd'
        a6 = 'abce'
        self.assertFalse(a5 > a6)
        self.assertTrue(a6 > a5)

class TestDateTime(unittest.TestCase):
    "Testing Date"
    def test_date_creation(self):
        "Date creation"
        date0 = Date()
        date1 = Date()
        date2 = Date.fromymd('        ')
        date5 = Date.fromordinal(0)
        date6 = Date.today()
        date7 = Date.max
        date8 = Date.min
        self.assertRaises(ValueError, Date.fromymd, '00000')
        self.assertRaises(ValueError, Date.fromymd, '00000000')
        self.assertRaises(ValueError, Date, 0, 0, 0)
    def test_date_compare(self):
        "Date comparisons"
        nodate1 = Date()
        nodate2 = Date()
        date1 = Date.fromordinal(1000)
        date2 = Date.fromordinal(2000)
        date3 = Date.fromordinal(3000)
        self.compareTimes(nodate1, nodate2, date1, date2, date3)

    def test_datetime_creation(self):
        "DateTime creation"
        datetime0 = DateTime()
        datetime1 = DateTime()
        datetime5 = DateTime.fromordinal(0)
        datetime6 = DateTime.today()
        datetime7 = DateTime.max
        datetime8 = DateTime.min
    def test_datetime_compare(self):
        "DateTime comparisons"
        nodatetime1 = DateTime()
        nodatetime2 = DateTime()
        datetime1 = Date.fromordinal(1000)
        datetime2 = Date.fromordinal(20000)
        datetime3 = Date.fromordinal(300000)
        self.compareTimes(nodatetime1, nodatetime2, datetime1, datetime2, datetime3)

    def test_datetime_replace(self):
        "DateTime replacements"
        datetime_target = DateTime(2001, 5, 31, 23, 59, 59, 999000)
        datetime1 = datetime.datetime(2001, 5, 31, 23, 59, 59, 999230)
        datetime2 = datetime.datetime(2001, 5, 31, 23, 59, 59, 999500)
        datetime3 = datetime.datetime(2001, 5, 31, 23, 59, 59, 999728)
        original_datetime = datetime.datetime
        for dt in (datetime1, datetime2, datetime3):
            class DateTimeNow(datetime.datetime):
                @classmethod
                def now(self):
                    datetime.datetime = original_datetime
                    return dt
            datetime.datetime = DateTimeNow
            result = DateTime.now()
            self.assertEqual(result, datetime_target, 'in: %r  out: %r  desired: %r' % (dt, result, datetime_target))
        

    def test_time_creation(self):
        "Time creation"
        time0 = Time()
        time1 = Time()
        time7 = Time.max
        time8 = Time.min
    def test_time_compare(self):
        "Time comparisons"
        notime1 = Time()
        notime2 = Time()
        time1 = Date.fromordinal(1000)
        time2 = Date.fromordinal(2000)
        time3 = Date.fromordinal(3000)
        self.compareTimes(notime1, notime2, time1, time2, time3)
    def test_arithmetic(self):
        "Date, DateTime, & Time Arithmetic"
        one_day = datetime.timedelta(1)
        a_day = Date(1970, 5, 20)
        self.assertEqual(a_day + one_day, Date(1970, 5, 21))
        self.assertEqual(a_day - one_day, Date(1970, 5, 19))
        self.assertEqual(datetime.date(1970, 5, 21) - a_day, one_day)
        a_time = Time(12)
        one_second = datetime.timedelta(0, 1, 0)
        self.assertEqual(a_time + one_second, Time(12, 0, 1))
        self.assertEqual(a_time - one_second, Time(11, 59, 59))
        self.assertEqual(datetime.time(12, 0, 1) - a_time, one_second)
        an_appt = DateTime(2012, 4, 15, 12, 30, 00)
        displacement = datetime.timedelta(1, 60*60*2+60*15)
        self.assertEqual(an_appt + displacement, DateTime(2012, 4, 16, 14, 45, 0))
        self.assertEqual(an_appt - displacement, DateTime(2012, 4, 14, 10, 15, 0))
        self.assertEqual(datetime.datetime(2012, 4, 16, 14, 45, 0) - an_appt, displacement)
    def test_none_compare(self):
        "comparisons to None"
        empty_date = Date()
        empty_time = Time()
        empty_datetime = DateTime()
        self.assertEqual(empty_date, None)
        self.assertEqual(empty_time, None)
        self.assertEqual(empty_datetime, None)
    def test_singletons(self):
        "singletons"
        empty_date = Date()
        empty_time = Time()
        empty_datetime = DateTime()
        self.assertTrue(empty_date is NullDate)
        self.assertTrue(empty_time is NullTime)
        self.assertTrue(empty_datetime is NullDateTime)
    def test_boolean_value(self):
        "boolean evaluation"
        empty_date = Date()
        empty_time = Time()
        empty_datetime = DateTime()
        self.assertEqual(bool(empty_date), False)
        self.assertEqual(bool(empty_time), False)
        self.assertEqual(bool(empty_datetime), False)
        actual_date = Date.today()
        actual_time = Time.now()
        actual_datetime = DateTime.now()
        self.assertEqual(bool(actual_date), True)
        self.assertEqual(bool(actual_time), True)
        self.assertEqual(bool(actual_datetime), True)
    def compareTimes(self, empty1, empty2, uno, dos, tres):
        self.assertEqual(empty1, empty2)
        self.assertEqual(uno < dos, True)
        self.assertEqual(uno <= dos, True)
        self.assertEqual(dos <= dos, True)
        self.assertEqual(dos <= tres, True)
        self.assertEqual(dos < tres, True)
        self.assertEqual(tres <= tres, True)
        self.assertEqual(uno == uno, True)
        self.assertEqual(dos == dos, True)
        self.assertEqual(tres == tres, True)
        self.assertEqual(uno != dos, True)
        self.assertEqual(dos != tres, True)
        self.assertEqual(tres != uno, True)
        self.assertEqual(tres >= tres, True)
        self.assertEqual(tres > dos, True)
        self.assertEqual(dos >= dos, True)
        self.assertEqual(dos >= uno, True)
        self.assertEqual(dos > uno, True)
        self.assertEqual(uno >= uno, True)
        self.assertEqual(uno >= dos, False)
        self.assertEqual(uno >= tres, False)
        self.assertEqual(dos >= tres, False)
        self.assertEqual(tres <= dos, False)
        self.assertEqual(tres <= uno, False)
        self.assertEqual(tres < tres, False)
        self.assertEqual(tres < dos, False)
        self.assertEqual(tres < uno, False)
        self.assertEqual(dos < dos, False)
        self.assertEqual(dos < uno, False)
        self.assertEqual(uno < uno, False)
        self.assertEqual(uno == dos, False)
        self.assertEqual(uno == tres, False)
        self.assertEqual(dos == uno, False)
        self.assertEqual(dos == tres, False)
        self.assertEqual(tres == uno, False)
        self.assertEqual(tres == dos, False)
        self.assertEqual(uno != uno, False)
        self.assertEqual(dos != dos, False)
        self.assertEqual(tres != tres, False)

class TestNull(unittest.TestCase):
    def test_all(self):
        null = Null = dbf.Null()
        self.assertTrue(null is dbf.Null())

        self.assertTrue(null + 1 is Null)
        self.assertTrue(1 + null is Null)
        null += 4
        self.assertTrue(null is Null)
        value = 5
        value += null
        self.assertTrue(value is Null)

        self.assertTrue(null - 2 is Null)
        self.assertTrue(2 - null is Null)
        null -= 5
        self.assertTrue(null is Null)
        value = 6
        value -= null
        self.assertTrue(value is Null)

        self.assertTrue(null / 0 is Null)
        self.assertTrue(3 / null is Null)
        null /= 6
        self.assertTrue(null is Null)
        value = 7
        value /= null
        self.assertTrue(value is Null)

        self.assertTrue(null * -3 is Null)
        self.assertTrue(4 * null is Null)
        null *= 7
        self.assertTrue(null is Null)
        value = 8
        value *= null
        self.assertTrue(value is Null)

        self.assertTrue(null % 1 is Null)
        self.assertTrue(7 % null is Null)
        null %= 1
        self.assertTrue(null is Null)
        value = 9
        value %= null
        self.assertTrue(value is Null)

        self.assertTrue(null ** 2 is Null)
        self.assertTrue(4 ** null is Null)
        null **= 3
        self.assertTrue(null is Null)
        value = 9
        value **= null
        self.assertTrue(value is Null)

        self.assertTrue(null & 1 is Null)
        self.assertTrue(1 & null is Null)
        null &= 1
        self.assertTrue(null is Null)
        value = 1
        value &= null
        self.assertTrue(value is Null)

        self.assertTrue(null ^ 1 is Null)
        self.assertTrue(1 ^ null is Null)
        null ^= 1
        self.assertTrue(null is Null)
        value = 1
        value ^= null
        self.assertTrue(value is Null)

        self.assertTrue(null | 1 is Null)
        self.assertTrue(1 | null is Null)
        null |= 1
        self.assertTrue(null is Null)
        value = 1
        value |= null
        self.assertTrue(value is Null)

        self.assertTrue(str(divmod(null, 1)) == '(<null>, <null>)')
        self.assertTrue(str(divmod(1, null)) == '(<null>, <null>)')

        self.assertTrue(null << 1 is Null)
        self.assertTrue(2 << null is Null)
        null <<=3
        self.assertTrue(null is Null)
        value = 9
        value <<= null
        self.assertTrue(value is Null)

        self.assertTrue(null >> 1 is Null)
        self.assertTrue(2 >> null is Null)
        null >>= 3
        self.assertTrue(null is Null)
        value = 9
        value >>= null
        self.assertTrue(value is Null)

        self.assertTrue(-null is Null)
        self.assertTrue(+null is Null)
        self.assertTrue(abs(null) is Null)
        self.assertTrue(~null is Null)

        self.assertTrue(null.attr is Null)
        self.assertTrue(null() is Null)
        self.assertTrue(getattr(null, 'fake') is Null)

        self.assertRaises(TypeError, hash, null)

class TestLogical(unittest.TestCase):
    "Testing Logical"
    def test_unknown(self):
        "Unknown"
        for unk in '', '?', ' ', None, Null, Unknown, Other:
            huh = unknown = Logical(unk)
            self.assertEqual(huh == None, True, "huh is %r from %r, which is not None" % (huh, unk))
            self.assertEqual(huh != None, False, "huh is %r from %r, which is not None" % (huh, unk))
            self.assertEqual(huh != True, True, "huh is %r from %r, which is not None" % (huh, unk))
            self.assertEqual(huh == True, False, "huh is %r from %r, which is not None" % (huh, unk))
            self.assertEqual(huh != False, True, "huh is %r from %r, which is not None" % (huh, unk))
            self.assertEqual(huh == False, False, "huh is %r from %r, which is not None" % (huh, unk))
            if py_ver >= (2, 5):
                self.assertRaises(ValueError, lambda : (0, 1, 2)[huh])
    def test_true(self):
        "true"
        for true in 'True', 'yes', 't', 'Y', 7, ['blah']:
            huh = Logical(true)
            self.assertEqual(huh == True, True)
            self.assertEqual(huh != True, False)
            self.assertEqual(huh == False, False, "%r is not True" % true)
            self.assertEqual(huh != False, True)
            self.assertEqual(huh == None, False)
            self.assertEqual(huh != None, True)
            if py_ver >= (2, 5):
                self.assertEqual((0, 1, 2)[huh], 1)
    def test_false(self):
        "false"
        for false in 'false', 'No', 'F', 'n', 0, []:
            huh = Logical(false)
            self.assertEqual(huh != False, False)
            self.assertEqual(huh == False, True)
            self.assertEqual(huh != True, True)
            self.assertEqual(huh == True, False)
            self.assertEqual(huh != None, True)
            self.assertEqual(huh == None, False)
            if py_ver >= (2, 5):
                self.assertEqual((0, 1, 2)[huh], 0)
    def test_singletons(self):
        "singletons"
        heh = Logical(True)
        hah = Logical('Yes')
        ick = Logical(False)
        ack = Logical([])
        unk = Logical('?')
        bla = Logical(None)
        self.assertEqual(heh is hah, True)
        self.assertEqual(ick is ack, True)
        self.assertEqual(unk is bla, True)
    def test_error(self):
        "errors"
        self.assertRaises(ValueError, Logical, 'wrong')
    def test_and(self):
        "and"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual((true & true) is true, True)
        self.assertEqual((true & false) is false, True)
        self.assertEqual((false & true) is false, True)
        self.assertEqual((false & false) is false, True)
        self.assertEqual((true & unknown) is unknown, True)
        self.assertEqual((false & unknown) is false, True)
        self.assertEqual((unknown & true) is unknown, True)
        self.assertEqual((unknown & false) is false, True)
        self.assertEqual((unknown & unknown) is unknown, True)
        self.assertEqual((true & True) is true, True)
        self.assertEqual((true & False) is false, True)
        self.assertEqual((false & True) is false, True)
        self.assertEqual((false & False) is false, True)
        self.assertEqual((true & None) is unknown, True)
        self.assertEqual((false & None) is false, True)
        self.assertEqual((unknown & True) is unknown, True)
        self.assertEqual((unknown & False) is false, True)
        self.assertEqual((unknown & None) is unknown, True)
        self.assertEqual((True & true) is true, True)
        self.assertEqual((True & false) is false, True)
        self.assertEqual((False & true) is false, True)
        self.assertEqual((False & false) is false, True)
        self.assertEqual((True & unknown) is unknown, True)
        self.assertEqual((False & unknown) is false, True)
        self.assertEqual((None & true) is unknown, True)
        self.assertEqual((None & false) is false, True)
        self.assertEqual((None & unknown) is unknown, True)
        self.assertEqual(type(true & 0), int)
        self.assertEqual(true & 0, 0)
        self.assertEqual(type(true & 3), int)
        self.assertEqual(true & 3, 1)
        self.assertEqual(type(false & 0), int)
        self.assertEqual(false & 0, 0)
        self.assertEqual(type(false & 2), int)
        self.assertEqual(false & 2, 0)
        self.assertEqual(type(unknown & 0), int)
        self.assertEqual(unknown & 0, 0)
        self.assertEqual(unknown & 2, unknown)

        t = true
        t &= true
        self.assertEqual(t is true, True)
        t = true
        t &= false
        self.assertEqual(t is false, True)
        f = false
        f &= true
        self.assertEqual(f is false, True)
        f = false
        f &= false
        self.assertEqual(f is false, True)
        t = true
        t &= unknown
        self.assertEqual(t is unknown, True)
        f = false
        f &= unknown
        self.assertEqual(f is false, True)
        u = unknown
        u &= true
        self.assertEqual(u is unknown, True)
        u = unknown
        u &= false
        self.assertEqual(u is false, True)
        u = unknown
        u &= unknown
        self.assertEqual(u is unknown, True)
        t = true
        t &= True
        self.assertEqual(t is true, True)
        t = true
        t &= False
        self.assertEqual(t is false, True)
        f = false
        f &= True
        self.assertEqual(f is false, True)
        f = false
        f &= False
        self.assertEqual(f is false, True)
        t = true
        t &= None
        self.assertEqual(t is unknown, True)
        f = false
        f &= None
        self.assertEqual(f is false, True)
        u = unknown
        u &= True
        self.assertEqual(u is unknown, True)
        u = unknown
        u &= False
        self.assertEqual(u is false, True)
        u = unknown
        u &= None
        self.assertEqual(u is unknown, True)
        t = True
        t &= true
        self.assertEqual(t is true, True)
        t = True
        t &= false
        self.assertEqual(t is false, True)
        f = False
        f &= true
        self.assertEqual(f is false, True)
        f = False
        f &= false
        self.assertEqual(f is false, True)
        t = True
        t &= unknown
        self.assertEqual(t is unknown, True)
        f = False
        f &= unknown
        self.assertEqual(f is false, True)
        u = None
        u &= true
        self.assertEqual(u is unknown, True)
        u = None
        u &= false
        self.assertEqual(u is false, True)
        u = None
        u &= unknown
        self.assertEqual(u is unknown, True)
        t = true
        t &= 0
        self.assertEqual(type(true & 0), int)
        t = true
        t &= 0
        self.assertEqual(true & 0, 0)
        t = true
        t &= 3
        self.assertEqual(type(true & 3), int)
        t = true
        t &= 3
        self.assertEqual(true & 3, 1)
        f = false
        f &= 0
        self.assertEqual(type(false & 0), int)
        f = false
        f &= 0
        self.assertEqual(false & 0, 0)
        f = false
        f &= 2
        self.assertEqual(type(false & 2), int)
        f = false
        f &= 2
        self.assertEqual(false & 2, 0)
        u = unknown
        u &= 0
        self.assertEqual(type(unknown & 0), int)
        u = unknown
        u &= 0
        self.assertEqual(unknown & 0, 0)
        u = unknown
        u &= 2
        self.assertEqual(unknown & 2, unknown)

    def test_or(self):
        "or"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual((true | true) is true, True)
        self.assertEqual((true | false) is true, True)
        self.assertEqual((false | true) is true, True)
        self.assertEqual((false | false) is false, True)
        self.assertEqual((true | unknown) is true, True)
        self.assertEqual((false | unknown) is unknown, True)
        self.assertEqual((unknown | true) is true, True)
        self.assertEqual((unknown | false) is unknown, True)
        self.assertEqual((unknown | unknown) is unknown, True)
        self.assertEqual((true | True) is true, True)
        self.assertEqual((true | False) is true, True)
        self.assertEqual((false | True) is true, True)
        self.assertEqual((false | False) is false, True)
        self.assertEqual((true | None) is true, True)
        self.assertEqual((false | None) is unknown, True)
        self.assertEqual((unknown | True) is true, True)
        self.assertEqual((unknown | False) is unknown, True)
        self.assertEqual((unknown | None) is unknown, True)
        self.assertEqual((True | true) is true, True)
        self.assertEqual((True | false) is true, True)
        self.assertEqual((False | true) is true, True)
        self.assertEqual((False | false) is false, True)
        self.assertEqual((True | unknown) is true, True)
        self.assertEqual((False | unknown) is unknown, True)
        self.assertEqual((None | true) is true, True)
        self.assertEqual((None | false) is unknown, True)
        self.assertEqual((None | unknown) is unknown, True)
        self.assertEqual(type(true | 0), int)
        self.assertEqual(true | 0, 1)
        self.assertEqual(type(true | 2), int)
        self.assertEqual(true | 2, 3)
        self.assertEqual(type(false | 0), int)
        self.assertEqual(false | 0, 0)
        self.assertEqual(type(false | 2), int)
        self.assertEqual(false | 2, 2)
        self.assertEqual(unknown | 0, unknown)
        self.assertEqual(unknown | 2, unknown)

        t = true
        t |= true
        self.assertEqual(t is true, True)
        t = true
        t |= false
        self.assertEqual(t is true, True)
        f = false
        f |= true
        self.assertEqual(f is true, True)
        f = false
        f |= false
        self.assertEqual(f is false, True)
        t = true
        t |= unknown
        self.assertEqual(t is true, True)
        f = false
        f |= unknown
        self.assertEqual(f is unknown, True)
        u = unknown
        u |= true
        self.assertEqual(u is true, True)
        u = unknown
        u |= false
        self.assertEqual(u is unknown, True)
        u = unknown
        u |= unknown
        self.assertEqual(u is unknown, True)
        t = true
        t |= True
        self.assertEqual(t is true, True)
        t = true
        t |= False
        self.assertEqual(t is true, True)
        f = false
        f |= True
        self.assertEqual(f is true, True)
        f = false
        f |= False
        self.assertEqual(f is false, True)
        t = true
        t |= None
        self.assertEqual(t is true, True)
        f = false
        f |= None
        self.assertEqual(f is unknown, True)
        u = unknown
        u |= True
        self.assertEqual(u is true, True)
        u = unknown
        u |= False
        self.assertEqual(u is unknown, True)
        u = unknown
        u |= None
        self.assertEqual(u is unknown, True)
        t = True
        t |= true
        self.assertEqual(t is true, True)
        t = True
        t |= false
        self.assertEqual(t is true, True)
        f = False
        f |= true
        self.assertEqual(f is true, True)
        f = False
        f |= false
        self.assertEqual(f is false, True)
        t = True
        t |= unknown
        self.assertEqual(t is true, True)
        f = False
        f |= unknown
        self.assertEqual(f is unknown, True)
        u = None
        u |= true
        self.assertEqual(u is true, True)
        u = None
        u |= false
        self.assertEqual(u is unknown, True)
        u = None
        u |= unknown
        self.assertEqual(u is unknown, True)
        t = true
        t |= 0
        self.assertEqual(type(t), int)
        t = true
        t |= 0
        self.assertEqual(t, 1)
        t = true
        t |= 2
        self.assertEqual(type(t), int)
        t = true
        t |= 2
        self.assertEqual(t, 3)
        f = false
        f |= 0
        self.assertEqual(type(f), int)
        f = false
        f |= 0
        self.assertEqual(f, 0)
        f = false
        f |= 2
        self.assertEqual(type(f), int)
        f = false
        f |= 2
        self.assertEqual(f, 2)
        u = unknown
        u |= 0
        self.assertEqual(u, unknown)

    def test_xor(self):
        "xor"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual((true ^ true) is false, True)
        self.assertEqual((true ^ false) is true, True)
        self.assertEqual((false ^ true) is true, True)
        self.assertEqual((false ^ false) is false, True)
        self.assertEqual((true ^ unknown) is unknown, True)
        self.assertEqual((false ^ unknown) is unknown, True)
        self.assertEqual((unknown ^ true) is unknown, True)
        self.assertEqual((unknown ^ false) is unknown, True)
        self.assertEqual((unknown ^ unknown) is unknown, True)
        self.assertEqual((true ^ True) is false, True)
        self.assertEqual((true ^ False) is true, True)
        self.assertEqual((false ^ True) is true, True)
        self.assertEqual((false ^ False) is false, True)
        self.assertEqual((true ^ None) is unknown, True)
        self.assertEqual((false ^ None) is unknown, True)
        self.assertEqual((unknown ^ True) is unknown, True)
        self.assertEqual((unknown ^ False) is unknown, True)
        self.assertEqual((unknown ^ None) is unknown, True)
        self.assertEqual((True ^ true) is false, True)
        self.assertEqual((True ^ false) is true, True)
        self.assertEqual((False ^ true) is true, True)
        self.assertEqual((False ^ false) is false, True)
        self.assertEqual((True ^ unknown) is unknown, True)
        self.assertEqual((False ^ unknown) is unknown, True)
        self.assertEqual((None ^ true) is unknown, True)
        self.assertEqual((None ^ false) is unknown, True)
        self.assertEqual((None ^ unknown) is unknown, True)
        self.assertEqual(type(true ^ 2), int)
        self.assertEqual(true ^ 2, 3)
        self.assertEqual(type(true ^ 0), int)
        self.assertEqual(true ^ 0, 1)
        self.assertEqual(type(false ^ 0), int)
        self.assertEqual(false ^ 0, 0)
        self.assertEqual(type(false ^ 2), int)
        self.assertEqual(false ^ 2, 2)
        self.assertEqual(unknown ^ 0, unknown)
        self.assertEqual(unknown ^ 2, unknown)

        t = true
        t ^= true
        self.assertEqual(t is false, True)
        t = true
        t ^= false
        self.assertEqual(t is true, True)
        f = false
        f ^= true
        self.assertEqual(f is true, True)
        f = false
        f ^= false
        self.assertEqual(f is false, True)
        t = true
        t ^= unknown
        self.assertEqual(t is unknown, True)
        f = false
        f ^= unknown
        self.assertEqual(f is unknown, True)
        u = unknown
        u ^= true
        self.assertEqual(u is unknown, True)
        u = unknown
        u ^= false
        self.assertEqual(u is unknown, True)
        u = unknown
        u ^= unknown
        self.assertEqual(u is unknown, True)
        t = true
        t ^= True
        self.assertEqual(t is false, True)
        t = true
        t ^= False
        self.assertEqual(t is true, True)
        f = false
        f ^= True
        self.assertEqual(f is true, True)
        f = false
        f ^= False
        self.assertEqual(f is false, True)
        t = true
        t ^= None
        self.assertEqual(t is unknown, True)
        f = false
        f ^= None
        self.assertEqual(f is unknown, True)
        u = unknown
        u ^= True
        self.assertEqual(u is unknown, True)
        u = unknown
        u ^= False
        self.assertEqual(u is unknown, True)
        u = unknown
        u ^= None
        self.assertEqual(u is unknown, True)
        t = True
        t ^= true
        self.assertEqual(t is false, True)
        t = True
        t ^= false
        self.assertEqual(t is true, True)
        f = False
        f ^= true
        self.assertEqual(f is true, True)
        f = False
        f ^= false
        self.assertEqual(f is false, True)
        t = True
        t ^= unknown
        self.assertEqual(t is unknown, True)
        f = False
        f ^= unknown
        self.assertEqual(f is unknown, True)
        u = None
        u ^= true
        self.assertEqual(u is unknown, True)
        u = None
        u ^= false
        self.assertEqual(u is unknown, True)
        u = None
        u ^= unknown
        self.assertEqual(u is unknown, True)
        t = true
        t ^= 0
        self.assertEqual(type(true ^ 0), int)
        t = true
        t ^= 0
        self.assertEqual(true ^ 0, 1)
        t = true
        t ^= 2
        self.assertEqual(type(true ^ 2), int)
        t = true
        t ^= 2
        self.assertEqual(true ^ 2, 3)
        f = false
        f ^= 0
        self.assertEqual(type(false ^ 0), int)
        f = false
        f ^= 0
        self.assertEqual(false ^ 0, 0)
        f = false
        f ^= 2
        self.assertEqual(type(false ^ 2), int)
        f = false
        f ^= 2
        self.assertEqual(false ^ 2, 2)
        u = unknown
        u ^= 0
        self.assertEqual(unknown ^ 0, unknown)
        u = unknown
        u ^= 2
        self.assertEqual(unknown ^ 2, unknown)

    def test_negation(self):
        "negation"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(-true, -1)
        self.assertEqual(-false, 0)
        self.assertEqual(-none, none)
    def test_posation(self):
        "posation"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(+true, 1)
        self.assertEqual(+false, 0)
        self.assertEqual(+none, none)
    def test_abs(self):
        "abs()"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(abs(true), 1)
        self.assertEqual(abs(false), 0)
        self.assertEqual(abs(none), none)
    def test_invert(self):
        "~ operator"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(~true, -2)
        self.assertEqual(~false, -1)
        self.assertEqual(~none, none)

    def test_complex(self):
        "complex"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(complex(true), complex(1))
        self.assertEqual(complex(false), complex(0))
        self.assertRaises(ValueError, complex, none)

    def test_int(self):
        "int"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(int(true), 1)
        self.assertEqual(int(false), 0)
        self.assertRaises(ValueError, int, none)

    if py_ver < (3, 0):
        def test_long(self):
            "long"
            true = Logical(True)
            false = Logical(False)
            none = Logical(None)
            self.assertEqual(long(true), long(1))
            self.assertEqual(long(false), long(0))
            self.assertRaises(ValueError, long, none)

    def test_float(self):
        "float"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(float(true), 1.0)
        self.assertEqual(float(false), 0.0)
        self.assertRaises(ValueError, float, none)

    def test_oct(self):
        "oct"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(oct(true), oct(1))
        self.assertEqual(oct(false), oct(0))
        self.assertRaises(ValueError, oct, none)

    def test_hex(self):
        "hex"
        true = Logical(True)
        false = Logical(False)
        none = Logical(None)
        self.assertEqual(hex(true), hex(1))
        self.assertEqual(hex(false), hex(0))
        self.assertRaises(ValueError, hex, none)

    def test_addition(self):
        "addition"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual(true + true, 2)
        self.assertEqual(true + false, 1)
        self.assertEqual(false + true, 1)
        self.assertEqual(false + false, 0)
        self.assertEqual(true + unknown, unknown)
        self.assertEqual(false + unknown, unknown)
        self.assertEqual(unknown + true, unknown)
        self.assertEqual(unknown + false, unknown)
        self.assertEqual(unknown + unknown, unknown)
        self.assertEqual(true + True, 2)
        self.assertEqual(true + False, 1)
        self.assertEqual(false + True, 1)
        self.assertEqual(false + False, 0)
        self.assertEqual(true + None, unknown)
        self.assertEqual(false + None, unknown)
        self.assertEqual(unknown + True, unknown)
        self.assertEqual(unknown + False, unknown)
        self.assertEqual(unknown + None, unknown)
        self.assertEqual(True + true, 2)
        self.assertEqual(True + false, 1)
        self.assertEqual(False + true, 1)
        self.assertEqual(False + false, 0)
        self.assertEqual(True + unknown, unknown)
        self.assertEqual(False + unknown, unknown)
        self.assertEqual(None + true, unknown)
        self.assertEqual(None + false, unknown)
        self.assertEqual(None + unknown, unknown)

        t = true
        t += true
        self.assertEqual(t, 2)
        t = true
        t += false
        self.assertEqual(t, 1)
        f = false
        f += true
        self.assertEqual(f, 1)
        f = false
        f += false
        self.assertEqual(f, 0)
        t = true
        t += unknown
        self.assertEqual(t, unknown)
        f = false
        f += unknown
        self.assertEqual(f, unknown)
        u = unknown
        u += true
        self.assertEqual(u, unknown)
        u = unknown
        u += false
        self.assertEqual(u, unknown)
        u = unknown
        u += unknown
        self.assertEqual(u, unknown)
        t = true
        t += True
        self.assertEqual(t, 2)
        t = true
        t += False
        self.assertEqual(t, 1)
        f = false
        f += True
        self.assertEqual(f, 1)
        f = false
        f += False
        self.assertEqual(f, 0)
        t = true
        t += None
        self.assertEqual(t, unknown)
        f = false
        f += None
        self.assertEqual(f, unknown)
        u = unknown
        u += True
        self.assertEqual(u, unknown)
        u = unknown
        u += False
        self.assertEqual(u, unknown)
        u = unknown
        u += None
        self.assertEqual(u, unknown)
        t = True
        t += true
        self.assertEqual(t, 2)
        t = True
        t += false
        self.assertEqual(t, 1)
        f = False
        f += true
        self.assertEqual(f, 1)
        f = False
        f += false
        self.assertEqual(f, 0)
        t = True
        t += unknown
        self.assertEqual(t, unknown)
        f = False
        f += unknown
        self.assertEqual(f, unknown)
        u = None
        u += true
        self.assertEqual(u, unknown)
        u = None
        u += false
        self.assertEqual(u, unknown)
        u = None
        u += unknown
        self.assertEqual(u, unknown)

    def test_multiplication(self):
        "multiplication"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual(true * true, 1)
        self.assertEqual(true * false, 0)
        self.assertEqual(false * true, 0)
        self.assertEqual(false * false, 0)
        self.assertEqual(true * unknown, unknown)
        self.assertEqual(false * unknown, 0)
        self.assertEqual(unknown * true, unknown)
        self.assertEqual(unknown * false, 0)
        self.assertEqual(unknown * unknown, unknown)
        self.assertEqual(true * True, 1)
        self.assertEqual(true * False, 0)
        self.assertEqual(false * True, 0)
        self.assertEqual(false * False, 0)
        self.assertEqual(true * None, unknown)
        self.assertEqual(false * None, 0)
        self.assertEqual(unknown * True, unknown)
        self.assertEqual(unknown * False, 0)
        self.assertEqual(unknown * None, unknown)
        self.assertEqual(True * true, 1)
        self.assertEqual(True * false, 0)
        self.assertEqual(False * true, 0)
        self.assertEqual(False * false, 0)
        self.assertEqual(True * unknown, unknown)
        self.assertEqual(False * unknown, 0)
        self.assertEqual(None * true, unknown)
        self.assertEqual(None * false, 0)
        self.assertEqual(None * unknown, unknown)

        t = true
        t *= true
        self.assertEqual(t, 1)
        t = true
        t *= false
        self.assertEqual(t, 0)
        f = false
        f *= true
        self.assertEqual(f, 0)
        f = false
        f *= false
        self.assertEqual(f, 0)
        t = true
        t *= unknown
        self.assertEqual(t, unknown)
        f = false
        f *= unknown
        self.assertEqual(f, 0)
        u = unknown
        u *= true
        self.assertEqual(u, unknown)
        u = unknown
        u *= false
        self.assertEqual(u, 0)
        u = unknown
        u *= unknown
        self.assertEqual(u, unknown)
        t = true
        t *= True
        self.assertEqual(t, 1)
        t = true
        t *= False
        self.assertEqual(t, 0)
        f = false
        f *= True
        self.assertEqual(f, 0)
        f = false
        f *= False
        self.assertEqual(f, 0)
        t = true
        t *= None
        self.assertEqual(t, unknown)
        f = false
        f *= None
        self.assertEqual(f, 0)
        u = unknown
        u *= True
        self.assertEqual(u, unknown)
        u = unknown
        u *= False
        self.assertEqual(u, 0)
        u = unknown
        u *= None
        self.assertEqual(u, unknown)
        t = True
        t *= true
        self.assertEqual(t, 1)
        t = True
        t *= false
        self.assertEqual(t, 0)
        f = False
        f *= true
        self.assertEqual(f, 0)
        f = False
        f *= false
        self.assertEqual(f, 0)
        t = True
        t *= unknown
        self.assertEqual(t, unknown)
        f = False
        f *= unknown
        self.assertEqual(f, 0)
        u = None
        u *= true
        self.assertEqual(u, unknown)
        u = None
        u *= false
        self.assertEqual(u, 0)
        u = None
        u *= unknown
        self.assertEqual(u, unknown)
    def test_subtraction(self):
        "subtraction"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual(true - true, 0)
        self.assertEqual(true - false, 1)
        self.assertEqual(false - true, -1)
        self.assertEqual(false - false, 0)
        self.assertEqual(true - unknown, unknown)
        self.assertEqual(false - unknown, unknown)
        self.assertEqual(unknown - true, unknown)
        self.assertEqual(unknown - false, unknown)
        self.assertEqual(unknown - unknown, unknown)
        self.assertEqual(true - True, 0)
        self.assertEqual(true - False, 1)
        self.assertEqual(false - True, -1)
        self.assertEqual(false - False, 0)
        self.assertEqual(true - None, unknown)
        self.assertEqual(false - None, unknown)
        self.assertEqual(unknown - True, unknown)
        self.assertEqual(unknown - False, unknown)
        self.assertEqual(unknown - None, unknown)
        self.assertEqual(True - true, 0)
        self.assertEqual(True - false, 1)
        self.assertEqual(False - true, -1)
        self.assertEqual(False - false, 0)
        self.assertEqual(True - unknown, unknown)
        self.assertEqual(False - unknown, unknown)
        self.assertEqual(None - true, unknown)
        self.assertEqual(None - false, unknown)
        self.assertEqual(None - unknown, unknown)

        t = true
        t -= true
        self.assertEqual(t, 0)
        t = true
        t -= false
        self.assertEqual(t, 1)
        f = false
        f -= true
        self.assertEqual(f, -1)
        f = false
        f -= false
        self.assertEqual(f, 0)
        t = true
        t -= unknown
        self.assertEqual(t, unknown)
        f = false
        f -= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u -= true
        self.assertEqual(u, unknown)
        u = unknown
        u -= false
        self.assertEqual(u, unknown)
        u = unknown
        u -= unknown
        self.assertEqual(u, unknown)
        t = true
        t -= True
        self.assertEqual(t, 0)
        t = true
        t -= False
        self.assertEqual(t, 1)
        f = false
        f -= True
        self.assertEqual(f, -1)
        f = false
        f -= False
        self.assertEqual(f, 0)
        t = true
        t -= None
        self.assertEqual(t, unknown)
        f = false
        f -= None
        self.assertEqual(f, unknown)
        u = unknown
        u -= True
        self.assertEqual(u, unknown)
        u = unknown
        u -= False
        self.assertEqual(u, unknown)
        u = unknown
        u -= None
        self.assertEqual(u, unknown)
        t = True
        t -= true
        self.assertEqual(t, 0)
        t = True
        t -= false
        self.assertEqual(t, 1)
        f = False
        f -= true
        self.assertEqual(f, -1)
        f = False
        f -= false
        self.assertEqual(f, 0)
        t = True
        t -= unknown
        self.assertEqual(t, unknown)
        f = False
        f -= unknown
        self.assertEqual(f, unknown)
        u = None
        u -= true
        self.assertEqual(u, unknown)
        u = None
        u -= false
        self.assertEqual(u, unknown)
        u = None
        u -= unknown
        self.assertEqual(u, unknown)

    def test_division(self):
        "division"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)
        self.assertEqual(true / true, 1)
        self.assertEqual(true / false, unknown)
        self.assertEqual(false / true, 0)
        self.assertEqual(false / false, unknown)
        self.assertEqual(true / unknown, unknown)
        self.assertEqual(false / unknown, unknown)
        self.assertEqual(unknown / true, unknown)
        self.assertEqual(unknown / false, unknown)
        self.assertEqual(unknown / unknown, unknown)
        self.assertEqual(true / True, 1)
        self.assertEqual(true / False, unknown)
        self.assertEqual(false / True, 0)
        self.assertEqual(false / False, unknown)
        self.assertEqual(true / None, unknown)
        self.assertEqual(false / None, unknown)
        self.assertEqual(unknown / True, unknown)
        self.assertEqual(unknown / False, unknown)
        self.assertEqual(unknown / None, unknown)
        self.assertEqual(True / true, 1)
        self.assertEqual(True / false, unknown)
        self.assertEqual(False / true, 0)
        self.assertEqual(False / false, unknown)
        self.assertEqual(True / unknown, unknown)
        self.assertEqual(False / unknown, unknown)
        self.assertEqual(None / true, unknown)
        self.assertEqual(None / false, unknown)
        self.assertEqual(None / unknown, unknown)

        t = true
        t /= true
        self.assertEqual(t, 1)
        t = true
        t /= false
        self.assertEqual(t, unknown)
        f = false
        f /= true
        self.assertEqual(f, 0)
        f = false
        f /= false
        self.assertEqual(f, unknown)
        t = true
        t /= unknown
        self.assertEqual(t, unknown)
        f = false
        f /= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u /= true
        self.assertEqual(u, unknown)
        u = unknown
        u /= false
        self.assertEqual(u, unknown)
        u = unknown
        u /= unknown
        self.assertEqual(u, unknown)
        t = true
        t /= True
        self.assertEqual(t, 1)
        t = true
        t /= False
        self.assertEqual(t, unknown)
        f = false
        f /= True
        self.assertEqual(f, 0)
        f = false
        f /= False
        self.assertEqual(f, unknown)
        t = true
        t /= None
        self.assertEqual(t, unknown)
        f = false
        f /= None
        self.assertEqual(f, unknown)
        u = unknown
        u /= True
        self.assertEqual(u, unknown)
        u = unknown
        u /= False
        self.assertEqual(u, unknown)
        u = unknown
        u /= None
        self.assertEqual(u, unknown)
        t = True
        t /= true
        self.assertEqual(t, 1)
        t = True
        t /= false
        self.assertEqual(t, unknown)
        f = False
        f /= true
        self.assertEqual(f, 0)
        f = False
        f /= false
        self.assertEqual(f, unknown)
        t = True
        t /= unknown
        self.assertEqual(t, unknown)
        f = False
        f /= unknown
        self.assertEqual(f, unknown)
        u = None
        u /= true
        self.assertEqual(u, unknown)
        u = None
        u /= false
        self.assertEqual(u, unknown)
        u = None
        u /= unknown
        self.assertEqual(u, unknown)


        self.assertEqual(true // true, 1)
        self.assertEqual(true // false, unknown)
        self.assertEqual(false // true, 0)
        self.assertEqual(false // false, unknown)
        self.assertEqual(true // unknown, unknown)
        self.assertEqual(false // unknown, unknown)
        self.assertEqual(unknown // true, unknown)
        self.assertEqual(unknown // false, unknown)
        self.assertEqual(unknown // unknown, unknown)
        self.assertEqual(true // True, 1)
        self.assertEqual(true // False, unknown)
        self.assertEqual(false // True, 0)
        self.assertEqual(false // False, unknown)
        self.assertEqual(true // None, unknown)
        self.assertEqual(false // None, unknown)
        self.assertEqual(unknown // True, unknown)
        self.assertEqual(unknown // False, unknown)
        self.assertEqual(unknown // None, unknown)
        self.assertEqual(True // true, 1)
        self.assertEqual(True // false, unknown)
        self.assertEqual(False // true, 0)
        self.assertEqual(False // false, unknown)
        self.assertEqual(True // unknown, unknown)
        self.assertEqual(False // unknown, unknown)
        self.assertEqual(None // true, unknown)
        self.assertEqual(None // false, unknown)
        self.assertEqual(None // unknown, unknown)

        t = true
        t //= true
        self.assertEqual(t, 1)
        t = true
        t //= false
        self.assertEqual(t, unknown)
        f = false
        f //= true
        self.assertEqual(f, 0)
        f = false
        f //= false
        self.assertEqual(f, unknown)
        t = true
        t //= unknown
        self.assertEqual(t, unknown)
        f = false
        f //= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u //= true
        self.assertEqual(u, unknown)
        u = unknown
        u //= false
        self.assertEqual(u, unknown)
        u = unknown
        u //= unknown
        self.assertEqual(u, unknown)
        t = true
        t //= True
        self.assertEqual(t, 1)
        t = true
        t //= False
        self.assertEqual(t, unknown)
        f = false
        f //= True
        self.assertEqual(f, 0)
        f = false
        f //= False
        self.assertEqual(f, unknown)
        t = true
        t //= None
        self.assertEqual(t, unknown)
        f = false
        f //= None
        self.assertEqual(f, unknown)
        u = unknown
        u //= True
        self.assertEqual(u, unknown)
        u = unknown
        u //= False
        self.assertEqual(u, unknown)
        u = unknown
        u //= None
        self.assertEqual(u, unknown)
        t = True
        t //= true
        self.assertEqual(t, 1)
        t = True
        t //= false
        self.assertEqual(t, unknown)
        f = False
        f //= true
        self.assertEqual(f, 0)
        f = False
        f //= false
        self.assertEqual(f, unknown)
        t = True
        t //= unknown
        self.assertEqual(t, unknown)
        f = False
        f //= unknown
        self.assertEqual(f, unknown)
        u = None
        u //= true
        self.assertEqual(u, unknown)
        u = None
        u //= false
        self.assertEqual(u, unknown)
        u = None
        u //= unknown
        self.assertEqual(u, unknown)
    def test_shift(self):
        "<< and >>"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)

        self.assertEqual(true >> true, 0)
        self.assertEqual(true >> false, 1)
        self.assertEqual(false >> true, 0)
        self.assertEqual(false >> false, 0)
        self.assertEqual(true >> unknown, unknown)
        self.assertEqual(false >> unknown, unknown)
        self.assertEqual(unknown >> true, unknown)
        self.assertEqual(unknown >> false, unknown)
        self.assertEqual(unknown >> unknown, unknown)
        self.assertEqual(true >> True, 0)
        self.assertEqual(true >> False, 1)
        self.assertEqual(false >> True, 0)
        self.assertEqual(false >> False, 0)
        self.assertEqual(true >> None, unknown)
        self.assertEqual(false >> None, unknown)
        self.assertEqual(unknown >> True, unknown)
        self.assertEqual(unknown >> False, unknown)
        self.assertEqual(unknown >> None, unknown)
        self.assertEqual(True >> true, 0)
        self.assertEqual(True >> false, 1)
        self.assertEqual(False >> true, 0)
        self.assertEqual(False >> false, 0)
        self.assertEqual(True >> unknown, unknown)
        self.assertEqual(False >> unknown, unknown)
        self.assertEqual(None >> true, unknown)
        self.assertEqual(None >> false, unknown)
        self.assertEqual(None >> unknown, unknown)

        self.assertEqual(true << true, 2)
        self.assertEqual(true << false, 1)
        self.assertEqual(false << true, 0)
        self.assertEqual(false << false, 0)
        self.assertEqual(true << unknown, unknown)
        self.assertEqual(false << unknown, unknown)
        self.assertEqual(unknown << true, unknown)
        self.assertEqual(unknown << false, unknown)
        self.assertEqual(unknown << unknown, unknown)
        self.assertEqual(true << True, 2)
        self.assertEqual(true << False, 1)
        self.assertEqual(false << True, 0)
        self.assertEqual(false << False, 0)
        self.assertEqual(true << None, unknown)
        self.assertEqual(false << None, unknown)
        self.assertEqual(unknown << True, unknown)
        self.assertEqual(unknown << False, unknown)
        self.assertEqual(unknown << None, unknown)
        self.assertEqual(True << true, 2)
        self.assertEqual(True << false, 1)
        self.assertEqual(False << true, 0)
        self.assertEqual(False << false, 0)
        self.assertEqual(True << unknown, unknown)
        self.assertEqual(False << unknown, unknown)
        self.assertEqual(None << true, unknown)
        self.assertEqual(None << false, unknown)
        self.assertEqual(None << unknown, unknown)

        t = true
        t >>= true
        self.assertEqual(t, 0)
        t = true
        t >>= false
        self.assertEqual(t, 1)
        f = false
        f >>= true
        self.assertEqual(f, 0)
        f = false
        f >>= false
        self.assertEqual(f, 0)
        t = true
        t >>= unknown
        self.assertEqual(t, unknown)
        f = false
        f >>= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u >>= true
        self.assertEqual(u, unknown)
        u = unknown
        u >>= false
        self.assertEqual(u, unknown)
        u = unknown
        u >>= unknown
        self.assertEqual(u, unknown)
        t = true
        t >>= True
        self.assertEqual(t, 0)
        t = true
        t >>= False
        self.assertEqual(t, 1)
        f = false
        f >>= True
        self.assertEqual(f, 0)
        f = false
        f >>= False
        self.assertEqual(f, 0)
        t = true
        t >>= None
        self.assertEqual(t, unknown)
        f = false
        f >>= None
        self.assertEqual(f, unknown)
        u = unknown
        u >>= True
        self.assertEqual(u, unknown)
        u = unknown
        u >>= False
        self.assertEqual(u, unknown)
        u = unknown
        u >>= None
        self.assertEqual(u, unknown)
        t = True
        t >>= true
        self.assertEqual(t, 0)
        t = True
        t >>= false
        self.assertEqual(t, 1)
        f = False
        f >>= true
        self.assertEqual(f, 0)
        f = False
        f >>= false
        self.assertEqual(f, 0)
        t = True
        t >>= unknown
        self.assertEqual(t, unknown)
        f = False
        f >>= unknown
        self.assertEqual(f, unknown)
        u = None
        u >>= true
        self.assertEqual(u, unknown)
        u = None
        u >>= false
        self.assertEqual(u, unknown)
        u = None
        u >>= unknown
        self.assertEqual(u, unknown)

        t = true
        t <<= true
        self.assertEqual(t, 2)
        t = true
        t <<= false
        self.assertEqual(t, 1)
        f = false
        f <<= true
        self.assertEqual(f, 0)
        f = false
        f <<= false
        self.assertEqual(f, 0)
        t = true
        t <<= unknown
        self.assertEqual(t, unknown)
        f = false
        f <<= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u <<= true
        self.assertEqual(u, unknown)
        u = unknown
        u <<= false
        self.assertEqual(u, unknown)
        u = unknown
        u <<= unknown
        self.assertEqual(u, unknown)
        t = true
        t <<= True
        self.assertEqual(t, 2)
        t = true
        t <<= False
        self.assertEqual(t, 1)
        f = false
        f <<= True
        self.assertEqual(f, 0)
        f = false
        f <<= False
        self.assertEqual(f, 0)
        t = true
        t <<= None
        self.assertEqual(t, unknown)
        f = false
        f <<= None
        self.assertEqual(f, unknown)
        u = unknown
        u <<= True
        self.assertEqual(u, unknown)
        u = unknown
        u <<= False
        self.assertEqual(u, unknown)
        u = unknown
        u <<= None
        self.assertEqual(u, unknown)
        t = True
        t <<= true
        self.assertEqual(t, 2)
        t = True
        t <<= false
        self.assertEqual(t, 1)
        f = False
        f <<= true
        self.assertEqual(f, 0)
        f = False
        f <<= false
        self.assertEqual(f, 0)
        t = True
        t <<= unknown
        self.assertEqual(t, unknown)
        f = False
        f <<= unknown
        self.assertEqual(f, unknown)
        u = None
        u <<= true
        self.assertEqual(u, unknown)
        u = None
        u <<= false
        self.assertEqual(u, unknown)
        u = None
        u <<= unknown
        self.assertEqual(u, unknown)

    def test_pow(self):
        "**"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)

        self.assertEqual(true ** true, 1)
        self.assertEqual(true ** false, 1)
        self.assertEqual(false ** true, 0)
        self.assertEqual(false ** false, 1)
        self.assertEqual(true ** unknown, unknown)
        self.assertEqual(false ** unknown, unknown)
        self.assertEqual(unknown ** true, unknown)
        self.assertEqual(unknown ** false, 1)
        self.assertEqual(unknown ** unknown, unknown)
        self.assertEqual(true ** True, 1)
        self.assertEqual(true ** False, 1)
        self.assertEqual(false ** True, 0)
        self.assertEqual(false ** False, 1)
        self.assertEqual(true ** None, unknown)
        self.assertEqual(false ** None, unknown)
        self.assertEqual(unknown ** True, unknown)
        self.assertEqual(unknown ** False, 1)
        self.assertEqual(unknown ** None, unknown)
        self.assertEqual(True ** true, 1)
        self.assertEqual(True ** false, 1)
        self.assertEqual(False ** true, 0)
        self.assertEqual(False ** false, 1)
        self.assertEqual(True ** unknown, unknown)
        self.assertEqual(False ** unknown, unknown)
        self.assertEqual(None ** true, unknown)
        self.assertEqual(None ** false, 1)
        self.assertEqual(None ** unknown, unknown)

        t = true
        t **= true
        self.assertEqual(t, 1)
        t = true
        t **= false
        self.assertEqual(t, 1)
        f = false
        f **= true
        self.assertEqual(f, 0)
        f = false
        f **= false
        self.assertEqual(f, 1)
        t = true
        t **= unknown
        self.assertEqual(t, unknown)
        f = false
        f **= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u **= true
        self.assertEqual(u, unknown)
        u = unknown
        u **= false
        self.assertEqual(u, 1)
        u = unknown
        u **= unknown
        self.assertEqual(u, unknown)
        t = true
        t **= True
        self.assertEqual(t, 1)
        t = true
        t **= False
        self.assertEqual(t, 1)
        f = false
        f **= True
        self.assertEqual(f, 0)
        f = false
        f **= False
        self.assertEqual(f, 1)
        t = true
        t **= None
        self.assertEqual(t, unknown)
        f = false
        f **= None
        self.assertEqual(f, unknown)
        u = unknown
        u **= True
        self.assertEqual(u, unknown)
        u = unknown
        u **= False
        self.assertEqual(u, 1)
        u = unknown
        u **= None
        self.assertEqual(u, unknown)
        t = True
        t **= true
        self.assertEqual(t, 1)
        t = True
        t **= false
        self.assertEqual(t, 1)
        f = False
        f **= true
        self.assertEqual(f, 0)
        f = False
        f **= false
        self.assertEqual(f, 1)
        t = True
        t **= unknown
        self.assertEqual(t, unknown)
        f = False
        f **= unknown
        self.assertEqual(f, unknown)
        u = None
        u **= true
        self.assertEqual(u, unknown)
        u = None
        u **= false
        self.assertEqual(u, 1)
        u = None
        u **= unknown
        self.assertEqual(u, unknown)

    def test_mod(self):
        "%"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)

        self.assertEqual(true % true, 0)
        self.assertEqual(true % false, unknown)
        self.assertEqual(false % true, 0)
        self.assertEqual(false % false, unknown)
        self.assertEqual(true % unknown, unknown)
        self.assertEqual(false % unknown, unknown)
        self.assertEqual(unknown % true, unknown)
        self.assertEqual(unknown % false, unknown)
        self.assertEqual(unknown % unknown, unknown)
        self.assertEqual(true % True, 0)
        self.assertEqual(true % False, unknown)
        self.assertEqual(false % True, 0)
        self.assertEqual(false % False, unknown)
        self.assertEqual(true % None, unknown)
        self.assertEqual(false % None, unknown)
        self.assertEqual(unknown % True, unknown)
        self.assertEqual(unknown % False, unknown)
        self.assertEqual(unknown % None, unknown)
        self.assertEqual(True % true, 0)
        self.assertEqual(True % false, unknown)
        self.assertEqual(False % true, 0)
        self.assertEqual(False % false, unknown)
        self.assertEqual(True % unknown, unknown)
        self.assertEqual(False % unknown, unknown)
        self.assertEqual(None % true, unknown)
        self.assertEqual(None % false, unknown)
        self.assertEqual(None % unknown, unknown)

        t = true
        t %= true
        self.assertEqual(t, 0)
        t = true
        t %= false
        self.assertEqual(t, unknown)
        f = false
        f %= true
        self.assertEqual(f, 0)
        f = false
        f %= false
        self.assertEqual(f, unknown)
        t = true
        t %= unknown
        self.assertEqual(t, unknown)
        f = false
        f %= unknown
        self.assertEqual(f, unknown)
        u = unknown
        u %= true
        self.assertEqual(u, unknown)
        u = unknown
        u %= false
        self.assertEqual(u, unknown)
        u = unknown
        u %= unknown
        self.assertEqual(u, unknown)
        t = true
        t %= True
        self.assertEqual(t, 0)
        t = true
        t %= False
        self.assertEqual(t, unknown)
        f = false
        f %= True
        self.assertEqual(f, 0)
        f = false
        f %= False
        self.assertEqual(f, unknown)
        t = true
        t %= None
        self.assertEqual(t, unknown)
        f = false
        f %= None
        self.assertEqual(f, unknown)
        u = unknown
        u %= True
        self.assertEqual(u, unknown)
        u = unknown
        u %= False
        self.assertEqual(u, unknown)
        u = unknown
        u %= None
        self.assertEqual(u, unknown)
        t = True
        t %= true
        self.assertEqual(t, 0)
        t = True
        t %= false
        self.assertEqual(t, unknown)
        f = False
        f %= true
        self.assertEqual(f, 0)
        f = False
        f %= false
        self.assertEqual(f, unknown)
        t = True
        t %= unknown
        self.assertEqual(t, unknown)
        f = False
        f %= unknown
        self.assertEqual(f, unknown)
        u = None
        u %= true
        self.assertEqual(u, unknown)
        u = None
        u %= false
        self.assertEqual(u, unknown)
        u = None
        u %= unknown
        self.assertEqual(u, unknown)

    def test_divmod(self):
        "divmod()"
        true = Logical(True)
        false = Logical(False)
        unknown = Logical(None)

        self.assertEqual(divmod(true, true), (1, 0))
        self.assertEqual(divmod(true, false), (unknown, unknown))
        self.assertEqual(divmod(false, true), (0, 0))
        self.assertEqual(divmod(false, false), (unknown, unknown))
        self.assertEqual(divmod(true, unknown), (unknown, unknown))
        self.assertEqual(divmod(false, unknown), (unknown, unknown))
        self.assertEqual(divmod(unknown, true), (unknown, unknown))
        self.assertEqual(divmod(unknown, false), (unknown, unknown))
        self.assertEqual(divmod(unknown, unknown), (unknown, unknown))
        self.assertEqual(divmod(true, True), (1, 0))
        self.assertEqual(divmod(true, False), (unknown, unknown))
        self.assertEqual(divmod(false, True), (0, 0))
        self.assertEqual(divmod(false, False), (unknown, unknown))
        self.assertEqual(divmod(true, None), (unknown, unknown))
        self.assertEqual(divmod(false, None), (unknown, unknown))
        self.assertEqual(divmod(unknown, True), (unknown, unknown))
        self.assertEqual(divmod(unknown, False), (unknown, unknown))
        self.assertEqual(divmod(unknown, None), (unknown, unknown))
        self.assertEqual(divmod(True, true), (1, 0))
        self.assertEqual(divmod(True, false), (unknown, unknown))
        self.assertEqual(divmod(False, true), (0, 0))
        self.assertEqual(divmod(False, false), (unknown, unknown))
        self.assertEqual(divmod(True, unknown), (unknown, unknown))
        self.assertEqual(divmod(False, unknown), (unknown, unknown))
        self.assertEqual(divmod(None, true), (unknown, unknown))
        self.assertEqual(divmod(None, false), (unknown, unknown))
        self.assertEqual(divmod(None, unknown), (unknown, unknown))

class TestQuantum(unittest.TestCase):
    "Testing Quantum"
    def test_exceptions(self):
        "errors"
        self.assertRaises(ValueError, Quantum, 'wrong')
        if py_ver >= (2, 5):
            self.assertRaises(TypeError, lambda : (0, 1, 2)[On])
            self.assertRaises(TypeError, lambda : (0, 1, 2)[Off])
            self.assertRaises(TypeError, lambda : (0, 1, 2)[Other])

    def test_other(self):
        "Other"
        huh = unknown = Quantum('')
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

        huh = Quantum('?')
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

        huh = Quantum(' ')
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

        huh = Quantum(None)
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

        huh = Quantum(Null())
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

        huh = Quantum(Other)
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

        huh = Quantum(Unknown)
        self.assertEqual(huh is dbf.Other, True)
        self.assertEqual((huh != huh) is unknown, True)
        self.assertEqual((huh != True) is unknown, True)
        self.assertEqual((huh != False) is unknown, True)

    def test_true(self):
        "true"
        huh = Quantum('True')
        unknown = Quantum('?')
        self.assertEqual(huh, True)
        self.assertNotEqual(huh, False)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum('yes')
        unknown = Quantum('?')
        self.assertEqual(huh, True)
        self.assertNotEqual(huh, False)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum('t')
        unknown = Quantum('?')
        self.assertEqual(huh, True)
        self.assertNotEqual(huh, False)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum('Y')
        unknown = Quantum('?')
        self.assertEqual(huh, True)
        self.assertNotEqual(huh, False)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum(7)
        unknown = Quantum('?')
        self.assertEqual(huh, True)
        self.assertNotEqual(huh, False)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum(['blah'])
        unknown = Quantum('?')
        self.assertEqual(huh, True)
        self.assertNotEqual(huh, False)
        self.assertEqual((huh != None) is unknown, True)

    def test_false(self):
        "false"
        huh = Quantum('false')
        unknown = Quantum('?')
        self.assertEqual(huh, False)
        self.assertNotEqual(huh, True)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum('No')
        unknown = Quantum('?')
        self.assertEqual(huh, False)
        self.assertNotEqual(huh, True)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum('F')
        unknown = Quantum('?')
        self.assertEqual(huh, False)
        self.assertNotEqual(huh, True)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum('n')
        unknown = Quantum('?')
        self.assertEqual(huh, False)
        self.assertNotEqual(huh, True)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum(0)
        unknown = Quantum('?')
        self.assertEqual(huh, False)
        self.assertNotEqual(huh, True)
        self.assertEqual((huh != None) is unknown, True)

        huh = Quantum([])
        unknown = Quantum('?')
        self.assertEqual(huh, False)
        self.assertNotEqual(huh, True)
        self.assertEqual((huh != None) is unknown, True)

    def test_singletons(self):
        "singletons"
        heh = Quantum(True)
        hah = Quantum('Yes')
        ick = Quantum(False)
        ack = Quantum([])
        unk = Quantum('?')
        bla = Quantum(None)
        self.assertEqual(heh is hah, True)
        self.assertEqual(ick is ack, True)
        self.assertEqual(unk is bla, True)

    def test_or(self):
        "or"
        true = Quantum(True)
        false = Quantum(False)
        unknown = Quantum(None)
        self.assertEqual(true + true, true)
        self.assertEqual(true + false, true)
        self.assertEqual(false + true, true)
        self.assertEqual(false + false, false)
        self.assertEqual(true + unknown, true)
        self.assertEqual(false + unknown is unknown, True)
        self.assertEqual(unknown + unknown is unknown, True)
        self.assertEqual(true | true, true)
        self.assertEqual(true | false, true)
        self.assertEqual(false | true, true)
        self.assertEqual(false | false, false)
        self.assertEqual(true | unknown, true)
        self.assertEqual(false | unknown is unknown, True)
        self.assertEqual(unknown | unknown is unknown, True)
        self.assertEqual(true + True, true)
        self.assertEqual(true + False, true)
        self.assertEqual(false + True, true)
        self.assertEqual(false + False, false)
        self.assertEqual(true + None, true)
        self.assertEqual(false + None is unknown, True)
        self.assertEqual(unknown + None is unknown, True)
        self.assertEqual(true | True, true)
        self.assertEqual(true | False, true)
        self.assertEqual(false | True, true)
        self.assertEqual(false | False, false)
        self.assertEqual(true | None, true)
        self.assertEqual(false | None is unknown, True)
        self.assertEqual(unknown | None is unknown, True)
        self.assertEqual(True + true, true)
        self.assertEqual(True + false, true)
        self.assertEqual(False + true, true)
        self.assertEqual(False + false, false)
        self.assertEqual(True + unknown, true)
        self.assertEqual(False + unknown is unknown, True)
        self.assertEqual(None + unknown is unknown, True)
        self.assertEqual(True | true, true)
        self.assertEqual(True | false, true)
        self.assertEqual(False | true, true)
        self.assertEqual(False | false, false)
        self.assertEqual(True | unknown, true)
        self.assertEqual(False | unknown is unknown, True)
        self.assertEqual(None | unknown is unknown, True)
    def test_and(self):
        "and"
        true = Quantum(True)
        false = Quantum(False)
        unknown = Quantum(None)
        self.assertEqual(true * true, true)
        self.assertEqual(true * false, false)
        self.assertEqual(false * true, false)
        self.assertEqual(false * false, false)
        self.assertEqual(true * unknown is unknown, True)
        self.assertEqual(false * unknown, false)
        self.assertEqual(unknown * unknown is unknown, True)
        self.assertEqual(true & true, true)
        self.assertEqual(true & false, false)
        self.assertEqual(false & true, false)
        self.assertEqual(false & false, false)
        self.assertEqual(true & unknown is unknown, True)
        self.assertEqual(false & unknown, false)
        self.assertEqual(unknown & unknown is unknown, True)
        self.assertEqual(true * True, true)
        self.assertEqual(true * False, false)
        self.assertEqual(false * True, false)
        self.assertEqual(false * False, false)
        self.assertEqual(true * None is unknown, True)
        self.assertEqual(false * None, false)
        self.assertEqual(unknown * None is unknown, True)
        self.assertEqual(true & True, true)
        self.assertEqual(true & False, false)
        self.assertEqual(false & True, false)
        self.assertEqual(false & False, false)
        self.assertEqual(true & None is unknown, True)
        self.assertEqual(false & None, false)
        self.assertEqual(unknown & None is unknown, True)
        self.assertEqual(True * true, true)
        self.assertEqual(True * false, false)
        self.assertEqual(False * true, false)
        self.assertEqual(False * false, false)
        self.assertEqual(True * unknown is unknown, True)
        self.assertEqual(False * unknown, false)
        self.assertEqual(None * unknown is unknown, True)
        self.assertEqual(True & true, true)
        self.assertEqual(True & false, false)
        self.assertEqual(False & true, false)
        self.assertEqual(False & false, false)
        self.assertEqual(True & unknown is unknown, True)
        self.assertEqual(False & unknown, false)
        self.assertEqual(None & unknown is unknown, True)
    def test_xor(self):
        "xor"
        true = Quantum(True)
        false = Quantum(False)
        unknown = Quantum(None)
        self.assertEqual(true ^ true, false)
        self.assertEqual(true ^ false, true)
        self.assertEqual(false ^ true, true)
        self.assertEqual(false ^ false, false)
        self.assertEqual(true ^ unknown is unknown, True)
        self.assertEqual(false ^ unknown is unknown, True)
        self.assertEqual(unknown ^ unknown is unknown, True)
        self.assertEqual(true ^ True, false)
        self.assertEqual(true ^ False, true)
        self.assertEqual(false ^ True, true)
        self.assertEqual(false ^ False, false)
        self.assertEqual(true ^ None is unknown, True)
        self.assertEqual(false ^ None is unknown, True)
        self.assertEqual(unknown ^ None is unknown, True)
        self.assertEqual(True ^ true, false)
        self.assertEqual(True ^ false, true)
        self.assertEqual(False ^ true, true)
        self.assertEqual(False ^ false, false)
        self.assertEqual(True ^ unknown is unknown, True)
        self.assertEqual(False ^ unknown is unknown, True)
        self.assertEqual(None ^ unknown is unknown, True)
    def test_implication_material(self):
        "implication, material"
        true = Quantum(True)
        false = Quantum(False)
        unknown = Quantum(None)
        self.assertEqual(true >> true, true)
        self.assertEqual(true >> false, false)
        self.assertEqual(false >> true, true)
        self.assertEqual(false >> false, true)
        self.assertEqual(true >> unknown is unknown, True)
        self.assertEqual(false >> unknown, true)
        self.assertEqual(unknown >> unknown is unknown, True)
        self.assertEqual(true >> True, true)
        self.assertEqual(true >> False, false)
        self.assertEqual(false >> True, true)
        self.assertEqual(false >> False, true)
        self.assertEqual(true >> None is unknown, True)
        self.assertEqual(false >> None, true)
        self.assertEqual(unknown >> None is unknown, True)
        self.assertEqual(True >> true, true)
        self.assertEqual(True >> false, false)
        self.assertEqual(False >> true, true)
        self.assertEqual(False >> false, true)
        self.assertEqual(True >> unknown is unknown, True)
        self.assertEqual(False >> unknown, true)
        self.assertEqual(None >> unknown is unknown, True)
    def test_implication_relevant(self):
        "implication, relevant"
        true = Quantum(True)
        false = Quantum(False)
        unknown = Quantum(None)
        Quantum.set_implication('relevant')
        self.assertEqual(true >> true, true)
        self.assertEqual(true >> false, false)
        self.assertEqual(false >> true is unknown, True)
        self.assertEqual(false >> false is unknown, True)
        self.assertEqual(true >> unknown is unknown, True)
        self.assertEqual(false >> unknown is unknown, True)
        self.assertEqual(unknown >> unknown is unknown, True)
        self.assertEqual(true >> True, true)
        self.assertEqual(true >> False, false)
        self.assertEqual(false >> True is unknown, True)
        self.assertEqual(false >> False is unknown, True)
        self.assertEqual(true >> None is unknown, True)
        self.assertEqual(false >> None is unknown, True)
        self.assertEqual(unknown >> None is unknown, True)
        self.assertEqual(True >> true, true)
        self.assertEqual(True >> false, false)
        self.assertEqual(False >> true is unknown, True)
        self.assertEqual(False >> false is unknown, True)
        self.assertEqual(True >> unknown is unknown, True)
        self.assertEqual(False >> unknown is unknown, True)
        self.assertEqual(None >> unknown is unknown, True)
    def test_nand(self):
        "negative and"
        true = Quantum(True)
        false = Quantum(False)
        unknown = Quantum(None)
        self.assertEqual(true.D(true), false)
        self.assertEqual(true.D(false), true)
        self.assertEqual(false.D(true), true)
        self.assertEqual(false.D(false), true)
        self.assertEqual(true.D(unknown) is unknown, True)
        self.assertEqual(false.D(unknown), true)
        self.assertEqual(unknown.D(unknown) is unknown, True)
        self.assertEqual(true.D(True), false)
        self.assertEqual(true.D(False), true)
        self.assertEqual(false.D(True), true)
        self.assertEqual(false.D(False), true)
        self.assertEqual(true.D(None) is unknown, True)
        self.assertEqual(false.D(None), true)
        self.assertEqual(unknown.D(None) is unknown, True)
    def test_negation(self):
        "negation"
        true = Quantum(True)
        false = Quantum(False)
        none = Quantum(None)
        self.assertEqual(-true, false)
        self.assertEqual(-false, true)
        self.assertEqual(-none is none, True)

class TestExceptions(unittest.TestCase):
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tempdir, True)

    def test_bad_field_specs_on_creation(self):
        self.assertRaises(FieldSpecError, Table, 'blah', 'age N(3,2)', on_disk=False)
        self.assertRaises(FieldSpecError, Table, 'blah', 'name C(300)', on_disk=False)
        self.assertRaises(FieldSpecError, Table, 'blah', 'born L(9)', on_disk=False)
        self.assertRaises(FieldSpecError, Table, 'blah', 'married D(12)', on_disk=False)
        self.assertRaises(FieldSpecError, Table, 'blah', 'desc M(1)', on_disk=False)

    def test_too_many_fields_on_creation(self):
        fields = []
        for i in range(255):
            fields.append('a%03d C(10)' % i)
        Table(':test:', ';'.join(fields), on_disk=False)
        fields.append('a255 C(10)')
        self.assertRaises(DbfError, Table, ':test:', ';'.join(fields), on_disk=False)

    def test_adding_too_many_fields(self):
        fields = []
        for i in range(255):
            fields.append('a%03d C(10)' % i)
        table = Table(':test:', ';'.join(fields), on_disk=False)
        table.open()
        self.assertRaises(DbfError, table.add_fields, 'a255 C(10)')

    def test_adding_too_many_fields_with_null(self):
        fields = []
        for i in range(254):
            fields.append('a%03d C(10) null' % i)
        table = Table(':test:', ';'.join(fields), dbf_type='vfp', on_disk=False)
        table.open()
        self.assertRaises(DbfError, table.add_fields, 'a255 C(10)')
        fields = []
        for i in range(254):
            fields.append('a%03d C(10) NULL' % i)
        table = Table(':test:', ';'.join(fields), dbf_type='vfp', on_disk=False)
        table.open()
        self.assertRaises(DbfError, table.add_fields, 'a255 C(10)')

    def test_too_many_records_in_table(self):
        "skipped -- test takes waaaaaaay too long"

    def test_too_many_fields_to_change_to_null(self):
        fields = []
        for i in range(255):
            fields.append('a%03d C(10)' % i)
        table = Table(':test:', ';'.join(fields), on_disk=False)
        table.open()
        self.assertRaises(DbfError, table.allow_nulls, 'a001')

    def test_adding_existing_field_to_table(self):
        table = Table(':blah:', 'name C(50)', on_disk=False)
        self.assertRaises(DbfError, table.add_fields, 'name C(10)')

    def test_deleting_non_existing_field_from_table(self):
        table = Table(':bleh:', 'name C(25)', on_disk=False)
        self.assertRaises(DbfError, table.delete_fields, 'age')

    def test_modify_packed_record(self):
        table = Table(':ummm:', 'name C(3); age N(3,0)', on_disk=False)
        table.open()
        for person in (('me', 25), ('you', 35), ('her', 29)):
            table.append(person)
        record = table[1]
        dbf.delete(record)
        table.pack()
        self.assertEqual(('you', 35), record)
        self.assertRaises(DbfError, dbf.write, record, **{'age':33})
    def test_read_only(self):
        table = Table(':ahhh:', 'name C(10)', on_disk=False)
        table.open(mode=dbf.READ_ONLY)
        self.assertRaises(DbfError, table.append, dict(name='uh uh!'))
    def test_clipper(self):
        table = Table(os.path.join(self.tempdir, 'temptable'), 'name C(377); thesis C(20179)', dbf_type='clp')
        self.assertRaises(BadDataError, Table, os.path.join(self.tempdir, 'temptable'))

class TestIndexLocation(unittest.TestCase):
    def test_false(self):
        self.assertFalse(IndexLocation(0, False))
        self.assertFalse(IndexLocation(42, False))
    def test_true(self):
        self.assertTrue(IndexLocation(0, True))
        self.assertTrue(IndexLocation(42, True))

class TestDbfCreation(unittest.TestCase):
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tempdir, True)

    "Testing table creation..."
    def test_db3_memory_tables(self):
        "dbf tables in memory"
        fields = ['name C(25)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)', 'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(':memory:', fieldlist, dbf_type='db3', on_disk=False)
                actualFields = table.structure()
                self.assertEqual(fieldlist, actualFields)
                self.assertTrue(all([type(x) is unicode for x in table.field_names]))
    def test_db3_disk_tables(self):
        "dbf table on disk"
        fields = ['name C(25)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)', 'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(os.path.join(self.tempdir, 'temptable'), ';'.join(fieldlist), dbf_type='db3')
                table = Table(os.path.join(self.tempdir, 'temptable'), dbf_type='db3')
                actualFields = table.structure()
                self.assertEqual(fieldlist, actualFields)
                table = open(table.filename, 'rb')
                try:
                    last_byte = table.read()[-1]
                finally:
                    table.close()
                self.assertEqual(last_byte, EOF)
    def test_clp_memory_tables(self):
        "clp tables in memory"
        fields = ['name C(10977)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)', 'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(':memory:', fieldlist, dbf_type='clp', on_disk=False)
                actualFields = table.structure()
                self.assertEqual(fieldlist, actualFields)
                self.assertTrue(all([type(x) is unicode for x in table.field_names]))
    def test_clp_disk_tables(self):
        "clp table on disk"
        table = Table(os.path.join(self.tempdir, 'temptable'), 'name C(377); thesis C(20179)', dbf_type='clp')
        self.assertEqual(table.record_length, 20557)
        fields = ['name C(10977)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)', 'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(os.path.join(self.tempdir, 'temptable'), ';'.join(fieldlist), dbf_type='clp')
                table = Table(os.path.join(self.tempdir, 'temptable'), dbf_type='clp')
                actualFields = table.structure()
                self.assertEqual(fieldlist, actualFields)
                table = open(table.filename, 'rb')
                try:
                    last_byte = table.read()[-1]
                finally:
                    table.close()
                self.assertEqual(last_byte, EOF)
    def test_fp_memory_tables(self):
        "fp tables in memory"
        fields = ['name C(25)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)',
                  'litres F(11,5)', 'blob G', 'graphic P', 'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(':memory:', ';'.join(fieldlist), dbf_type='vfp', on_disk=False)
                actualFields = table.structure()
                self.assertEqual(fieldlist, actualFields)
    def test_fp_disk_tables(self):
        "fp tables on disk"
        fields = ['name C(25)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)',
                  'litres F(11,5)', 'blob G', 'graphic P', 'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(os.path.join(self.tempdir, 'tempfp'), ';'.join(fieldlist), dbf_type='vfp')
                table = Table(os.path.join(self.tempdir, 'tempfp'), dbf_type='vfp')
                actualFields = table.structure()
                self.assertEqual(fieldlist, actualFields)
    def test_vfp_memory_tables(self):
        "vfp tables in memory"
        fields = ['name C(25)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)',
                  'mass B', 'litres F(11,5)', 'int I', 'birth T', 'blob G', 'graphic P',
                  'menu C(50) binary', 'graduated L null', 'fired D null', 'cipher C(50) nocptrans null',
                  'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(':memory:', ';'.join(fieldlist), dbf_type='vfp', on_disk=False)
                actualFields = table.structure()
                fieldlist = [f.replace('nocptrans','binary') for f in fieldlist]
                self.assertEqual(fieldlist, actualFields)
    def test_vfp_disk_tables(self):
        "vfp tables on disk"
        fields = ['name C(25)', 'hiredate D', 'male L', 'wisdom M', 'qty N(3,0)',
                  'mass B', 'litres F(11,5)', 'int I', 'birth T', 'blob G', 'graphic P',
                  'menu C(50) binary', 'graduated L null', 'fired D null', 'cipher C(50) nocptrans null',
                  'weight F(7,3)']
        for i in range(1, len(fields)+1):
            for fieldlist in combinate(fields, i):
                table = Table(os.path.join(self.tempdir, 'tempvfp'), ';'.join(fieldlist), dbf_type='vfp')
                table = Table(os.path.join(self.tempdir, 'tempvfp'), dbf_type='vfp')
                actualFields = table.structure()
                fieldlist = [f.replace('nocptrans','binary') for f in fieldlist]
                self.assertEqual(fieldlist, actualFields)
    def test_codepage(self):
        table = Table(os.path.join(self.tempdir, 'tempvfp'), 'name C(25); male L; fired D null', dbf_type='vfp')
        self.assertEqual(dbf.default_codepage, 'ascii')
        self.assertEqual(table.codepage, dbf.CodePage('ascii'))
        table.close()
        table.open()
        table.close()
        table = Table(os.path.join(self.tempdir, 'tempvfp'), 'name C(25); male L; fired D null', dbf_type='vfp', codepage='cp850')
        self.assertEqual(table.codepage, dbf.CodePage('cp850'))

        newtable = table.new('tempvfp2', codepage='cp437')
        self.assertEqual(newtable.codepage, dbf.CodePage('cp437'))
        newtable.open()
        newtable.create_backup()
        newtable.close()
        bckup = Table(os.path.join(self.tempdir, newtable.backup))
        self.assertEqual(bckup.codepage, newtable.codepage)
    def test_db3_ignore_memos(self):
        table = Table(os.path.join(self.tempdir, 'tempdb3'), 'name C(25); wisdom M', dbf_type='db3').open()
        table.append(('QC Tester', 'check it twice!  check it thrice!  check it . . . uh . . . again!'))
        table.close()
        table = Table(os.path.join(self.tempdir, 'tempdb3'), dbf_type='db3', ignore_memos=True)
        table.open()
        try:
            self.assertEqual(table[0].wisdom, '')
        finally:
            table.close()
    def test_fp_ignore_memos(self):
        table = Table(os.path.join(self.tempdir, 'tempdb3'), 'name C(25); wisdom M', dbf_type='fp').open()
        table.append(('QC Tester', 'check it twice!  check it thrice!  check it . . . uh . . . again!'))
        table.close()
        table = Table(os.path.join(self.tempdir, 'tempdb3'), dbf_type='fp', ignore_memos=True)
        table.open()
        try:
            self.assertEqual(table[0].wisdom, '')
        finally:
            table.close()
    def test_vfp_ignore_memos(self):
        table = Table(os.path.join(self.tempdir, 'tempdb3'), 'name C(25); wisdom M', dbf_type='vfp').open()
        table.append(('QC Tester', 'check it twice!  check it thrice!  check it . . . uh . . . again!'))
        table.close()
        table = Table(os.path.join(self.tempdir, 'tempdb3'), dbf_type='vfp', ignore_memos=True)
        table.open()
        try:
            self.assertEqual(table[0].wisdom, '')
        finally:
            table.close()
    def test_clp_ignore_memos(self):
        table = Table(os.path.join(self.tempdir, 'tempdb3'), 'name C(25); wisdom M', dbf_type='clp').open()
        table.append(('QC Tester', 'check it twice!  check it thrice!  check it . . . uh . . . again!'))
        table.close()
        table = Table(os.path.join(self.tempdir, 'tempdb3'), dbf_type='clp', ignore_memos=True)
        table.open()
        try:
            self.assertEqual(table[0].wisdom, '')
        finally:
            table.close()

class TestDbfRecords(unittest.TestCase):
    "Testing records"

    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        self.dbf_table = Table(
                os.path.join(self.tempdir, 'dbf_table'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M',
                dbf_type='db3',
                )
        self.vfp_table = Table(
                os.path.join(self.tempdir, 'vfp_table'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M; mass B;' +
                ' weight F(18,3); age I; meeting T; misc G; photo P; price Y',
                dbf_type='vfp',
                )

    def tearDown(self):
        self.dbf_table.close()
        self.vfp_table.close()
        shutil.rmtree(self.tempdir, True)

    def test_slicing(self):
        table = self.dbf_table
        table.open()
        table.append(('myself', True, 5.97, dbf.Date(2012, 5, 21), 'really cool'))
        self.assertEqual(table.first_record['name':'qty'], table[0][:3])
    def test_dbf_adding_records(self):
        "dbf table:  adding records"
        table = self.dbf_table
        table.open()
        namelist = []
        paidlist = []
        qtylist = []
        orderlist = []
        desclist = []
        for i in range(len(floats)):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            namelist.append(name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc})
            record = table[-1]

            t = open(table.filename, 'rb')
            last_byte = t.read()[-1]
            t.close()
            self.assertEqual(last_byte, EOF)
            self.assertEqual(record.name.strip(), name)
            self.assertEqual(record.paid, paid)
            self.assertEqual(record.qty, round(qty, 5))
            self.assertEqual(record.orderdate, orderdate)
            self.assertEqual(record.desc.strip(), desc)
        # plus a blank record
        namelist.append('')
        paidlist.append(None)
        qtylist.append(None)
        orderlist.append(None)
        desclist.append('')
        table.append()
        self.assertEqual(len(table), len(floats)+1)
        for field in table.field_names:
            self.assertEqual(1, table.field_names.count(field))
        table.close()
        t = open(table.filename, 'rb')
        last_byte = t.read()[-1]
        t.close()
        self.assertEqual(last_byte, EOF)
        table = Table(table.filename, dbf_type='db3')
        table.open()
        self.assertEqual(len(table), len(floats)+1)
        for field in table.field_names:
            self.assertEqual(1, table.field_names.count(field))
        i = 0
        for record in table[:-1]:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name.strip(), namelist[i])
            self.assertEqual(record.name.strip(), namelist[i])
            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(table[i].desc.strip(), desclist[i])
            self.assertEqual(record.desc.strip(), desclist[i])
            i += 1
        record = table[-1]
        self.assertEqual(dbf.recno(record), i)
        self.assertEqual(table[i].name.strip(), namelist[i])
        self.assertEqual(record.name.strip(), namelist[i])
        self.assertEqual(table[i].paid, paidlist[i])
        self.assertEqual(record.paid, paidlist[i])
        self.assertEqual(table[i].qty, qtylist[i])
        self.assertEqual(record.qty, qtylist[i])
        self.assertEqual(table[i].orderdate, orderlist[i])
        self.assertEqual(record.orderdate, orderlist[i])
        self.assertEqual(table[i].desc, desclist[i])
        self.assertEqual(record.desc, desclist[i])
        i += 1
        self.assertEqual(i, len(table))
    def test_vfp_adding_records(self):
        "vfp table:  adding records"
        table = self.vfp_table
        table.open()
        namelist = []
        paidlist = []
        qtylist = []
        orderlist = []
        desclist = []
        masslist = []
        weightlist = []
        agelist = []
        meetlist = []
        misclist = []
        photolist = []
        pricelist = []
        for i in range(len(floats)):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            mass = floats[i] * floats[i] / 2.0
            weight = floats[i] * 3
            age = numbers[i]
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1, \
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            misc = (' '.join(words[i:i+50:3])).encode('ascii')
            photo = (' '.join(words[i:i+50:7])).encode('ascii')
            price = Decimal(round(floats[i] * 2.182737, 4))
            namelist.append(name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            masslist.append(mass)
            weightlist.append(weight)
            agelist.append(age)
            meetlist.append(meeting)
            misclist.append(misc)
            photolist.append(photo)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc, \
                    'mass':mass, 'weight':weight, 'age':age, 'meeting':meeting, 'misc':misc, 'photo':photo})
            record = table[-1]
            self.assertEqual(record.name.strip(), name)
            self.assertEqual(record.paid, paid)
            self.assertEqual(record.qty, round(qty, 5))
            self.assertEqual(record.orderdate, orderdate)
            self.assertEqual(record.desc.strip(), desc)
            self.assertEqual(record.mass, mass)
            self.assertEqual(record.weight, round(weight, 3))
            self.assertEqual(record.age, age)
            self.assertEqual(record.meeting, meeting)
            self.assertEqual(record.misc, misc)
            self.assertEqual(record.photo, photo)
        # plus a blank record
        namelist.append('')
        paidlist.append(Unknown)
        qtylist.append(None)
        orderlist.append(NullDate)
        desclist.append('')
        masslist.append(0.0)
        weightlist.append(None)
        agelist.append(0)
        meetlist.append(NullDateTime)
        misclist.append(''.encode('ascii'))
        photolist.append(''.encode('ascii'))
        pricelist.append(Decimal('0.0'))
        table.append()
        table.close()
        table = Table(table.filename, dbf_type='vfp')
        table.open()
        self.assertEqual(len(table), len(floats)+1)
        i = 0
        for record in table[:-1]:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name.strip(), namelist[i])
            self.assertEqual(record.name.strip(), namelist[i])
            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(table[i].desc.strip(), desclist[i])
            self.assertEqual(record.desc.strip(), desclist[i])
            self.assertEqual(record.mass, masslist[i])
            self.assertEqual(table[i].mass, masslist[i])
            self.assertEqual(record.weight, round(weightlist[i], 3))
            self.assertEqual(table[i].weight, round(weightlist[i], 3))
            self.assertEqual(record.age, agelist[i])
            self.assertEqual(table[i].age, agelist[i])
            self.assertEqual(record.meeting, meetlist[i])
            self.assertEqual(table[i].meeting, meetlist[i])
            self.assertEqual(record.misc, misclist[i])
            self.assertEqual(table[i].misc, misclist[i])
            self.assertEqual(record.photo, photolist[i])
            self.assertEqual(table[i].photo, photolist[i])
            i += 1
        record = table[-1]
        self.assertEqual(dbf.recno(record), i)
        self.assertEqual(table[i].name.strip(), namelist[i])
        self.assertEqual(record.name.strip(), namelist[i])
        self.assertEqual(table[i].paid is None, True)
        self.assertEqual(record.paid is None, True)
        self.assertEqual(table[i].qty, None)
        self.assertEqual(record.qty, None)
        self.assertEqual(table[i].orderdate, orderlist[i])
        self.assertEqual(record.orderdate, orderlist[i])
        self.assertEqual(table[i].desc, desclist[i])
        self.assertEqual(record.desc, desclist[i])
        self.assertEqual(record.mass, masslist[i])
        self.assertEqual(table[i].mass, masslist[i])
        self.assertEqual(record.weight, weightlist[i])
        self.assertEqual(table[i].weight, weightlist[i])
        self.assertEqual(record.age, agelist[i])
        self.assertEqual(table[i].age, agelist[i])
        self.assertEqual(record.meeting, meetlist[i])
        self.assertEqual(table[i].meeting, meetlist[i])
        self.assertEqual(record.misc, misclist[i])
        self.assertEqual(table[i].misc, misclist[i])
        self.assertEqual(record.photo, photolist[i])
        self.assertEqual(table[i].photo, photolist[i])
        i += 1

    def test_char_memo_return_type(self):
        "check character fields return type"
        table = Table(':memory:', 'text C(50); memo M', codepage='cp1252', dbf_type='vfp', on_disk=False)
        table.open()
        table.append(('another one bites the dust', "and another one's gone, and another one's gone..."))
        table.append()
        for record in table:
            self.assertTrue(type(record.text) is unicode)
            self.assertTrue(type(record.memo) is unicode)

        table = Table(':memory:', 'text C(50); memo M', codepage='cp1252', dbf_type='vfp',
            default_data_types=dict(C=Char, M=Char), on_disk=False)
        table.open()
        table.append(('another one bites the dust', "and another one's gone, and another one's gone..."))
        table.append()
        for record in table:
            self.assertTrue(type(record.text) is Char)
            self.assertTrue(type(record.memo) is Char)

        table = Table(':memory:', 'text C(50); memo M', codepage='cp1252', dbf_type='vfp',
            default_data_types=dict(C=(Char, NoneType), M=(Char, NoneType)), on_disk=False)
        table.open()
        table.append(('another one bites the dust', "and another one's gone, and another one's gone..."))
        table.append()
        record = table[0]
        self.assertTrue(type(record.text) is Char)
        self.assertTrue(type(record.memo) is Char)
        record = table[1]
        self.assertTrue(type(record.text) is NoneType)
        self.assertTrue(type(record.memo) is NoneType)
    def test_empty_is_none(self):
        "empty and None values"
        table = Table(':memory:', 'name C(20); born L; married D; appt T; wisdom M', dbf_type='vfp', on_disk=False)
        table.open()
        table.append()
        record = table[-1]
        self.assertTrue(record.born is None)
        self.assertTrue(record.married is None)
        self.assertTrue(record.appt is None)
        self.assertEqual(record.wisdom, '')
        appt = DateTime.now()
        dbf.write(
                record,
                born = True,
                married = Date(1992, 6, 27),
                appt = appt,
                wisdom = 'Choose Python',
                )
        self.assertTrue(record.born)
        self.assertEqual(record.married, Date(1992, 6, 27))
        self.assertEqual(record.appt, appt)
        self.assertEqual(record.wisdom, 'Choose Python')
        dbf.write(
                record,
                born = Unknown,
                married = NullDate,
                appt = NullDateTime,
                wisdom = '',
                )
        self.assertTrue(record.born is None)
        self.assertTrue(record.married is None)
        self.assertTrue(record.appt is None)
        self.assertEqual(record.wisdom, '')
    def test_custom_data_type(self):
        "custom data types"
        table = Table(
            filename=':memory:',
            field_specs='name C(20); born L; married D; appt T; wisdom M',
            field_data_types=dict(name=Char, born=Logical, married=Date, appt=DateTime, wisdom=Char,),
            dbf_type='vfp',
            on_disk=False,
            )
        table.open()
        table.append()
        record = table[-1]
        self.assertTrue(type(record.name) is Char, "record.name is %r, not Char" % type(record.name))
        self.assertTrue(type(record.born) is Logical, "record.born is %r, not Logical" % type(record.born))
        self.assertTrue(type(record.married) is Date, "record.married is %r, not Date" % type(record.married))
        self.assertTrue(type(record.appt) is DateTime, "record.appt is %r, not DateTime" % type(record.appt))
        self.assertTrue(type(record.wisdom) is Char, "record.wisdom is %r, not Char" % type(record.wisdom))
        self.assertEqual(record.name, ' ' * 20)
        self.assertTrue(record.born is Unknown, "record.born is %r, not Unknown" % record.born)
        self.assertTrue(record.married is NullDate, "record.married is %r, not NullDate" % record.married)
        self.assertEqual(record.married, None)
        self.assertTrue(record.appt is NullDateTime, "record.appt is %r, not NullDateTime" % record.appt)
        self.assertEqual(record.appt, None)
        appt = DateTime.now()
        dbf.write(
                record,
                name = 'Ethan               ',
                born = True,
                married = Date(1992, 6, 27),
                appt = appt,
                wisdom = 'Choose Python',
                )
        self.assertEqual(type(record.name), Char, "record.wisdom is %r, but should be Char" % record.wisdom)
        self.assertTrue(record.born is Truth)
        self.assertEqual(record.married, Date(1992, 6, 27))
        self.assertEqual(record.appt, appt)
        self.assertEqual(type(record.wisdom), Char, "record.wisdom is %r, but should be Char" % record.wisdom)
        self.assertEqual(record.wisdom, 'Choose Python')
        dbf.write(record, born=Falsth)
        self.assertEqual(record.born, False)
        dbf.write(record, born=None, married=None, appt=None, wisdom=None)
        self.assertTrue(record.born is Unknown)
        self.assertTrue(record.married is NullDate)
        self.assertTrue(record.appt is NullDateTime)
        self.assertTrue(type(record.wisdom) is Char, "record.wisdom is %r, but should be Char" % type(record.wisdom))
    def test_datatypes_param(self):
        "field_types with normal data type but None on empty"
        table = Table(
            filename=':memory:',
            field_specs='name C(20); born L; married D; wisdom M',
            field_data_types=dict(name=(str, NoneType), born=(bool, bool)),
            dbf_type='db3',
            on_disk=False,
            )
        table.open()
        table.append()
        record = table[-1]
        self.assertTrue(type(record.name) is type(None), "record.name is %r, not None" % type(record.name))
        self.assertTrue(type(record.born) is bool, "record.born is %r, not bool" % type(record.born))
        self.assertTrue(record.name is None)
        self.assertTrue(record.born is False, "record.born is %r, not False" % record.born)
        dbf.write(record, name='Ethan               ', born=True)
        self.assertEqual(type(record.name), str, "record.name is %r, but should be Char" % record.wisdom)
        self.assertTrue(record.born is True)
        dbf.write(record, born=False)
        self.assertEqual(record.born, False)
        dbf.write(
            record,
            name = None,
            born = None,
            )
        self.assertTrue(record.name is None)
        self.assertTrue(record.born is False)
    def test_null_type(self):
        "NullType"
        from pprint import pprint
        table = Table(
            filename=':memory:',
            field_specs='name C(20) null; born L null; married D null; appt T null; wisdom M null',
            default_data_types=dict(
                    C=(Char, NoneType, NullType),
                    L=(Logical, NoneType, NullType),
                    D=(Date, NoneType, NullType),
                    T=(DateTime, NoneType, NullType),
                    M=(Char, NoneType, NullType),
                    ),
            dbf_type='vfp',
            on_disk=False,
            )
        table.open()
        table.append()
        record = table[-1]
        self.assertEqual(record.name, None)
        self.assertEqual(record.born, None)
        self.assertEqual(record.married, None)
        self.assertEqual(record.appt, None)
        self.assertEqual(record.wisdom, None)
        appt = datetime.datetime(2012, 12, 15, 9, 37, 11)
        dbf.write(
                record,
                name = 'Ethan               ',
                born = True,
                married = datetime.date(2001, 6, 27),
                appt = appt,
                wisdom = 'timing is everything',
                )
        self.assertEqual(record.name, 'Ethan')
        self.assertEqual(type(record.name), Char)
        self.assertTrue(record.born)
        self.assertTrue(record.born is Truth)
        self.assertEqual(record.married, datetime.date(2001, 6, 27))
        self.assertEqual(type(record.married), Date)
        self.assertEqual(record.appt, datetime.datetime(2012, 12, 15, 9, 37, 11))
        self.assertEqual(type(record.appt), DateTime)
        self.assertEqual(record.wisdom, 'timing is everything')
        self.assertEqual(type(record.wisdom), Char)
        dbf.write(record, name=Null, born=Null, married=Null, appt=Null, wisdom=Null)
        self.assertTrue(record.name is Null)
        self.assertTrue(record.born is Null)
        self.assertTrue(record.born is Null)
        self.assertTrue(record.married is Null)
        self.assertTrue(record.appt is Null)
        self.assertTrue(record.wisdom is Null)
        dbf.write(
                record,
                name = None,
                born = None,
                married = None,
                appt = None,
                wisdom = None,
                )
        self.assertTrue(record.name is None)
        self.assertTrue(record.born is None)
        self.assertTrue(record.married is None)
        self.assertTrue(record.appt is None)
        self.assertTrue(record.wisdom is None)

    def test_nonascii_text_cptrans(self):
        "check non-ascii text to unicode"
        table = Table(':memory:', 'data C(50); memo M', codepage='cp437', dbf_type='vfp', on_disk=False)
        table.open()
        decoder = codecs.getdecoder('cp437')
        if py_ver < (3, 0):
            high_ascii = decoder(''.join(chr(c) for c in range(128, 128+50)))[0]
        else:
            high_ascii = bytes(range(128, 128+50)).decode('cp437')
        table.append(dict(data=high_ascii, memo=high_ascii))
        self.assertEqual(table[0].data, high_ascii)
        self.assertEqual(table[0].memo, high_ascii)
        table.close()

    def test_nonascii_text_no_cptrans(self):
        "check non-ascii text to bytes"
        table = Table(':memory:', 'bindata C(50) binary; binmemo M binary', codepage='cp1252', dbf_type='vfp', on_disk=False)
        table.open()
        if py_ver < (3, 0):
            high_ascii = ''.join(chr(c) for c in range(128, 128+50))
        else:
            high_ascii = bytes(range(128, 128+50))
        table.append(dict(bindata=high_ascii, binmemo=high_ascii))
        self.assertEqual(table[0].bindata, high_ascii)
        self.assertEqual(table[0].binmemo, high_ascii)
        table.close()

    # def test_backup_of_different_codepage(self):
    #     "check backups work when different codepage specified"
    #     table = Table(':memory:', 'string M', dbf_type='db3', on_disk=False, codepage='utf8')
    #     table.open()
    #     weird = ''.join(chr(i) for i in range(256))
    #     if py_ver < (3, 0):
    #         weird = weird.decode('latin-1')
    #     table.append((weird,))
    #     table.codepage = CodePage('cp437')
    #     self.assertRaises(UnicodeDecodeError, table.__getitem__, 0)

    def test_add_null_field(self):
        "adding a null field to an existing table"
        table = Table(
            self.vfp_table.filename,
            'name C(50); age N(3,0)',
            dbf_type='vfp',
            )
        table.open()
        def _50(text):
            return text + ' ' * (50 - len(text))
        data = ( (_50('Ethan'), 29), (_50('Joseph'), 33), (_50('Michael'), 54), )
        for datum in data:
            table.append(datum)
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum, tuple(recordnum))
        table.add_fields('fired D null')
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum, tuple(recordnum)[:2])
        data += ((_50('Daniel'), 44, Null), )
        table.append(('Daniel', 44, Null))
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
        self.assertTrue(datum[2] is recordnum[2])
        table.close()
        table = Table(table.filename)
        table.open()
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[0:2], tuple(recordnum)[:2])
        self.assertTrue(datum[2] is recordnum[2])
        table.close()

    def test_remove_null_field(self):
        "removing null fields from an existing table"
        table = Table(
            self.vfp_table.filename,
            'name C(50); age N(3,0); fired D null',
            dbf_type='vfp',
            )
        table.open()
        def _50(text):
            return text + ' ' * (50 - len(text))
        data = ( (_50('Ethan'), 29, Null), (_50('Joseph'), 33, Null), (_50('Michael'), 54, Date(2010, 5, 3)))
        for datum in data:
            table.append(datum)
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
            self.assertTrue(datum[2] is recordnum[2] or datum[2] == recordnum[2])
        table.delete_fields('fired')
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum))
        data += ((_50('Daniel'), 44), )
        table.append(('Daniel', 44))
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum))
        table.close()
        table = Table(table.filename)
        table.open()
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum))
        table.close()

    def test_change_null_field(self):
        "making an existing field nullable (or not)"
        table = self.vfp_table
        table.open()
        namelist = []
        paidlist = []
        qtylist = []
        orderlist = []
        desclist = []
        for i in range(10):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            namelist.append(name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc})
        # plus a blank record
        namelist.append('')
        paidlist.append(None)
        qtylist.append(None)
        orderlist.append(None)
        desclist.append('')
        table.append()
        for field in table.field_names:
            self.assertEqual(table.nullable_field(field), False)
        self.assertRaises(FieldMissingError, table.allow_nulls, 'not_here')
        table.allow_nulls('name, qty')
        for field in table.field_names:
            if field in 'name qty'.split():
                self.assertEqual(table.nullable_field(field), True)
            else:
                self.assertEqual(table.nullable_field(field), False)
        dbf.write(table[0], name=Null, qty=Null)
        self.assertTrue(table[0].name is Null)
        self.assertTrue(table[0].qty is Null)
        self.assertRaises(FieldMissingError, table.disallow_nulls, 'not_here')
        table.disallow_nulls('qty')
        for field in table.field_names:
            if field in 'name'.split():
                self.assertEqual(table.nullable_field(field), True)
            else:
                self.assertEqual(table.nullable_field(field), False)
        table.disallow_nulls('name')
        for field in table.field_names:
            self.assertEqual(table.nullable_field(field), False)
        table.close()

    def test_add_field_to_null(self):
        "adding a normal field to a table with null fields"
        table = Table(
            self.vfp_table.filename,
            'name C(50); age N(3,0); fired D null',
            dbf_type='vfp',
            )
        table.open()
        def _50(text):
            return text + ' ' * (50 - len(text))
        data = ( (_50('Ethan'), 29, Null), (_50('Joseph'), 33, Null), (_50('Michael'), 54, Date(2010, 7, 4)), )
        for datum in data:
            table.append(datum)
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
            self.assertTrue(datum[2] is recordnum[2] or datum[2] == recordnum[2])
        table.add_fields('tenure N(3,0)')
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
            self.assertTrue(datum[2] is recordnum[2] or datum[2] == recordnum[2])
        data += ((_50('Daniel'), 44, Date(2005, 1, 31), 15 ), )
        table.append(('Daniel', 44, Date(2005, 1, 31), 15))
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
            self.assertTrue(datum[2] is recordnum[2] or datum[2] == recordnum[2])
        self.assertEqual(datum[3], recordnum[3])
        table.close()
        table = Table(table.filename)
        table.open()
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
            self.assertTrue(datum[2] is recordnum[2] or datum[2] == recordnum[2])
        self.assertEqual(datum[3], recordnum[3])
        table.close()

    def test_remove_field_from_null(self):
        "removing a normal field from a table with null fields"
        mfd = self.vfp_table._meta.mfd
        mfd = None
        table = Table(
            self.vfp_table.filename,
            'name C(50); age N(3,0); fired D null',
            dbf_type='vfp',
            )
        table.open()
        def _50(text):
            return text + ' ' * (50 - len(text))
        data = ( (_50('Ethan'), 29, Null), (_50('Joseph'), 33, Null), (_50('Michael'), 54, Date(2010, 7, 4)), )
        for datum in data:
            table.append(datum)
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[:2], tuple(recordnum)[:2])
            self.assertTrue(datum[2] is recordnum[2] or datum[2] == recordnum[2])
        table.delete_fields('age')
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[0], recordnum[0])
            self.assertTrue(datum[-1] is recordnum[1] or datum[-1] == recordnum[1])
        data += ((_50('Daniel'), Date(2001, 11, 13)), )
        table.append(('Daniel', Date(2001, 11, 13)))
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[0], recordnum[0])
            self.assertTrue(datum[-1] is recordnum[1] or datum[-1] == recordnum[1])
        table.close()
        table = Table(table.filename)
        table.open()
        for datum, recordnum in zip(data, table):
            self.assertEqual(datum[0], recordnum[0])
            self.assertTrue(datum[-1] is recordnum[-1] or datum[-1] == recordnum[-1], "name = %s; datum[-1] = %r;  recordnum[-1] = %r" % (datum[0], datum[-1], recordnum[-1]))
        table.close()
    def test_flux_internal(self):
        "commit and rollback of flux record (implementation detail)"
        table = self.dbf_table
        table.open()
        table.append(('dbf master', True, 77, Date(2012, 5, 20), "guru of some things dbf-y"))
        record = table[-1]
        old_data = dbf.scatter(record)
        record._start_flux()
        record.name = 'novice'
        record.paid = False
        record.qty = 69
        record.orderdate = Date(2011, 1, 1)
        record.desc = 'master of all he surveys'
        self.assertEqual(
                dbf.scatter(record),
                dict(
                    name=unicode('novice                   '),
                    paid=False,
                    qty=69,
                    orderdate=datetime.date(2011, 1, 1),
                    desc='master of all he surveys',
                    ))
        record._rollback_flux()
        self.assertEqual(old_data, dbf.scatter(record))
        record._start_flux()
        record.name = 'novice'
        record.paid = False
        record.qty = 69
        record.orderdate = Date(2011, 1, 1)
        record._commit_flux()
        self.assertEqual(
                dbf.scatter(record),
                dict(
                    name=unicode('novice                   '),
                    paid=False,
                    qty=69,
                    orderdate=datetime.date(2011, 1, 1),
                    desc='guru of some things dbf-y',
                    ))
        self.assertNotEqual(old_data, dbf.scatter(record))

class TestDbfRecordTemplates(unittest.TestCase):
    "Testing records"
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        self.dbf_table = Table(
                os.path.join(self.tempdir, 'dbf_table'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M',
                dbf_type='db3',
                )
        self.vfp_table = Table(
                os.path.join(self.tempdir, 'vfp_table'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M; mass B;' +
                ' weight F(18,3); age I; meeting T; misc G; photo P; price Y',
                dbf_type='vfp',
                )

    def tearDown(self):
        self.dbf_table.close()
        self.vfp_table.close()
        shutil.rmtree(self.tempdir, True)

    def test_dbf_storage(self):
        table = self.dbf_table
        table.open()
        record = table.create_template()
        record.name = 'Stoneleaf'
        record.paid = True
        record.qty = 1
        record.orderdate = Date.today()
        record.desc = 'some Python dude'
        table.append(record)

    def test_vfp_storage(self):
        table = self.vfp_table
        table.open()
        record = table.create_template()
        record.name = 'Stoneleaf'
        record.paid = True
        record.qty = 1
        record.orderdate = Date.today()
        record.desc = 'some Python dude'
        record.mass = 251.9287
        record.weight = 971204.39
        record.age = 29
        record.meeting = DateTime.now()
        record.misc = MISC
        record.photo = PHOTO
        record.price = 19.99
        table.append(record)

class TestDbfFunctions(unittest.TestCase):
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        "create a dbf and vfp table"
        self.dbf_table = table = Table(
            os.path.join(self.tempdir, 'temptable'),
            'name C(25); paid L; qty N(11,5); orderdate D; desc M', dbf_type='db3'
            )
        table.open()
        namelist = self.dbf_namelist = []
        paidlist = self.dbf_paidlist = []
        qtylist = self.dbf_qtylist = []
        orderlist = self.dbf_orderlist = []
        desclist = self.dbf_desclist = []
        for i in range(len(floats)):
            name = '%-25s' % words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            namelist.append(name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc})
        table.close()

        self.vfp_table = table = Table(
                os.path.join(self.tempdir, 'tempvfp'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M; mass B;'
                ' weight F(18,3); age I; meeting T; misc G; photo P',
                dbf_type='vfp',
                )
        table.open()
        namelist = self.vfp_namelist = []
        paidlist = self.vfp_paidlist = []
        qtylist = self.vfp_qtylist = []
        orderlist = self.vfp_orderlist = []
        desclist = self.vfp_desclist = []
        masslist = self.vfp_masslist = []
        weightlist = self.vfp_weightlist = []
        agelist = self.vfp_agelist = []
        meetlist = self.vfp_meetlist = []
        misclist = self.vfp_misclist = []
        photolist = self.vfp_photolist = []
        for i in range(len(floats)):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            mass = floats[i] * floats[i] / 2.0
            weight = round(floats[i] * 3, 3)
            age = numbers[i]
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1, \
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            misc = ' '.join(words[i:i+50:3]).encode('latin1')
            photo = ' '.join(words[i:i+50:7]).encode('latin1')
            namelist.append('%-25s' % name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            masslist.append(mass)
            weightlist.append(weight)
            agelist.append(age)
            meetlist.append(meeting)
            misclist.append(misc)
            photolist.append(photo)
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1,
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc,
                    'mass':mass, 'weight':weight, 'age':age, 'meeting':meeting, 'misc':misc, 'photo':photo})
        table.close()
    def tearDown(self):
        self.dbf_table.close()
        self.vfp_table.close()
        shutil.rmtree(self.tempdir, True)

    def test_add_fields_to_dbf_table(self):
        "dbf table:  adding and deleting fields"
        table = self.dbf_table
        table.open()
        dbf._debug = True
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        table.delete_fields('name')
        table.close()
        table = Table(table.filename, dbf_type='db3')
        table.open()
        for field in table.field_names:
            self.assertEqual(1, table.field_names.count(field))
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)

            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(table[i].desc, desclist[i])
            self.assertEqual(record.desc, desclist[i])
            i += 1
        first, middle, last = table[0], table[len(table)//2], table[-1]
        table.delete_fields('paid, orderdate')
        for field in table.field_names:
            self.assertEqual(1, table.field_names.count(field))
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].desc, desclist[i])
            self.assertEqual(record.desc, desclist[i])
            i += 1
        self.assertEqual(i, len(table))
        self.assertTrue('paid' not in dbf.field_names(first))
        self.assertTrue('orderdate' not in dbf.field_names(first))
        table.add_fields('name C(25); paid L; orderdate D')
        for field in table.field_names:
            self.assertEqual(1, table.field_names.count(field))
        self.assertEqual(i, len(table))
        i = 0
        for i, record in enumerate(table):
            self.assertEqual(record.name, ' ' * 25)
            self.assertEqual(record.paid, None)
            self.assertEqual(record.orderdate, None)
            self.assertEqual(record.desc, desclist[i])
            i += 1
        self.assertEqual(i, len(table))
        i = 0
        for record in table:
            data = dict()
            data['name'] = namelist[dbf.recno(record)]
            data['paid'] = paidlist[dbf.recno(record)]
            data['orderdate'] = orderlist[dbf.recno(record)]
            dbf.gather(record, data)
            i += 1
        self.assertEqual(i, len(table))
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name, namelist[i])
            self.assertEqual(record.name, namelist[i])
            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(table[i].desc, desclist[i])
            self.assertEqual(record.desc, desclist[i])
            i += 1
        table.close()
    def test_add_fields_to_vfp_table(self):
        "vfp table:  adding and deleting fields"
        table = self.vfp_table
        table.open()
        namelist = self.vfp_namelist
        paidlist = self.vfp_paidlist
        qtylist = self.vfp_qtylist
        orderlist = self.vfp_orderlist
        desclist = self.vfp_desclist
        masslist = self.vfp_masslist
        weightlist = self.vfp_weightlist
        agelist = self.vfp_agelist
        meetlist = self.vfp_meetlist
        misclist = self.vfp_misclist
        photolist = self.vfp_photolist
        self.assertEqual(len(table), len(floats))
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name, namelist[i])
            self.assertEqual(record.name, namelist[i])
            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(table[i].desc, desclist[i])
            self.assertEqual(record.desc, desclist[i])
            self.assertEqual(record.mass, masslist[i])
            self.assertEqual(table[i].mass, masslist[i])
            self.assertEqual(record.weight, weightlist[i])
            self.assertEqual(table[i].weight, weightlist[i])
            self.assertEqual(record.age, agelist[i])
            self.assertEqual(table[i].age, agelist[i])
            self.assertEqual(record.meeting, meetlist[i])
            self.assertEqual(table[i].meeting, meetlist[i])
            self.assertEqual(record.misc, misclist[i])
            self.assertEqual(table[i].misc, misclist[i])
            self.assertEqual(record.photo, photolist[i])
            self.assertEqual(table[i].photo, photolist[i])
            i += 1
        table.delete_fields('desc')
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name, namelist[i])
            self.assertEqual(record.name, namelist[i])
            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(record.weight, weightlist[i])
            self.assertEqual(table[i].weight, weightlist[i])
            self.assertEqual(record.age, agelist[i])
            self.assertEqual(table[i].age, agelist[i])
            self.assertEqual(record.meeting, meetlist[i])
            self.assertEqual(table[i].meeting, meetlist[i])
            self.assertEqual(record.misc, misclist[i])
            self.assertEqual(table[i].misc, misclist[i])
            self.assertEqual(record.photo, photolist[i])
            self.assertEqual(table[i].photo, photolist[i])
            self.assertEqual(record.mass, masslist[i])
            self.assertEqual(table[i].mass, masslist[i])
            i += 1
        table.delete_fields('paid, mass')
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name, namelist[i])
            self.assertEqual(record.name, namelist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(record.weight, weightlist[i])
            self.assertEqual(table[i].weight, weightlist[i])
            self.assertEqual(record.age, agelist[i])
            self.assertEqual(table[i].age, agelist[i])
            self.assertEqual(record.meeting, meetlist[i])
            self.assertEqual(table[i].meeting, meetlist[i])
            self.assertEqual(record.misc, misclist[i])
            self.assertEqual(table[i].misc, misclist[i])
            self.assertEqual(record.photo, photolist[i])
            self.assertEqual(table[i].photo, photolist[i])
            i += 1
        table.add_fields('desc M; paid L; mass B')
        i = 0
        for record in table:
            self.assertEqual(record.desc, unicode(''))
            self.assertEqual(record.paid is None, True)
            self.assertEqual(record.mass, 0.0)
            i += 1
        self.assertEqual(i, len(table))
        i = 0
        for record in Process(table):
            record.desc = desclist[dbf.recno(record)]
            record.paid = paidlist[dbf.recno(record)]
            record.mass = masslist[dbf.recno(record)]
            i += 1
        self.assertEqual(i, len(table))
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            self.assertEqual(table[i].name, namelist[i])
            self.assertEqual(record.name, namelist[i])
            self.assertEqual(table[i].paid, paidlist[i])
            self.assertEqual(record.paid, paidlist[i])
            self.assertEqual(abs(table[i].qty - qtylist[i]) < .00001, True)
            self.assertEqual(abs(record.qty - qtylist[i]) < .00001, True)
            self.assertEqual(table[i].orderdate, orderlist[i])
            self.assertEqual(record.orderdate, orderlist[i])
            self.assertEqual(table[i].desc, desclist[i])
            self.assertEqual(record.desc, desclist[i])
            self.assertEqual(record.mass, masslist[i])
            self.assertEqual(table[i].mass, masslist[i])
            self.assertEqual(record.weight, weightlist[i])
            self.assertEqual(table[i].weight, weightlist[i])
            self.assertEqual(record.age, agelist[i])
            self.assertEqual(table[i].age, agelist[i])
            self.assertEqual(record.meeting, meetlist[i])
            self.assertEqual(table[i].meeting, meetlist[i])
            self.assertEqual(record.misc, misclist[i])
            self.assertEqual(table[i].misc, misclist[i])
            self.assertEqual(record.photo, photolist[i])
            self.assertEqual(table[i].photo, photolist[i])
            i += 1
        table.close()
    def test_len_contains_iter(self):
        "basic function tests - len, contains & iterators"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        for field in table.field_names:
            self.assertEqual(1, table.field_names.count(field))
        length = sum([1 for rec in table])
        self.assertEqual(length, len(table))
        i = 0
        for record in table:
            self.assertEqual(record, table[i])
            self.assertTrue(record in table)
            self.assertTrue(tuple(record) in table)
            self.assertTrue(scatter(record) in table)
            self.assertTrue(create_template(record) in table)
            i += 1
        self.assertEqual(i, len(table))
        table.close()

    def test_undelete(self):
        "delete, undelete"
        table = Table(':memory:', 'name C(10)', dbf_type='db3', on_disk=False)
        table.open()
        table.append()
        self.assertEqual(table.next_record, table[0])
        table = Table(':memory:', 'name C(10)', dbf_type='db3', on_disk=False)
        table.open()
        table.append(multiple=10)
        self.assertEqual(table.next_record, table[0])
        table = self.dbf_table              # Table(os.path.join(self.tempdir, 'temptable'), dbf_type='db3')
        table.open()
        total = len(table)
        table.bottom()
        self.assertEqual(dbf.recno(table.current_record), total)
        table.top()
        self.assertEqual(dbf.recno(table.current_record), -1)
        table.goto(27)
        self.assertEqual(dbf.recno(table.current_record), 27)
        table.goto(total-1)
        self.assertEqual(dbf.recno(table.current_record), total-1)
        table.goto(0)
        self.assertEqual(dbf.recno(table.current_record), 0)
        self.assertRaises(IndexError, table.goto, total)
        self.assertRaises(IndexError, table.goto, -len(table)-1)
        table.top()
        self.assertRaises(dbf.Bof, table.skip, -1)
        table.bottom()
        self.assertRaises(Eof, table.skip)
        for record in table:
            dbf.delete(record)
        active_records = table.create_index(active)
        active_records.top()
        self.assertRaises(Eof, active_records.skip)
        dbf._debug = True
        active_records.bottom()
        self.assertRaises(Bof, active_records.skip, -1)
        for record in table:
            dbf.undelete(record)

        # delete every third record
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            if i % 3 == 0:
                dbf.delete(record)
            i += 1
        i = 0
        # and verify
        for record in table:
            self.assertEqual(dbf.is_deleted(record), i%3==0)
            self.assertEqual(dbf.is_deleted(table[i]), i%3==0)
            i += 1

        # check that deletes were saved to disk..
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable'), dbf_type='db3')
        table.open()
        active_records = table.create_index(active)
        i = 0
        for record in table:
            self.assertEqual(dbf.is_deleted(record), i%3==0)
            self.assertEqual(dbf.is_deleted(table[i]), i%3==0)
            i += 1

        # verify record numbers
        i = 0
        for record in table:
            self.assertEqual(dbf.recno(record), i)
            i += 1

        # verify that deleted records are skipped
        i = 0
        for record in active_records:
            self.assertNotEqual(dbf.recno(record)%3, 0)
        active_records.goto(1)
        active_records.skip()
        self.assertEqual(dbf.recno(active_records.current_record), 4)
        active_records.skip(-1)
        self.assertEqual(dbf.recno(active_records.current_record), 2)

        # verify that deleted records are skipped in slices
        list_of_records = active_records[3:6]
        self.assertEqual(len(list_of_records), 3)
        self.assertEqual(dbf.recno(list_of_records[0]), 5)
        self.assertEqual(dbf.recno(list_of_records[1]), 7)
        self.assertEqual(dbf.recno(list_of_records[2]), 8)

        # verify behavior when all records are deleted
        for record in table:
            dbf.delete(record)
        active_records.bottom()
        self.assertRaises(Eof, active_records.skip)
        self.assertEqual(active_records.eof, True)
        active_records.top()
        self.assertRaises(Bof, active_records.skip, -1)
        self.assertEqual(active_records.bof, True)

        # verify deleted records are seen with active record index
        deleted_records = table.create_index(inactive)
        i = 0
        for record in deleted_records:
            self.assertEqual(dbf.recno(record), i)
            i += 1

        # verify undelete using table[index]
        for record in table:
            dbf.delete(record)
            self.assertTrue(dbf.is_deleted(record))
        for i, record in enumerate(table):
            dbf.undelete(table[i])
            self.assertEqual(dbf.is_deleted(record), False)
            self.assertEqual(dbf.is_deleted(table[i]), False)
            self.assertFalse(record in deleted_records)

        # verify all records have been undeleted (recalled)
        self.assertEqual(len(active_records), len(table))
        self.assertEqual(len(deleted_records), 0)
        table.close()

    def test_finding_ordering_searching(self):
        "finding, ordering, searching"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist

        # find (brute force)
        unordered = []
        for record in table:
            unordered.append(record.name)
        for word in unordered:                                  # returns records
            # records = table.query("select * where name == %r" % word)
            # self.assertEqual(len(records), unordered.count(word))
            records = [rec for rec in table if rec.name == word]
            self.assertEqual(len(records), unordered.count(word))

        # ordering by one field
        ordered = unordered[:]
        ordered.sort()
        name_index = table.create_index(lambda rec: rec.name)
        self.assertEqual(list(name_index[::-1]), list(reversed(name_index)))
        i = 0
        for record in name_index:
            self.assertEqual(record.name, ordered[i])
            i += 1

        # search (binary)
        for word in unordered:
            records = name_index.search(match=word)
            self.assertEqual(len(records), unordered.count(word), "num records: %d\nnum words: %d\nfailure with %r" % (len(records), unordered.count(word), word))
            # records = table.query("select * where name == %r" % word)
            # self.assertEqual(len(records), unordered.count(word))
            # records = dbf.pql(table, "select * where name == %r" % word)
            # self.assertEqual(len(records), unordered.count(word))

        # ordering by two fields
        ordered = unordered[:]
        ordered.sort()
        nd_index = table.create_index(lambda rec: (rec.name, rec.desc))
        self.assertEqual(list(nd_index[::-1]), list(reversed(nd_index)))
        i = 0
        for record in nd_index:
            self.assertEqual(record.name, ordered[i])
            i += 1

        # search (binary)
        for word in unordered:
            records = nd_index.search(match=(word, ), partial=True)
            ucount = sum([1 for wrd in unordered if wrd.startswith(word)])
            self.assertEqual(len(records), ucount)

        for record in table[::2]:
            dbf.write(record, qty=-record.qty)
        unordered = []
        for record in table:
            unordered.append(record.qty)
        ordered = unordered[:]
        ordered.sort()
        qty_index = table.create_index(lambda rec: rec.qty)
        self.assertEqual(list(qty_index[::-1]), list(reversed(qty_index)))
        i = 0
        for record in qty_index:
            self.assertEqual(record.qty, ordered[i])
            i += 1
        for number in unordered:
            records = qty_index.search(match=(number, ))
            self.assertEqual(len(records), unordered.count(number))

        table.close()
    def test_scatter_gather_new(self):
        "scattering and gathering fields, and new()"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        table2 = table.new(os.path.join(self.tempdir, 'temptable2'))
        table2.open()
        for record in table:
            table2.append()
            newrecord = table2[-1]
            testdict = dbf.scatter(record)
            for key in field_names(testdict):
                self.assertEqual(testdict[key], record[key])
            dbf.gather(newrecord, dbf.scatter(record))
            for field in dbf.field_names(record):
                self.assertEqual(newrecord[field], record[field])
        table2.close()
        table2 = None
        table2 = Table(os.path.join(self.tempdir, 'temptable2'), dbf_type='db3')
        table2.open()
        for i in range(len(table)):
            temp1 = dbf.scatter(table[i])
            temp2 = dbf.scatter(table2[i])
            for key in field_names(temp1):
                self.assertEqual(temp1[key], temp2[key])
            for key in field_names(temp2):
                self.assertEqual(temp1[key], temp2[key])
        table2.close()
        table3 = table.new(':memory:', on_disk=False)
        table3.open()
        for record in table:
            table3.append(record)
        table4 = self.vfp_table
        table4.open()
        table5 = table4.new(':memory:', on_disk=False)
        table5.open()
        for record in table4:
            table5.append(record)
        table.close()
        table3.close()
        table4.close()
        table5.close()
    def test_rename_contains_has_key(self):
        "renaming fields, __contains__, has_key"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        for field in table.field_names:
            oldfield = field
            table.rename_field(oldfield, 'newfield')
            self.assertEqual(oldfield in table.field_names, False)
            self.assertEqual('newfield' in table.field_names, True)
            table.close()
            table = Table(os.path.join(self.tempdir, 'temptable'), dbf_type='db3')
            table.open()
            self.assertEqual(oldfield in table.field_names, False)
            self.assertEqual('newfield' in table.field_names, True)
            table.rename_field('newfield', oldfield)
            self.assertEqual(oldfield in table.field_names, True)
            self.assertEqual('newfield' in table.field_names, False)
        table.close()

    def test_dbf_record_kamikaze(self):
        "kamikaze"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        table2 = table.new(os.path.join(self.tempdir, 'temptable2'))
        table2.open()
        for record in table:
            table2.append(record)
            newrecord = table2[-1]
            for key in table.field_names:
                if key not in table.memo_types:
                    self.assertEqual(newrecord[key], record[key])
            for field in dbf.field_names(newrecord):
                if key not in table2.memo_types:
                    self.assertEqual(newrecord[field], record[field])
        table2.close()
        table2 = Table(os.path.join(self.tempdir, 'temptable2'), dbf_type='db3')
        table2.open()
        for i in range(len(table)):
            dict1 = dbf.scatter(table[i], as_type=dict)
            dict2 = dbf.scatter(table2[i], as_type=dict)
            for key in dict1.keys():
                if key not in table.memo_types:
                    self.assertEqual(dict1[key], dict2[key])
            for key in dict2.keys():
                if key not in table2.memo_types:
                    self.assertEqual(dict1[key], dict2[key])
        for i in range(len(table)):
            template1 = dbf.scatter(table[i])
            template2 = dbf.scatter(table2[i])
            for key in dbf.field_names(template1):
                if key not in table.memo_types:
                    self.assertEqual(template1[key], template2[key])
            for key in dbf.field_names(template2):
                if key not in table2.memo_types:
                    self.assertEqual(template1[key], template2[key])
        table.close()
        table2.close()

    def test_multiple_append(self):
        "multiple append"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        table2 = table.new(os.path.join(self.tempdir, 'temptable2'))
        table2.open()
        record = table.next_record
        table2.append(dbf.scatter(record), multiple=100)
        for samerecord in table2:
            for field in dbf.field_names(record):
                self.assertEqual(record[field], samerecord[field])
        table2.close()
        table2 = Table(os.path.join(self.tempdir, 'temptable2'), dbf_type='db3')
        table2.open()
        for samerecord in table2:
            for field in dbf.field_names(record):
                self.assertEqual(record[field], samerecord[field])
        table2.close()
        table3 = table.new(os.path.join(self.tempdir, 'temptable3'))
        table3.open()
        record = table.next_record
        table3.append(record, multiple=100)
        for samerecord in table3:
            for field in dbf.field_names(record):
                self.assertEqual(record[field], samerecord[field])
        table3.close()
        table3 = Table(os.path.join(self.tempdir, 'temptable3'), dbf_type='db3')
        table3.open()
        for samerecord in table3:
            for field in dbf.field_names(record):
                self.assertEqual(record[field], samerecord[field])
        table3.close()
        table.close()
    def test_slices(self):
        "slices"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        slice1 = [table[0], table[1], table[2]]
        self.assertEqual(slice1, list(table[:3]))
        slice2 = [table[-3], table[-2], table[-1]]
        self.assertEqual(slice2, list(table[-3:]))
        slice3 = [record for record in table]
        self.assertEqual(slice3, list(table[:]))
        slice4 = [table[9]]
        self.assertEqual(slice4, list(table[9:10]))
        slice5 = [table[15], table[16], table[17], table[18]]
        self.assertEqual(slice5, list(table[15:19]))
        slice6 = [table[0], table[2], table[4], table[6], table[8]]
        self.assertEqual(slice6, list(table[:9:2]))
        slice7 = [table[-1], table[-2], table[-3]]
        self.assertEqual(slice7, list(table[-1:-4:-1]))
        table.close()
    def test_record_reset(self):
        "reset record"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        for record in table:
            dbf.reset(record)
            dbf.write(record)
        self.assertEqual(table[0].name, table[1].name)
        dbf.write(table[0], name='Python rocks!')
        self.assertNotEqual(table[0].name, table[1].name)
        table.close()
    def test_adding_memos(self):
        "adding memos to existing records"
        table = Table(':memory:', 'name C(50); age N(3,0)', dbf_type='db3', on_disk=False)
        table.open()
        table.append(('user', 0))
        table.add_fields('motto M')
        dbf.write(table[0], motto='Are we there yet??')
        self.assertEqual(table[0].motto, 'Are we there yet??')
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable4'), 'name C(50); age N(3,0)', dbf_type='db3')
        table.open()
        table.append(('user', 0))
        table.close()
        table.open()
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable4'), dbf_type='db3')
        table.open()
        table.add_fields('motto M')
        dbf.write(table[0], motto='Are we there yet??')
        self.assertEqual(table[0].motto, 'Are we there yet??')
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable4'), dbf_type='db3')
        table.open()
        self.assertEqual(table[0].motto, 'Are we there yet??')
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable4'), 'name C(50); age N(3,0)', dbf_type='vfp')
        table.open()
        table.append(('user', 0))
        table.close()
        table.open()
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable4'), dbf_type='vfp')
        table.open()
        table.add_fields('motto M')
        dbf.write(table[0], motto='Are we there yet??')
        self.assertEqual(table[0].motto, 'Are we there yet??')
        table.close()
        table = Table(os.path.join(self.tempdir, 'temptable4'), dbf_type='vfp')
        table.open()
        self.assertEqual(table[0].motto, 'Are we there yet??')
        table.close()
    def test_from_csv(self):
        "from_csv"
        table = self.dbf_table
        table.open()
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        dbf.export(table, table.filename, header=False)
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'))
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]), csvtable[i][j])
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), to_disk=True, filename=os.path.join(self.tempdir, 'temptable5'))
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]).strip(), csvtable[i][j].strip())
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), field_names=['field1','field2'])
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]), csvtable[i][j])
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), field_names=['field1','field2'], to_disk=True, filename=os.path.join(self.tempdir, 'temptable5'))
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]).strip(), csvtable[i][j].strip())
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), extra_fields=['count N(5,0)','id C(10)'])
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]), csvtable[i][j])
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), extra_fields=['count N(5,0)','id C(10)'], to_disk=True, filename=os.path.join(self.tempdir, 'temptable5'))
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]).strip(), csvtable[i][j].strip())
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), field_names=['name','qty','paid','desc'], extra_fields='test1 C(15);test2 L'.split(';'))
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]), csvtable[i][j])
        csvtable.close()
        csvtable = dbf.from_csv(os.path.join(self.tempdir, 'temptable.csv'), field_names=['name','qty','paid','desc'], extra_fields='test1 C(15);test2 L'.split(';'), to_disk=True, filename=os.path.join(self.tempdir, 'temptable5'))
        csvtable.open()
        for i in index(table):
            for j in index(table.field_names):
                self.assertEqual(str(table[i][j]).strip(), csvtable[i][j].strip())

    def test_resize(self):
        "resize"
        table = self.dbf_table
        table.open()
        test_record = dbf.scatter(table[5])
        namelist = self.dbf_namelist
        paidlist = self.dbf_paidlist
        qtylist = self.dbf_qtylist
        orderlist = self.dbf_orderlist
        desclist = self.dbf_desclist
        test_record = dbf.scatter(table[5])
        table.resize_field('name', 40)
        new_record = dbf.scatter(table[5])
        self.assertEqual(test_record['orderdate'], new_record['orderdate'])
        table.close()
    def test_memos_after_close(self):
        "memos available after close/open"
        table = dbf.Table('tempy', 'name C(20); desc M', dbf_type='db3', default_data_types=dict(C=Char))
        table.open()
        table.append(('Author','dashing, debonair, delightful'))
        table.close()
        table.open()
        self.assertEqual(tuple(table[0]), ('Author','dashing, debonair, delightful'))
        table.close()
        table2 = dbf.Table('tempy', 'name C(20); desc M', dbf_type='db3')
        table2.open()
        table2.append(('Benedict', 'brilliant, bombastic, bothered'))
        table2.close()
        table.open()
        self.assertEqual(table[0].name, 'Benedict')
        self.assertEqual(table[0].desc, 'brilliant, bombastic, bothered')
        table.close()
    def test_field_type(self):
        "table.type(field) == ('C', Char)"
        table = dbf.Table('tempy', 'name C(20); desc M', dbf_type='db3', default_data_types=dict(C=Char))
        table.open()
        field_info = table.field_info('name')
        if py_ver < (3, 0):
            self.assertEqual(field_info, ('C', 20, 0, Char))
            self.assertEqual(field_info.field_type, 'C')
        else:
            self.assertEqual(field_info, (dbf.FieldType.CHAR, 20, 0, Char))
            self.assertEqual(field_info.field_type, dbf.FieldType.CHAR)
        self.assertEqual(field_info.length, 20)
        self.assertEqual(field_info.decimal, 0)
        self.assertEqual(field_info.py_type, Char)
        table.close()

    def test_memo_after_backup(self):
        "memo fields accessible after .backup()"
        table = self.dbf_table
        table.open()
        table.create_backup()
        backup = dbf.Table(table.backup)
        backup.open()
        desclist = self.dbf_desclist
        for i in range(len(desclist)):
            self.assertEqual(desclist[i], backup[i].desc)
        backup.close()
        table.close()
    def test_write_loop(self):
        "Process loop commits changes"
        table = self.dbf_table
        table.open()
        for record in Process(table):
            record.name = '!BRAND NEW NAME!'
        for record in table:
            self.assertEqual(record.name, '!BRAND NEW NAME!         ')
        table.close()
    def test_export(self):
        for table in self.dbf_table, self.vfp_table:
            table.open()
            dbf.export(table, filename='test_export.csv')
    def test_index_search(self):
        table = Table("unordered", "icao C(20)", default_data_types=dict(C=Char), on_disk=False).open()
        icao = ("kilo charlie echo golf papa hotel delta tango india sierra juliet lima zulu mike "
                "bravo november alpha oscar quebec romeo uniform victor whiskey x-ray yankee foxtrot".split())
        for alpha in icao:
            table.append((alpha,))
        sorted = table.create_index(lambda rec: rec.icao)
        self.assertTrue(sorted.index_search('alpha'))
        self.assertTrue(sorted.index_search('bravo'))
        self.assertTrue(sorted.index_search('charlie'))
        self.assertTrue(sorted.index_search('delta'))
        self.assertTrue(sorted.index_search('echo'))
        self.assertTrue(sorted.index_search('foxtrot'))
        self.assertTrue(sorted.index_search('golf'))
        self.assertTrue(sorted.index_search('hotel'))
        self.assertTrue(sorted.index_search('india'))
        self.assertTrue(sorted.index_search('juliet'))
        self.assertTrue(sorted.index_search('kilo'))
        self.assertTrue(sorted.index_search('lima'))
        self.assertTrue(sorted.index_search('mike'))
        self.assertTrue(sorted.index_search('november'))
        self.assertTrue(sorted.index_search('oscar'))
        self.assertTrue(sorted.index_search('papa'))
        self.assertTrue(sorted.index_search('quebec'))
        self.assertTrue(sorted.index_search('romeo'))
        self.assertTrue(sorted.index_search('sierra'))
        self.assertTrue(sorted.index_search('tango'))
        self.assertTrue(sorted.index_search('uniform'))
        self.assertTrue(sorted.index_search('victor'))
        self.assertTrue(sorted.index_search('whiskey'))
        self.assertTrue(sorted.index_search('x-ray'))
        self.assertTrue(sorted.index_search('yankee'))
        self.assertTrue(sorted.index_search('zulu'))
        self.assertEqual(sorted.index_search('alpha'), 0)
        self.assertEqual(sorted.index_search('bravo'), 1)
        self.assertEqual(sorted.index_search('charlie'), 2)
        self.assertEqual(sorted.index_search('delta'), 3)
        self.assertEqual(sorted.index_search('echo'), 4)
        self.assertEqual(sorted.index_search('foxtrot'), 5)
        self.assertEqual(sorted.index_search('golf'), 6)
        self.assertEqual(sorted.index_search('hotel'), 7)
        self.assertEqual(sorted.index_search('india'), 8)
        self.assertEqual(sorted.index_search('juliet'), 9)
        self.assertEqual(sorted.index_search('kilo'), 10)
        self.assertEqual(sorted.index_search('lima'), 11)
        self.assertEqual(sorted.index_search('mike'), 12)
        self.assertEqual(sorted.index_search('november'), 13)
        self.assertEqual(sorted.index_search('oscar'), 14)
        self.assertEqual(sorted.index_search('papa'), 15)
        self.assertEqual(sorted.index_search('quebec'), 16)
        self.assertEqual(sorted.index_search('romeo'), 17)
        self.assertEqual(sorted.index_search('sierra'), 18)
        self.assertEqual(sorted.index_search('tango'), 19)
        self.assertEqual(sorted.index_search('uniform'), 20)
        self.assertEqual(sorted.index_search('victor'), 21)
        self.assertEqual(sorted.index_search('whiskey'), 22)
        self.assertEqual(sorted.index_search('x-ray'), 23)
        self.assertEqual(sorted.index_search('yankee'), 24)
        self.assertEqual(sorted.index_search('zulu'), 25)
        self.assertRaises(NotFoundError, sorted.index_search, 'john')
        self.assertRaises(NotFoundError, sorted.index_search, 'john', partial=True)
        self.assertEqual(sorted.index_search('able', nearest=True), 0)
        self.assertFalse(sorted.index_search('able', nearest=True))
        self.assertEqual(sorted.index_search('alp', partial=True), 0)
        self.assertTrue(sorted.index_search('alp', partial=True))
        self.assertEqual(sorted.index_search('john', nearest=True), 9)
        self.assertFalse(sorted.index_search('john', nearest=True))
        self.assertEqual(sorted.index_search('jul', partial=True), 9)
        self.assertTrue(sorted.index_search('jul', partial=True))

class TestDbfNavigation(unittest.TestCase):
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        "create a dbf and vfp table"
        self.dbf_table = table = Table(
            os.path.join(self.tempdir, 'temptable'),
            'name C(25); paid L; qty N(11,5); orderdate D; desc M', dbf_type='db3'
            )
        table.open()
        namelist = self.dbf_namelist = []
        paidlist = self.dbf_paidlist = []
        qtylist = self.dbf_qtylist = []
        orderlist = self.dbf_orderlist = []
        desclist = self.dbf_desclist = []
        for i in range(len(floats)):
            name = '%-25s' % words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            namelist.append(name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc})
        table.close()

        self.vfp_table = table = Table(
                os.path.join(self.tempdir, 'tempvfp'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M; mass B;'
                ' weight F(18,3); age I; meeting T; misc G; photo P',
                dbf_type='vfp',
                )
        table.open()
        namelist = self.vfp_namelist = []
        paidlist = self.vfp_paidlist = []
        qtylist = self.vfp_qtylist = []
        orderlist = self.vfp_orderlist = []
        desclist = self.vfp_desclist = []
        masslist = self.vfp_masslist = []
        weightlist = self.vfp_weightlist = []
        agelist = self.vfp_agelist = []
        meetlist = self.vfp_meetlist = []
        misclist = self.vfp_misclist = []
        photolist = self.vfp_photolist = []
        for i in range(len(floats)):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = floats[i]
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            mass = floats[i] * floats[i] / 2.0
            weight = floats[i] * 3
            age = numbers[i]
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1, \
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            misc = ' '.join(words[i:i+50:3]).encode('ascii')
            photo = ' '.join(words[i:i+50:7]).encode('ascii')
            namelist.append('%-25s' % name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            masslist.append(mass)
            weightlist.append(weight)
            agelist.append(age)
            meetlist.append(meeting)
            misclist.append(misc)
            photolist.append(photo)
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1,
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc,
                    'mass':mass, 'weight':weight, 'age':age, 'meeting':meeting, 'misc':misc, 'photo':photo})
        table.close()
    def tearDown(self):
        self.dbf_table.close()
        self.vfp_table.close()
        shutil.rmtree(self.tempdir, True)

    def test_top(self):
        "top, current in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        table.goto(mid)
        list.goto(mid)
        index.goto(mid)
        self.assertTrue(table.current != -1)
        self.assertTrue(list.current != -1)
        self.assertTrue(index.current != -1)
        table.top()
        list.top()
        index.top()
        self.assertEqual(table.current, -1)
        self.assertEqual(list.current, -1)
        self.assertEqual(index.current, -1)

    def test_bottom(self):
        "bottom, current in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        table.goto(mid)
        list.goto(mid)
        index.goto(mid)
        self.assertTrue(table.current != -1)
        self.assertTrue(list.current != -1)
        self.assertTrue(index.current != -1)
        table.bottom()
        list.bottom()
        index.bottom()
        self.assertEqual(table.current, total)
        self.assertEqual(list.current, total)
        self.assertEqual(index.current, total)

    def test_goto(self):
        "goto, current in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        table.goto(mid)
        list.goto(mid)
        index.goto(mid)
        self.assertEqual(table.current, mid)
        self.assertEqual(list.current, mid)
        self.assertEqual(index.current, mid)
        table.goto('top')
        list.goto('top')
        index.goto('top')
        self.assertEqual(table.current, -1)
        self.assertEqual(list.current, -1)
        self.assertEqual(index.current, -1)
        table.goto('bottom')
        list.goto('bottom')
        index.goto('bottom')
        self.assertEqual(table.current, total)
        self.assertEqual(list.current, total)
        self.assertEqual(index.current, total)
        dbf.delete(table[10])
        self.assertTrue(dbf.is_deleted(list[10]))
        self.assertTrue(dbf.is_deleted(index[10]))
        table.goto(10)
        list.goto(10)
        index.goto(10)
        self.assertEqual(table.current, 10)
        self.assertEqual(list.current, 10)
        self.assertEqual(index.current, 10)
        table.close()

    def test_skip(self):
        "skip, current in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        self.assertEqual(table.current, -1)
        self.assertEqual(list.current, -1)
        self.assertEqual(index.current, -1)
        table.skip(1)
        list.skip(1)
        index.skip(1)
        self.assertEqual(table.current, 0)
        self.assertEqual(list.current, 0)
        self.assertEqual(index.current, 0)
        table.skip(10)
        list.skip(10)
        index.skip(10)
        self.assertEqual(table.current, 10)
        self.assertEqual(list.current, 10)
        self.assertEqual(index.current, 10)
        table.close()

    def test_first_record(self):
        "first_record in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        self.assertTrue(table[0] is list[0])
        self.assertTrue(table[0] is index[0])
        self.assertTrue(table.first_record is table[0])
        self.assertTrue(list.first_record is table[0])
        self.assertTrue(index.first_record is table[0])
        table.close()

    def test_prev_record(self):
        "prev_record in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        self.assertTrue(table[0] is list[0])
        self.assertTrue(table[0] is index[0])
        table.top()
        list.top()
        index.top()
        self.assertTrue(isinstance(table.prev_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(list.prev_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(index.prev_record, dbf.RecordVaporWare))
        table.skip()
        list.skip()
        index.skip()
        self.assertTrue(isinstance(table.prev_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(list.prev_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(index.prev_record, dbf.RecordVaporWare))
        table.skip()
        list.skip()
        index.skip()
        self.assertTrue(table.prev_record is table[0])
        self.assertTrue(list.prev_record is table[0])
        self.assertTrue(index.prev_record is table[0])
        table.close()

    def test_current_record(self):
        "current_record in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        table.top()
        list.top()
        index.top()
        self.assertTrue(isinstance(table.current_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(list.current_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(index.current_record, dbf.RecordVaporWare))
        table.bottom()
        list.bottom()
        index.bottom()
        self.assertTrue(isinstance(table.current_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(list.current_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(index.current_record, dbf.RecordVaporWare))
        table.goto(mid)
        list.goto(mid)
        index.goto(mid)
        self.assertTrue(table.current_record is table[mid])
        self.assertTrue(list.current_record is table[mid])
        self.assertTrue(index.current_record is table[mid])
        table.close()

    def test_next_record(self):
        "prev_record in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        self.assertTrue(table[0] is list[0])
        self.assertTrue(table[0] is index[0])
        table.bottom()
        list.bottom()
        index.bottom()
        self.assertTrue(isinstance(table.next_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(list.next_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(index.next_record, dbf.RecordVaporWare))
        table.skip(-1)
        list.skip(-1)
        index.skip(-1)
        self.assertTrue(isinstance(table.next_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(list.next_record, dbf.RecordVaporWare))
        self.assertTrue(isinstance(index.next_record, dbf.RecordVaporWare))
        table.skip(-1)
        list.skip(-1)
        index.skip(-1)
        self.assertTrue(table.next_record is table[-1])
        self.assertTrue(list.next_record is table[-1])
        self.assertTrue(index.next_record is table[-1])
        table.close()

    def test_last_record(self):
        "last_record in Tables, Lists, and Indexes"
        table = self.dbf_table
        table.open()
        list = List(table)
        index = Index(table, key=lambda rec: dbf.recno(rec))
        total = len(table)
        mid = total // 2
        self.assertTrue(table[-1] is list[-1])
        self.assertTrue(table[-1] is index[-1])
        self.assertTrue(table.last_record is table[-1])
        self.assertTrue(list.last_record is table[-1])
        self.assertTrue(index.last_record is table[-1])
        table.close()

class TestDbfLists(unittest.TestCase):
    "DbfList tests"
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        "create a dbf table"
        self.dbf_table = table = Table(
            os.path.join(self.tempdir, 'temptable'),
            'name C(25); paid L; qty N(11,5); orderdate D; desc M', dbf_type='db3'
            )
        table.open()
        records = []
        for i in range(len(floats)):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = round(floats[i], 5)
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            data = {'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc}
            table.append(data)
            records.append(data)
        table.close()
        table.open()
        for trec, drec in zip(table, records):
            self.assertEqual(trec.name.strip(), drec['name'])
            self.assertEqual(trec.paid, drec['paid'])
            self.assertEqual(trec.qty, drec['qty'])
            self.assertEqual(trec.orderdate, drec['orderdate'])
            self.assertEqual(trec.desc, drec['desc'])
        table.close()
    def tearDown(self):
        self.dbf_table.close()
        shutil.rmtree(self.tempdir, True)
    def test_exceptions(self):
        table = self.dbf_table
        table.open()
        list = table[::5]
        record = table[5]
        dbf.delete(record)
        self.assertTrue(list[0] is table[0])
        self.assertTrue(record in list)
        self.assertRaises(TypeError, list.__contains__, 'some string')
        self.assertRaises(TypeError, list.__getitem__, 'some string')
        self.assertRaises(TypeError, list.__delitem__, 'some string')
        self.assertRaises(TypeError, list.remove, 'some string')
        self.assertRaises(TypeError, list.index, 'some string')
        self.assertRaises(IndexError, list.__getitem__, 100)
        self.assertRaises(IndexError, list.pop, 1000)
        self.assertRaises(IndexError, list.goto, 1000)
        list.top()
        self.assertRaises(Bof, list.skip, -1)
        list.bottom()
        self.assertRaises(Eof, list.skip)
        table.pack()
        self.assertRaises(DbfError, list.__contains__, record)

        list = List()
        self.assertRaises(IndexError, list.goto, 0)
        self.assertRaises(Bof, list.skip, -1)
        self.assertRaises(Eof, list.skip)
        self.assertRaises(ValueError, list.remove, table[0])
        self.assertRaises(ValueError, list.index, table[1])

    def test_add_subtract(self):
        "addition and subtraction"
        table1 = self.dbf_table
        table1.open()
        list1 = table1[::2]
        list2 = table1[::3]
        list3 = table1[:] - list1 - list2
        self.assertEqual(100, len(table1))
        self.assertEqual(list1[0], list2[0])
        self.assertEqual(list1[3], list2[2])
        self.assertEqual(50, len(list1))
        self.assertEqual(34, len(list2))
        self.assertEqual(33, len(list3))
        self.assertEqual(117, len(list1) + len(list2) + len(list3))
        self.assertEqual(len(table1), len(list1 + list2 + list3))
        self.assertEqual(67, len(list1 + list2))
        self.assertEqual(33, len(list1 - list2))
        self.assertEqual(17, len(list2 - list1))
        table1.close()
    def test_append_extend(self):
        "appending and extending"
        table1 = self.dbf_table
        table1.open()
        list1 = table1[::2]
        list2 = table1[::3]
        list3 = table1[:] - list1 - list2
        list1.extend(list2)
        list2.append(table1[1])
        self.assertEqual(67, len(list1))
        self.assertEqual(35, len(list2))
        list1.append(table1[1])
        list2.extend(list3)
        self.assertEqual(68, len(list1))
        self.assertEqual(67, len(list2))
        table1.close()
    def test_index(self):
        "indexing"
        table1 = self.dbf_table
        table1.open()
        list1 = table1[::2]
        list2 = table1[::3]
        list3 = table1[:] - list1 - list2
        for i, rec in enumerate(list1):
            self.assertEqual(i, list1.index(rec))
        for rec in list3:
            self.assertRaises(ValueError, list1.index, rec )
        table1.close()
    def test_sort(self):
        "sorting"
        table1 = self.dbf_table
        table1.open()
        list1 = table1[::2]
        list2 = table1[::3]
        list3 = table1[:] - list1 - list2
        list4 = table1[:]
        index = table1.create_index(key = lambda rec: rec.name )
        list4.sort(key=lambda rec: rec.name)
        for trec, lrec in zip(index, list4):
            self.assertEqual(dbf.recno(trec), dbf.recno(lrec))
        table1.close()
    def test_keys(self):
        "keys"
        table1 = self.dbf_table
        table1.open()
        field = table1.field_names[0]
        list1 = List(table1, key=lambda rec: rec[field])
        unique = set()
        for rec in table1:
            if rec[field] not in unique:
                unique.add(rec[field])
            else:
                self.assertRaises(NotFoundError, list1.index, rec)
                self.assertFalse(rec in list1)
            self.assertTrue(rec[field] in unique)
        self.assertEqual(len(unique), len(list1))
        table1.close()
    def test_contains(self):
        table = self.dbf_table
        table.open()
        list = List(table)
        i = 0
        for record in list:
            self.assertEqual(record, list[i])
            self.assertTrue(record in list)
            self.assertTrue(tuple(record) in list)
            self.assertTrue(scatter(record) in list)
            self.assertTrue(create_template(record) in list)
            i += 1
        self.assertEqual(i, len(list))
        table.close()

class TestWhatever(unittest.TestCase):
    "move tests here to run one at a time while debugging"
    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        "create a dbf and vfp table"
        self.dbf_table = table = Table(
            os.path.join(self.tempdir, 'temptable'),
            'name C(25); paid L; qty N(11,5); orderdate D; desc M', dbf_type='db3'
            )
        table.open()
        namelist = self.dbf_namelist = []
        paidlist = self.dbf_paidlist = []
        qtylist = self.dbf_qtylist = []
        orderlist = self.dbf_orderlist = []
        desclist = self.dbf_desclist = []
        for i in range(len(floats)):
            name = '%-25s' % words[i]
            paid = len(words[i]) % 3 == 0
            qty = round(floats[i], 5)
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            namelist.append(name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc})
        table.close()

        self.vfp_table = table = Table(
                os.path.join(self.tempdir, 'tempvfp'),
                'name C(25); paid L; qty N(11,5); orderdate D; desc M; mass B;'
                ' weight F(18,3); age I; meeting T; misc G; photo P',
                dbf_type='vfp',
                )
        table.open()
        namelist = self.vfp_namelist = []
        paidlist = self.vfp_paidlist = []
        qtylist = self.vfp_qtylist = []
        orderlist = self.vfp_orderlist = []
        desclist = self.vfp_desclist = []
        masslist = self.vfp_masslist = []
        weightlist = self.vfp_weightlist = []
        agelist = self.vfp_agelist = []
        meetlist = self.vfp_meetlist = []
        misclist = self.vfp_misclist = []
        photolist = self.vfp_photolist = []
        for i in range(len(floats)):
            name = words[i]
            paid = len(words[i]) % 3 == 0
            qty = round(floats[i], 5)
            orderdate = datetime.date((numbers[i] + 1) * 2, (numbers[i] % 12) +1, (numbers[i] % 27) + 1)
            desc = ' '.join(words[i:i+50])
            mass = floats[i] * floats[i] / 2.0
            weight = round(floats[i] * 3, 3)
            age = numbers[i]
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1, \
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            misc = ' '.join(words[i:i+50:3]).encode('ascii')
            photo = ' '.join(words[i:i+50:7]).encode('ascii')
            namelist.append('%-25s' % name)
            paidlist.append(paid)
            qtylist.append(qty)
            orderlist.append(orderdate)
            desclist.append(desc)
            masslist.append(mass)
            weightlist.append(weight)
            agelist.append(age)
            meetlist.append(meeting)
            misclist.append(misc)
            photolist.append(photo)
            meeting = datetime.datetime((numbers[i] + 2000), (numbers[i] % 12)+1, (numbers[i] % 28)+1,
                      (numbers[i] % 24), numbers[i] % 60, (numbers[i] * 3) % 60)
            table.append({'name':name, 'paid':paid, 'qty':qty, 'orderdate':orderdate, 'desc':desc,
                    'mass':mass, 'weight':weight, 'age':age, 'meeting':meeting, 'misc':misc, 'photo':photo})
        table.close()
    def tearDown(self):
        self.dbf_table.close()
        self.vfp_table.close()
        shutil.rmtree(self.tempdir, True)
# main
if __name__ == '__main__':
    unittest.main()