File: test_license_expression.py

package info (click to toggle)
python-license-expression 30.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,464 kB
  • sloc: python: 5,968; sh: 315; makefile: 45
file content (2390 lines) | stat: -rw-r--r-- 100,983 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/license-expression for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import json
import pathlib
import sys
from collections import namedtuple
from os.path import abspath
from os.path import join
from os.path import dirname
from unittest import TestCase

from boolean.boolean import PARSE_UNBALANCED_CLOSING_PARENS
from boolean.boolean import PARSE_INVALID_SYMBOL_SEQUENCE

from license_expression import PARSE_INVALID_EXPRESSION
from license_expression import PARSE_INVALID_NESTING
from license_expression import PARSE_INVALID_EXCEPTION
from license_expression import PARSE_INVALID_SYMBOL_AS_EXCEPTION
from license_expression import PARSE_INVALID_OPERATOR_SEQUENCE

from license_expression import ExpressionError
from license_expression import Keyword
from license_expression import Licensing
from license_expression import LicenseExpression
from license_expression import LicenseSymbol
from license_expression import LicenseSymbolLike
from license_expression import LicenseWithExceptionSymbol
from license_expression import ParseError
from license_expression import Token

from license_expression import build_token_groups_for_with_subexpression
from license_expression import validate_symbols

from license_expression import TOKEN_AND
from license_expression import TOKEN_LPAR
from license_expression import TOKEN_OR
from license_expression import TOKEN_RPAR
from license_expression import TOKEN_SYMBOL
from license_expression import TOKEN_WITH
from license_expression import build_licensing
from license_expression import build_spdx_licensing
from license_expression import combine_expressions
from license_expression import get_license_index


def _parse_error_as_dict(pe):
    """
    Return a dict for a ParseError.
    """
    return dict(
        token_type=pe.token_type,
        token_string=pe.token_string,
        position=pe.position,
        error_code=pe.error_code,
    )


class LicenseSymbolTest(TestCase):

    def test_LicenseSymbol(self):
        sym1 = LicenseSymbol('MIT', ['MIT license'])
        assert sym1 == sym1
        assert 'MIT' == sym1.key
        assert ('MIT license',) == sym1.aliases

        sym2 = LicenseSymbol('mit', ['MIT license'])
        assert 'mit' == sym2.key
        assert ('MIT license',) == sym2.aliases
        assert not sym2.is_exception
        assert sym1 != sym2
        assert sym1 is not sym2

        sym3 = LicenseSymbol('mit', ['MIT license'], is_exception=True)
        assert 'mit' == sym3.key
        assert ('MIT license',) == sym3.aliases
        assert sym3.is_exception
        assert sym2 != sym3

        sym4 = LicenseSymbol('mit', ['MIT license'])
        assert 'mit' == sym4.key
        assert ('MIT license',) == sym4.aliases
        # symbol equality is based ONLY on the key
        assert sym2 == sym4
        assert sym1 != sym4

        sym5 = LicenseWithExceptionSymbol(sym2, sym3)
        assert sym2 == sym5.license_symbol
        assert sym3 == sym5.exception_symbol

        sym6 = LicenseWithExceptionSymbol(sym4, sym3)
        # symbol euqality is based ONLY on the key
        assert sym5 == sym6


class LicensingTest(TestCase):

    def test_Licensing_create(self):
        Licensing()
        Licensing(None)
        Licensing(list())


class LicensingTokenizeWithoutSymbolsTest(TestCase):

    def test_tokenize_plain1(self):
        licensing = Licensing()
        expected = [
            (TOKEN_LPAR, '(', 1),
            (LicenseSymbol(key='mit'), 'mit', 3),
            (TOKEN_RPAR, ')', 7),
            (TOKEN_AND, 'and', 9),
            (LicenseSymbol(key='gpl'), 'gpl', 13)
        ]
        assert list(licensing.tokenize(' ( mit ) and gpl')) == expected

    def test_tokenize_plain2(self):
        licensing = Licensing()
        expected = [
            (TOKEN_LPAR, '(', 0),
            (LicenseSymbol(key='mit'), 'mit', 1),
            (TOKEN_AND, 'and', 5),
            (LicenseSymbol(key='gpl'), 'gpl', 9),
            (TOKEN_RPAR, ')', 12)
        ]
        assert list(licensing.tokenize('(mit and gpl)')) == expected

    def test_tokenize_plain3(self):
        licensing = Licensing()
        expected = [
            (LicenseSymbol(key='mit'), 'mit', 0),
            (TOKEN_AND, 'AND', 4),
            (LicenseSymbol(key='gpl'), 'gpl', 8),
            (TOKEN_OR, 'or', 12),
            (LicenseSymbol(key='gpl'), 'gpl', 15)
        ]
        assert list(licensing.tokenize('mit AND gpl or gpl')) == expected

    def test_tokenize_plain4(self):
        licensing = Licensing()
        expected = [
            (TOKEN_LPAR, '(', 0),
            (TOKEN_LPAR, '(', 1),
            (LicenseSymbol(key=u'l-a+'), 'l-a+', 2),
            (TOKEN_AND, 'AND', 7),
            (LicenseSymbol(key=u'l-b'), 'l-b', 11),
            (TOKEN_RPAR, ')', 14),
            (TOKEN_OR, 'OR', 16),
            (TOKEN_LPAR, '(', 19),
            (LicenseSymbol(key='l-c+'), 'l-c+', 20),
            (TOKEN_RPAR, ')', 24),
            (TOKEN_RPAR, ')', 25)
        ]
        assert list(licensing.tokenize('((l-a+ AND l-b) OR (l-c+))')) == expected

    def test_tokenize_plain5(self):
        licensing = Licensing()
        expected = [
            (TOKEN_LPAR, '(', 0),
            (TOKEN_LPAR, '(', 1),
            (LicenseSymbol(key='l-a+'), 'l-a+', 2),
            (TOKEN_AND, 'AND', 7),
            (LicenseSymbol(key='l-b'), 'l-b', 11),
            (TOKEN_RPAR, ')', 14),
            (TOKEN_OR, 'OR', 16),
            (TOKEN_LPAR, '(', 19),
            (LicenseSymbol(key='l-c+'), 'l-c+', 20),
            (TOKEN_RPAR, ')', 24),
            (TOKEN_RPAR, ')', 25),
            (TOKEN_AND, 'and', 27),
            (LicenseWithExceptionSymbol(
                license_symbol=LicenseSymbol(key='gpl'),
                exception_symbol=LicenseSymbol(key='classpath')),
             'gpl with classpath', 31
            )
        ]
        tokens = licensing.tokenize(
            '((l-a+ AND l-b) OR (l-c+)) and gpl with classpath'
        )
        assert list(tokens) == expected


class LicensingTokenizeWithSymbolsTest(TestCase):

    def get_symbols_and_licensing(self):
        gpl_20 = LicenseSymbol('GPL-2.0', ['The GNU GPL 20'])
        gpl_20_plus = LicenseSymbol('gpl-2.0+',
            ['The GNU GPL 20 or later', 'GPL-2.0 or later', 'GPL v2.0 or later'])
        lgpl_21 = LicenseSymbol('LGPL-2.1', ['LGPL v2.1'])
        mit = LicenseSymbol('MIT', ['MIT license'])
        symbols = [gpl_20, gpl_20_plus, lgpl_21, mit]
        licensing = Licensing(symbols)
        return gpl_20, gpl_20_plus, lgpl_21, mit, licensing

    def test_tokenize_1_with_symbols(self):
        gpl_20, _gpl_20_plus, lgpl_21, mit, licensing = self.get_symbols_and_licensing()

        result = licensing.tokenize('The GNU GPL 20 or LGPL v2.1 AND MIT license ')
        #                                      111111111122222222223333333333444
        #                            0123456789012345678901234567890123456789012

        expected = [
            (gpl_20, 'The GNU GPL 20', 0),
            (TOKEN_OR, 'or', 15),
            (lgpl_21, 'LGPL v2.1', 18),
            (TOKEN_AND, 'AND', 28),
            (mit, 'MIT license', 32)
        ]
        assert list(result) == expected

    def test_tokenize_1_no_symbols(self):
        licensing = Licensing()

        result = licensing.tokenize('The GNU GPL 20 or LGPL v2.1 AND MIT license')

        expected = [
            (LicenseSymbol(u'The GNU GPL 20'), 'The GNU GPL 20', 0),
            (TOKEN_OR, 'or', 15),
            (LicenseSymbol(u'LGPL v2.1'), 'LGPL v2.1', 18),
            (TOKEN_AND, 'AND', 28),
            (LicenseSymbol(u'MIT license'), 'MIT license', 32)
        ]

        assert list(result) == expected

    def test_tokenize_with_trailing_unknown(self):
        gpl_20, _gpl_20_plus, lgpl_21, _mit, licensing = self.get_symbols_and_licensing()
        result = licensing.tokenize('The GNU GPL 20 or LGPL-2.1 and mit2')
        expected = [
            (gpl_20, 'The GNU GPL 20', 0),
            (TOKEN_OR, 'or', 15),
            (lgpl_21, 'LGPL-2.1', 18),
            (TOKEN_AND, 'and', 27),
            (LicenseSymbol(key='mit2'), 'mit2', 31),
        ]
        assert list(result) == expected

    def test_tokenize_3(self):
        gpl_20, gpl_20_plus, lgpl_21, mit, licensing = self.get_symbols_and_licensing()

        result = licensing.tokenize('The GNU GPL 20 or later or (LGPL-2.1 and mit) or The GNU GPL 20 or mit')
        expected = [
            (gpl_20_plus, 'The GNU GPL 20 or later', 0),
            (TOKEN_OR, 'or', 24),
            (TOKEN_LPAR, '(', 27),
            (lgpl_21, 'LGPL-2.1', 28),
            (TOKEN_AND, 'and', 37),
            (mit, 'mit', 41),
            (TOKEN_RPAR, ')', 44),
            (TOKEN_OR, 'or', 46),
            (gpl_20, 'The GNU GPL 20', 49),
            (2, 'or', 64),
            (mit, 'mit', 67)
        ]
        assert list(result) == expected

    def test_tokenize_unknown_as_trailing_single_attached_character(self):
        symbols = [LicenseSymbol('MIT', ['MIT license'])]
        l = Licensing(symbols)
        result = list(l.tokenize('mit2'))
        expected = [
            (LicenseSymbol(u'mit2'), 'mit2', 0),
        ]
        assert result == expected

    def test_tokenize_with_unknown_symbol_containing_known_symbol_leading(self):
        l = Licensing(['gpl-2.0'])
        result = list(l.tokenize('gpl-2.0 AND gpl-2.0-plus', strict=False))
        result = [s for s, _, _ in result]
        expected = [
            LicenseSymbol(key='gpl-2.0'),
            TOKEN_AND,
            LicenseSymbol(key='gpl-2.0-plus'),
        ]
        assert result == expected

    def test_tokenize_with_unknown_symbol_containing_known_symbol_contained(self):
        l = Licensing(['gpl-2.0'])
        result = list(l.tokenize('gpl-2.0 WITH exception-gpl-2.0-plus', strict=False))
        result = [s for s, _, _ in result]
        expected = [
            LicenseWithExceptionSymbol(
                LicenseSymbol(u'gpl-2.0'),
                LicenseSymbol(u'exception-gpl-2.0-plus')
            )
        ]
        assert result == expected

    def test_tokenize_with_unknown_symbol_containing_known_symbol_trailing(self):
        l = Licensing(['gpl-2.0'])
        result = list(l.tokenize('gpl-2.0 AND exception-gpl-2.0', strict=False))
        result = [s for s, _, _ in result]
        expected = [
            LicenseSymbol(u'gpl-2.0'),
            TOKEN_AND,
            LicenseSymbol(u'exception-gpl-2.0')
        ]
        assert result == expected


