aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/prettytable/py3/tests/test_prettytable.py
blob: 9b51e4a2ce3fbe8035de1872bd23bc06c10f954d (plain) (blame)
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
from __future__ import annotations

import datetime as dt
import io
import random
import sqlite3
from math import e, pi, sqrt
from typing import Any

import pytest
from pytest_lazy_fixtures import lf

import prettytable
from prettytable import (
    ALL,
    DEFAULT,
    DOUBLE_BORDER,
    FRAME,
    HEADER,
    MARKDOWN,
    MSWORD_FRIENDLY,
    NONE,
    ORGMODE,
    PLAIN_COLUMNS,
    RANDOM,
    SINGLE_BORDER,
    PrettyTable,
    from_csv,
    from_db_cursor,
    from_html,
    from_html_one,
    from_json,
)


def test_version() -> None:
    assert isinstance(prettytable.__version__, str)
    assert prettytable.__version__[0].isdigit()
    assert prettytable.__version__.count(".") >= 2
    assert prettytable.__version__[-1].isdigit()


def helper_table(rows: int = 3) -> PrettyTable:
    table = PrettyTable(["", "Field 1", "Field 2", "Field 3"])
    v = 1
    for row in range(rows):
        # Some have spaces, some not, to help test padding columns of different widths
        table.add_row([v, f"value {v}", f"value{v+1}", f"value{v+2}"])
        v += 3
    return table


@pytest.fixture
def row_prettytable() -> PrettyTable:
    # Row by row...
    table = PrettyTable()
    table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
    table.add_row(["Adelaide", 1295, 1158259, 600.5])
    table.add_row(["Brisbane", 5905, 1857594, 1146.4])
    table.add_row(["Darwin", 112, 120900, 1714.7])
    table.add_row(["Hobart", 1357, 205556, 619.5])
    table.add_row(["Sydney", 2058, 4336374, 1214.8])
    table.add_row(["Melbourne", 1566, 3806092, 646.9])
    table.add_row(["Perth", 5386, 1554769, 869.4])
    return table


@pytest.fixture
def col_prettytable() -> PrettyTable:
    # Column by column...
    table = PrettyTable()
    table.add_column(
        "City name",
        ["Adelaide", "Brisbane", "Darwin", "Hobart", "Sydney", "Melbourne", "Perth"],
    )
    table.add_column("Area", [1295, 5905, 112, 1357, 2058, 1566, 5386])
    table.add_column(
        "Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]
    )
    table.add_column(
        "Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]
    )
    return table


@pytest.fixture
def mix_prettytable() -> PrettyTable:
    # A mix of both!
    table = PrettyTable()
    table.field_names = ["City name", "Area"]
    table.add_row(["Adelaide", 1295])
    table.add_row(["Brisbane", 5905])
    table.add_row(["Darwin", 112])
    table.add_row(["Hobart", 1357])
    table.add_row(["Sydney", 2058])
    table.add_row(["Melbourne", 1566])
    table.add_row(["Perth", 5386])
    table.add_column(
        "Population", [1158259, 1857594, 120900, 205556, 4336374, 3806092, 1554769]
    )
    table.add_column(
        "Annual Rainfall", [600.5, 1146.4, 1714.7, 619.5, 1214.8, 646.9, 869.4]
    )
    return table


class TestNoneOption:
    def test_none_char_valid_option(self) -> None:
        PrettyTable(["Field 1", "Field 2", "Field 3"], none_format="")

    def test_none_char_invalid_option(self) -> None:
        with pytest.raises(TypeError) as exc:
            PrettyTable(["Field 1", "Field 2", "Field 3"], none_format=2)
        assert "must be a string" in str(exc.value)

    def test_no_value_replace_none(self) -> None:
        table = PrettyTable(["Field 1", "Field 2", "Field 3"])
        table.add_row(["value 1", None, "value 2"])
        assert (
            table.get_string().strip()
            == """
+---------+---------+---------+
| Field 1 | Field 2 | Field 3 |
+---------+---------+---------+
| value 1 |   None  | value 2 |
+---------+---------+---------+
""".strip()
        )

    def test_no_value_replace_none_with_default_field_names(self) -> None:
        table = PrettyTable()
        table.add_row(["value 1", "None", "value 2"])
        assert (
            table.get_string().strip()
            == """
+---------+---------+---------+
| Field 1 | Field 2 | Field 3 |
+---------+---------+---------+
| value 1 |   None  | value 2 |
+---------+---------+---------+
""".strip()
        )

    def test_replace_none_all(self) -> None:
        table = PrettyTable(["Field 1", "Field 2", "Field 3"], none_format="N/A")
        table.add_row(["value 1", None, "None"])
        assert (
            table.get_string().strip()
            == """
+---------+---------+---------+
| Field 1 | Field 2 | Field 3 |
+---------+---------+---------+
| value 1 |   N/A   |   N/A   |
+---------+---------+---------+
""".strip()
        )

    def test_replace_none_by_col(self) -> None:
        table = PrettyTable(["Field 1", "Field 2", "Field 3"])
        table.none_format["Field 2"] = "N/A"
        table.none_format["Field 3"] = ""
        table.add_row(["value 1", None, None])
        assert (
            table.get_string().strip()
            == """
+---------+---------+---------+
| Field 1 | Field 2 | Field 3 |
+---------+---------+---------+
| value 1 |   N/A   |         |
+---------+---------+---------+
""".strip()
        )

    def test_replace_none_recompute_width(self) -> None:
        table = PrettyTable()
        table.add_row([None])
        table.none_format = "0123456789"
        assert (
            table.get_string().strip()
            == """
+------------+
|  Field 1   |
+------------+
| 0123456789 |
+------------+
""".strip()
        )

    def test_replace_none_maintain_width_on_recompute(self) -> None:
        table = PrettyTable()
        table.add_row(["Hello"])
        table.none_format = "0123456789"
        assert (
            table.get_string().strip()
            == """
+---------+
| Field 1 |
+---------+
|  Hello  |
+---------+
""".strip()
        )

    def test_replace_none_recompute_width_multi_column(self) -> None:
        table = PrettyTable()
        table.add_row(["Hello", None, "World"])
        table.none_format = "0123456789"
        assert (
            table.get_string().strip()
            == """
+---------+------------+---------+
| Field 1 |  Field 2   | Field 3 |
+---------+------------+---------+
|  Hello  | 0123456789 |  World  |
+---------+------------+---------+
""".strip()
        )


class TestBuildEquivalence:
    """Make sure that building a table row-by-row and column-by-column yield the same
    results"""

    @pytest.mark.parametrize(
        ["left_hand", "right_hand"],
        [
            (
                lf("row_prettytable"),
                lf("col_prettytable"),
            ),
            (
                lf("row_prettytable"),
                lf("mix_prettytable"),
            ),
        ],
    )
    def test_equivalence_ascii(
        self, left_hand: PrettyTable, right_hand: PrettyTable
    ) -> None:
        assert left_hand.get_string() == right_hand.get_string()

    @pytest.mark.parametrize(
        ["left_hand", "right_hand"],
        [
            (
                lf("row_prettytable"),
                lf("col_prettytable"),
            ),
            (
                lf("row_prettytable"),
                lf("mix_prettytable"),
            ),
        ],
    )
    def test_equivalence_html(
        self, left_hand: PrettyTable, right_hand: PrettyTable
    ) -> None:
        assert left_hand.get_html_string() == right_hand.get_html_string()

    @pytest.mark.parametrize(
        ["left_hand", "right_hand"],
        [
            (
                lf("row_prettytable"),
                lf("col_prettytable"),
            ),
            (
                lf("row_prettytable"),
                lf("mix_prettytable"),
            ),
        ],
    )
    def test_equivalence_latex(
        self, left_hand: PrettyTable, right_hand: PrettyTable
    ) -> None:
        assert left_hand.get_latex_string() == right_hand.get_latex_string()


class TestDeleteColumn:
    def test_delete_column(self) -> None:
        table = PrettyTable()
        table.add_column("City name", ["Adelaide", "Brisbane", "Darwin"])
        table.add_column("Area", [1295, 5905, 112])
        table.add_column("Population", [1158259, 1857594, 120900])
        table.del_column("Area")

        without_row = PrettyTable()
        without_row.add_column("City name", ["Adelaide", "Brisbane", "Darwin"])
        without_row.add_column("Population", [1158259, 1857594, 120900])

        assert table.get_string() == without_row.get_string()

    def test_delete_illegal_column_raises_error(self) -> None:
        table = PrettyTable()
        table.add_column("City name", ["Adelaide", "Brisbane", "Darwin"])

        with pytest.raises(ValueError):
            table.del_column("City not-a-name")


@pytest.fixture(scope="function")
def field_name_less_table() -> PrettyTable:
    table = PrettyTable()
    table.add_row(["Adelaide", 1295, 1158259, 600.5])
    table.add_row(["Brisbane", 5905, 1857594, 1146.4])
    table.add_row(["Darwin", 112, 120900, 1714.7])
    table.add_row(["Hobart", 1357, 205556, 619.5])
    table.add_row(["Sydney", 2058, 4336374, 1214.8])
    table.add_row(["Melbourne", 1566, 3806092, 646.9])
    table.add_row(["Perth", 5386, 1554769, 869.4])
    return table