class LicensingParseTest(TestCase):

    def test_parse_does_not_raise_error_for_empty_expression(self):
        licensing = Licensing()
        assert None == licensing.parse('')

    def test_parse(self):
        expression = ' ( (( gpl and bsd ) or lgpl)  and gpl-exception) '
        expected = '((gpl AND bsd) OR lgpl) AND gpl-exception'
        licensing = Licensing()
        self.assertEqual(expected, str(licensing.parse(expression)))

    def test_parse_raise_ParseError(self):
        expression = ' ( (( gpl and bsd ) or lgpl)  and gpl-exception)) '
        licensing = Licensing()
        try:
            licensing.parse(expression)
            self.fail('ParseError should be raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_UNBALANCED_CLOSING_PARENS,
                'position': 48,
                'token_string': ')',
                'token_type': TOKEN_RPAR
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_raise_ExpressionError_when_validating(self):
        expression = 'gpl and bsd or lgpl with exception'
        licensing = Licensing()
        try:
            licensing.parse(expression, validate=True)
            self.fail('Exception not raised')
        except ExpressionError as ee:
            assert 'Unknown license key(s): gpl, bsd, lgpl, exception' == str(ee)

    def test_parse_raise_ParseError_when_validating_strict(self):
        expression = 'gpl and bsd or lgpl with exception'
        licensing = Licensing()
        try:
            licensing.parse(expression, validate=True, strict=True)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_SYMBOL_AS_EXCEPTION,
                'position': 25,
                'token_string': 'exception',
                'token_type': TOKEN_SYMBOL
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_raise_ParseError_when_strict_no_validate(self):
        expression = 'gpl and bsd or lgpl with exception'
        licensing = Licensing()
        try:
            licensing.parse(expression, validate=False, strict=True)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_SYMBOL_AS_EXCEPTION,
                'position': 25,
                'token_string': 'exception',
                'token_type': TOKEN_SYMBOL
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_raise_ExpressionError_when_validating_strict_with_unknown(self):
        expression = 'gpl and bsd or lgpl with exception'
        licensing = Licensing(symbols=[LicenseSymbol('exception', is_exception=True)])
        try:
            licensing.parse(expression, validate=True, strict=True)
        except ExpressionError as ee:
            assert 'Unknown license key(s): gpl, bsd, lgpl' == str(ee)

    def test_parse_in_strict_mode_for_solo_symbol(self):
        expression = 'lgpl'
        licensing = Licensing()
        licensing.parse(expression, strict=True)

    def test_parse_invalid_expression_raise_exception(self):
        licensing = Licensing()
        expr = 'wrong'
        licensing.parse(expr)

    def test_parse_not_invalid_expression_rais_not_exception(self):
        licensing = Licensing()
        expr = 'l-a AND none'
        licensing.parse(expr)

    def test_parse_invalid_expression_raise_exception3(self):
        licensing = Licensing()
        expr = '(l-a + AND l-b'
        try:
            licensing.parse(expr)
            self.fail("Exception not raised when validating '%s'" % expr)
        except ParseError:
            pass

    def test_parse_invalid_expression_raise_exception4(self):
        licensing = Licensing()
        expr = '(l-a + AND l-b))'
        try:
            licensing.parse(expr)
            self.fail("Exception not raised when validating '%s'" % expr)
        except ParseError:
            pass

    def test_parse_invalid_expression_raise_exception5(self):
        licensing = Licensing()
        expr = 'l-a AND'
        try:
            licensing.parse(expr)
            self.fail("Exception not raised when validating '%s'" % expr)
        except ExpressionError as ee:
            assert 'AND requires two or more licenses as in: MIT AND BSD' == str(ee)

    def test_parse_invalid_expression_raise_exception6(self):
        licensing = Licensing()
        expr = 'OR l-a'
        try:
            licensing.parse(expr)
            self.fail("Exception not raised when validating '%s'" % expr)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 0,
                'token_string': 'OR',
                'token_type': TOKEN_OR
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_not_invalid_expression_raise_no_exception2(self):
        licensing = Licensing()
        expr = '+l-a'
        licensing.parse(expr)

    def test_parse_can_parse(self):
        licensing = Licensing()
        expr = ' GPL-2.0 or LGPL2.1 and mit '
        parsed = licensing.parse(expr)
        gpl2 = LicenseSymbol('GPL-2.0')
        lgpl = LicenseSymbol('LGPL2.1')
        mit = LicenseSymbol('mit')
        expected = [gpl2, lgpl, mit]
        self.assertEqual(expected, licensing.license_symbols(parsed))
        self.assertEqual(expected, licensing.license_symbols(expr))
        self.assertEqual('GPL-2.0 OR (LGPL2.1 AND mit)', str(parsed))

        expected = licensing.OR(gpl2, licensing.AND(lgpl, mit))
        assert parsed == expected

    def test_parse_errors_catch_invalid_nesting(self):
        licensing = Licensing()
        try:
            licensing.parse('mit (and LGPL 2.1)')
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_NESTING,
                'position': 4,
                'token_string': '(',
                'token_type': TOKEN_LPAR
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_errors_catch_invalid_expression_with_bare_and(self):
        licensing = Licensing()
        try:
            licensing.parse('and')
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 0,
                'token_string': 'and',
                'token_type': TOKEN_AND
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_errors_catch_invalid_expression_with_or_and_no_other(self):
        licensing = Licensing()
        try:
            licensing.parse('or that')
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 0,
                'token_string': 'or',
                'token_type': TOKEN_OR
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_errors_catch_invalid_expression_with_empty_parens(self):
        licensing = Licensing()
        try:
            licensing.parse('with ( )this')
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_EXPRESSION,
                'position': 0,
                'token_string': 'with',
                'token_type': TOKEN_WITH
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_errors_catch_invalid_non_unicode_byte_strings_on_python3(self):
        py2 = sys.version_info[0] == 2
        py3 = sys.version_info[0] == 3

        licensing = Licensing()

        if py2:
            extra_bytes = bytes(chr(0) + chr(12) + chr(255))
            try:
                licensing.parse('mit (and LGPL 2.1)'.encode('utf-8') + extra_bytes)
                self.fail('Exception not raised')
            except ExpressionError as ee:
                assert str(ee).startswith('expression must be a string and')

        if py3:
            extra_bytes = bytes(chr(0) + chr(12) + chr(255), encoding='utf-8')
            try:
                licensing.parse('mit (and LGPL 2.1)'.encode('utf-8') + extra_bytes)
                self.fail('Exception not raised')
            except ExpressionError as ee:
                assert str(ee).startswith('Invalid license key')

    def test_parse_errors_does_not_raise_error_on_plain_non_unicode_raw_string(self):
        # plain non-unicode string does not raise error
        licensing = Licensing()
        x = licensing.parse(r'mit and (LGPL-2.1)')
        self.assertTrue(isinstance(x, LicenseExpression))

    def test_parse_simplify_and_contain_and_equal(self):
        licensing = Licensing()

        expr = licensing.parse(' GPL-2.0 or LGPL2.1 and mit ')

        expr2 = licensing.parse(' (mit and LGPL2.1) or GPL-2.0 ')
        self.assertEqual(expr2.simplify(), expr.simplify())
        self.assertEqual(expr2, expr)

        expr3 = licensing.parse('mit and LGPL2.1')
        self.assertTrue(expr3 in expr2)

    def test_parse_simplify_no_sort(self):
        licensing = Licensing()
        expr = licensing.parse('gpl-2.0 OR apache-2.0')
        expr2 = licensing.parse('apache-2.0 OR gpl-2.0')

        self.assertEqual(expr, expr2)
        self.assertEqual(expr.simplify(), expr2.simplify())
        self.assertEqual(expr.simplify(sort=False), expr2.simplify())
        self.assertNotEqual(expr.simplify(sort=False).pretty(), expr2.pretty())

    def test_license_expression_is_equivalent(self):
        lic = Licensing()
        is_equiv = lic.is_equivalent

        self.assertTrue(is_equiv(lic.parse('mit AND gpl'), lic.parse('mit AND gpl')))
        self.assertTrue(is_equiv(lic.parse('mit AND gpl'), lic.parse('gpl AND mit')))
        self.assertTrue(is_equiv(lic.parse('mit AND gpl and apache'), lic.parse('apache and gpl AND mit')))
        self.assertTrue(is_equiv(lic.parse('mit AND (gpl AND apache)'), lic.parse('(mit AND gpl) AND apache')))

        # same but without parsing:
        self.assertTrue(is_equiv('mit AND gpl', 'mit AND gpl'))
        self.assertTrue(is_equiv('mit AND gpl', 'gpl AND mit'))
        self.assertTrue(is_equiv('mit AND gpl and apache', 'apache and gpl AND mit'))
        self.assertTrue(is_equiv('mit AND (gpl AND apache)', '(mit AND gpl) AND apache'))

        # Real-case example of generated expression vs. stored expression:
        ex1 = '''Commercial
            AND apache-1.1 AND apache-2.0 AND aslr AND bsd-new
            AND cpl-1.0 AND epl-1.0
            AND ibm-icu AND ijg AND jdom AND lgpl-2.1
            AND mit-open-group AND mpl-1.1 AND sax-pd AND unicode AND w3c AND
            w3c-documentation'''

        ex2 = '''
            apache-1.1 AND apache-2.0 AND aslr AND bsd-new
            AND cpl-1.0 AND epl-1.0
            AND lgpl-2.1 AND ibm-icu AND ijg
            AND jdom AND mit-open-group
            AND mpl-1.1 AND Commercial AND sax-pd AND unicode
            AND w3c-documentation AND w3c'''

        self.assertTrue(is_equiv(lic.parse(ex1), lic.parse(ex2)))
        self.assertFalse(is_equiv(lic.parse('mit AND gpl'), lic.parse('mit OR gpl')))
        self.assertFalse(is_equiv(lic.parse('mit AND gpl'), lic.parse('gpl OR mit')))

    def test_license_expression_license_keys(self):
        licensing = Licensing()
        assert ['mit', 'gpl'] == licensing.license_keys(licensing.parse(' ( mit ) and gpl'))
        assert ['mit', 'gpl'] == licensing.license_keys(licensing.parse('(mit and gpl)'))
        # these two are surprising for now: this is because the expression is a
        # logical expression so the order may be different on more complex expressions
        assert ['mit', 'gpl'] == licensing.license_keys(licensing.parse('mit AND gpl or gpl'))
        assert ['l-a+', 'l-b', '+l-c'] == licensing.license_keys(licensing.parse('((l-a+ AND l-b) OR (+l-c))'))
        # same without parsing
        assert ['mit', 'gpl'] == licensing.license_keys('mit AND gpl or gpl')
        assert ['l-a+', 'l-b', 'l-c+'] == licensing.license_keys('((l-a+ AND l-b) OR (l-c+))')

    def test_end_to_end(self):
        # these were formerly doctest ported to actual real code tests here
        l = Licensing()
        expr = l.parse(' GPL-2.0 or LGPL-2.1 and mit ')
        expected = 'GPL-2.0 OR (LGPL-2.1 AND mit)'
        assert str(expr) == expected

        expected = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LGPL-2.1'),
            LicenseSymbol('mit'),
        ]
        assert l.license_symbols(expr) == expected

    def test_pretty(self):
        l = Licensing()
        expr = l.parse(' GPL-2.0 or LGPL2.1 and mit ')

        expected = '''OR(
  LicenseSymbol('GPL-2.0'),
  AND(
    LicenseSymbol('LGPL2.1'),
    LicenseSymbol('mit')
  )
)'''
        assert expr.pretty() == expected

    def test_simplify_and_contains(self):
        l = Licensing()

        expr = l.parse(' GPL-2.0 or LGPL2.1 and mit ')
        expr2 = l.parse(' GPL-2.0 or (mit and LGPL2.1) ')
        assert expr2.simplify() == expr.simplify()
        expr3 = l.parse('mit and LGPL2.1')
        assert expr3 in expr2

    def test_dedup_expressions_can_be_simplified_1(self):
        l = Licensing()
        exp = 'mit OR mit AND apache-2.0 AND bsd-new OR mit'
        result = l.dedup(exp)
        expected = l.parse('mit OR (mit AND apache-2.0 AND bsd-new)')
        assert result == expected

    def test_dedup_expressions_can_be_simplified_2(self):
        l = Licensing()
        exp = 'mit AND (mit OR bsd-new) AND mit OR mit'
        result = l.dedup(exp)
        expected = l.parse('(mit AND (mit OR bsd-new)) OR mit')
        assert result == expected

    def test_dedup_expressions_multiple_occurrences(self):
        l = Licensing()
        exp = ' GPL-2.0 or (mit and LGPL-2.1) or bsd Or GPL-2.0  or (mit and LGPL-2.1)'
        result = l.dedup(exp)
        expected = l.parse('GPL-2.0 OR (mit AND LGPL-2.1) OR bsd')
        assert result == expected

    def test_dedup_expressions_cannot_be_simplified(self):
        l = Licensing()
        exp = l.parse('mit AND (mit OR bsd-new)')
        result = l.dedup(exp)
        expected = l.parse('mit AND (mit OR bsd-new)')
        assert result == expected

    def test_dedup_expressions_single_license(self):
        l = Licensing()
        exp = l.parse('mit')
        result = l.dedup(exp)
        expected = l.parse('mit')
        assert result == expected

    def test_dedup_expressions_WITH(self):
        l = Licensing()
        exp = l.parse('gpl-2.0 with autoconf-exception-2.0')
        result = l.dedup(exp)
        expected = l.parse('gpl-2.0 with autoconf-exception-2.0')
        assert result == expected

    def test_dedup_expressions_WITH_OR(self):
        l = Licensing()
        exp = l.parse('gpl-2.0 with autoconf-exception-2.0 OR gpl-2.0')
        result = l.dedup(exp)
        expected = l.parse('gpl-2.0 with autoconf-exception-2.0 OR gpl-2.0')
        assert result == expected

    def test_dedup_expressions_WITH_AND(self):
        l = Licensing()
        exp = l.parse('gpl-2.0 AND gpl-2.0 with autoconf-exception-2.0 AND gpl-2.0')
        result = l.dedup(exp)
        expected = l.parse('gpl-2.0 AND gpl-2.0 with autoconf-exception-2.0')
        assert result == expected

    def test_dedup_licensexpressions_can_be_simplified_3(self):
        l = Licensing()
        exp = l.parse('mit AND mit')
        result = l.dedup(exp)
        expected = l.parse('mit')
        assert result == expected

    def test_dedup_licensexpressions_works_with_subexpressions(self):
        l = Licensing()
        exp = l.parse('(mit OR gpl-2.0) AND mit AND bsd-new AND (mit OR gpl-2.0)')
        result = l.dedup(exp)
        expected = l.parse('(mit OR gpl-2.0) AND mit AND bsd-new')
        assert result == expected

    def test_simplify_and_equivalent_and_contains(self):
        l = Licensing()
        expr2 = l.parse(' GPL-2.0 or (mit and LGPL-2.1) or bsd Or GPL-2.0  or (mit and LGPL-2.1)')
        # note thats simplification does SORT the symbols such that they can
        # eventually be compared sequence-wise. This sorting is based on license key
        expected = 'GPL-2.0 OR bsd OR (LGPL-2.1 AND mit)'
        assert str(expr2.simplify()) == expected

        # Two expressions can be compared for equivalence:
        expr1 = l.parse(' GPL-2.0 or (LGPL-2.1 and mit) ')
        assert 'GPL-2.0 OR (LGPL-2.1 AND mit)' == str(expr1)
        expr2 = l.parse(' (mit and LGPL-2.1)  or GPL-2.0 ')
        assert '(mit AND LGPL-2.1) OR GPL-2.0' == str(expr2)
        assert l.is_equivalent(expr1, expr2)

        assert 'GPL-2.0 OR (LGPL-2.1 AND mit)' == str(expr1.simplify())
        assert 'GPL-2.0 OR (LGPL-2.1 AND mit)' == str(expr2.simplify())
        assert expr1.simplify() == expr2.simplify()

        expr3 = l.parse(' GPL-2.0 or mit or LGPL-2.1')
        assert not l.is_equivalent(expr2, expr3)
        expr4 = l.parse('mit and LGPL-2.1')
        assert expr4.simplify() in expr2.simplify()

        assert l.contains(expr2, expr4)

    def test_contains_works_with_plain_symbol(self):
        l = Licensing()
        assert not l.contains('mit', 'mit and LGPL-2.1')
        assert l.contains('mit and LGPL-2.1', 'mit')
        assert l.contains('mit', 'mit')
        assert not l.contains(l.parse('mit'), l.parse('mit and LGPL-2.1'))
        assert l.contains(l.parse('mit and LGPL-2.1'), l.parse('mit'))

        assert l.contains('mit with GPL', 'GPL')
        assert l.contains('mit with GPL', 'mit')
        assert l.contains('mit with GPL', 'mit with GPL')
        assert not l.contains('mit with GPL', 'GPL with mit')
        assert not l.contains('mit with GPL', 'GPL and mit')
        assert not l.contains('GPL', 'mit with GPL')
        assert l.contains('mit with GPL and GPL and BSD', 'GPL and BSD')

    def test_create_from_python(self):
        # Expressions can be built from Python expressions, using bitwise operators
        # between Licensing objects, but use with caution. The behavior is not as
        # well specified that using text expression and parse

        licensing = Licensing()
        expr1 = (licensing.LicenseSymbol('GPL-2.0')
                 | (licensing.LicenseSymbol('mit')
                    & licensing.LicenseSymbol('LGPL-2.1')))
        expr2 = licensing.parse(' GPL-2.0 or (mit and LGPL-2.1) ')

        assert 'GPL-2.0 OR (LGPL-2.1 AND mit)' == str(expr1.simplify())
        assert 'GPL-2.0 OR (LGPL-2.1 AND mit)' == str(expr2.simplify())

        assert licensing.is_equivalent(expr1, expr2)

        a = licensing.OR(
            LicenseSymbol(key='gpl-2.0'),
            licensing.AND(LicenseSymbol(key='mit'),
                LicenseSymbol(key='lgpl-2.1')
                )
            )
        b = licensing.OR(
             LicenseSymbol(key='gpl-2.0'),
             licensing.AND(LicenseSymbol(key='mit'),
                 LicenseSymbol(key='lgpl-2.1')
                 )
            )
        assert a == b

    def test_parse_with_repeated_or_later_does_not_raise_parse_error(self):
        l = Licensing()
        expr = 'LGPL2.1+ + and mit'
        parsed = l.parse(expr)
        assert 'LGPL2.1+ + AND mit' == str(parsed)

    def test_render_complex(self):
        licensing = Licensing()
        expression = '''
        EPL-1.0 AND Apache-1.1 AND Apache-2.0 AND BSD-Modified AND CPL-1.0 AND
        ICU-Composite-License AND JPEG-License AND JDOM-License AND LGPL-2.0 AND
        MIT-Open-Group AND MPL-1.1 AND SAX-PD AND Unicode-Inc-License-Agreement
        AND W3C-Software-Notice and License AND W3C-Documentation-License'''

        result = licensing.parse(expression)
        expected = ('EPL-1.0 AND Apache-1.1 AND Apache-2.0 AND BSD-Modified '
        'AND CPL-1.0 AND ICU-Composite-License AND JPEG-License '
        'AND JDOM-License AND LGPL-2.0 AND MIT-Open-Group AND MPL-1.1 '
        'AND SAX-PD AND Unicode-Inc-License-Agreement '
        'AND W3C-Software-Notice AND License AND W3C-Documentation-License')

        assert result.render('{symbol.key}') == expected
        expectedkey = ('EPL-1.0 AND Apache-1.1 AND Apache-2.0 AND BSD-Modified AND '
        'CPL-1.0 AND ICU-Composite-License AND JPEG-License AND JDOM-License AND '
        'LGPL-2.0 AND MIT-Open-Group AND MPL-1.1 AND SAX-PD AND '
        'Unicode-Inc-License-Agreement AND W3C-Software-Notice AND License AND'
        ' W3C-Documentation-License')
        assert expectedkey == result.render('{symbol.key}')

    def test_render_with(self):
        licensing = Licensing()
        expression = 'GPL-2.0 with Classpath-2.0 OR BSD-new'
        result = licensing.parse(expression)

        expected = 'GPL-2.0 WITH Classpath-2.0 OR BSD-new'
        assert result.render('{symbol.key}') == expected

        expected_html = (
            '<a href="path/GPL-2.0">GPL-2.0</a> WITH '
            '<a href="path/Classpath-2.0">Classpath-2.0</a> '
            'OR <a href="path/BSD-new">BSD-new</a>')
        assert expected_html == result.render('<a href="path/{symbol.key}">{symbol.key}</a>')

        expected = 'GPL-2.0 WITH Classpath-2.0 OR BSD-new'
        assert result.render('{symbol.key}') == expected

    def test_parse_complex(self):
        licensing = Licensing()
        expression = ' GPL-2.0 or later with classpath-Exception and mit or  LPL-2.1 and mit or later '
        result = licensing.parse(expression)
        # this may look weird, but we did not provide symbols hence in "or later",
        # "later" is treated as if it were a license
        expected = 'GPL-2.0 OR (later WITH classpath-Exception AND mit) OR (LPL-2.1 AND mit) OR later'
        assert result.render('{symbol.key}') == expected

    def test_parse_complex2(self):
        licensing = Licensing()
        expr = licensing.parse(" GPL-2.0 or LGPL-2.1 and mit ")
        expected = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LGPL-2.1'),
            LicenseSymbol('mit')
        ]
        assert sorted(licensing.license_symbols(expr)) == expected
        expected = 'GPL-2.0 OR (LGPL-2.1 AND mit)'
        assert expr.render('{symbol.key}') == expected

    def test_Licensing_can_tokenize_valid_expressions_with_symbols_that_contain_and_with_or(self):
        licensing = Licensing()
        expression = 'orgpl or withbsd with orclasspath and andmit or anlgpl and ormit or withme'

        result = list(licensing.tokenize(expression))
        expected = [
            (LicenseSymbol(key='orgpl'), 'orgpl', 0),
            (2, 'or', 6),
            (LicenseWithExceptionSymbol(
                license_symbol=LicenseSymbol(key='withbsd'),
                exception_symbol=LicenseSymbol(key='orclasspath')),
             'withbsd with orclasspath', 9),
            (1, 'and', 34),
            (LicenseSymbol(key='andmit'), 'andmit', 38),
            (2, 'or', 45),
            (LicenseSymbol(key='anlgpl'), 'anlgpl', 48),
            (1, 'and', 55),
            (LicenseSymbol(key='ormit'), 'ormit', 59),
            (2, 'or', 65),
            (LicenseSymbol(key='withme'), 'withme', 68)
        ]

        assert result == expected

    def test_Licensing_can_simple_tokenize_valid_expressions_with_symbols_that_contain_and_with_or(self):
        licensing = Licensing()
        expression = 'orgpl or withbsd with orclasspath and andmit or andlgpl and ormit or withme'

        result = [r.string for r in licensing.simple_tokenizer(expression)]
        expected = [
            'orgpl',
            ' ',
            'or',
            ' ',
            'withbsd',
            ' ',
            'with',
            ' ',
            'orclasspath',
            ' ',
            'and',
            ' ',
            'andmit',
            ' ',
            'or',
            ' ',
            'andlgpl',
            ' ',
            'and',
            ' ',
            'ormit',
            ' ',
            'or',
            ' ',
            'withme'
        ]
        assert result == expected

    def test_Licensing_can_parse_valid_expressions_with_symbols_that_contain_and_with_or(self):
        licensing = Licensing()
        expression = 'orgpl or withbsd with orclasspath and andmit or anlgpl and ormit or withme'

        result = licensing.parse(expression)
        expected = 'orgpl OR (withbsd WITH orclasspath AND andmit) OR (anlgpl AND ormit) OR withme'
        assert result.render('{symbol.key}') == expected

    def test_Licensing_can_parse_valid_expressions_with_symbols_that_contain_spaces(self):
        licensing = Licensing()
        expression = ' GPL-2.0 or (mit and LGPL 2.1) or bsd Or GPL-2.0  or (mit and LGPL 2.1)'
        parsed = licensing.parse(expression)
        expected = 'GPL-2.0 OR (mit AND LGPL 2.1) OR bsd OR GPL-2.0 OR (mit AND LGPL 2.1)'
        assert str(parsed) == expected

    def test_parse_invalid_expression_with_trailing_or(self):
        licensing = Licensing()
        expr = 'mit or'
        try:
            licensing.parse(expr)
            self.fail("Exception not raised when validating '%s'" % expr)
        except ExpressionError as ee:
            assert 'OR requires two or more licenses as in: MIT OR BSD' == str(ee)

    def test_parse_invalid_expression_with_trailing_or_and_valid_start_does_not_raise_exception(self):
        licensing = Licensing()
        expression = ' mit or mit or '
        parsed = licensing.parse(expression)
        # ExpressionError: OR requires two or more licenses as in: MIT OR BSD
        expected = 'mit OR mit'
        assert str(parsed) == expected

    def test_parse_invalid_expression_with_repeated_trailing_or_raise_exception(self):
        licensing = Licensing()
        expression = 'mit or mit or or'
        try:
            licensing.parse(expression, simple=False)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 14,
                'token_string': 'or',
                'token_type': TOKEN_OR
            }
            assert _parse_error_as_dict(pe) == expected

    def test_parse_invalid_expression_drops_single_trailing_or(self):
        licensing = Licensing()
        expression = 'mit or mit or'
        e = licensing.parse(expression, simple=False)
        assert str(e) == 'mit OR mit'

    def test_parse_invalid_expression_drops_single_trailing_or2(self):
        licensing = Licensing()
        expression = 'mit or mit or'
        e = licensing.parse(expression, simple=True)
        assert str(e) == 'mit OR mit'

    def test_parse_invalid_expression_with_single_trailing_and_raise_exception(self):
        licensing = Licensing()
        expression = 'mit or mit and'
        try:
            licensing.parse(expression, simple=False)
            self.fail('Exception not raised')
        except ExpressionError as ee:
            assert 'AND requires two or more licenses as in: MIT AND BSD' == str(ee)

    def test_parse_invalid_expression_with_single_leading_or_raise_exception(self):
        licensing = Licensing()
        expression = 'or mit or mit'
        try:
            licensing.parse(expression, simple=False)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 0,
                'token_string': 'or',
                'token_type': TOKEN_OR
            }
            assert _parse_error_as_dict(pe) == expected

    def test_Licensing_can_parse_expressions_with_symbols_that_contain_a_colon(self):
        licensing = Licensing()
        expression = 'DocumentRef-James-1.0:LicenseRef-Eric-2.0'

        result = licensing.parse(expression)
        expected = 'DocumentRef-James-1.0:LicenseRef-Eric-2.0'
        assert result.render('{symbol.key}') == expected


class LicensingParseWithSymbolsSimpleTest(TestCase):

    def test_Licensing_with_overlapping_symbols_with_keywords_does_not_raise_Exception(self):
        Licensing([
            'GPL-2.0 or LATER',
            'classpath Exception',
            'something with else+',
            'mit',
            'LGPL 2.1',
            'mit or later'
        ])

    def get_syms_and_licensing(self):
        a = LicenseSymbol('l-a')
        ap = LicenseSymbol('L-a+', ['l-a +'])
        b = LicenseSymbol('l-b')
        c = LicenseSymbol('l-c')
        symbols = [a, ap, b, c]
        return a, ap, b, c, Licensing(symbols)

    def test_parse_license_expression1(self):
        a, _ap, _b, _c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a'
        result = licensing.parse(express_string)
        assert express_string == str(result)
        expected = a
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression_with_alias(self):
        _a, ap, _b, _c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a +'
        result = licensing.parse(express_string)
        assert 'L-a+' == str(result)
        expected = ap
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression3(self):
        _a, ap, _b, _c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a+'
        result = licensing.parse(express_string)
        assert 'L-a+' == str(result)
        expected = ap
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression4(self):
        _a, _ap, _b, _c, licensing = self.get_syms_and_licensing()
        express_string = '(l-a)'
        result = licensing.parse(express_string)
        assert 'l-a' == str(result)
        expected = LicenseSymbol(key='l-a', aliases=())
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression5(self):
        _a, ap, b, c, licensing = self.get_syms_and_licensing()
        express_string = '((l-a+ AND l-b) OR (l-c))'
        result = licensing.parse(express_string)
        assert '(L-a+ AND l-b) OR l-c' == str(result)
        expected = licensing.OR(licensing.AND(ap, b), c)
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression6(self):
        a, _ap, b, _c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a and l-b'
        result = licensing.parse(express_string)
        assert 'l-a AND l-b' == str(result)
        expected = licensing.AND(a, b)
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression7(self):
        a, _ap, b, _c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a or l-b'
        result = licensing.parse(express_string)
        assert 'l-a OR l-b' == str(result)
        expected = licensing.OR(a, b)
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression8(self):
        a, _ap, b, c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a and l-b OR l-c'
        result = licensing.parse(express_string)
        assert '(l-a AND l-b) OR l-c' == str(result)
        expected = licensing.OR(licensing.AND(a, b), c)
        assert result == expected
        assert [] == licensing.unknown_license_keys(result)

    def test_parse_license_expression8_twice(self):
        _a, _ap, _b, _c, licensing = self.get_syms_and_licensing()
        express_string = 'l-a and l-b OR l-c'
        result = licensing.parse(express_string)
        assert '(l-a AND l-b) OR l-c' == str(result)
        # there was some issues with reusing a Licensing
        result = licensing.parse(express_string)
        assert '(l-a AND l-b) OR l-c' == str(result)

    def test_parse_license_expression_with_trailing_space_plus(self):
        symbols = [
            LicenseSymbol('l-a'),
            LicenseSymbol('L-a+', ['l-a +']),
            LicenseSymbol('l-b'),
            LicenseSymbol('l-c'),
        ]
        licensing = Licensing(symbols)

        expresssion_str = 'l-a'
        result = licensing.parse(expresssion_str)
        assert str(result) == expresssion_str
        assert licensing.unknown_license_keys(result) == []

        # plus sign is not attached to the symbol, but an alias
        expresssion_str = 'l-a +'
        result = licensing.parse(expresssion_str)
        assert str(result).lower() == 'l-a+'
        assert licensing.unknown_license_keys(result) == []

        expresssion_str = '(l-a)'
        result = licensing.parse(expresssion_str)
        assert str(result).lower() == 'l-a'
        assert licensing.unknown_license_keys(result) == []

        expresssion_str = '((l-a+ AND l-b) OR (l-c))'
        result = licensing.parse(expresssion_str)
        assert str(result) == '(L-a+ AND l-b) OR l-c'
        assert licensing.unknown_license_keys(result) == []

        expresssion_str = 'l-a and l-b'
        result = licensing.parse(expresssion_str)
        assert str(result) == 'l-a AND l-b'
        assert licensing.unknown_license_keys(result) == []

        expresssion_str = 'l-a or l-b'
        result = licensing.parse(expresssion_str)
        assert str(result) == 'l-a OR l-b'
        assert licensing.unknown_license_keys(result) == []

        expresssion_str = 'l-a and l-b OR l-c'
        result = licensing.parse(expresssion_str)
        assert str(result) == '(l-a AND l-b) OR l-c'
        assert licensing.unknown_license_keys(result) == []

    def test_parse_of_side_by_side_symbols_raise_exception(self):
        gpl2 = LicenseSymbol('gpl')
        l = Licensing([gpl2])
        try:
            l.parse('gpl mit')
            self.fail('ParseError not raised')
        except ParseError:
            pass

    def test_validate_symbols(self):
        symbols = [
            LicenseSymbol('l-a', is_exception=True),
            LicenseSymbol('l-a'),
            LicenseSymbol('l-b'),
            LicenseSymbol('l-c'),
        ]
        warnings, errors = validate_symbols(symbols)

        expectedw = []
        assert warnings == expectedw

        expectede = [
            "Invalid duplicated license key: 'l-a'.",
        ]
        assert errors == expectede