class TestFieldNameLessTable:
    """Make sure that building and stringing a table with no fieldnames works fine"""

    def test_can_string_ascii(self, field_name_less_table: prettytable) -> None:
        output = field_name_less_table.get_string()
        assert "|  Field 1  | Field 2 | Field 3 | Field 4 |" in output
        assert "|  Adelaide |   1295  | 1158259 |  600.5  |" in output

    def test_can_string_html(self, field_name_less_table: prettytable) -> None:
        output = field_name_less_table.get_html_string()
        assert "<th>Field 1</th>" in output
        assert "<td>Adelaide</td>" in output

    def test_can_string_latex(self, field_name_less_table: prettytable) -> None:
        output = field_name_less_table.get_latex_string()
        assert "Field 1 & Field 2 & Field 3 & Field 4 \\\\" in output
        assert "Adelaide & 1295 & 1158259 & 600.5 \\\\" in output

    def test_add_field_names_later(self, field_name_less_table: prettytable) -> None:
        field_name_less_table.field_names = [
            "City name",
            "Area",
            "Population",
            "Annual Rainfall",
        ]
        assert (
            "City name | Area | Population | Annual Rainfall"
            in field_name_less_table.get_string()
        )


@pytest.fixture(scope="function")
def aligned_before_table() -> PrettyTable:
    table = PrettyTable()
    table.align = "r"
    table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
    table.add_row(["Adelaide", 1295, 1158259, 600.5])
    table.add_row(["Brisbane", 5905, 1857594, 1146.4])
    table.add_row(["Darwin", 112, 120900, 1714.7])
    table.add_row(["Hobart", 1357, 205556, 619.5])
    table.add_row(["Sydney", 2058, 4336374, 1214.8])
    table.add_row(["Melbourne", 1566, 3806092, 646.9])
    table.add_row(["Perth", 5386, 1554769, 869.4])
    return table


@pytest.fixture(scope="function")
def aligned_after_table() -> PrettyTable:
    table = PrettyTable()
    table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
    table.add_row(["Adelaide", 1295, 1158259, 600.5])
    table.add_row(["Brisbane", 5905, 1857594, 1146.4])
    table.add_row(["Darwin", 112, 120900, 1714.7])
    table.add_row(["Hobart", 1357, 205556, 619.5])
    table.add_row(["Sydney", 2058, 4336374, 1214.8])
    table.add_row(["Melbourne", 1566, 3806092, 646.9])
    table.add_row(["Perth", 5386, 1554769, 869.4])
    table.align = "r"
    return table


class TestAlignment:
    """Make sure alignment works regardless of when it was set"""

    def test_aligned_ascii(
        self, aligned_before_table: prettytable, aligned_after_table: prettytable
    ) -> None:
        before = aligned_before_table.get_string()
        after = aligned_after_table.get_string()
        assert before == after

    def test_aligned_html(
        self, aligned_before_table: prettytable, aligned_after_table: prettytable
    ) -> None:
        before = aligned_before_table.get_html_string()
        after = aligned_after_table.get_html_string()
        assert before == after

    def test_aligned_latex(
        self, aligned_before_table: prettytable, aligned_after_table: prettytable
    ) -> None:
        before = aligned_before_table.get_latex_string()
        after = aligned_after_table.get_latex_string()
        assert before == after


@pytest.fixture(scope="function")
def city_data_prettytable() -> PrettyTable:
    """Just build the Australian capital city data example table."""
    table = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
    table.add_row(["Adelaide", 1295, 1158259, 600.5])
    table.add_row(["Brisbane", 5905, 1857594, 1146.4])
    table.add_row(["Darwin", 112, 120900, 1714.7])
    table.add_row(["Hobart", 1357, 205556, 619.5])
    table.add_row(["Sydney", 2058, 4336374, 1214.8])
    table.add_row(["Melbourne", 1566, 3806092, 646.9])
    table.add_row(["Perth", 5386, 1554769, 869.4])
    return table


@pytest.fixture(scope="function")
def city_data_from_csv() -> PrettyTable:
    csv_string = """City name, Area, Population, Annual Rainfall
    Sydney, 2058, 4336374, 1214.8
    Melbourne, 1566, 3806092, 646.9
    Brisbane, 5905, 1857594, 1146.4
    Perth, 5386, 1554769, 869.4
    Adelaide, 1295, 1158259, 600.5
    Hobart, 1357, 205556, 619.5
    Darwin, 0112, 120900, 1714.7"""
    csv_fp = io.StringIO(csv_string)
    return from_csv(csv_fp)


class TestOptionOverride:
    """Make sure all options are properly overwritten by get_string."""

    def test_border(self, city_data_prettytable: prettytable) -> None:
        default = city_data_prettytable.get_string()
        override = city_data_prettytable.get_string(border=False)
        assert default != override

    def test_header(self, city_data_prettytable) -> None:
        default = city_data_prettytable.get_string()
        override = city_data_prettytable.get_string(header=False)
        assert default != override

    def test_hrules_all(self, city_data_prettytable) -> None:
        default = city_data_prettytable.get_string()
        override = city_data_prettytable.get_string(hrules=ALL)
        assert default != override

    def test_hrules_none(self, city_data_prettytable) -> None:
        default = city_data_prettytable.get_string()
        override = city_data_prettytable.get_string(hrules=NONE)
        assert default != override


class TestOptionAttribute:
    """Make sure all options which have an attribute interface work as they should.
    Also make sure option settings are copied correctly when a table is cloned by
    slicing."""

    def test_set_for_all_columns(self, city_data_prettytable) -> None:
        city_data_prettytable.field_names = sorted(city_data_prettytable.field_names)
        city_data_prettytable.align = "l"
        city_data_prettytable.max_width = 10
        city_data_prettytable.start = 2
        city_data_prettytable.end = 4
        city_data_prettytable.sortby = "Area"
        city_data_prettytable.reversesort = True
        city_data_prettytable.header = True
        city_data_prettytable.border = False
        city_data_prettytable.hrules = True
        city_data_prettytable.int_format = "4"
        city_data_prettytable.float_format = "2.2"
        city_data_prettytable.padding_width = 2
        city_data_prettytable.left_padding_width = 2
        city_data_prettytable.right_padding_width = 2
        city_data_prettytable.vertical_char = "!"
        city_data_prettytable.horizontal_char = "~"
        city_data_prettytable.junction_char = "*"
        city_data_prettytable.top_junction_char = "@"
        city_data_prettytable.bottom_junction_char = "#"
        city_data_prettytable.right_junction_char = "$"
        city_data_prettytable.left_junction_char = "%"
        city_data_prettytable.top_right_junction_char = "^"
        city_data_prettytable.top_left_junction_char = "&"
        city_data_prettytable.bottom_right_junction_char = "("
        city_data_prettytable.bottom_left_junction_char = ")"
        city_data_prettytable.format = True
        city_data_prettytable.attributes = {"class": "prettytable"}
        assert (
            city_data_prettytable.get_string() == city_data_prettytable[:].get_string()
        )

    def test_set_for_one_column(self, city_data_prettytable) -> None:
        city_data_prettytable.align["Rainfall"] = "l"
        city_data_prettytable.max_width["Name"] = 10
        city_data_prettytable.int_format["Population"] = "4"
        city_data_prettytable.float_format["Area"] = "2.2"
        assert (
            city_data_prettytable.get_string() == city_data_prettytable[:].get_string()
        )

    def test_preserve_internal_border(self) -> None:
        table = PrettyTable(preserve_internal_border=True)
        assert table.preserve_internal_border is True


@pytest.fixture(scope="module")
def db_cursor():
    conn = sqlite3.connect(":memory:")
    cur = conn.cursor()
    yield cur
    cur.close()
    conn.close()


@pytest.fixture(scope="module")
def init_db(db_cursor):
    db_cursor.execute(
        "CREATE TABLE cities "
        "(name TEXT, area INTEGER, population INTEGER, rainfall REAL)"
    )
    db_cursor.execute('INSERT INTO cities VALUES ("Adelaide", 1295, 1158259, 600.5)')
    db_cursor.execute('INSERT INTO cities VALUES ("Brisbane", 5905, 1857594, 1146.4)')
    db_cursor.execute('INSERT INTO cities VALUES ("Darwin", 112, 120900, 1714.7)')
    db_cursor.execute('INSERT INTO cities VALUES ("Hobart", 1357, 205556, 619.5)')
    db_cursor.execute('INSERT INTO cities VALUES ("Sydney", 2058, 4336374, 1214.8)')
    db_cursor.execute('INSERT INTO cities VALUES ("Melbourne", 1566, 3806092, 646.9)')
    db_cursor.execute('INSERT INTO cities VALUES ("Perth", 5386, 1554769, 869.4)')
    yield
    db_cursor.execute("DROP TABLE cities")