class LicensingParseWithSymbolsTest(TestCase):

    def test_parse_raise_ParseError_when_validating_strict_with_non_exception_symbols(self):
        licensing = Licensing(['gpl', 'bsd', 'lgpl', 'exception'])

        expression = 'gpl and bsd or lgpl with exception'
        try:
            licensing.parse(expression, validate=True, strict=True)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_SYMBOL_AS_EXCEPTION,
                'position': 25,
                'token_string': 'exception',
                'token_type': TOKEN_SYMBOL}
            assert _parse_error_as_dict(pe) == expected

    def test_parse_raise_ParseError_when_validating_strict_with_exception_symbols_in_incorrect_spot(self):
        licensing = Licensing([LicenseSymbol('gpl', is_exception=False),
                               LicenseSymbol('exception', is_exception=True)])
        licensing.parse('gpl with exception', validate=True, strict=True)
        try:
            licensing.parse('exception with gpl', validate=True, strict=True)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_EXCEPTION,
                'position': 0,
                'token_string': 'exception',
                'token_type': TOKEN_SYMBOL}
            assert _parse_error_as_dict(pe) == expected

        try:
            licensing.parse('gpl with gpl', validate=True, strict=True)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_SYMBOL_AS_EXCEPTION,
                'position': 9,
                'token_string': 'gpl',
                'token_type': TOKEN_SYMBOL}
            assert _parse_error_as_dict(pe) == expected

    def test_with_unknown_symbol_string_contained_in_known_symbol_does_not_crash_with(self):
        l = Licensing(['lgpl-3.0-plus'])
        license_expression = 'lgpl-3.0-plus WITH openssl-exception-lgpl-3.0-plus'
        l.parse(license_expression)

    def test_with_unknown_symbol_string_contained_in_known_symbol_does_not_crash_and(self):
        l = Licensing(['lgpl-3.0-plus'])
        license_expression = 'lgpl-3.0-plus AND openssl-exception-lgpl-3.0-plus'
        l.parse(license_expression)

    def test_with_unknown_symbol_string_contained_in_known_symbol_does_not_crash_or(self):
        l = Licensing(['lgpl-3.0-plus'])
        license_expression = 'lgpl-3.0-plus OR openssl-exception-lgpl-3.0-plus'
        l.parse(license_expression)

    def test_with_known_symbol_string_contained_in_known_symbol_does_not_crash_or(self):
        l = Licensing(['lgpl-3.0-plus', 'openssl-exception-lgpl-3.0-plus'])
        license_expression = 'lgpl-3.0-plus OR openssl-exception-lgpl-3.0-plus'
        l.parse(license_expression)

    def test_with_known_symbol_string_contained_in_known_symbol_does_not_crash_with(self):
        l = Licensing(['lgpl-3.0-plus', 'openssl-exception-lgpl-3.0-plus'])
        license_expression = 'lgpl-3.0-plus WITH openssl-exception-lgpl-3.0-plus'
        l.parse(license_expression)


class LicensingSymbolsReplacement(TestCase):

    def get_symbols_and_licensing(self):
        gpl2 = LicenseSymbol('gpl-2.0', ['The GNU GPL 20', 'GPL-2.0', 'GPL v2.0'])
        gpl2plus = LicenseSymbol('gpl-2.0+', ['The GNU GPL 20 or later', 'GPL-2.0 or later', 'GPL v2.0 or later'])
        lgpl = LicenseSymbol('LGPL-2.1', ['LGPL v2.1'])
        mit = LicenseSymbol('MIT', ['MIT license'])
        mitand2 = LicenseSymbol('mitand2', ['mitand2', 'mitand2 license'])
        symbols = [gpl2, gpl2plus, lgpl, mit, mitand2]
        licensing = Licensing(symbols)
        return gpl2, gpl2plus, lgpl, mit, mitand2, licensing

    def test_simple_substitution(self):
        gpl2, gpl2plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        subs = {gpl2plus: gpl2}

        expr = licensing.parse('gpl-2.0 or gpl-2.0+')
        result = expr.subs(subs)
        assert 'gpl-2.0 OR gpl-2.0' == result.render()

    def test_advanced_substitution(self):
        _gpl2, _gpl2plus, lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        source = licensing.parse('gpl-2.0+ and mit')
        target = lgpl
        subs = {source: target}

        expr = licensing.parse('gpl-2.0 or gpl-2.0+ and mit')
        result = expr.subs(subs)
        assert 'gpl-2.0 OR LGPL-2.1' == result.render()

    def test_multiple_substitutions(self):
        gpl2, gpl2plus, lgpl, mit, _mitand2, licensing = self.get_symbols_and_licensing()

        source1 = licensing.parse('gpl-2.0+ and mit')
        target1 = lgpl

        source2 = licensing.parse('mitand2')
        target2 = mit

        source3 = gpl2
        target3 = gpl2plus

        subs = dict([
            (source1, target1),
            (source2, target2),
            (source3, target3),
        ])

        expr = licensing.parse('gpl-2.0 or gpl-2.0+ and mit')
        # step 1: yields 'gpl-2.0 or lgpl'
        # step 2: yields 'gpl-2.0+ or LGPL-2.1'
        result = expr.subs(subs)
        assert 'gpl-2.0+ OR LGPL-2.1' == result.render()

    def test_multiple_substitutions_complex(self):
        gpl2, gpl2plus, lgpl, mit, _mitand2, licensing = self.get_symbols_and_licensing()

        source1 = licensing.parse('gpl-2.0+ and mit')
        target1 = lgpl

        source2 = licensing.parse('mitand2')
        target2 = mit

        source3 = gpl2
        target3 = gpl2plus

        subs = dict([
            (source1, target1),
            (source2, target2),
            (source3, target3),
        ])

        expr = licensing.parse('(gpl-2.0 or gpl-2.0+ and mit) and (gpl-2.0 or gpl-2.0+ and mit)')
        # step 1: yields 'gpl-2.0 or lgpl'
        # step 2: yields 'gpl-2.0+ or LGPL-2.1'
        result = expr.subs(subs)
        assert '(gpl-2.0+ OR LGPL-2.1) AND (gpl-2.0+ OR LGPL-2.1)' == result.render()

        expr = licensing.parse('(gpl-2.0 or mit and gpl-2.0+) and (gpl-2.0 or gpl-2.0+ and mit)')
        # step 1: yields 'gpl-2.0 or lgpl'
        # step 2: yields 'gpl-2.0+ or LGPL-2.1'
        result = expr.subs(subs)
        assert '(gpl-2.0+ OR LGPL-2.1) AND (gpl-2.0+ OR LGPL-2.1)' == result.render()


class LicensingParseWithSymbolsAdvancedTest(TestCase):

    def get_symbols_and_licensing(self):
        gpl2 = LicenseSymbol('gpl-2.0', ['The GNU GPL 20', 'GPL-2.0', 'GPL v2.0'])
        gpl2plus = LicenseSymbol('gpl-2.0+', ['The GNU GPL 20 or later', 'GPL-2.0 or later', 'GPL v2.0 or later'])
        lgpl = LicenseSymbol('LGPL-2.1', ['LGPL v2.1'])
        mit = LicenseSymbol('MIT', ['MIT license'])
        mitand2 = LicenseSymbol('mitand2', ['mitand2', 'mitand2 license'])
        symbols = [gpl2, gpl2plus, lgpl, mit, mitand2]
        licensing = Licensing(symbols)
        return gpl2, gpl2plus, lgpl, mit, mitand2, licensing

    def test_parse_trailing_char_does_not_raise_exception_without_validate(self):
        _gpl2, _gpl2plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        e = licensing.parse('The GNU GPL 20 or LGPL-2.1 and mit2', validate=False)
        assert 'gpl-2.0 OR (LGPL-2.1 AND mit2)' == str(e)

    def test_parse_trailing_char_raise_exception_with_validate(self):
        _gpl2, _gpl2plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        try:
            licensing.parse('The GNU GPL 20 or LGPL-2.1 and mit2', validate=True)
            self.fail('Exception not raised')
        except ExpressionError as ee:
            assert 'Unknown license key(s): mit2' == str(ee)

    def test_parse_expression_with_trailing_unknown_should_raise_exception(self):
        gpl2, gpl2plus, lgpl, mit, _mitand2, licensing = self.get_symbols_and_licensing()
        unknown = LicenseSymbol(key='123')

        tokens = list(licensing.tokenize('The GNU GPL 20 or later or (LGPL-2.1 and mit) or The GNU GPL 20 or mit 123'))
        expected = [
            (gpl2plus, 'The GNU GPL 20 or later', 0),
            (TOKEN_OR, 'or', 24),
            (TOKEN_LPAR, '(', 27),
            (lgpl, 'LGPL-2.1', 28),
            (TOKEN_AND, 'and', 37),
            (mit, 'mit', 41),
            (TOKEN_RPAR, ')', 44),
            (TOKEN_OR, 'or', 46),
            (gpl2, 'The GNU GPL 20', 49),
            (TOKEN_OR, 'or', 64),
            (mit, 'mit', 67),
            (unknown, '123', 71)
        ]
        assert tokens == expected

        try:
            licensing.parse('The GNU GPL 20 or later or (LGPL-2.1 and mit) or The GNU GPL 20 or mit 123')
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {'error_code': PARSE_INVALID_SYMBOL_SEQUENCE, 'position': 71,
                        'token_string': '123', 'token_type': unknown}
            assert _parse_error_as_dict(pe) == expected

    def test_parse_expression_with_trailing_unknown_should_raise_exception2(self):
        _gpl2, _gpl2_plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        unknown = LicenseSymbol(key='123')
        try:
            licensing.parse('The GNU GPL 20 or mit 123')
            #                01234567890123456789012345
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {'error_code': PARSE_INVALID_SYMBOL_SEQUENCE, 'position': 22,
                        'token_string': '123', 'token_type': unknown}
            assert _parse_error_as_dict(pe) == expected

    def test_parse_expression_with_WITH(self):
        gpl2, _gpl2plus, lgpl, mit, mitand2, _ = self.get_symbols_and_licensing()
        mitexp = LicenseSymbol('mitexp', ('mit exp',), is_exception=True)
        gpl_20_or_later = LicenseSymbol('GPL-2.0+', ['The GNU GPL 20 or later'])

        symbols = [gpl2, lgpl, mit, mitand2, mitexp, gpl_20_or_later]
        licensing = Licensing(symbols)
        expr = 'The GNU GPL 20 or later or (LGPL-2.1 and mit) or The GNU GPL 20 or mit with mit exp'
        tokens = list(licensing.tokenize(expr))
        expected = [
            (gpl_20_or_later, 'The GNU GPL 20 or later', 0),
            (TOKEN_OR, 'or', 24),
            (TOKEN_LPAR, '(', 27),
            (lgpl, 'LGPL-2.1', 28),
            (TOKEN_AND, 'and', 37),
            (mit, 'mit', 41),
            (TOKEN_RPAR, ')', 44),
            (TOKEN_OR, 'or', 46),
            (gpl2, 'The GNU GPL 20', 49),
            (TOKEN_OR, 'or', 64),
            (LicenseWithExceptionSymbol(mit, mitexp), 'mit with mit exp', 67)
        ]

        assert tokens == expected

        parsed = licensing.parse(expr)
        expected = 'GPL-2.0+ OR (LGPL-2.1 AND MIT) OR gpl-2.0 OR MIT WITH mitexp'
        assert str(parsed) == expected
        expected = 'GPL-2.0+ OR (LGPL-2.1 AND MIT) OR gpl-2.0 OR MIT WITH mitexp'
        assert parsed.render() == expected

    def test_parse_expression_with_WITH_and_unknown_symbol(self):
        gpl2, _gpl2plus, lgpl, mit, mitand2, _ = self.get_symbols_and_licensing()
        mitexp = LicenseSymbol('mitexp', ('mit exp',), is_exception=True)
        gpl_20_or_later = LicenseSymbol('GPL-2.0+', ['The GNU GPL 20 or later'])

        symbols = [gpl2, lgpl, mit, mitand2, mitexp, gpl_20_or_later]
        licensing = Licensing(symbols)
        expr = 'The GNU GPL 20 or later or (LGPL-2.1 and mit) or The GNU GPL 20 or mit with 123'
        parsed = licensing.parse(expr)

        assert ['123'] == licensing.unknown_license_keys(parsed)
        assert ['123'] == licensing.unknown_license_keys(expr)

    def test_unknown_keys(self):
        _gpl2, _gpl2plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        expr = 'The GNU GPL 20 or LGPL-2.1 and mit'
        parsed = licensing.parse(expr)
        expected = 'gpl-2.0 OR (LGPL-2.1 AND MIT)'
        assert str(parsed) == expected
        assert 'gpl-2.0 OR (LGPL-2.1 AND MIT)' == parsed.render('{symbol.key}')
        assert [] == licensing.unknown_license_keys(parsed)
        assert [] == licensing.unknown_license_keys(expr)

    def test_unknown_keys_with_trailing_char(self):
        gpl2, _gpl2plus, lgpl, _mit, mitand2, licensing = self.get_symbols_and_licensing()
        expr = 'The GNU GPL 20 or LGPL-2.1 and mitand2'
        parsed = licensing.parse(expr)
        expected = [gpl2, lgpl, mitand2]
        assert licensing.license_symbols(parsed) == expected
        assert licensing.license_symbols(licensing.parse(parsed)) == expected
        assert licensing.license_symbols(expr) == expected
        assert [] == licensing.unknown_license_keys(parsed)
        assert [] == licensing.unknown_license_keys(expr)

    def test_unknown_keys_with_trailing_char_2_with_validate(self):
        _gpl2, _gpl2plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        expr = 'The GNU GPL 20 or LGPL-2.1 and mitand3'

        try:
            licensing.parse(expr, validate=True)
            self.fail('Exception should be raised')
        except ExpressionError as ee:
            assert 'Unknown license key(s): mitand3' == str(ee)

    def test_unknown_keys_with_trailing_char_2_without_validate(self):
        _gpl2, _gpl2plus, _lgpl, _mit, _mitand2, licensing = self.get_symbols_and_licensing()
        expr = 'The GNU GPL 20 or LGPL-2.1 and mitand3'
        parsed = licensing.parse(expr, validate=False)
        assert 'gpl-2.0 OR (LGPL-2.1 AND mitand3)' == str(parsed)

    def test_parse_with_overlapping_key_without_symbols(self):
        expression = 'mit or mit AND zlib or mit or mit with verylonglicense'
        #             1111111111222222222233333333334444444444555555555566666
        #             0123456789012345678901234567890123456789012345678901234

        licensing = Licensing()
        results = str(licensing.parse(expression))
        expected = 'mit OR (mit AND zlib) OR mit OR mit WITH verylonglicense'
        assert results == expected

    def test_advanced_tokenizer_tokenize_with_overlapping_key_with_symbols_and_trailing_unknown(self):
        expression = 'mit or mit AND zlib or mit or mit with verylonglicense'
        #                       111111111122222222223333333333444444444455555
        #             0123456789012345678901234567890123456789012345678901234

        symbols = [
            LicenseSymbol('MIT', ['MIT license']),
            LicenseSymbol('LGPL-2.1', ['LGPL v2.1']),
            LicenseSymbol('zlib', ['zlib']),
            LicenseSymbol('d-zlib', ['D zlib']),
            LicenseSymbol('mito', ['mit o']),
            LicenseSymbol('hmit', ['h verylonglicense']),
        ]
        licensing = Licensing(symbols)
        results = list(licensing.get_advanced_tokenizer().tokenize(expression))
        expected = [
            Token(0, 2, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(4, 5, 'or', Keyword(value=u'or', type=2)),
            Token(7, 9, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(11, 13, 'AND', Keyword(value=u'and', type=1)),
            Token(15, 18, 'zlib', LicenseSymbol(u'zlib', aliases=(u'zlib',))),
            Token(20, 21, 'or', Keyword(value=u'or', type=2)),
            Token(23, 25, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(27, 28, 'or', Keyword(value=u'or', type=2)),
            Token(30, 32, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(34, 37, 'with', Keyword(value=u'with', type=10)),
            Token(39, 53, 'verylonglicense', None),
        ]

        assert results == expected

    def test_advanced_tokenizer_iter_with_overlapping_key_with_symbols_and_trailing_unknown(self):
        expression = 'mit or mit AND zlib or mit or mit with verylonglicense'
        #                       111111111122222222223333333333444444444455555
        #             0123456789012345678901234567890123456789012345678901234

        symbols = [
            LicenseSymbol('MIT', ['MIT license']),
            LicenseSymbol('LGPL-2.1', ['LGPL v2.1']),
            LicenseSymbol('zlib', ['zlib']),
            LicenseSymbol('d-zlib', ['D zlib']),
            LicenseSymbol('mito', ['mit o']),
            LicenseSymbol('hmit', ['h verylonglicense']),
        ]
        licensing = Licensing(symbols)
        results = list(licensing.get_advanced_tokenizer().iter(expression, include_unmatched=True))
        expected = [
            Token(0, 2, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(4, 5, 'or', Keyword(value=u'or', type=2)),
            Token(7, 9, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(11, 13, 'AND', Keyword(value=u'and', type=1)),
            Token(15, 18, 'zlib', LicenseSymbol(u'zlib', aliases=(u'zlib',))),
            Token(20, 21, 'or', Keyword(value=u'or', type=2)),
            Token(23, 25, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(27, 28, 'or', Keyword(value=u'or', type=2)),
            Token(30, 32, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(34, 37, 'with', Keyword(value=u'with', type=10)),
            Token(39, 53, 'verylonglicense', None),
        ]
        assert results == expected

    def test_advanced_tokenizer_iter_with_overlapping_key_with_symbols_and_trailing_unknown2(self):
        expression = 'mit with verylonglicense'
        symbols = [
            LicenseSymbol('MIT', ['MIT license']),
            LicenseSymbol('hmit', ['h verylonglicense']),
        ]
        licensing = Licensing(symbols)
        results = list(licensing.get_advanced_tokenizer().iter(expression, include_unmatched=True))
        expected = [
            Token(0, 2, 'mit', LicenseSymbol(u'MIT', aliases=(u'MIT license',))),
            Token(4, 7, 'with', Keyword(value=u'with', type=10)),
            Token(9, 23, 'verylonglicense', None),
        ]
        assert results == expected

    def test_tokenize_with_overlapping_key_with_symbols_and_trailing_unknown(self):
        expression = 'mit or mit AND zlib or mit or mit with verylonglicense'
        #             1111111111222222222233333333334444444444555555555566666
        #             0123456789012345678901234567890123456789012345678901234

        symbols = [
            LicenseSymbol('MIT', ['MIT license']),
            LicenseSymbol('LGPL-2.1', ['LGPL v2.1']),
            LicenseSymbol('zlib', ['zlib']),
            LicenseSymbol('d-zlib', ['D zlib']),
            LicenseSymbol('mito', ['mit o']),
            LicenseSymbol('hmit', ['h verylonglicense']),
        ]
        licensing = Licensing(symbols)

        results = list(licensing.tokenize(expression))
        expected = [
            (LicenseSymbol(u'MIT', aliases=(u'MIT license',)), 'mit', 0),
            (2, 'or', 4),
            (LicenseSymbol(u'MIT', aliases=(u'MIT license',)), 'mit', 7),
            (1, 'AND', 11),
            (LicenseSymbol(u'zlib', aliases=(u'zlib',)), 'zlib', 15),
            (2, 'or', 20),
            (LicenseSymbol(u'MIT', aliases=(u'MIT license',)), 'mit', 23),
            (2, 'or', 27),
            (LicenseWithExceptionSymbol(
                license_symbol=LicenseSymbol(u'MIT', aliases=(u'MIT license',)),
                exception_symbol=LicenseSymbol(u'verylonglicense')), 'mit with verylonglicense',
             30)
        ]

        assert results == expected

        results = str(licensing.parse(expression))
        expected = 'MIT OR (MIT AND zlib) OR MIT OR MIT WITH verylonglicense'
        assert results == expected


class LicensingSymbolsTest(TestCase):

    def test_get_license_symbols(self):
        symbols = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('mit'),
            LicenseSymbol('LGPL 2.1')
        ]
        l = Licensing(symbols)
        assert symbols == l.license_symbols(l.parse(' GPL-2.0 and mit or LGPL 2.1 and mit '))

    def test_get_license_symbols2(self):
        symbols = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LATER'),
            LicenseSymbol('mit'),
            LicenseSymbol('LGPL 2.1+'),
            LicenseSymbol('Foo exception', is_exception=True),
        ]
        l = Licensing(symbols)
        expr = ' GPL-2.0 or LATER and mit or LGPL 2.1+ and mit with Foo exception '
        expected = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LATER'),
            LicenseSymbol('mit'),
            LicenseSymbol('LGPL 2.1+'),
            LicenseSymbol('mit'),
            LicenseSymbol('Foo exception', is_exception=True),
        ]
        assert l.license_symbols(l.parse(expr), unique=False) == expected

    def test_get_license_symbols3(self):
        symbols = [
            LicenseSymbol('mit'),
            LicenseSymbol('LGPL 2.1+'),
            LicenseSymbol('Foo exception', is_exception=True),
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LATER'),
        ]
        l = Licensing(symbols)
        expr = 'mit or LGPL 2.1+ and mit with Foo exception or GPL-2.0 or LATER '
        assert symbols == l.license_symbols(l.parse(expr))

    def test_get_license_symbols4(self):
        symbols = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LATER'),
            LicenseSymbol('big exception', is_exception=True),
            LicenseSymbol('mit'),
            LicenseSymbol('LGPL 2.1+'),
            LicenseSymbol('Foo exception', is_exception=True),
        ]
        l = Licensing(symbols)
        expr = (' GPL-2.0 or LATER with big exception and mit or '
                'LGPL 2.1+ and mit or later with Foo exception ')
        expected = [
            LicenseSymbol('GPL-2.0'),
            LicenseSymbol('LATER'),
            LicenseSymbol('big exception', is_exception=True),
            LicenseSymbol('mit'),
            LicenseSymbol('LGPL 2.1+'),
            LicenseSymbol('mit'),
            LicenseSymbol('LATER'),
            LicenseSymbol('Foo exception', is_exception=True),
        ]

        assert l.license_symbols(l.parse(expr), unique=False) == expected

    def test_license_symbols(self):
        licensing = Licensing([
            'GPL-2.0 or LATER',
            'classpath Exception',
            'something with else+',
            'mit',
            'LGPL 2.1',
            'mit or later'
        ])

        expr = (' GPL-2.0 or LATER with classpath Exception and mit and '
                'mit with SOMETHING with ELSE+ or LGPL 2.1 and '
                'GPL-2.0 or LATER with classpath Exception and '
                'mit or later or LGPL 2.1 or mit or GPL-2.0 or LATER '
                'with SOMETHING with ELSE+ and lgpl 2.1')

        gpl2plus = LicenseSymbol(key='GPL-2.0 or LATER')
        cpex = LicenseSymbol(key='classpath Exception')
        someplus = LicenseSymbol(key='something with else+')
        mitplus = LicenseSymbol(key='mit or later')
        mit = LicenseSymbol(key='mit')
        lgpl = LicenseSymbol(key='LGPL 2.1')
        gpl_with_cp = LicenseWithExceptionSymbol(license_symbol=gpl2plus, exception_symbol=cpex)
        mit_with_some = LicenseWithExceptionSymbol(license_symbol=mit, exception_symbol=someplus)
        gpl2_with_someplus = LicenseWithExceptionSymbol(license_symbol=gpl2plus, exception_symbol=someplus)

        parsed = licensing.parse(expr)
        expected = [gpl_with_cp, mit, mit_with_some, lgpl, gpl_with_cp, mitplus, lgpl, mit, gpl2_with_someplus, lgpl]

        assert licensing.license_symbols(parsed, unique=False, decompose=False) == expected

        expected = [gpl_with_cp, mit, mit_with_some, lgpl, mitplus, gpl2_with_someplus]
        assert licensing.license_symbols(parsed, unique=True, decompose=False) == expected

        expected = [gpl2plus, cpex, mit, mit, someplus, lgpl, gpl2plus, cpex, mitplus, lgpl, mit, gpl2plus, someplus, lgpl]
        assert licensing.license_symbols(parsed, unique=False, decompose=True) == expected

        expected = [gpl2plus, cpex, mit, someplus, lgpl, mitplus]
        assert licensing.license_symbols(parsed, unique=True, decompose=True) == expected

    def test_primary_license_symbol_and_primary_license_key(self):
        licensing = Licensing([
            'GPL-2.0 or LATER',
            'classpath Exception',
            'mit',
            'LGPL 2.1',
            'mit or later'
        ])

        expr = ' GPL-2.0 or LATER with classpath Exception and mit or LGPL 2.1 and mit or later '
        gpl = LicenseSymbol('GPL-2.0 or LATER')
        cpex = LicenseSymbol('classpath Exception')
        expected = LicenseWithExceptionSymbol(gpl, cpex)
        parsed = licensing.parse(expr)
        assert licensing.primary_license_symbol(parsed, decompose=False) == expected
        assert gpl == licensing.primary_license_symbol(parsed, decompose=True)
        assert 'GPL-2.0 or LATER' == licensing.primary_license_key(parsed)

        expr = ' GPL-2.0 or later with classpath Exception and mit or LGPL 2.1 and mit or later '
        expected = 'GPL-2.0 or LATER WITH classpath Exception'
        result = licensing.primary_license_symbol(
            parsed,
            decompose=False
        ).render('{symbol.key}')
        assert result == expected

    def test_render_plain(self):
        l = Licensing()
        result = l.parse('gpl-2.0 WITH exception-gpl-2.0-plus or MIT').render()
        expected = 'gpl-2.0 WITH exception-gpl-2.0-plus OR MIT'
        assert result == expected

    def test_render_as_readable_does_not_wrap_in_parens_single_with(self):
        l = Licensing()
        result = l.parse('gpl-2.0 WITH exception-gpl-2.0-plus').render_as_readable()
        expected = 'gpl-2.0 WITH exception-gpl-2.0-plus'
        assert result == expected

    def test_render_as_readable_wraps_in_parens_with_and_other_subexpressions(self):
        l = Licensing()
        result = l.parse('mit AND gpl-2.0 WITH exception-gpl-2.0-plus').render_as_readable()
        expected = 'mit AND (gpl-2.0 WITH exception-gpl-2.0-plus)'
        assert result == expected

    def test_render_as_readable_does_not_wrap_in_parens_if_no_with(self):
        l = Licensing()
        result1 = l.parse('gpl-2.0 and exception OR that').render_as_readable()
        result2 = l.parse('gpl-2.0 and exception OR that').render()
        assert result1 == result2


class SplitAndTokenizeTest(TestCase):

    def test_simple_tokenizer(self):
        expr = (' GPL-2.0 or later with classpath Exception and mit and '
                'mit with SOMETHING with ELSE+ or LGPL 2.1 and '
                'GPL-2.0 or LATER with (Classpath Exception and '
                'mit or later) or LGPL 2.1 or mit or GPL-2.0 or LATER '
                'with SOMETHING with ELSE+ and lgpl 2.1')
        licensing = Licensing()
        results = list(licensing.simple_tokenizer(expr))
        expected = [
            Token(0, 0, ' ', None),
            Token(1, 7, 'GPL-2.0', LicenseSymbol(key='GPL-2.0')),
            Token(8, 8, ' ', None),
            Token(9, 10, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(11, 11, ' ', None),
            Token(12, 16, 'later', LicenseSymbol(key='later')),
            Token(17, 17, ' ', None),
            Token(18, 21, 'with', Keyword(value='with', type=TOKEN_WITH)),
            Token(22, 22, ' ', None),
            Token(23, 31, 'classpath', LicenseSymbol(key='classpath')),
            Token(32, 32, ' ', None),
            Token(33, 41, 'Exception', LicenseSymbol(key='Exception')),
            Token(42, 42, ' ', None),
            Token(43, 45, 'and', Keyword(value='and', type=TOKEN_AND)),
            Token(46, 46, ' ', None),
            Token(47, 49, 'mit', LicenseSymbol(key='mit')),
            Token(50, 50, ' ', None),
            Token(51, 53, 'and', Keyword(value='and', type=TOKEN_AND)),
            Token(54, 54, ' ', None),
            Token(55, 57, 'mit', LicenseSymbol(key='mit')),
            Token(58, 58, ' ', None),
            Token(59, 62, 'with', Keyword(value='with', type=TOKEN_WITH)),
            Token(63, 63, ' ', None),
            Token(64, 72, 'SOMETHING', LicenseSymbol(key='SOMETHING')),
            Token(73, 73, ' ', None),
            Token(74, 77, 'with', Keyword(value='with', type=TOKEN_WITH)),
            Token(78, 78, ' ', None),
            Token(79, 83, 'ELSE+', LicenseSymbol(key='ELSE+')),
            Token(84, 84, ' ', None),
            Token(85, 86, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(87, 87, ' ', None),
            Token(88, 91, 'LGPL', LicenseSymbol(key='LGPL')),
            Token(92, 92, ' ', None),
            Token(93, 95, '2.1', LicenseSymbol(key='2.1')),
            Token(96, 96, ' ', None),
            Token(97, 99, 'and', Keyword(value='and', type=TOKEN_AND)),
            Token(100, 100, ' ', None),
            Token(101, 107, 'GPL-2.0', LicenseSymbol(key='GPL-2.0')),
            Token(108, 108, ' ', None),
            Token(109, 110, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(111, 111, ' ', None),
            Token(112, 116, 'LATER', LicenseSymbol(key='LATER')),
            Token(117, 117, ' ', None),
            Token(118, 121, 'with', Keyword(value='with', type=TOKEN_WITH)),
            Token(122, 122, ' ', None),
            Token(123, 123, '(', Keyword(value='(', type=TOKEN_LPAR)),
            Token(124, 132, 'Classpath', LicenseSymbol(key='Classpath')),
            Token(133, 133, ' ', None),
            Token(134, 142, 'Exception', LicenseSymbol(key='Exception')),
            Token(143, 143, ' ', None),
            Token(144, 146, 'and', Keyword(value='and', type=TOKEN_AND)),
            Token(147, 147, ' ', None),
            Token(148, 150, 'mit', LicenseSymbol(key='mit')),
            Token(151, 151, ' ', None),
            Token(152, 153, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(154, 154, ' ', None),
            Token(155, 159, 'later', LicenseSymbol(key='later')),
            Token(160, 160, ')', Keyword(value=')', type=TOKEN_RPAR)),
            Token(161, 161, ' ', None),
            Token(162, 163, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(164, 164, ' ', None),
            Token(165, 168, 'LGPL', LicenseSymbol(key='LGPL')),
            Token(169, 169, ' ', None),
            Token(170, 172, '2.1', LicenseSymbol(key='2.1')),
            Token(173, 173, ' ', None),
            Token(174, 175, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(176, 176, ' ', None),
            Token(177, 179, 'mit', LicenseSymbol(key='mit')),
            Token(180, 180, ' ', None),
            Token(181, 182, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(183, 183, ' ', None),
            Token(184, 190, 'GPL-2.0', LicenseSymbol(key='GPL-2.0')),
            Token(191, 191, ' ', None),
            Token(192, 193, 'or', Keyword(value='or', type=TOKEN_OR)),
            Token(194, 194, ' ', None),
            Token(195, 199, 'LATER', LicenseSymbol(key='LATER')),
            Token(200, 200, ' ', None),
            Token(201, 204, 'with', Keyword(value='with', type=TOKEN_WITH)),
            Token(205, 205, ' ', None),
            Token(206, 214, 'SOMETHING', LicenseSymbol(key='SOMETHING')),
            Token(215, 215, ' ', None),
            Token(216, 219, 'with', Keyword(value='with', type=TOKEN_WITH)),
            Token(220, 220, ' ', None),
            Token(221, 225, 'ELSE+', LicenseSymbol(key='ELSE+')),
            Token(226, 226, ' ', None),
            Token(227, 229, 'and', Keyword(value='and', type=TOKEN_AND)),
            Token(230, 230, ' ', None),
            Token(231, 234, 'lgpl', LicenseSymbol(key='lgpl')),
            Token(235, 235, ' ', None),
            Token(236, 238, '2.1', LicenseSymbol(key='2.1',))
        ]
        assert results == expected

    def test_tokenize_can_handle_expressions_with_symbols_that_contain_a_colon(self):
        licensing = Licensing()
        expression = 'DocumentRef-James-1.0:LicenseRef-Eric-2.0'

        result = list(licensing.tokenize(expression))
        expected = [
            (LicenseSymbol(u'DocumentRef-James-1.0:LicenseRef-Eric-2.0', is_exception=False),
             u'DocumentRef-James-1.0:LicenseRef-Eric-2.0', 0)
        ]

        assert result == expected

    def test_tokenize_simple_can_handle_expressions_with_symbols_that_contain_a_colon(self):
        licensing = Licensing()
        expression = 'DocumentRef-James-1.0:LicenseRef-Eric-2.0'

        result = list(licensing.tokenize(expression, simple=True))
        expected = [
            (LicenseSymbol(u'DocumentRef-James-1.0:LicenseRef-Eric-2.0', is_exception=False),
             u'DocumentRef-James-1.0:LicenseRef-Eric-2.0', 0)
        ]

        assert result == expected

    def test_tokenize_can_handle_expressions_with_tabs_and_new_lines(self):
        licensing = Licensing()
        expression = 'this\t \tis \n\n an expression'
        result = list(licensing.tokenize(expression, simple=False))
        expected = [
            (LicenseSymbol(u'this is an expression', is_exception=False),
            u'this is an expression', 0)
        ]
        assert result == expected

    def test_tokenize_simple_can_handle_expressions_with_tabs_and_new_lines(self):
        licensing = Licensing()
        expression = 'this\t \tis \n\n an expression'
        result = list(licensing.tokenize(expression, simple=True))
        expected = [
            (LicenseSymbol(u'this', is_exception=False), u'this', 0),
            (LicenseSymbol(u'is', is_exception=False), u'is', 7),
            (LicenseSymbol(u'an', is_exception=False), u'an', 13),
            (LicenseSymbol(u'expression', is_exception=False), u'expression', 16)
        ]
        assert result == expected

    def test_tokenize_step_by_step_does_not_munge_trailing_symbols(self):
        gpl2 = LicenseSymbol(key='GPL-2.0')
        gpl2plus = LicenseSymbol(key='GPL-2.0 or LATER')
        cpex = LicenseSymbol(key='classpath Exception', is_exception=True)

        mitthing = LicenseSymbol(key='mithing')
        mitthing_with_else = LicenseSymbol(key='mitthing with else+', is_exception=False)

        mit = LicenseSymbol(key='mit')
        mitplus = LicenseSymbol(key='mit or later')

        elsish = LicenseSymbol(key='else')
        elsishplus = LicenseSymbol(key='else+')

        lgpl = LicenseSymbol(key='LGPL 2.1')

        licensing = Licensing([
            gpl2,
            gpl2plus,
            cpex,
            mitthing,
            mitthing_with_else,
            mit,
            mitplus,
            elsish,
            elsishplus,
            lgpl,
        ])

        expr = (' GPL-2.0 or later with classpath Exception and mit and '
                'mit with mitthing with ELSE+ or LGPL 2.1 and '
                'GPL-2.0 or LATER with Classpath Exception and '
                'mit or later or LGPL 2.1 or mit or GPL-2.0 or LATER '
                'with mitthing with ELSE+ and lgpl 2.1 or gpl-2.0')

        # fist tokenize
        tokenizer = licensing.get_advanced_tokenizer()
        result = list(tokenizer.tokenize(expr))
        expected = [
            Token(1, 16, 'GPL-2.0 or later', LicenseSymbol(u'GPL-2.0 or LATER')),
            Token(18, 21, 'with', Keyword(value=u'with', type=10)),
            Token(23, 41, 'classpath Exception', LicenseSymbol(u'classpath Exception', is_exception=True)),
            Token(43, 45, 'and', Keyword(value=u'and', type=1)),
            Token(47, 49, 'mit', LicenseSymbol(u'mit')),
            Token(51, 53, 'and', Keyword(value=u'and', type=1)),
            Token(55, 57, 'mit', LicenseSymbol(u'mit')),
            Token(59, 62, 'with', Keyword(value=u'with', type=10)),
            Token(64, 82, 'mitthing with ELSE+', LicenseSymbol(u'mitthing with else+')),
            Token(84, 85, 'or', Keyword(value=u'or', type=2)),
            Token(87, 94, 'LGPL 2.1', LicenseSymbol(u'LGPL 2.1')),
            Token(96, 98, 'and', Keyword(value=u'and', type=1)),
            Token(100, 115, 'GPL-2.0 or LATER', LicenseSymbol(u'GPL-2.0 or LATER')),
            Token(117, 120, 'with', Keyword(value=u'with', type=10)),
            Token(122, 140, 'Classpath Exception', LicenseSymbol(u'classpath Exception', is_exception=True)),
            Token(142, 144, 'and', Keyword(value=u'and', type=1)),
            Token(146, 157, 'mit or later', LicenseSymbol(u'mit or later')),
            Token(159, 160, 'or', Keyword(value=u'or', type=2)),
            Token(162, 169, 'LGPL 2.1', LicenseSymbol(u'LGPL 2.1')),
            Token(171, 172, 'or', Keyword(value=u'or', type=2)),
            Token(174, 176, 'mit', LicenseSymbol(u'mit')),
            Token(178, 179, 'or', Keyword(value=u'or', type=2)),
            Token(181, 196, 'GPL-2.0 or LATER', LicenseSymbol(u'GPL-2.0 or LATER')),
            Token(198, 201, 'with', Keyword(value=u'with', type=10)),
            Token(203, 221, 'mitthing with ELSE+', LicenseSymbol(u'mitthing with else+')),
            Token(223, 225, 'and', Keyword(value=u'and', type=1)),
            Token(227, 234, 'lgpl 2.1', LicenseSymbol(u'LGPL 2.1')),
            Token(236, 237, 'or', Keyword(value=u'or', type=2)),
            Token(239, 245, 'gpl-2.0', LicenseSymbol(u'GPL-2.0'))
        ]

        assert result == expected

        expected_groups = [
            (Token(1, 16, 'GPL-2.0 or later', LicenseSymbol(u'GPL-2.0 or LATER')),
             Token(18, 21, 'with', Keyword(value=u'with', type=10)),
             Token(23, 41, 'classpath Exception', LicenseSymbol(u'classpath Exception', is_exception=True))),

            (Token(43, 45, 'and', Keyword(value=u'and', type=1)),),
            (Token(47, 49, 'mit', LicenseSymbol(u'mit')),),
            (Token(51, 53, 'and', Keyword(value=u'and', type=1)),),

            (Token(55, 57, 'mit', LicenseSymbol(u'mit')),
             Token(59, 62, 'with', Keyword(value=u'with', type=10)),
             Token(64, 82, 'mitthing with ELSE+', LicenseSymbol(u'mitthing with else+'))),

            (Token(84, 85, 'or', Keyword(value=u'or', type=2)),),
            (Token(87, 94, 'LGPL 2.1', LicenseSymbol(u'LGPL 2.1')),),
            (Token(96, 98, 'and', Keyword(value=u'and', type=1)),),

            (Token(100, 115, 'GPL-2.0 or LATER', LicenseSymbol(u'GPL-2.0 or LATER')),
             Token(117, 120, 'with', Keyword(value=u'with', type=10)),
             Token(122, 140, 'Classpath Exception', LicenseSymbol(u'classpath Exception', is_exception=True))),

            (Token(142, 144, 'and', Keyword(value=u'and', type=1)),),
            (Token(146, 157, 'mit or later', LicenseSymbol(u'mit or later')),),
            (Token(159, 160, 'or', Keyword(value=u'or', type=2)),),
            (Token(162, 169, 'LGPL 2.1', LicenseSymbol(u'LGPL 2.1')),),
            (Token(171, 172, 'or', Keyword(value=u'or', type=2)),),
            (Token(174, 176, 'mit', LicenseSymbol(u'mit')),),
            (Token(178, 179, 'or', Keyword(value=u'or', type=2)),),

            (Token(181, 196, 'GPL-2.0 or LATER', LicenseSymbol(u'GPL-2.0 or LATER')),
             Token(198, 201, 'with', Keyword(value=u'with', type=10)),
             Token(203, 221, 'mitthing with ELSE+', LicenseSymbol(u'mitthing with else+'))),

            (Token(223, 225, 'and', Keyword(value=u'and', type=1)),),
            (Token(227, 234, 'lgpl 2.1', LicenseSymbol(u'LGPL 2.1')),),
            (Token(236, 237, 'or', Keyword(value=u'or', type=2)),),
            (Token(239, 245, 'gpl-2.0', LicenseSymbol(u'GPL-2.0')),)
        ]
        result_groups = list(build_token_groups_for_with_subexpression(result))
        assert expected_groups == result_groups

        # finally retest it all with tokenize

        gpl2plus_with_cpex = LicenseWithExceptionSymbol(license_symbol=gpl2plus, exception_symbol=cpex)
        gpl2plus_with_someplus = LicenseWithExceptionSymbol(license_symbol=gpl2plus, exception_symbol=mitthing_with_else)

        mit_with_mitthing_with_else = LicenseWithExceptionSymbol(license_symbol=mit, exception_symbol=mitthing_with_else)

        expected = [
            (gpl2plus_with_cpex, 'GPL-2.0 or later with classpath Exception', 1),
            (TOKEN_AND, 'and', 43),
            (mit, 'mit', 47),
            (TOKEN_AND, 'and', 51),
            (mit_with_mitthing_with_else, 'mit with mitthing with ELSE+', 55),
            (TOKEN_OR, 'or', 84),
            (lgpl, 'LGPL 2.1', 87),
            (TOKEN_AND, 'and', 96),
            (gpl2plus_with_cpex, 'GPL-2.0 or LATER with Classpath Exception', 100),
            (TOKEN_AND, 'and', 142),
            (mitplus, 'mit or later', 146),
            (TOKEN_OR, 'or', 159),
            (lgpl, 'LGPL 2.1', 162),
            (TOKEN_OR, 'or', 171),
            (mit, 'mit', 174),
            (TOKEN_OR, 'or', 178),
            (gpl2plus_with_someplus, 'GPL-2.0 or LATER with mitthing with ELSE+', 181),
            (TOKEN_AND, 'and', 223),
            (lgpl, 'lgpl 2.1', 227),
            (TOKEN_OR, 'or', 236),
            (gpl2, 'gpl-2.0', 239),
        ]

        assert list(licensing.tokenize(expr)) == expected


class LicensingExpression(TestCase):

    def test_is_equivalent_with_same_Licensing(self):
        licensing = Licensing()
        parsed1 = licensing.parse('gpl-2.0 AND zlib')
        parsed2 = licensing.parse('gpl-2.0 AND zlib AND zlib')
        assert licensing.is_equivalent(parsed1, parsed2)
        assert Licensing().is_equivalent(parsed1, parsed2)

    def test_is_equivalent_with_same_Licensing2(self):
        licensing = Licensing()
        parsed1 = licensing.parse('(gpl-2.0 AND zlib) or lgpl')
        parsed2 = licensing.parse('lgpl or (gpl-2.0 AND zlib)')
        assert licensing.is_equivalent(parsed1, parsed2)
        assert Licensing().is_equivalent(parsed1, parsed2)

    def test_is_equivalent_with_different_Licensing_and_compound_expression(self):
        licensing1 = Licensing()
        licensing2 = Licensing()
        parsed1 = licensing1.parse('gpl-2.0 AND zlib')
        parsed2 = licensing2.parse('gpl-2.0 AND zlib AND zlib')
        assert Licensing().is_equivalent(parsed1, parsed2)
        assert licensing1.is_equivalent(parsed1, parsed2)
        assert licensing2.is_equivalent(parsed1, parsed2)

    def test_is_equivalent_with_different_Licensing_and_compound_expression2(self):
        licensing1 = Licensing()
        licensing2 = Licensing()
        parsed1 = licensing1.parse('gpl-2.0 AND zlib')
        parsed2 = licensing2.parse('zlib and gpl-2.0')
        assert Licensing().is_equivalent(parsed1, parsed2)
        assert licensing1.is_equivalent(parsed1, parsed2)
        assert licensing2.is_equivalent(parsed1, parsed2)

    def test_is_equivalent_with_different_Licensing_and_simple_expression(self):
        licensing1 = Licensing()
        licensing2 = Licensing()
        parsed1 = licensing1.parse('gpl-2.0')
        parsed2 = licensing2.parse('gpl-2.0')
        assert Licensing().is_equivalent(parsed1, parsed2)
        assert licensing1.is_equivalent(parsed1, parsed2)
        assert licensing2.is_equivalent(parsed1, parsed2)

    def test_is_equivalent_with_symbols_and_complex_expression(self):
        licensing_no_sym = Licensing()
        licensing1 = Licensing([
            'GPL-2.0 or LATER',
            'classpath Exception',
            'agpl+',
            'mit',
            'LGPL 2.1',
        ])
        licensing2 = Licensing([
            'GPL-2.0 or LATER',
            'classpath Exception',
            'agpl+',
            'mit',
            'LGPL 2.1',
        ])

        parsed1 = licensing1.parse(' ((LGPL 2.1 or mit) and GPL-2.0 or LATER with classpath Exception) and agpl+')
        parsed2 = licensing2.parse(' agpl+ and (GPL-2.0 or LATER with classpath Exception and (mit  or LGPL 2.1))')
        assert licensing1.is_equivalent(parsed1, parsed2)
        assert licensing2.is_equivalent(parsed1, parsed2)
        assert licensing_no_sym.is_equivalent(parsed1, parsed2)

        parsed3 = licensing1.parse(' ((LGPL 2.1 or mit) OR GPL-2.0 or LATER with classpath Exception) and agpl+')
        assert not licensing1.is_equivalent(parsed1, parsed3)
        assert not licensing2.is_equivalent(parsed1, parsed3)
        assert not licensing_no_sym.is_equivalent(parsed1, parsed3)

    def test_all_symbol_classes_can_compare_and_sort(self):
        l1 = LicenseSymbol('a')
        l2 = LicenseSymbol('b')
        lx = LicenseWithExceptionSymbol(l1, l2)
        lx2 = LicenseWithExceptionSymbol(l1, l2)
        assert not (lx < lx2)
        assert not (lx2 < lx)
        assert lx2 == lx
        assert not (lx2 != lx)
        assert l1 < l2
        assert l2 > l1
        assert not (l2 == l1)
        assert l2 != l1

        class SymLike(object):

            def __init__(self, key, is_exception=False):
                self.key = key
                self.is_exception = is_exception

        l3 = LicenseSymbolLike(SymLike('b'))
        lx3 = LicenseWithExceptionSymbol(l1, l3)
        assert not (lx < lx3)
        assert not (lx3 < lx)
        assert lx3 == lx
        assert hash(lx3) == hash(lx)
        assert not (lx3 != lx)

        assert l2 == l3
        assert hash(l2) == hash(l3)

        l4 = LicenseSymbolLike(SymLike('c'))

        expected = [l1, lx, lx2, lx3, l3, l2, l4]
        assert sorted([l4, l3, l2, l1, lx , lx2, lx3]) == expected


class MockLicensesTest(TestCase):

    def test_licensing_can_use_mocklicense_tuple(self):
        MockLicense = namedtuple('MockLicense', 'key aliases is_exception')

        licenses = [
            MockLicense('gpl-2.0', ['GPL-2.0'], False),
            MockLicense('classpath-2.0', ['Classpath-Exception-2.0'], True),
            MockLicense('gpl-2.0-plus', ['GPL-2.0-or-later', 'GPL-2.0 or-later'], False),
            MockLicense('lgpl-2.1-plus', ['LGPL-2.1-or-later'], False),
        ]
        licensing = Licensing(licenses)

        ex1 = '(GPL-2.0-or-later with Classpath-Exception-2.0 or GPL-2.0 or-later) and LGPL-2.1-or-later'
        expression1 = licensing.parse(ex1, validate=False, strict=False)
        assert ['gpl-2.0-plus', 'classpath-2.0', 'lgpl-2.1-plus'] == licensing.license_keys(expression1)

        ex2 = 'LGPL-2.1-or-later and (GPL-2.0-or-later oR GPL-2.0-or-later with Classpath-Exception-2.0)'
        expression2 = licensing.parse(ex2, validate=True, strict=False)

        ex3 = 'LGPL-2.1-or-later and (GPL-2.0-or-later oR GPL-2.0-or-later)'
        expression3 = licensing.parse(ex3, validate=True, strict=False)

        self.assertTrue(licensing.is_equivalent(expression1, expression2))
        self.assertTrue(licensing.is_equivalent(expression2, expression1))
        self.assertFalse(licensing.is_equivalent(expression1, expression3))
        self.assertFalse(licensing.is_equivalent(expression2, expression3))

    def test_and_and_or_is_invalid(self):
        expression = 'gpl-2.0 with classpath and and or gpl-2.0-plus'
        licensing = Licensing()
        try:
            licensing.parse(expression)
            self.fail('Exception not raised')
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 27,
                'token_string': 'and',
                'token_type': TOKEN_AND}
            assert _parse_error_as_dict(pe) == expected

    def test_or_or_is_invalid(self):
        expression = 'gpl-2.0 with classpath or or or or gpl-2.0-plus'
        licensing = Licensing()
        try:
            licensing.parse(expression)
        except ParseError as pe:
            expected = {
                'error_code': PARSE_INVALID_OPERATOR_SEQUENCE,
                'position': 26,
                'token_string': 'or',
                'token_type': TOKEN_OR}
            assert _parse_error_as_dict(pe) == expected

    def test_tokenize_or_or(self):
        expression = 'gpl-2.0 with classpath or or or gpl-2.0-plus'
        licensing = Licensing()
        results = list(licensing.tokenize(expression))
        expected = [
            (LicenseWithExceptionSymbol(
                license_symbol=LicenseSymbol(u'gpl-2.0'),
                exception_symbol=LicenseSymbol(u'classpath')), 'gpl-2.0 with classpath', 0),
            (2, 'or', 23),
            (2, 'or', 26),
            (2, 'or', 29),
            (LicenseSymbol(u'gpl-2.0-plus'), 'gpl-2.0-plus', 32)
        ]

        assert results == expected


class LicensingValidateTest(TestCase):
    licensing = Licensing(
        [
            LicenseSymbol(key='GPL-2.0-or-later', is_exception=False),
            LicenseSymbol(key='MIT', is_exception=False),
            LicenseSymbol(key='Apache-2.0', is_exception=False),
            LicenseSymbol(key='WxWindows-exception-3.1', is_exception=True),
        ]
    )

    def test_validate_simple(self):
        result = self.licensing.validate('GPL-2.0-or-later AND MIT')
        assert result.original_expression == 'GPL-2.0-or-later AND MIT'
        assert result.normalized_expression == 'GPL-2.0-or-later AND MIT'
        assert result.errors == []
        assert result.invalid_symbols == []

    def test_validation_invalid_license_key(self):
        result = self.licensing.validate('cool-license')
        assert result.original_expression == 'cool-license'
        assert not result.normalized_expression
        assert result.errors == ['Unknown license key(s): cool-license']
        assert result.invalid_symbols == ['cool-license']

    def test_validate_exception(self):
        result = self.licensing.validate('GPL-2.0-or-later WITH WxWindows-exception-3.1')
        assert result.original_expression == 'GPL-2.0-or-later WITH WxWindows-exception-3.1'
        assert result.normalized_expression == 'GPL-2.0-or-later WITH WxWindows-exception-3.1'
        assert result.errors == []
        assert result.invalid_symbols == []

    def test_validation_exception_with_choice(self):
        result = self.licensing.validate('GPL-2.0-or-later WITH WxWindows-exception-3.1 OR MIT')
        assert result.original_expression == 'GPL-2.0-or-later WITH WxWindows-exception-3.1 OR MIT'
        assert result.normalized_expression == 'GPL-2.0-or-later WITH WxWindows-exception-3.1 OR MIT'
        assert result.errors == []
        assert result.invalid_symbols == []

    def test_validation_exception_as_regular_key(self):
        result = self.licensing.validate('GPL-2.0-or-later AND WxWindows-exception-3.1')
        assert result.original_expression == 'GPL-2.0-or-later AND WxWindows-exception-3.1'
        assert not result.normalized_expression
        assert result.errors == ['A license exception symbol can only be used as an exception in a "WITH exception" statement. for token: "WxWindows-exception-3.1" at position: 21']
        assert result.invalid_symbols == ['WxWindows-exception-3.1']

    def test_validation_bad_syntax(self):
        result = self.licensing.validate('Apache-2.0 + MIT')
        assert result.original_expression == 'Apache-2.0 + MIT'
        assert not result.normalized_expression
        assert result.errors == ['Invalid symbols sequence such as (A B) for token: "+" at position: 11']
        assert result.invalid_symbols == ['+']

    def test_validation_invalid_license_exception(self):
        result = self.licensing.validate('Apache-2.0 WITH MIT')
        assert result.original_expression == 'Apache-2.0 WITH MIT'
        assert not result.normalized_expression
        assert result.errors == ["A plain license symbol cannot be used as an exception in a \"WITH symbol\" statement. for token: \"MIT\" at position: 16"]
        assert result.invalid_symbols == ['MIT']

    def test_validation_invalid_license_exception_strict_false(self):
        result = self.licensing.validate('Apache-2.0 WITH MIT', strict=False)
        assert result.original_expression == 'Apache-2.0 WITH MIT'
        assert result.normalized_expression == 'Apache-2.0 WITH MIT'
        assert result.errors == []
        assert result.invalid_symbols == []


class UtilTest(TestCase):
    test_data_dir = join(dirname(__file__), 'data')

    def test_build_licensing(self):
        test_license_index_location = join(self.test_data_dir, 'test_license_key_index.json')
        with open(test_license_index_location) as f:
            license_info = json.load(f)
        lics = [
            {
                'key': l.get('license_key', ''),
                'is_exception': l.get('is_exception', ''),
            } for l in license_info if l.get('spdx_license_key')
        ]
        syms = [LicenseSymbol(**l) for l in lics]
        expected = Licensing(syms)

        test_license_index = get_license_index(license_index_location=test_license_index_location)
        result = build_licensing(test_license_index)

        assert result.known_symbols == expected.known_symbols
        assert result.known_symbols_lowercase == expected.known_symbols_lowercase
        # Ensure deprecated licenses are not loaded
        assert 'aladdin-md5' not in result.known_symbols
        assert 'aladdin-md5' not in result.known_symbols_lowercase

    def test_build_spdx_licensing(self):
        test_license_index_location = join(self.test_data_dir, 'test_license_key_index.json')
        with open(test_license_index_location) as f:
            license_info = json.load(f)
        lics = [
            {
                'key': l.get('spdx_license_key', ''),
                'aliases': l.get('other_spdx_license_keys', ''),
                'is_exception': l.get('is_exception', ''),
            } for l in license_info if l.get('spdx_license_key')
        ]
        syms = [LicenseSymbol(**l) for l in lics]
        expected = Licensing(syms)

        test_license_index = get_license_index(license_index_location=test_license_index_location)
        result = build_spdx_licensing(test_license_index)

        assert result.known_symbols == expected.known_symbols
        assert result.known_symbols_lowercase == expected.known_symbols_lowercase
        # Ensure deprecated licenses are not loaded
        assert 'aladdin-md5' not in result.known_symbols
        assert 'aladdin-md5' not in result.known_symbols_lowercase

    def test_get_license_key_info(self):
        test_license_index_location = join(self.test_data_dir, 'test_license_key_index.json')
        with open(test_license_index_location) as f:
            expected = json.load(f)
        result = get_license_index(test_license_index_location)
        assert result == expected

    def test_get_license_key_info_vendored(self):
        curr_dir = dirname(abspath(__file__))
        parent_dir = pathlib.Path(curr_dir).parent
        vendored_license_key_index_location = parent_dir.joinpath(
            'src',
            'license_expression',
            'data',
            'scancode-licensedb-index.json'
        )
        with open(vendored_license_key_index_location) as f:
            expected = json.load(f)
        result = get_license_index()
        assert result == expected


class CombineExpressionTest(TestCase):

    def test_combine_expressions_with_empty_input(self):
        assert combine_expressions(None) == None
        assert combine_expressions([]) == None

    def test_combine_expressions_with_regular(self):
        assert str(combine_expressions(['mit', 'apache-2.0'])) == 'mit AND apache-2.0'

    def test_combine_expressions_with_duplicated_elements(self):
        assert str(combine_expressions(['mit', 'apache-2.0', 'mit'])) == 'mit AND apache-2.0'

    def test_combine_expressions_with_or_relationship(self):
        assert str(combine_expressions(['mit', 'apache-2.0'], 'OR')) == 'mit OR apache-2.0'