class TestBasic:
    """Some very basic tests."""

    def test_table_rows(self, city_data_prettytable: PrettyTable) -> None:
        rows = city_data_prettytable.rows
        assert len(rows) == 7
        assert rows[0] == ["Adelaide", 1295, 1158259, 600.5]

    def _test_no_blank_lines(self, table: prettytable) -> None:
        string = table.get_string()
        lines = string.split("\n")
        assert "" not in lines

    def _test_all_length_equal(self, table: prettytable) -> None:
        string = table.get_string()
        lines = string.split("\n")
        lengths = [len(line) for line in lines]
        lengths = set(lengths)
        assert len(lengths) == 1

    def test_no_blank_lines(self, city_data_prettytable) -> None:
        """No table should ever have blank lines in it."""
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal(self, city_data_prettytable) -> None:
        """All lines in a table should be of the same length."""
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_with_title(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.title = "My table"
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_with_title(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.title = "My table"
        self._test_all_length_equal(city_data_prettytable)

    def test_all_lengths_equal_with_long_title(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length, even with a long title."""
        city_data_prettytable.title = "My table (75 characters wide) " + "=" * 45
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_without_border(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.border = False
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_without_border(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.border = False
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_without_header(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.header = False
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_without_header(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.header = False
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_with_hrules_none(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.hrules = NONE
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_with_hrules_none(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.hrules = NONE
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_with_hrules_all(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.hrules = ALL
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_with_hrules_all(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.hrules = ALL
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_with_style_msword(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.set_style(MSWORD_FRIENDLY)
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_with_style_msword(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.set_style(MSWORD_FRIENDLY)
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_with_int_format(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.int_format = "04"
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_with_int_format(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.int_format = "04"
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_with_float_format(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """No table should ever have blank lines in it."""
        city_data_prettytable.float_format = "6.2f"
        self._test_no_blank_lines(city_data_prettytable)

    def test_all_lengths_equal_with_float_format(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        """All lines in a table should be of the same length."""
        city_data_prettytable.float_format = "6.2f"
        self._test_all_length_equal(city_data_prettytable)

    def test_no_blank_lines_from_csv(self, city_data_from_csv: PrettyTable) -> None:
        """No table should ever have blank lines in it."""
        self._test_no_blank_lines(city_data_from_csv)

    def test_all_lengths_equal_from_csv(self, city_data_from_csv: PrettyTable) -> None:
        """All lines in a table should be of the same length."""
        self._test_all_length_equal(city_data_from_csv)

    @pytest.mark.usefixtures("init_db")
    def test_no_blank_lines_from_db(self, db_cursor) -> None:
        """No table should ever have blank lines in it."""
        db_cursor.execute("SELECT * FROM cities")
        pt = from_db_cursor(db_cursor)
        self._test_no_blank_lines(pt)

    @pytest.mark.usefixtures("init_db")
    def test_all_lengths_equal_from_db(self, db_cursor) -> None:
        """No table should ever have blank lines in it."""
        db_cursor.execute("SELECT * FROM cities")
        pt = from_db_cursor(db_cursor)
        self._test_all_length_equal(pt)


class TestEmptyTable:
    """Make sure the print_empty option works"""

    def test_print_empty_true(self, city_data_prettytable: PrettyTable) -> None:
        table = PrettyTable()
        table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

        assert table.get_string(print_empty=True) != ""
        assert table.get_string(print_empty=True) != city_data_prettytable.get_string(
            print_empty=True
        )

    def test_print_empty_false(self, city_data_prettytable: PrettyTable) -> None:
        table = PrettyTable()
        table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

        assert table.get_string(print_empty=False) == ""
        assert table.get_string(print_empty=False) != city_data_prettytable.get_string(
            print_empty=False
        )

    def test_interaction_with_border(self) -> None:
        table = PrettyTable()
        table.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

        assert table.get_string(border=False, print_empty=True) == ""


class TestSlicing:
    def test_slice_all(self, city_data_prettytable: PrettyTable) -> None:
        table = city_data_prettytable[:]
        assert city_data_prettytable.get_string() == table.get_string()

    def test_slice_first_two_rows(self, city_data_prettytable: PrettyTable) -> None:
        table = city_data_prettytable[0:2]
        string = table.get_string()
        assert len(string.split("\n")) == 6
        assert "Adelaide" in string
        assert "Brisbane" in string
        assert "Melbourne" not in string
        assert "Perth" not in string

    def test_slice_last_two_rows(self, city_data_prettytable: PrettyTable) -> None:
        table = city_data_prettytable[-2:]
        string = table.get_string()
        assert len(string.split("\n")) == 6
        assert "Adelaide" not in string
        assert "Brisbane" not in string
        assert "Melbourne" in string
        assert "Perth" in string


class TestSorting:
    def test_sort_by_different_per_columns(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        city_data_prettytable.sortby = city_data_prettytable.field_names[0]
        old = city_data_prettytable.get_string()
        for field in city_data_prettytable.field_names[1:]:
            city_data_prettytable.sortby = field
            new = city_data_prettytable.get_string()
            assert new != old

    def test_reverse_sort(self, city_data_prettytable: PrettyTable) -> None:
        for field in city_data_prettytable.field_names:
            city_data_prettytable.sortby = field
            city_data_prettytable.reversesort = False
            forward = city_data_prettytable.get_string()
            city_data_prettytable.reversesort = True
            backward = city_data_prettytable.get_string()
            forward_lines = forward.split("\n")[2:]  # Discard header lines
            backward_lines = backward.split("\n")[2:]
            backward_lines.reverse()
            assert forward_lines == backward_lines

    def test_sort_key(self, city_data_prettytable: PrettyTable) -> None:
        # Test sorting by length of city name
        def key(vals):
            vals[0] = len(vals[0])
            return vals

        city_data_prettytable.sortby = "City name"
        city_data_prettytable.sort_key = key
        assert (
            city_data_prettytable.get_string().strip()
            == """
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|   Perth   | 5386 |  1554769   |      869.4      |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
| Melbourne | 1566 |  3806092   |      646.9      |
+-----------+------+------------+-----------------+
""".strip()
        )

    def test_sort_slice(self) -> None:
        """Make sure sorting and slicing interact in the expected way"""
        table = PrettyTable(["Foo"])
        for i in range(20, 0, -1):
            table.add_row([i])
        new_style = table.get_string(sortby="Foo", end=10)
        assert "10" in new_style
        assert "20" not in new_style
        oldstyle = table.get_string(sortby="Foo", end=10, oldsortslice=True)
        assert "10" not in oldstyle
        assert "20" in oldstyle


@pytest.fixture(scope="function")
def float_pt() -> PrettyTable:
    table = PrettyTable(["Constant", "Value"])
    table.add_row(["Pi", pi])
    table.add_row(["e", e])
    table.add_row(["sqrt(2)", sqrt(2)])
    return table


class TestFloatFormat:
    def test_no_decimals(self, float_pt: PrettyTable) -> None:
        float_pt.float_format = ".0f"
        float_pt.caching = False
        assert "." not in float_pt.get_string()

    def test_round_to_5dp(self, float_pt: PrettyTable) -> None:
        float_pt.float_format = ".5f"
        string = float_pt.get_string()
        assert "3.14159" in string
        assert "3.141592" not in string
        assert "2.71828" in string
        assert "2.718281" not in string
        assert "2.718282" not in string
        assert "1.41421" in string
        assert "1.414213" not in string

    def test_pad_with_2zeroes(self, float_pt: PrettyTable) -> None:
        float_pt.float_format = "06.2f"
        string = float_pt.get_string()
        assert "003.14" in string
        assert "002.72" in string
        assert "001.41" in string


class TestBreakLine:
    @pytest.mark.parametrize(
        ["rows", "hrule", "expected_result"],
        [
            (
                [["value 1", "value2\nsecond line"], ["value 3", "value4"]],
                ALL,
                """
+---------+-------------+
| Field 1 |   Field 2   |
+---------+-------------+
| value 1 |    value2   |
|         | second line |
+---------+-------------+
| value 3 |    value4   |
+---------+-------------+
""",
            ),
            (
                [
                    ["value 1", "value2\nsecond line"],
                    ["value 3\n\nother line", "value4\n\n\nvalue5"],
                ],
                ALL,
                """
+------------+-------------+
|  Field 1   |   Field 2   |
+------------+-------------+
|  value 1   |    value2   |
|            | second line |
+------------+-------------+
|  value 3   |    value4   |
|            |             |
| other line |             |
|            |    value5   |
+------------+-------------+
""",
            ),
            (
                [
                    ["value 1", "value2\nsecond line"],
                    ["value 3\n\nother line", "value4\n\n\nvalue5"],
                ],
                FRAME,
                """
+------------+-------------+
|  Field 1   |   Field 2   |
+------------+-------------+
|  value 1   |    value2   |
|            | second line |
|  value 3   |    value4   |
|            |             |
| other line |             |
|            |    value5   |
+------------+-------------+
""",
            ),
        ],
    )
    def test_break_line_ascii(
        self, rows: list[list[Any]], hrule: int, expected_result: str
    ) -> None:
        table = PrettyTable(["Field 1", "Field 2"])
        for row in rows:
            table.add_row(row)
        result = table.get_string(hrules=hrule)
        assert result.strip() == expected_result.strip()

    def test_break_line_html(self) -> None:
        table = PrettyTable(["Field 1", "Field 2"])
        table.add_row(["value 1", "value2\nsecond line"])
        table.add_row(["value 3", "value4"])
        result = table.get_html_string(hrules=ALL)
        assert (
            result.strip()
            == """
<table>
    <thead>
        <tr>
            <th>Field 1</th>
            <th>Field 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>value 1</td>
            <td>value2<br>second line</td>
        </tr>
        <tr>
            <td>value 3</td>
            <td>value4</td>
        </tr>
    </tbody>
</table>
""".strip()
        )


class TestAnsiWidth:
    colored = "\033[31mC\033[32mO\033[31mL\033[32mO\033[31mR\033[32mE\033[31mD\033[0m"

    def test_color(self) -> None:
        table = PrettyTable(["Field 1", "Field 2"])
        table.add_row([self.colored, self.colored])
        table.add_row(["nothing", "neither"])
        result = table.get_string()
        assert (
            result.strip()
            == f"""
+---------+---------+
| Field 1 | Field 2 |
+---------+---------+
| {self.colored} | {self.colored} |
| nothing | neither |
+---------+---------+
""".strip()
        )

    def test_reset(self) -> None:
        table = PrettyTable(["Field 1", "Field 2"])
        table.add_row(["abc def\033(B", "\033[31mabc def\033[m"])
        table.add_row(["nothing", "neither"])
        result = table.get_string()
        assert (
            result.strip()
            == """
+---------+---------+
| Field 1 | Field 2 |
+---------+---------+
| abc def\033(B | \033[31mabc def\033[m |
| nothing | neither |
+---------+---------+
""".strip()
        )


class TestFromDB:
    @pytest.mark.usefixtures("init_db")
    def test_non_select_cursor(self, db_cursor) -> None:
        db_cursor.execute(
            'INSERT INTO cities VALUES ("Adelaide", 1295, 1158259, 600.5)'
        )
        assert from_db_cursor(db_cursor) is None


class TestJSONOutput:
    def test_json_output(self) -> None:
        t = helper_table()
        result = t.get_json_string()
        assert (
            result.strip()
            == """
[
    [
        "",
        "Field 1",
        "Field 2",
        "Field 3"
    ],
    {
        "": 1,
        "Field 1": "value 1",
        "Field 2": "value2",
        "Field 3": "value3"
    },
    {
        "": 4,
        "Field 1": "value 4",
        "Field 2": "value5",
        "Field 3": "value6"
    },
    {
        "": 7,
        "Field 1": "value 7",
        "Field 2": "value8",
        "Field 3": "value9"
    }
]""".strip()
        )

    def test_json_output_options(self) -> None:
        t = helper_table()
        result = t.get_json_string(header=False, indent=None, separators=(",", ":"))
        assert (
            result
            == """[{"":1,"Field 1":"value 1","Field 2":"value2","Field 3":"value3"},"""
            """{"":4,"Field 1":"value 4","Field 2":"value5","Field 3":"value6"},"""
            """{"":7,"Field 1":"value 7","Field 2":"value8","Field 3":"value9"}]"""
        )


class TestHtmlOutput:
    def test_html_output(self) -> None:
        t = helper_table()
        result = t.get_html_string()
        assert (
            result.strip()
            == """
<table>
    <thead>
        <tr>
            <th></th>
            <th>Field 1</th>
            <th>Field 2</th>
            <th>Field 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>value 1</td>
            <td>value2</td>
            <td>value3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>value 4</td>
            <td>value5</td>
            <td>value6</td>
        </tr>
        <tr>
            <td>7</td>
            <td>value 7</td>
            <td>value8</td>
            <td>value9</td>
        </tr>
    </tbody>
</table>
""".strip()
        )

    def test_html_output_formatted(self) -> None:
        t = helper_table()
        result = t.get_html_string(format=True)
        assert (
            result.strip()
            == """
<table frame="box" rules="cols">
    <thead>
        <tr>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center"></th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 1</th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 2</th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">1</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 1</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value2</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value3</td>
        </tr>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">4</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 4</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value5</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value6</td>
        </tr>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">7</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 7</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value8</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value9</td>
        </tr>
    </tbody>
</table>
""".strip()  # noqa: E501
        )

    def test_html_output_with_title(self) -> None:
        t = helper_table()
        t.title = "Title & Title"
        result = t.get_html_string(attributes={"bgcolor": "red", "a<b": "1<2"})
        assert (
            result.strip()
            == """
<table bgcolor="red" a&lt;b="1&lt;2">
    <caption>Title &amp; Title</caption>
    <thead>
        <tr>
            <th></th>
            <th>Field 1</th>
            <th>Field 2</th>
            <th>Field 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>value 1</td>
            <td>value2</td>
            <td>value3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>value 4</td>
            <td>value5</td>
            <td>value6</td>
        </tr>
        <tr>
            <td>7</td>
            <td>value 7</td>
            <td>value8</td>
            <td>value9</td>
        </tr>
    </tbody>
</table>
""".strip()
        )

    def test_html_output_formatted_with_title(self) -> None:
        t = helper_table()
        t.title = "Title & Title"
        result = t.get_html_string(
            attributes={"bgcolor": "red", "a<b": "1<2"}, format=True
        )
        assert (
            result.strip()
            == """
<table frame="box" rules="cols" bgcolor="red" a&lt;b="1&lt;2">
    <caption>Title &amp; Title</caption>
    <thead>
        <tr>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center"></th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 1</th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 2</th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">1</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 1</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value2</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value3</td>
        </tr>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">4</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 4</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value5</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value6</td>
        </tr>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">7</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 7</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value8</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value9</td>
        </tr>
    </tbody>
</table>
""".strip()  # noqa: E501
        )


class TestPositionalJunctions:
    """Verify different cases for positional-junction characters"""

    def test_default(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)

        assert (
            city_data_prettytable.get_string().strip()
            == """
╔═══════════╦══════╦════════════╦═════════════════╗
║ City name ║ Area ║ Population ║ Annual Rainfall ║
╠═══════════╬══════╬════════════╬═════════════════╣
║  Adelaide ║ 1295 ║  1158259   ║      600.5      ║
║  Brisbane ║ 5905 ║  1857594   ║      1146.4     ║
║   Darwin  ║ 112  ║   120900   ║      1714.7     ║
║   Hobart  ║ 1357 ║   205556   ║      619.5      ║
║   Sydney  ║ 2058 ║  4336374   ║      1214.8     ║
║ Melbourne ║ 1566 ║  3806092   ║      646.9      ║
║   Perth   ║ 5386 ║  1554769   ║      869.4      ║
╚═══════════╩══════╩════════════╩═════════════════╝""".strip()
        )

    def test_no_header(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)
        city_data_prettytable.header = False

        assert (
            city_data_prettytable.get_string().strip()
            == """
╔═══════════╦══════╦═════════╦════════╗
║  Adelaide ║ 1295 ║ 1158259 ║ 600.5  ║
║  Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
║   Darwin  ║ 112  ║  120900 ║ 1714.7 ║
║   Hobart  ║ 1357 ║  205556 ║ 619.5  ║
║   Sydney  ║ 2058 ║ 4336374 ║ 1214.8 ║
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9  ║
║   Perth   ║ 5386 ║ 1554769 ║ 869.4  ║
╚═══════════╩══════╩═════════╩════════╝""".strip()
        )

    def test_with_title(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)
        city_data_prettytable.title = "Title"

        assert (
            city_data_prettytable.get_string().strip()
            == """
╔═════════════════════════════════════════════════╗
║                      Title                      ║
╠═══════════╦══════╦════════════╦═════════════════╣
║ City name ║ Area ║ Population ║ Annual Rainfall ║
╠═══════════╬══════╬════════════╬═════════════════╣
║  Adelaide ║ 1295 ║  1158259   ║      600.5      ║
║  Brisbane ║ 5905 ║  1857594   ║      1146.4     ║
║   Darwin  ║ 112  ║   120900   ║      1714.7     ║
║   Hobart  ║ 1357 ║   205556   ║      619.5      ║
║   Sydney  ║ 2058 ║  4336374   ║      1214.8     ║
║ Melbourne ║ 1566 ║  3806092   ║      646.9      ║
║   Perth   ║ 5386 ║  1554769   ║      869.4      ║
╚═══════════╩══════╩════════════╩═════════════════╝""".strip()
        )

    def test_with_title_no_header(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)
        city_data_prettytable.title = "Title"
        city_data_prettytable.header = False
        assert (
            city_data_prettytable.get_string().strip()
            == """
╔═════════════════════════════════════╗
║                Title                ║
╠═══════════╦══════╦═════════╦════════╣
║  Adelaide ║ 1295 ║ 1158259 ║ 600.5  ║
║  Brisbane ║ 5905 ║ 1857594 ║ 1146.4 ║
║   Darwin  ║ 112  ║  120900 ║ 1714.7 ║
║   Hobart  ║ 1357 ║  205556 ║ 619.5  ║
║   Sydney  ║ 2058 ║ 4336374 ║ 1214.8 ║
║ Melbourne ║ 1566 ║ 3806092 ║ 646.9  ║
║   Perth   ║ 5386 ║ 1554769 ║ 869.4  ║
╚═══════════╩══════╩═════════╩════════╝""".strip()
        )

    def test_hrule_all(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)
        city_data_prettytable.title = "Title"
        city_data_prettytable.hrules = ALL
        assert (
            city_data_prettytable.get_string().strip()
            == """
╔═════════════════════════════════════════════════╗
║                      Title                      ║
╠═══════════╦══════╦════════════╦═════════════════╣
║ City name ║ Area ║ Population ║ Annual Rainfall ║
╠═══════════╬══════╬════════════╬═════════════════╣
║  Adelaide ║ 1295 ║  1158259   ║      600.5      ║
╠═══════════╬══════╬════════════╬═════════════════╣
║  Brisbane ║ 5905 ║  1857594   ║      1146.4     ║
╠═══════════╬══════╬════════════╬═════════════════╣
║   Darwin  ║ 112  ║   120900   ║      1714.7     ║
╠═══════════╬══════╬════════════╬═════════════════╣
║   Hobart  ║ 1357 ║   205556   ║      619.5      ║
╠═══════════╬══════╬════════════╬═════════════════╣
║   Sydney  ║ 2058 ║  4336374   ║      1214.8     ║
╠═══════════╬══════╬════════════╬═════════════════╣
║ Melbourne ║ 1566 ║  3806092   ║      646.9      ║
╠═══════════╬══════╬════════════╬═════════════════╣
║   Perth   ║ 5386 ║  1554769   ║      869.4      ║
╚═══════════╩══════╩════════════╩═════════════════╝""".strip()
        )

    def test_vrules_none(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)
        city_data_prettytable.vrules = NONE
        assert (
            city_data_prettytable.get_string().strip()
            == "═══════════════════════════════════════════════════\n"
            "  City name   Area   Population   Annual Rainfall  \n"
            "═══════════════════════════════════════════════════\n"
            "   Adelaide   1295    1158259          600.5       \n"
            "   Brisbane   5905    1857594          1146.4      \n"
            "    Darwin    112      120900          1714.7      \n"
            "    Hobart    1357     205556          619.5       \n"
            "    Sydney    2058    4336374          1214.8      \n"
            "  Melbourne   1566    3806092          646.9       \n"
            "    Perth     5386    1554769          869.4       \n"
            "═══════════════════════════════════════════════════".strip()
        )

    def test_vrules_frame_with_title(self, city_data_prettytable: PrettyTable) -> None:
        city_data_prettytable.set_style(DOUBLE_BORDER)
        city_data_prettytable.vrules = FRAME
        city_data_prettytable.title = "Title"
        assert (
            city_data_prettytable.get_string().strip()
            == """
╔═════════════════════════════════════════════════╗
║                      Title                      ║
╠═════════════════════════════════════════════════╣
║ City name   Area   Population   Annual Rainfall ║
╠═════════════════════════════════════════════════╣
║  Adelaide   1295    1158259          600.5      ║
║  Brisbane   5905    1857594          1146.4     ║
║   Darwin    112      120900          1714.7     ║
║   Hobart    1357     205556          619.5      ║
║   Sydney    2058    4336374          1214.8     ║
║ Melbourne   1566    3806092          646.9      ║
║   Perth     5386    1554769          869.4      ║
╚═════════════════════════════════════════════════╝""".strip()
        )


class TestStyle:
    @pytest.mark.parametrize(
        "style, expected",
        [
            pytest.param(
                DEFAULT,
                """
+---+---------+---------+---------+
|   | Field 1 | Field 2 | Field 3 |
+---+---------+---------+---------+
| 1 | value 1 |  value2 |  value3 |
| 4 | value 4 |  value5 |  value6 |
| 7 | value 7 |  value8 |  value9 |
+---+---------+---------+---------+
""",
                id="DEFAULT",
            ),
            pytest.param(
                MARKDOWN,  # TODO fix
                """
|     | Field 1 | Field 2 | Field 3 |
| :-: | :-----: | :-----: | :-----: |
|  1  | value 1 |  value2 |  value3 |
|  4  | value 4 |  value5 |  value6 |
|  7  | value 7 |  value8 |  value9 |
""",
                id="MARKDOWN",
            ),
            pytest.param(
                MSWORD_FRIENDLY,
                """
|   | Field 1 | Field 2 | Field 3 |
| 1 | value 1 |  value2 |  value3 |
| 4 | value 4 |  value5 |  value6 |
| 7 | value 7 |  value8 |  value9 |
""",
                id="MSWORD_FRIENDLY",
            ),
            pytest.param(
                ORGMODE,
                """
|---+---------+---------+---------|
|   | Field 1 | Field 2 | Field 3 |
|---+---------+---------+---------|
| 1 | value 1 |  value2 |  value3 |
| 4 | value 4 |  value5 |  value6 |
| 7 | value 7 |  value8 |  value9 |
|---+---------+---------+---------|
""",
                id="ORGMODE",
            ),
            pytest.param(
                PLAIN_COLUMNS,
                """
         Field 1        Field 2        Field 3        
1        value 1         value2         value3        
4        value 4         value5         value6        
7        value 7         value8         value9
""",  # noqa: W291
                id="PLAIN_COLUMNS",
            ),
            pytest.param(
                RANDOM,
                """
'^^^^^'^^^^^^^^^^^'^^^^^^^^^^'^^^^^^^^^^'
%    1%    value 1%    value2%    value3%
'^^^^^'^^^^^^^^^^^'^^^^^^^^^^'^^^^^^^^^^'
%    4%    value 4%    value5%    value6%
'^^^^^'^^^^^^^^^^^'^^^^^^^^^^'^^^^^^^^^^'
%    7%    value 7%    value8%    value9%
'^^^^^'^^^^^^^^^^^'^^^^^^^^^^'^^^^^^^^^^'
""",
                id="RANDOM",
            ),
            pytest.param(
                DOUBLE_BORDER,
                """
╔═══╦═════════╦═════════╦═════════╗
║   ║ Field 1 ║ Field 2 ║ Field 3 ║
╠═══╬═════════╬═════════╬═════════╣
║ 1 ║ value 1 ║  value2 ║  value3 ║
║ 4 ║ value 4 ║  value5 ║  value6 ║
║ 7 ║ value 7 ║  value8 ║  value9 ║
╚═══╩═════════╩═════════╩═════════╝
""",
            ),
            pytest.param(
                SINGLE_BORDER,
                """
┌───┬─────────┬─────────┬─────────┐
│   │ Field 1 │ Field 2 │ Field 3 │
├───┼─────────┼─────────┼─────────┤
│ 1 │ value 1 │  value2 │  value3 │
│ 4 │ value 4 │  value5 │  value6 │
│ 7 │ value 7 │  value8 │  value9 │
└───┴─────────┴─────────┴─────────┘
""",
            ),
        ],
    )
    def test_style(self, style, expected) -> None:
        # Arrange
        t = helper_table()
        random.seed(1234)

        # Act
        t.set_style(style)

        # Assert
        result = t.get_string()
        assert result.strip() == expected.strip()

    def test_style_invalid(self) -> None:
        # Arrange
        t = helper_table()

        # Act / Assert
        # This is an hrule style, not a table style
        with pytest.raises(ValueError):
            t.set_style(ALL)

    @pytest.mark.parametrize(
        "style, expected",
        [
            pytest.param(
                MARKDOWN,
                """
| l |  c  | r | Align left | Align centre | Align right |
| :-| :-: |-: | :----------| :----------: |-----------: |
| 1 |  2  | 3 | value 1    |    value2    |      value3 |
| 4 |  5  | 6 | value 4    |    value5    |      value6 |
| 7 |  8  | 9 | value 7    |    value8    |      value9 |
""",
                id="MARKDOWN",
            ),
        ],
    )
    def test_style_align(self, style, expected) -> None:
        # Arrange
        t = PrettyTable(["l", "c", "r", "Align left", "Align centre", "Align right"])
        v = 1
        for row in range(3):
            # Some have spaces, some not, to help test padding columns of
            # different widths
            t.add_row([v, v + 1, v + 2, f"value {v}", f"value{v + 1}", f"value{v + 2}"])
            v += 3

        # Act
        t.set_style(style)
        t.align["l"] = t.align["Align left"] = "l"
        t.align["c"] = t.align["Align centre"] = "c"
        t.align["r"] = t.align["Align right"] = "r"

        # Assert
        result = t.get_string()
        assert result.strip() == expected.strip()


class TestCsvOutput:
    def test_csv_output(self) -> None:
        t = helper_table()
        assert t.get_csv_string(delimiter="\t", header=False) == (
            "1\tvalue 1\tvalue2\tvalue3\r\n"
            "4\tvalue 4\tvalue5\tvalue6\r\n"
            "7\tvalue 7\tvalue8\tvalue9\r\n"
        )
        assert t.get_csv_string() == (
            ",Field 1,Field 2,Field 3\r\n"
            "1,value 1,value2,value3\r\n"
            "4,value 4,value5,value6\r\n"
            "7,value 7,value8,value9\r\n"
        )


class TestLatexOutput:
    def test_latex_output(self) -> None:
        t = helper_table()
        assert t.get_latex_string() == (
            "\\begin{tabular}{cccc}\r\n"
            " & Field 1 & Field 2 & Field 3 \\\\\r\n"
            "1 & value 1 & value2 & value3 \\\\\r\n"
            "4 & value 4 & value5 & value6 \\\\\r\n"
            "7 & value 7 & value8 & value9 \\\\\r\n"
            "\\end{tabular}"
        )
        options = {"fields": ["Field 1", "Field 3"]}
        assert t.get_latex_string(**options) == (
            "\\begin{tabular}{cc}\r\n"
            "Field 1 & Field 3 \\\\\r\n"
            "value 1 & value3 \\\\\r\n"
            "value 4 & value6 \\\\\r\n"
            "value 7 & value9 \\\\\r\n"
            "\\end{tabular}"
        )

    def test_latex_output_formatted(self) -> None:
        t = helper_table()
        assert t.get_latex_string(format=True) == (
            "\\begin{tabular}{|c|c|c|c|}\r\n"
            "\\hline\r\n"
            " & Field 1 & Field 2 & Field 3 \\\\\r\n"
            "1 & value 1 & value2 & value3 \\\\\r\n"
            "4 & value 4 & value5 & value6 \\\\\r\n"
            "7 & value 7 & value8 & value9 \\\\\r\n"
            "\\hline\r\n"
            "\\end{tabular}"
        )

        options = {"fields": ["Field 1", "Field 3"]}
        assert t.get_latex_string(format=True, **options) == (
            "\\begin{tabular}{|c|c|}\r\n"
            "\\hline\r\n"
            "Field 1 & Field 3 \\\\\r\n"
            "value 1 & value3 \\\\\r\n"
            "value 4 & value6 \\\\\r\n"
            "value 7 & value9 \\\\\r\n"
            "\\hline\r\n"
            "\\end{tabular}"
        )

        options = {"vrules": FRAME}
        assert t.get_latex_string(format=True, **options) == (
            "\\begin{tabular}{|cccc|}\r\n"
            "\\hline\r\n"
            " & Field 1 & Field 2 & Field 3 \\\\\r\n"
            "1 & value 1 & value2 & value3 \\\\\r\n"
            "4 & value 4 & value5 & value6 \\\\\r\n"
            "7 & value 7 & value8 & value9 \\\\\r\n"
            "\\hline\r\n"
            "\\end{tabular}"
        )

        options = {"hrules": ALL}
        assert t.get_latex_string(format=True, **options) == (
            "\\begin{tabular}{|c|c|c|c|}\r\n"
            "\\hline\r\n"
            " & Field 1 & Field 2 & Field 3 \\\\\r\n"
            "\\hline\r\n"
            "1 & value 1 & value2 & value3 \\\\\r\n"
            "\\hline\r\n"
            "4 & value 4 & value5 & value6 \\\\\r\n"
            "\\hline\r\n"
            "7 & value 7 & value8 & value9 \\\\\r\n"
            "\\hline\r\n"
            "\\end{tabular}"
        )

    def test_latex_output_header(self) -> None:
        t = helper_table()
        assert t.get_latex_string(format=True, hrules=HEADER) == (
            "\\begin{tabular}{|c|c|c|c|}\r\n"
            " & Field 1 & Field 2 & Field 3 \\\\\r\n"
            "\\hline\r\n"
            "1 & value 1 & value2 & value3 \\\\\r\n"
            "4 & value 4 & value5 & value6 \\\\\r\n"
            "7 & value 7 & value8 & value9 \\\\\r\n"
            "\\end{tabular}"
        )


class TestJSONConstructor:
    def test_json_and_back(self, city_data_prettytable: PrettyTable) -> None:
        json_string = city_data_prettytable.get_json_string()
        new_table = from_json(json_string)
        assert new_table.get_string() == city_data_prettytable.get_string()


class TestHtmlConstructor:
    def test_html_and_back(self, city_data_prettytable: PrettyTable) -> None:
        html_string = city_data_prettytable.get_html_string()
        new_table = from_html(html_string)[0]
        assert new_table.get_string() == city_data_prettytable.get_string()

    def test_html_one_and_back(self, city_data_prettytable: PrettyTable) -> None:
        html_string = city_data_prettytable.get_html_string()
        new_table = from_html_one(html_string)
        assert new_table.get_string() == city_data_prettytable.get_string()

    def test_html_one_fail_on_many(self, city_data_prettytable: PrettyTable) -> None:
        html_string = city_data_prettytable.get_html_string()
        html_string += city_data_prettytable.get_html_string()
        with pytest.raises(ValueError):
            from_html_one(html_string)


@pytest.fixture
def japanese_pretty_table() -> PrettyTable:
    table = PrettyTable(["Kanji", "Hiragana", "English"])
    table.add_row(["神戸", "こうべ", "Kobe"])
    table.add_row(["京都", "きょうと", "Kyoto"])
    table.add_row(["長崎", "ながさき", "Nagasaki"])
    table.add_row(["名古屋", "なごや", "Nagoya"])
    table.add_row(["大阪", "おおさか", "Osaka"])
    table.add_row(["札幌", "さっぽろ", "Sapporo"])
    table.add_row(["東京", "とうきょう", "Tokyo"])
    table.add_row(["横浜", "よこはま", "Yokohama"])
    return table


@pytest.fixture
def emoji_pretty_table() -> PrettyTable:
    thunder1 = [
        '\033[38;5;226m _`/""\033[38;5;250m.-.    \033[0m',
        "\033[38;5;226m  ,\\_\033[38;5;250m(   ).  \033[0m",
        "\033[38;5;226m   /\033[38;5;250m(___(__) \033[0m",
        "\033[38;5;228;5m    ⚡\033[38;5;111;25mʻ ʻ\033[38;5;228;5m"
        "⚡\033[38;5;111;25mʻ ʻ \033[0m",
        "\033[38;5;111m    ʻ ʻ ʻ ʻ  \033[0m",
    ]
    thunder2 = [
        "\033[38;5;240;1m     .-.     \033[0m",
        "\033[38;5;240;1m    (   ).   \033[0m",
        "\033[38;5;240;1m   (___(__)  \033[0m",
        "\033[38;5;21;1m  ‚ʻ\033[38;5;228;5m⚡\033[38;5;21;25mʻ‚\033[38;5;228;5m"
        "⚡\033[38;5;21;25m‚ʻ   \033[0m",
        "\033[38;5;21;1m  ‚ʻ‚ʻ\033[38;5;228;5m⚡\033[38;5;21;25mʻ‚ʻ   \033[0m",
    ]
    table = PrettyTable(["Thunderbolt", "Lightning"])
    for i in range(len(thunder1)):
        table.add_row([thunder1[i], thunder2[i]])
    return table


class TestMultiPattern:
    @pytest.mark.parametrize(
        ["pt", "expected_output", "test_type"],
        [
            (
                lf("city_data_prettytable"),
                """
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+
""",
                "English Table",
            ),
            (
                lf("japanese_pretty_table"),
                """
+--------+------------+----------+
| Kanji  |  Hiragana  | English  |
+--------+------------+----------+
|  神戸  |   こうべ   |   Kobe   |
|  京都  |  きょうと  |  Kyoto   |
|  長崎  |  ながさき  | Nagasaki |
| 名古屋 |   なごや   |  Nagoya  |
|  大阪  |  おおさか  |  Osaka   |
|  札幌  |  さっぽろ  | Sapporo  |
|  東京  | とうきょう |  Tokyo   |
|  横浜  |  よこはま  | Yokohama |
+--------+------------+----------+

""",
                "Japanese table",
            ),
            (
                lf("emoji_pretty_table"),
                """
+-----------------+-----------------+
|   Thunderbolt   |    Lightning    |
+-----------------+-----------------+
|  \x1b[38;5;226m _`/""\x1b[38;5;250m.-.    \x1b[0m  |  \x1b[38;5;240;1m     .-.     \x1b[0m  |
|  \x1b[38;5;226m  ,\\_\x1b[38;5;250m(   ).  \x1b[0m  |  \x1b[38;5;240;1m    (   ).   \x1b[0m  |
|  \x1b[38;5;226m   /\x1b[38;5;250m(___(__) \x1b[0m  |  \x1b[38;5;240;1m   (___(__)  \x1b[0m  |
| \x1b[38;5;228;5m    ⚡\x1b[38;5;111;25mʻ ʻ\x1b[38;5;228;5m⚡\x1b[38;5;111;25mʻ ʻ \x1b[0m | \x1b[38;5;21;1m  ‚ʻ\x1b[38;5;228;5m⚡\x1b[38;5;21;25mʻ‚\x1b[38;5;228;5m⚡\x1b[38;5;21;25m‚ʻ   \x1b[0m |
|  \x1b[38;5;111m    ʻ ʻ ʻ ʻ  \x1b[0m  |  \x1b[38;5;21;1m  ‚ʻ‚ʻ\x1b[38;5;228;5m⚡\x1b[38;5;21;25mʻ‚ʻ   \x1b[0m |
+-----------------+-----------------+
            """,  # noqa: E501
                "Emoji table",
            ),
        ],
    )
    def test_multi_pattern_outputs(
        self, pt: PrettyTable, expected_output: str, test_type: str
    ) -> None:
        printed_table = pt.get_string()
        assert (
            printed_table.strip() == expected_output.strip()
        ), f"Error output for test output of type {test_type}"


def test_paginate() -> None:
    # Arrange
    t = helper_table(rows=7)
    expected_page_1 = """
+----+----------+---------+---------+
|    | Field 1  | Field 2 | Field 3 |
+----+----------+---------+---------+
| 1  | value 1  |  value2 |  value3 |
| 4  | value 4  |  value5 |  value6 |
| 7  | value 7  |  value8 |  value9 |
| 10 | value 10 | value11 | value12 |
+----+----------+---------+---------+
    """.strip()
    expected_page_2 = """
+----+----------+---------+---------+
|    | Field 1  | Field 2 | Field 3 |
+----+----------+---------+---------+
| 13 | value 13 | value14 | value15 |
| 16 | value 16 | value17 | value18 |
| 19 | value 19 | value20 | value21 |
+----+----------+---------+---------+
""".strip()

    # Act
    paginated = t.paginate(page_length=4)

    # Assert
    paginated = paginated.strip()
    assert paginated.startswith(expected_page_1)
    assert "\f" in paginated
    assert paginated.endswith(expected_page_2)

    # Act
    paginated = t.paginate(page_length=4, line_break="\n")

    # Assert
    assert "\f" not in paginated
    assert "\n" in paginated


def test_add_rows() -> None:
    """A table created with multiple add_row calls
    is the same as one created with a single add_rows
    """
    # Arrange
    table1 = PrettyTable(["A", "B", "C"])
    table2 = PrettyTable(["A", "B", "C"])
    table1.add_row([1, 2, 3])
    table1.add_row([4, 5, 6])
    rows = [
        [1, 2, 3],
        [4, 5, 6],
    ]

    # Act
    table2.add_rows(rows)

    # Assert
    assert str(table1) == str(table2)


def test_autoindex() -> None:
    """Testing that a table with a custom index row is
    equal to the one produced by the function
    .add_autoindex()
    """
    table1 = PrettyTable()
    table1.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
    table1.add_row(["Adelaide", 1295, 1158259, 600.5])
    table1.add_row(["Brisbane", 5905, 1857594, 1146.4])
    table1.add_row(["Darwin", 112, 120900, 1714.7])
    table1.add_row(["Hobart", 1357, 205556, 619.5])
    table1.add_row(["Sydney", 2058, 4336374, 1214.8])
    table1.add_row(["Melbourne", 1566, 3806092, 646.9])
    table1.add_row(["Perth", 5386, 1554769, 869.4])
    table1.add_autoindex(fieldname="Test")

    table2 = PrettyTable()
    table2.field_names = ["Test", "City name", "Area", "Population", "Annual Rainfall"]
    table2.add_row([1, "Adelaide", 1295, 1158259, 600.5])
    table2.add_row([2, "Brisbane", 5905, 1857594, 1146.4])
    table2.add_row([3, "Darwin", 112, 120900, 1714.7])
    table2.add_row([4, "Hobart", 1357, 205556, 619.5])
    table2.add_row([5, "Sydney", 2058, 4336374, 1214.8])
    table2.add_row([6, "Melbourne", 1566, 3806092, 646.9])
    table2.add_row([7, "Perth", 5386, 1554769, 869.4])

    assert str(table1) == str(table2)


@pytest.fixture(scope="function")
def unpadded_pt() -> PrettyTable:
    table = PrettyTable(header=False, padding_width=0)
    table.add_row("abc")
    table.add_row("def")
    table.add_row("g..")
    return table


class TestUnpaddedTable:
    def test_unbordered(self, unpadded_pt: PrettyTable) -> None:
        unpadded_pt.border = False
        result = unpadded_pt.get_string()
        expected = """
abc
def
g..
"""
        assert result.strip() == expected.strip()

    def test_bordered(self, unpadded_pt: PrettyTable) -> None:
        unpadded_pt.border = True
        result = unpadded_pt.get_string()
        expected = """
+-+-+-+
|a|b|c|
|d|e|f|
|g|.|.|
+-+-+-+
"""
        assert result.strip() == expected.strip()


class TestCustomFormatter:
    def test_init_custom_format_is_empty(self) -> None:
        table = PrettyTable()
        assert table.custom_format == {}

    def test_init_custom_format_set_value(self) -> None:
        table = PrettyTable(
            custom_format={"col1": (lambda col_name, value: f"{value:.2}")}
        )
        assert len(table.custom_format) == 1

    def test_init_custom_format_throw_error_is_not_callable(self) -> None:
        with pytest.raises(ValueError) as e:
            PrettyTable(custom_format={"col1": "{:.2}"})

        assert "Invalid value for custom_format.col1. Must be a function." in str(
            e.value
        )

    def test_can_set_custom_format_from_property_setter(self) -> None:
        table = PrettyTable()
        table.custom_format = {"col1": (lambda col_name, value: f"{value:.2}")}
        assert len(table.custom_format) == 1

    def test_set_custom_format_to_none_set_empty_dict(self) -> None:
        table = PrettyTable()
        table.custom_format = None
        assert len(table.custom_format) == 0
        assert isinstance(table.custom_format, dict)

    def test_set_custom_format_invalid_type_throw_error(self) -> None:
        table = PrettyTable()
        with pytest.raises(TypeError) as e:
            table.custom_format = "Some String"
        assert "The custom_format property need to be a dictionary or callable" in str(
            e.value
        )

    def test_use_custom_formatter_for_int(
        self, city_data_prettytable: PrettyTable
    ) -> None:
        city_data_prettytable.custom_format["Annual Rainfall"] = lambda n, v: f"{v:.2f}"
        assert (
            city_data_prettytable.get_string().strip()
            == """
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.50     |
|  Brisbane | 5905 |  1857594   |     1146.40     |
|   Darwin  | 112  |   120900   |     1714.70     |
|   Hobart  | 1357 |   205556   |      619.50     |
|   Sydney  | 2058 |  4336374   |     1214.80     |
| Melbourne | 1566 |  3806092   |      646.90     |
|   Perth   | 5386 |  1554769   |      869.40     |
+-----------+------+------------+-----------------+
""".strip()
        )

    def test_custom_format_multi_type(self) -> None:
        table = PrettyTable(["col_date", "col_str", "col_float", "col_int"])
        table.add_row([dt.date(2021, 1, 1), "January", 12345.12345, 12345678])
        table.add_row([dt.date(2021, 2, 1), "February", 54321.12345, 87654321])
        table.custom_format["col_date"] = lambda f, v: v.strftime("%d %b %Y")
        table.custom_format["col_float"] = lambda f, v: f"{v:.3f}"
        table.custom_format["col_int"] = lambda f, v: f"{v:,}"
        assert (
            table.get_string().strip()
            == """
+-------------+----------+-----------+------------+
|   col_date  | col_str  | col_float |  col_int   |
+-------------+----------+-----------+------------+
| 01 Jan 2021 | January  | 12345.123 | 12,345,678 |
| 01 Feb 2021 | February | 54321.123 | 87,654,321 |
+-------------+----------+-----------+------------+
""".strip()
        )

    def test_custom_format_multi_type_using_on_function(self) -> None:
        table = PrettyTable(["col_date", "col_str", "col_float", "col_int"])
        table.add_row([dt.date(2021, 1, 1), "January", 12345.12345, 12345678])
        table.add_row([dt.date(2021, 2, 1), "February", 54321.12345, 87654321])

        def my_format(col: str, value: Any) -> str:
            if col == "col_date":
                return value.strftime("%d %b %Y")
            if col == "col_float":
                return f"{value:.3f}"
            if col == "col_int":
                return f"{value:,}"
            return str(value)

        table.custom_format = my_format
        assert (
            table.get_string().strip()
            == """
+-------------+----------+-----------+------------+
|   col_date  | col_str  | col_float |  col_int   |
+-------------+----------+-----------+------------+
| 01 Jan 2021 | January  | 12345.123 | 12,345,678 |
| 01 Feb 2021 | February | 54321.123 | 87,654,321 |
+-------------+----------+-----------+------------+
""".strip()
        )


class TestRepr:
    def test_default_repr(self, row_prettytable: PrettyTable) -> None:
        assert row_prettytable.__str__() == row_prettytable.__repr__()

    def test_jupyter_repr(self, row_prettytable: PrettyTable) -> None:
        assert row_prettytable._repr_html_() == row_prettytable.get_html_string()


class TestMinTableWidth:
    @pytest.mark.parametrize(
        "loops, fields, desired_width, border, internal_border",
        [
            (15, ["Test table"], 20, True, False),
            (16, ["Test table"], 21, True, False),
            (18, ["Test table", "Test table 2"], 40, True, False),
            (19, ["Test table", "Test table 2"], 41, True, False),
            (21, ["Test table", "Test col 2", "Test col 3"], 50, True, False),
            (22, ["Test table", "Test col 2", "Test col 3"], 51, True, False),
            (19, ["Test table"], 20, False, False),
            (20, ["Test table"], 21, False, False),
            (25, ["Test table", "Test table 2"], 40, False, False),
            (26, ["Test table", "Test table 2"], 41, False, False),
            (25, ["Test table", "Test col 2", "Test col 3"], 50, False, False),
            (26, ["Test table", "Test col 2", "Test col 3"], 51, False, False),
            (18, ["Test table"], 20, False, True),
            (19, ["Test table"], 21, False, True),
            (23, ["Test table", "Test table 2"], 40, False, True),
            (24, ["Test table", "Test table 2"], 41, False, True),
            (22, ["Test table", "Test col 2", "Test col 3"], 50, False, True),
            (23, ["Test table", "Test col 2", "Test col 3"], 51, False, True),
        ],
    )
    def test_min_table_width(
        self, loops, fields, desired_width, border, internal_border
    ) -> None:
        for col_width in range(loops):
            x = prettytable.PrettyTable()
            x.border = border
            x.preserve_internal_border = internal_border
            x.field_names = fields
            x.add_row(["X" * col_width] + ["" for _ in range(len(fields) - 1)])
            x.min_table_width = desired_width
            t = x.get_string()
            if border is False and internal_border is False:
                assert [len(x) for x in t.split("\n")] == [desired_width, desired_width]
            elif border is False and internal_border is True:
                assert [len(x) for x in t.split("\n")] == [
                    desired_width,
                    desired_width - 1,
                    desired_width,
                ]
            else:
                assert [len(x) for x in t.split("\n")] == [
                    desired_width,
                    desired_width,
                    desired_width,
                    desired_width,
                    desired_width,
                ]


class TestMaxTableWidth:
    def test_max_table_width(self) -> None:
        table = PrettyTable()
        table.max_table_width = 5
        table.add_row([0])

        # FIXME: Table is wider than table.max_table_width
        assert (
            table.get_string().strip()
            == """
+----+
| Fi |
+----+
| 0  |
+----+
""".strip()
        )

    def test_max_table_width_wide(self) -> None:
        table = PrettyTable()
        table.max_table_width = 52
        table.add_row(
            [
                0,
                0,
                0,
                0,
                0,
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
                "nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam "
                "erat, sed diam voluptua",
            ]
        )

        assert (
            table.get_string().strip()
            == """
+---+---+---+---+---+------------------------------+
| F | F | F | F | F |           Field 6            |
+---+---+---+---+---+------------------------------+
| 0 | 0 | 0 | 0 | 0 | Lorem ipsum dolor sit amet,  |
|   |   |   |   |   | consetetur sadipscing elitr, |
|   |   |   |   |   |    sed diam nonumy eirmod    |
|   |   |   |   |   | tempor invidunt ut labore et |
|   |   |   |   |   | dolore magna aliquyam erat,  |
|   |   |   |   |   |      sed diam voluptua       |
+---+---+---+---+---+------------------------------+""".strip()
        )

    def test_max_table_width_wide2(self) -> None:
        table = PrettyTable()
        table.max_table_width = 70
        table.add_row(
            [
                "Lorem",
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam ",
                "ipsum",
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam ",
                "dolor",
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam ",
            ]
        )

        assert (
            table.get_string().strip()
            == """
+---+-----------------+---+-----------------+---+-----------------+
| F |     Field 2     | F |     Field 4     | F |     Field 6     |
+---+-----------------+---+-----------------+---+-----------------+
| L |   Lorem ipsum   | i |   Lorem ipsum   | d |   Lorem ipsum   |
| o | dolor sit amet, | p | dolor sit amet, | o | dolor sit amet, |
| r |    consetetur   | s |    consetetur   | l |    consetetur   |
| e |    sadipscing   | u |    sadipscing   | o |    sadipscing   |
| m | elitr, sed diam | m | elitr, sed diam | r | elitr, sed diam |
+---+-----------------+---+-----------------+---+-----------------+""".strip()
        )

    def test_max_table_width_wide_vrules_frame(self) -> None:
        table = PrettyTable()
        table.max_table_width = 52
        table.vrules = FRAME
        table.add_row(
            [
                0,
                0,
                0,
                0,
                0,
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
                "nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam "
                "erat, sed diam voluptua",
            ]
        )

        assert (
            table.get_string().strip()
            == """
+--------------------------------------------------+
| F   F   F   F   F             Field 6            |
+--------------------------------------------------+
| 0   0   0   0   0   Lorem ipsum dolor sit amet,  |
|                     consetetur sadipscing elitr, |
|                        sed diam nonumy eirmod    |
|                     tempor invidunt ut labore et |
|                     dolore magna aliquyam erat,  |
|                          sed diam voluptua       |
+--------------------------------------------------+""".strip()
        )

    def test_max_table_width_wide_vrules_none(self) -> None:
        table = PrettyTable()
        table.max_table_width = 52
        table.vrules = NONE
        table.add_row(
            [
                0,
                0,
                0,
                0,
                0,
                "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam "
                "nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam "
                "erat, sed diam voluptua",
            ]
        )

        assert (
            table.get_string().strip()
            == """
----------------------------------------------------
  F   F   F   F   F             Field 6             
----------------------------------------------------
  0   0   0   0   0   Lorem ipsum dolor sit amet,   
                      consetetur sadipscing elitr,  
                         sed diam nonumy eirmod     
                      tempor invidunt ut labore et  
                      dolore magna aliquyam erat,   
                           sed diam voluptua        
----------------------------------------------------""".strip()  # noqa: W291
        )


class TestRowEndSection:
    def test_row_end_section(self) -> None:
        table = PrettyTable()
        v = 1
        for row in range(4):
            if row % 2 == 0:
                table.add_row(
                    [f"value {v}", f"value{v+1}", f"value{v+2}"], divider=True
                )
            else:
                table.add_row(
                    [f"value {v}", f"value{v+1}", f"value{v+2}"], divider=False
                )
            v += 3
        table.del_row(0)
        assert (
            table.get_string().strip()
            == """
+----------+---------+---------+
| Field 1  | Field 2 | Field 3 |
+----------+---------+---------+
| value 4  |  value5 |  value6 |
| value 7  |  value8 |  value9 |
+----------+---------+---------+
| value 10 | value11 | value12 |
+----------+---------+---------+
""".strip()
        )


class TestClearing:
    def test_clear_rows(self, row_prettytable: PrettyTable) -> None:
        t = helper_table()
        t.add_row([0, "a", "b", "c"], divider=True)
        t.clear_rows()
        assert t.rows == []
        assert t.dividers == []
        assert t.field_names == ["", "Field 1", "Field 2", "Field 3"]

    def test_clear(self, row_prettytable: PrettyTable) -> None:
        t = helper_table()
        t.add_row([0, "a", "b", "c"], divider=True)
        t.clear()
        assert t.rows == []
        assert t.dividers == []
        assert t.field_names == []


class TestPreservingInternalBorders:
    def test_internal_border_preserved(self) -> None:
        pt = helper_table(3)
        pt.border = False
        pt.preserve_internal_border = True

        assert (
            pt.get_string().strip()
            == """
   | Field 1 | Field 2 | Field 3  
---+---------+---------+---------
 1 | value 1 |  value2 |  value3  
 4 | value 4 |  value5 |  value6  
 7 | value 7 |  value8 |  value9  
""".strip()  # noqa: W291
        )

    def test_internal_border_preserved_latex(self) -> None:
        pt = helper_table(3)
        pt.border = False
        pt.format = True
        pt.preserve_internal_border = True

        assert pt.get_latex_string().strip() == (
            "\\begin{tabular}{c|c|c|c}\r\n"
            " & Field 1 & Field 2 & Field 3 \\\\\r\n"
            "1 & value 1 & value2 & value3 \\\\\r\n"
            "4 & value 4 & value5 & value6 \\\\\r\n"
            "7 & value 7 & value8 & value9 \\\\\r\n"
            "\\end{tabular}"
        )

    def test_internal_border_preserved_html(self) -> None:
        pt = helper_table(3)
        pt.format = True
        pt.border = False
        pt.preserve_internal_border = True

        assert (
            pt.get_html_string().strip()
            == """
<table rules="cols">
    <thead>
        <tr>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center"></th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 1</th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 2</th>
            <th style="padding-left: 1em; padding-right: 1em; text-align: center">Field 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">1</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 1</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value2</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value3</td>
        </tr>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">4</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 4</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value5</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value6</td>
        </tr>
        <tr>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">7</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value 7</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value8</td>
            <td style="padding-left: 1em; padding-right: 1em; text-align: center; vertical-align: top">value9</td>
        </tr>
    </tbody>
</table>
""".strip()  # noqa: E501
        )


class TestGeneralOutput:
    def test_copy(self) -> None:
        # Arrange
        t = helper_table()

        # Act
        t_copy = t.copy()

        # Assert
        assert t.get_string() == t_copy.get_string()

    def test_text(self) -> None:
        t = helper_table()
        assert t.get_formatted_string("text") == t.get_string()
        # test with default arg, too
        assert t.get_formatted_string() == t.get_string()
        # args passed through
        assert t.get_formatted_string(border=False) == t.get_string(border=False)

    def test_csv(self) -> None:
        t = helper_table()
        assert t.get_formatted_string("csv") == t.get_csv_string()
        # args passed through
        assert t.get_formatted_string("csv", border=False) == t.get_csv_string(
            border=False
        )

    def test_json(self) -> None:
        t = helper_table()
        assert t.get_formatted_string("json") == t.get_json_string()
        # args passed through
        assert t.get_formatted_string("json", border=False) == t.get_json_string(
            border=False
        )

    def test_html(self) -> None:
        t = helper_table()
        assert t.get_formatted_string("html") == t.get_html_string()
        # args passed through
        assert t.get_formatted_string("html", border=False) == t.get_html_string(
            border=False
        )

    def test_latex(self) -> None:
        t = helper_table()
        assert t.get_formatted_string("latex") == t.get_latex_string()
        # args passed through
        assert t.get_formatted_string("latex", border=False) == t.get_latex_string(
            border=False
        )

    def test_invalid(self) -> None:
        t = helper_table()
        with pytest.raises(ValueError):
            t.get_formatted_string("pdf")