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
//! The `pact_matching` crate provides the core logic to performing matching on HTTP requests
//! and responses. It implements the [V3 Pact specification](https://github.com/pact-foundation/pact-specification/tree/version-3)
//! and [V4 Pact specification](https://github.com/pact-foundation/pact-specification/tree/version-4).
//!
//! ## To use it
//!
//! To use it, add it to your dependencies in your cargo manifest.
//!
//! This crate provides three functions: [`match_request`](fn.match_request.html), [`match_response`](fn.match_response.html)
//! and [`match_message`](fn.match_message.html).
//! These functions take an expected and actual request, response or message
//! model from the [`models`)(models/index.html) module, and return a vector of mismatches.
//!
//! To compare any incoming request, it first needs to be converted to a [`models::Request`](models/struct.Request.html) and then can be compared. Same for
//! any response.
//!
//! ## Reading and writing Pact files
//!
//! The [`Pact`](models/struct.Pact.html) struct in the [`models`)(models/index.html) module has methods to read and write pact JSON files. It supports all the specification
//! versions up to V4, but will convert a V1, V1.1 or V2 spec file to a V3 format.
//!
//! ## Matching request and response parts
//!
//! V3 specification matching is supported for both JSON and XML bodies, headers, query strings and request paths.
//!
//! To understand the basic rules of matching, see [Matching Gotchas](https://github.com/realestate-com-au/pact/wiki/Matching-gotchas).
//! For example test cases for matching, see the [Pact Specification Project, version 3](https://github.com/bethesque/pact-specification/tree/version-3).
//!
//! By default, Pact will use string equality matching following Postel's Law. This means
//! that for an actual value to match an expected one, they both must consist of the same
//! sequence of characters. For collections (basically Maps and Lists), they must have the
//! same elements that match in the same sequence, with cases where the additional elements
//! in an actual Map are ignored.
//!
//! Matching rules can be defined for both request and response elements based on a pseudo JSON-Path
//! syntax.
//!
//! ### Matching Bodies
//!
//! For the most part, matching involves matching request and response bodies in JSON or XML format.
//! Other formats will either have their own matching rules, or will follow the JSON one.
//!
//! #### JSON body matching rules
//!
//! Bodies consist of Objects (Maps of Key-Value pairs), Arrays (Lists) and values (Strings, Numbers, true, false, null).
//! Body matching rules are prefixed with `$`.
//!
//! The following method is used to determine if two bodies match:
//!
//! 1. If both the actual body and expected body are empty, the bodies match.
//! 2. If the actual body is non-empty, and the expected body empty, the bodies match.
//! 3. If the actual body is empty, and the expected body non-empty, the bodies don't match.
//! 4. Otherwise do a comparison on the contents of the bodies.
//!
//! ##### For the body contents comparison:
//!
//! 1. If the actual and expected values are both Objects, compare as Maps.
//! 2. If the actual and expected values are both Arrays, compare as Lists.
//! 3. If the expected value is an Object, and the actual is not, they don't match.
//! 4. If the expected value is an Array, and the actual is not, they don't match.
//! 5. Otherwise, compare the values
//!
//! ##### For comparing Maps
//!
//! 1. If the actual map is non-empty while the expected is empty, they don't match.
//! 2. If we allow unexpected keys, and the number of expected keys is greater than the actual keys,
//! they don't match.
//! 3. If we don't allow unexpected keys, and the expected and actual maps don't have the
//! same number of keys, they don't match.
//! 4. Otherwise, for each expected key and value pair:
//!     1. if the actual map contains the key, compare the values
//!     2. otherwise they don't match
//!
//! Postel's law governs if we allow unexpected keys or not.
//!
//! ##### For comparing lists
//!
//! 1. If there is a body matcher defined that matches the path to the list, default
//! to that matcher and then compare the list contents.
//! 2. If the expected list is empty and the actual one is not, the lists don't match.
//! 3. Otherwise
//!     1. compare the list sizes
//!     2. compare the list contents
//!
//! ###### For comparing list contents
//!
//! 1. For each value in the expected list:
//!     1. If the index of the value is less than the actual list's size, compare the value
//!        with the actual value at the same index using the method for comparing values.
//!     2. Otherwise the value doesn't match
//!
//! ##### For comparing values
//!
//! 1. If there is a matcher defined that matches the path to the value, default to that
//! matcher
//! 2. Otherwise compare the values using equality.
//!
//! #### XML body matching rules
//!
//! Bodies consist of a root element, Elements (Lists with children), Attributes (Maps) and values (Strings).
//! Body matching rules are prefixed with `$`.
//!
//! The following method is used to determine if two bodies match:
//!
//! 1. If both the actual body and expected body are empty, the bodies match.
//! 2. If the actual body is non-empty, and the expected body empty, the bodies match.
//! 3. If the actual body is empty, and the expected body non-empty, the bodies don't match.
//! 4. Otherwise do a comparison on the contents of the bodies.
//!
//! ##### For the body contents comparison:
//!
//! Start by comparing the root element.
//!
//! ##### For comparing elements
//!
//! 1. If there is a body matcher defined that matches the path to the element, default
//! to that matcher on the elements name or children.
//! 2. Otherwise the elements match if they have the same name.
//!
//! Then, if there are no mismatches:
//!
//! 1. compare the attributes of the element
//! 2. compare the child elements
//! 3. compare the text nodes
//!
//! ##### For comparing attributes
//!
//! Attributes are treated as a map of key-value pairs.
//!
//! 1. If the actual map is non-empty while the expected is empty, they don't match.
//! 2. If we allow unexpected keys, and the number of expected keys is greater than the actual keys,
//! they don't match.
//! 3. If we don't allow unexpected keys, and the expected and actual maps don't have the
//! same number of keys, they don't match.
//!
//! Then, for each expected key and value pair:
//!
//! 1. if the actual map contains the key, compare the values
//! 2. otherwise they don't match
//!
//! Postel's law governs if we allow unexpected keys or not. Note for matching paths, attribute names are prefixed with an `@`.
//!
//! ###### For comparing child elements
//!
//! 1. If there is a matcher defined for the path to the child elements, then pad out the expected child elements to have the
//! same size as the actual child elements.
//! 2. Otherwise
//!     1. If the actual children is non-empty while the expected is empty, they don't match.
//!     2. If we allow unexpected keys, and the number of expected children is greater than the actual children,
//!     they don't match.
//!     3. If we don't allow unexpected keys, and the expected and actual children don't have the
//!     same number of elements, they don't match.
//!
//! Then, for each expected and actual element pair, compare them using the rules for comparing elements.
//!
//! ##### For comparing text nodes
//!
//! Text nodes are combined into a single string and then compared as values.
//!
//! 1. If there is a matcher defined that matches the path to the text node (text node paths end with `#text`), default to that
//! matcher
//! 2. Otherwise compare the text using equality.
//!
//!
//! ##### For comparing values
//!
//! 1. If there is a matcher defined that matches the path to the value, default to that
//! matcher
//! 2. Otherwise compare the values using equality.
//!
//! ### Matching Paths
//!
//! Paths are matched by the following:
//!
//! 1. If there is a matcher defined for `path`, default to that matcher.
//! 2. Otherwise paths are compared as Strings
//!
//! ### Matching Queries
//!
//! 1. If the actual and expected query strings are empty, they match.
//! 2. If the actual is not empty while the expected is, they don't match.
//! 3. If the actual is empty while the expected is not, they don't match.
//! 4. Otherwise convert both into a Map of keys mapped to a list values, and compare those.
//!
//! #### Matching Query Maps
//!
//! Query strings are parsed into a Map of keys mapped to lists of values. Key value
//! pairs can be in any order, but when the same key appears more than once the values
//! are compared in the order they appear in the query string.
//!
//! ### Matching Headers
//!
//! 1. Do a case-insensitive sort of the headers by keys
//! 2. For each expected header in the sorted list:
//!     1. If the actual headers contain that key, compare the header values
//!     2. Otherwise the header does not match
//!
//! For matching header values:
//!
//! 1. If there is a matcher defined for `header.<HEADER_KEY>`, default to that matcher
//! 2. Otherwise strip all whitespace after commas and compare the resulting strings.
//!
//! #### Matching Request Headers
//!
//! Request headers are matched by excluding the cookie header.
//!
//! #### Matching Request cookies
//!
//! If the list of expected cookies contains all the actual cookies, the cookies match.
//!
//! ### Matching Status Codes
//!
//! Status codes are compared as integer values.
//!
//! ### Matching HTTP Methods
//!
//! The actual and expected methods are compared as case-insensitive strings.
//!
//! ## Matching Rules
//!
//! Pact supports extending the matching rules on each type of object (Request or Response) with a `matchingRules` element in the pact file.
//! This is a map of JSON path strings to a matcher. When an item is being compared, if there is an entry in the matching
//! rules that corresponds to the path to the item, the comparison will be delegated to the defined matcher. Note that the
//! matching rules cascade, so a rule can be specified on a value and will apply to all children of that value.
//!
//! ## Matcher Path expressions
//!
//! Pact does not support the full JSON path expressions, only ones that match the following rules:
//!
//! 1. All paths start with a dollar (`$`), representing the root.
//! 2. All path elements are separated by periods (`.`), except array indices which use square brackets (`[]`).
//! 3. Path elements represent keys.
//! 4. A star (`*`) can be used to match all keys of a map or all items of an array (one level only).
//!
//! So the expression `$.item1.level[2].id` will match the highlighted item in the following body:
//!
//! ```js,ignore
//! {
//!   "item1": {
//!     "level": [
//!       {
//!         "id": 100
//!       },
//!       {
//!         "id": 101
//!       },
//!       {
//!         "id": 102 // <---- $.item1.level[2].id
//!       },
//!       {
//!         "id": 103
//!       }
//!     ]
//!   }
//! }
//! ```
//!
//! while `$.*.level[*].id` will match all the ids of all the levels for all items.
//!
//! ### Matcher selection algorithm
//!
//! Due to the star notation, there can be multiple matcher paths defined that correspond to an item. The first, most
//! specific expression is selected by assigning weightings to each path element and taking the product of the weightings.
//! The matcher with the path with the largest weighting is used.
//!
//! * The root node (`$`) is assigned the value 2.
//! * Any path element that does not match is assigned the value 0.
//! * Any property name that matches a path element is assigned the value 2.
//! * Any array index that matches a path element is assigned the value 2.
//! * Any star (`*`) that matches a property or array index is assigned the value 1.
//! * Everything else is assigned the value 0.
//!
//! So for the body with highlighted item:
//!
//! ```js,ignore
//! {
//!   "item1": {
//!     "level": [
//!       {
//!         "id": 100
//!       },
//!       {
//!         "id": 101
//!       },
//!       {
//!         "id": 102 // <--- Item under consideration
//!       },
//!       {
//!         "id": 103
//!       }
//!     ]
//!   }
//! }
//! ```
//!
//! The expressions will have the following weightings:
//!
//! | expression | weighting calculation | weighting |
//! |------------|-----------------------|-----------|
//! | $ | $(2) | 2 |
//! | $.item1 | $(2).item1(2) | 4 |
//! | $.item2 | $(2).item2(0) | 0 |
//! | $.item1.level | $(2).item1(2).level(2) | 8 |
//! | $.item1.level\[1\] | $(2).item1(2).level(2)\[1(2)\] | 16 |
//! | $.item1.level\[1\].id | $(2).item1(2).level(2)\[1(2)\].id(2) | 32 |
//! | $.item1.level\[1\].name | $(2).item1(2).level(2)\[1(2)\].name(0) | 0 |
//! | $.item1.level\[2\] | $(2).item1(2).level(2)\[2(0)\] | 0 |
//! | $.item1.level\[2\].id | $(2).item1(2).level(2)\[2(0)\].id(2) | 0 |
//! | $.item1.level\[*\].id | $(2).item1(2).level(2)\[*(1)\].id(2) | 16 |
//! | $.\*.level\[\*\].id | $(2).*(1).level(2)\[*(1)\].id(2) | 8 |
//!
//! So for the item with id 102, the matcher with path `$.item1.level\[1\].id` and weighting 32 will be selected.
//!
//! ## Supported matchers
//!
//! The following matchers are supported:
//!
//! | matcher | Spec Version | example configuration | description |
//! |---------|--------------|-----------------------|-------------|
//! | Equality | V1 | `{ "match": "equality" }` | This is the default matcher, and relies on the equals operator |
//! | Regex | V2 | `{ "match": "regex", "regex": "\\d+" }` | This executes a regular expression match against the string representation of a values. |
//! | Type | V2 | `{ "match": "type" }` | This executes a type based match against the values, that is, they are equal if they are the same type. |
//! | MinType | V2 | `{ "match": "type", "min": 2 }` | This executes a type based match against the values, that is, they are equal if they are the same type. In addition, if the values represent a collection, the length of the actual value is compared against the minimum. |
//! | MaxType | V2 | `{ "match": "type", "max": 10 }` | This executes a type based match against the values, that is, they are equal if they are the same type. In addition, if the values represent a collection, the length of the actual value is compared against the maximum. |
//! | MinMaxType | V2 | `{ "match": "type", "max": 10, "min": 2 }` | This executes a type based match against the values, that is, they are equal if they are the same type. In addition, if the values represent a collection, the length of the actual value is compared against the minimum and maximum. |
//! | Include | V3 | `{ "match": "include", "value": "substr" }` | This checks if the string representation of a value contains the substring. |
//! | Integer | V3 | `{ "match": "integer" }` | This checks if the type of the value is an integer. |
//! | Decimal | V3 | `{ "match": "decimal" }` | This checks if the type of the value is a number with decimal places. |
//! | Number | V3 | `{ "match": "number" }` | This checks if the type of the value is a number. |
//! | Timestamp | V3 | `{ "match": "datetime", "format": "yyyy-MM-dd HH:ss:mm" }` | Matches the string representation of a value against the datetime format |
//! | Time  | V3 | `{ "match": "time", "format": "HH:ss:mm" }` | Matches the string representation of a value against the time format |
//! | Date  | V3 | `{ "match": "date", "format": "yyyy-MM-dd" }` | Matches the string representation of a value against the date format |
//! | Null  | V3 | `{ "match": "null" }` | Match if the value is a null value (this is content specific, for JSON will match a JSON null) |
//! | Boolean  | V3 | `{ "match": "boolean" }` | Match if the value is a boolean value (booleans and the string values `true` and `false`) |
//! | ContentType  | V3 | `{ "match": "contentType", "value": "image/jpeg" }` | Match binary data by its content type (magic file check) |
//! | Values  | V3 | `{ "match": "values" }` | Match the values in a map, ignoring the keys |
//! | ArrayContains | V4 | `{ "match": "arrayContains", "variants": [...] }` | Checks if all the variants are present in an array. |
//! | StatusCode | V4 | `{ "match": "statusCode", "status": "success" }` | Matches the response status code. |
//! | NotEmpty | V4 | `{ "match": "notEmpty" }` | Value must be present and not empty (not null or the empty string) |
//! | Semver | V4 | `{ "match": "semver" }` | Value must be valid based on the semver specification |
//! | Semver | V4 | `{ "match": "semver" }` | Value must be valid based on the semver specification |
//! | EachKey | V4 | `{ "match": "eachKey", "rules": [{"match": "regex", "regex": "\\$(\\.\\w+)+"}], "value": "$.test.one" }` | Allows defining matching rules to apply to the keys in a map |
//! | EachValue | V4 | `{ "match": "eachValue", "rules": [{"match": "regex", "regex": "\\$(\\.\\w+)+"}], "value": "$.test.one" }` | Allows defining matching rules to apply to the values in a collection. For maps, delgates to the Values matcher. |

#![warn(missing_docs)]

use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::{Debug, Display};
use std::fmt::Formatter;
use std::hash::Hash;
use std::str;
use std::str::from_utf8;

use ansi_term::*;
use ansi_term::Colour::*;
use anyhow::anyhow;
use bytes::Bytes;
use itertools::{Either, Itertools};
use lazy_static::*;
use log::*;
use maplit::{hashmap, hashset};
use pact_models::bodies::OptionalBody;
use pact_models::content_types::ContentType;
use pact_models::generators::{apply_generators, GenerateValue, GeneratorCategory, GeneratorTestMode, VariantMatcher};
use pact_models::http_parts::HttpPart;
use pact_models::interaction::Interaction;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::{Category, MatchingRule, MatchingRuleCategory, RuleList};
use pact_models::pact::Pact;
use pact_models::PactSpecification;
use pact_models::path_exp::DocPath;
use pact_models::v4::http_parts::{HttpRequest, HttpResponse};
use pact_models::v4::message_parts::MessageContents;
use pact_models::v4::sync_message::SynchronousMessage;
use pact_plugin_driver::catalogue_manager::find_content_matcher;
use pact_plugin_driver::plugin_models::PluginInteractionConfig;
use serde_json::{json, Value};

use crate::generators::{DefaultVariantMatcher, generators_process_body};
use crate::headers::{match_header_value, match_headers};
use crate::json::match_json;
use crate::matchers::*;
use crate::matchingrules::DisplayForMismatch;

/// Simple macro to convert a string slice to a `String` struct.
#[macro_export]
macro_rules! s {
    ($e:expr) => ($e.to_string())
}

/// Version of the library
pub const PACT_RUST_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");

pub mod matchers;
pub mod json;
pub mod logging;
pub mod matchingrules;
pub mod metrics;

mod xml;
mod binary_utils;
mod headers;
mod generators;

/// Context used to apply matching logic
pub trait MatchingContext {
  /// If there is a matcher defined at the path in this context
  fn matcher_is_defined(&self, path: &DocPath) -> bool;

  /// Selected the best matcher from the context for the given path
  fn select_best_matcher(&self, path: &DocPath) -> RuleList;

  /// If there is a type matcher defined at the path in this context
  fn type_matcher_defined(&self, path: &DocPath) -> bool;

  /// If there is a values matcher defined at the path in this context
  fn values_matcher_defined(&self, path: &DocPath) -> bool;

  /// If a matcher defined at the path (ignoring parents)
  fn direct_matcher_defined(&self, path: &DocPath, matchers: &HashSet<&str>) -> bool;

  /// Matches the keys of the expected and actual maps
  fn match_keys(&self, path: &DocPath, expected: &BTreeSet<String>, actual: &BTreeSet<String>) -> Result<(), Vec<Mismatch>>;

  /// Returns the plugin configuration associated with the context
  fn plugin_configuration(&self) -> &HashMap<String, PluginInteractionConfig>;

  /// Returns the matching rules for the matching context
  fn matchers(&self) -> &MatchingRuleCategory;

  /// Configuration to apply when matching with the context
  fn config(&self) -> DiffConfig;

  /// Clones the current context with the provided matching rules
  fn clone_with(&self, matchers: &MatchingRuleCategory) -> Box<dyn MatchingContext>;
}

#[derive(Debug, Clone)]
/// Core implementation of a matching context
pub struct CoreMatchingContext {
  /// Matching rules that apply when matching with the context
  pub matchers: MatchingRuleCategory,
  /// Configuration to apply when matching with the context
  pub config: DiffConfig,
  /// Specification version to apply when matching with the context
  pub matching_spec: PactSpecification,
  /// Any plugin configuration available for the interaction
  pub plugin_configuration: HashMap<String, PluginInteractionConfig>
}

impl CoreMatchingContext {
  /// Creates a new context with the given config and matching rules
  pub fn new(
    config: DiffConfig,
    matchers: &MatchingRuleCategory,
    plugin_configuration: &HashMap<String, PluginInteractionConfig>
  ) -> Self {
    CoreMatchingContext {
      matchers: matchers.clone(),
      config,
      plugin_configuration: plugin_configuration.clone(),
      .. CoreMatchingContext::default()
    }
  }

  /// Creates a new empty context with the given config
  pub fn with_config(config: DiffConfig) -> Self {
    CoreMatchingContext {
      config,
      .. CoreMatchingContext::default()
    }
  }

  fn matchers_for_exact_path(&self, path: &DocPath) -> MatchingRuleCategory {
    match self.matchers.name {
      Category::HEADER | Category::QUERY => self.matchers.filter(|&(val, _)| {
        path.len() == 1 && path.first_field() == val.first_field()
      }),
      Category::BODY => self.matchers.filter(|&(val, _)| {
        let p = path.to_vec();
        let p_slice = p.iter().map(|p| p.as_str()).collect_vec();
        val.matches_path_exactly(p_slice.as_slice())
      }),
      _ => self.matchers.filter(|_| false)
    }
  }
}

impl Default for CoreMatchingContext {
  fn default() -> Self {
    CoreMatchingContext {
      matchers: Default::default(),
      config: DiffConfig::AllowUnexpectedKeys,
      matching_spec: PactSpecification::V3,
      plugin_configuration: Default::default()
    }
  }
}

impl MatchingContext for CoreMatchingContext {
  fn matcher_is_defined(&self, path: &DocPath) -> bool {
    let path = path.to_vec();
    let path_slice = path.iter().map(|p| p.as_str()).collect_vec();
    self.matchers.matcher_is_defined(path_slice.as_slice())
  }

  fn select_best_matcher(&self, path: &DocPath) -> RuleList {
    let path = path.to_vec();
    let path_slice = path.iter().map(|p| p.as_str()).collect_vec();
    self.matchers.select_best_matcher(path_slice.as_slice())
  }

  fn type_matcher_defined(&self, path: &DocPath) -> bool {
    let path = path.to_vec();
    let path_slice = path.iter().map(|p| p.as_str()).collect_vec();
    self.matchers.resolve_matchers_for_path(path_slice.as_slice()).type_matcher_defined()
  }

  fn values_matcher_defined(&self, path: &DocPath) -> bool {
    self.matchers_for_exact_path(path).values_matcher_defined()
  }

  fn direct_matcher_defined(&self, path: &DocPath, matchers: &HashSet<&str>) -> bool {
    let actual = self.matchers_for_exact_path(path);
    if matchers.is_empty() {
      actual.is_not_empty()
    } else {
      actual.as_rule_list().rules.iter().any(|r| matchers.contains(r.name().as_str()))
    }
  }

  fn match_keys(&self, path: &DocPath, expected: &BTreeSet<String>, actual: &BTreeSet<String>) -> Result<(), Vec<Mismatch>> {
    let mut expected_keys = expected.iter().cloned().collect::<Vec<String>>();
    expected_keys.sort();
    let mut actual_keys = actual.iter().cloned().collect::<Vec<String>>();
    actual_keys.sort();
    let missing_keys: Vec<String> = expected.iter().filter(|key| !actual.contains(*key)).cloned().collect();
    let mut result = vec![];

    if !self.direct_matcher_defined(path, &hashset! { "values", "each-value" }) {
      match self.config {
        DiffConfig::AllowUnexpectedKeys if !missing_keys.is_empty() => {
          result.push(Mismatch::BodyMismatch {
            path: path.to_string(),
            expected: Some(expected.for_mismatch().into()),
            actual: Some(actual.for_mismatch().into()),
            mismatch: format!("Actual map is missing the following keys: {}", missing_keys.join(", ")),
          });
        }
        DiffConfig::NoUnexpectedKeys if expected_keys != actual_keys => {
          result.push(Mismatch::BodyMismatch {
            path: path.to_string(),
            expected: Some(expected.for_mismatch().into()),
            actual: Some(actual.for_mismatch().into()),
            mismatch: format!("Expected a Map with keys {} but received one with keys {}",
                              expected_keys.join(", "), actual_keys.join(", ")),
          });
        }
        _ => {}
      }
    }

    if self.direct_matcher_defined(path, &Default::default()) {
      let matchers = self.select_best_matcher(path);
      for matcher in matchers.rules {
        match matcher {
          MatchingRule::EachKey(definition) => {
            for sub_matcher in definition.rules {
              match sub_matcher {
                Either::Left(rule) => {
                  for key in &actual_keys {
                    let key_path = path.join(key);
                    String::default().matches_with(key, &rule, false)
                      .map_err(|err| {
                        result.push(Mismatch::BodyMismatch {
                          path: key_path.to_string(),
                          expected: Some("".to_string().into()),
                          actual: Some(key.clone().into()),
                          mismatch: err.to_string(),
                        });
                      });
                  }
                }
                Either::Right(name) => {
                  result.push(Mismatch::BodyMismatch {
                    path: path.to_string(),
                    expected: Some(expected.for_mismatch().into()),
                    actual: Some(actual.for_mismatch().into()),
                    mismatch: format!("Expected a matching rule, found an unresolved reference '{}'",
                      name.name),
                  });
                }
              }
            }
          }
          _ => {}
        }
      }
    }

    if result.is_empty() {
      Ok(())
    } else {
      Err(result)
    }
  }

  fn plugin_configuration(&self) -> &HashMap<String, PluginInteractionConfig> {
    &self.plugin_configuration
  }

  fn matchers(&self) -> &MatchingRuleCategory {
    &self.matchers
  }

  fn config(&self) -> DiffConfig {
    self.config
  }

  fn clone_with(&self, matchers: &MatchingRuleCategory) -> Box<dyn MatchingContext> {
    Box::new(CoreMatchingContext {
      matchers: matchers.clone(),
      config: self.config.clone(),
      matching_spec: self.matching_spec,
      plugin_configuration: self.plugin_configuration.clone()
    })
  }
}

lazy_static! {
  static ref BODY_MATCHERS: [
    (fn(content_type: &ContentType) -> bool,
    fn(expected: &dyn HttpPart, actual: &dyn HttpPart, context: &dyn MatchingContext) -> Result<(), Vec<Mismatch>>); 4]
     = [
      (|content_type| { content_type.is_json() }, json::match_json),
      (|content_type| { content_type.is_xml() }, xml::match_xml),
      (|content_type| { content_type.base_type() == "application/octet-stream" }, binary_utils::match_octet_stream),
      (|content_type| { content_type.base_type() == "multipart/form-data" }, binary_utils::match_mime_multipart)
  ];
}

/// Enum that defines the different types of mismatches that can occur.
#[derive(Debug, Clone, PartialOrd, Ord, Eq)]
pub enum Mismatch {
    /// Request Method mismatch
    MethodMismatch {
        /// Expected request method
        expected: String,
        /// Actual request method
        actual: String
    },
    /// Request Path mismatch
    PathMismatch {
        /// expected request path
        expected: String,
        /// actual request path
        actual: String,
        /// description of the mismatch
        mismatch: String
    },
    /// Response status mismatch
    StatusMismatch {
        /// expected response status
      expected: u16,
      /// actual response status
      actual: u16,
      /// description of the mismatch
      mismatch: String
    },
    /// Request query mismatch
    QueryMismatch {
        /// query parameter name
        parameter: String,
        /// expected value
        expected: String,
        /// actual value
        actual: String,
        /// description of the mismatch
        mismatch: String
    },
    /// Header mismatch
    HeaderMismatch {
        /// header key
        key: String,
        /// expected value
        expected: String,
        /// actual value
        actual: String,
        /// description of the mismatch
        mismatch: String
    },
    /// Mismatch in the content type of the body
    BodyTypeMismatch {
      /// expected content type of the body
      expected: String,
      /// actual content type of the body
      actual: String,
      /// description of the mismatch
      mismatch: String,
      /// expected value
      expected_body: Option<Bytes>,
      /// actual value
      actual_body: Option<Bytes>
    },
    /// Body element mismatch
    BodyMismatch {
      /// path expression to where the mismatch occurred
      path: String,
      /// expected value
      expected: Option<Bytes>,
      /// actual value
      actual: Option<Bytes>,
      /// description of the mismatch
      mismatch: String
    },
    /// Message metadata mismatch
    MetadataMismatch {
      /// key
      key: String,
      /// expected value
      expected: String,
      /// actual value
      actual: String,
      /// description of the mismatch
      mismatch: String
    }
}

impl Mismatch {
  /// Converts the mismatch to a `Value` struct.
  pub fn to_json(&self) -> serde_json::Value {
    match self {
      Mismatch::MethodMismatch { expected: e, actual: a } => {
        json!({
          "type" : "MethodMismatch",
          "expected" : e,
          "actual" : a
        })
      },
      Mismatch::PathMismatch { expected: e, actual: a, mismatch: m } => {
        json!({
          "type" : "PathMismatch",
          "expected" : e,
          "actual" : a,
          "mismatch" : m
        })
      },
      Mismatch::StatusMismatch { expected: e, actual: a, mismatch: m } => {
        json!({
          "type" : "StatusMismatch",
          "expected" : e,
          "actual" : a,
          "mismatch": m
        })
      },
      Mismatch::QueryMismatch { parameter: p, expected: e, actual: a, mismatch: m } => {
        json!({
          "type" : "QueryMismatch",
          "parameter" : p,
          "expected" : e,
          "actual" : a,
          "mismatch" : m
        })
      },
      Mismatch::HeaderMismatch { key: k, expected: e, actual: a, mismatch: m } => {
        json!({
          "type" : "HeaderMismatch",
          "key" : k,
          "expected" : e,
          "actual" : a,
          "mismatch" : m
        })
      },
      Mismatch::BodyTypeMismatch {
        expected,
        actual,
        mismatch,
        expected_body,
        actual_body
      } => {
        json!({
          "type" : "BodyTypeMismatch",
          "expected" : expected,
          "actual" : actual,
          "mismatch" : mismatch,
          "expectedBody": match expected_body {
            Some(v) => serde_json::Value::String(str::from_utf8(v)
              .unwrap_or("ERROR: could not convert to UTF-8 from bytes").into()),
            None => serde_json::Value::Null
          },
          "actualBody": match actual_body {
            Some(v) => serde_json::Value::String(str::from_utf8(v)
              .unwrap_or("ERROR: could not convert to UTF-8 from bytes").into()),
            None => serde_json::Value::Null
          }
        })
      },
      Mismatch::BodyMismatch { path, expected, actual, mismatch } => {
        json!({
          "type" : "BodyMismatch",
          "path" : path,
          "expected" : match expected {
            Some(v) => serde_json::Value::String(str::from_utf8(v).unwrap_or("ERROR: could not convert from bytes").into()),
            None => serde_json::Value::Null
          },
          "actual" : match actual {
            Some(v) => serde_json::Value::String(str::from_utf8(v).unwrap_or("ERROR: could not convert from bytes").into()),
            None => serde_json::Value::Null
          },
          "mismatch" : mismatch
        })
      }
      Mismatch::MetadataMismatch { key, expected, actual, mismatch } => {
        json!({
          "type" : "MetadataMismatch",
          "key" : key,
          "expected" : expected,
          "actual" : actual,
          "mismatch" : mismatch
        })
      }
    }
  }

    /// Returns the type of the mismatch as a string
    pub fn mismatch_type(&self) -> &str {
      match *self {
        Mismatch::MethodMismatch { .. } => "MethodMismatch",
        Mismatch::PathMismatch { .. } => "PathMismatch",
        Mismatch::StatusMismatch { .. } => "StatusMismatch",
        Mismatch::QueryMismatch { .. } => "QueryMismatch",
        Mismatch::HeaderMismatch { .. } => "HeaderMismatch",
        Mismatch::BodyTypeMismatch { .. } => "BodyTypeMismatch",
        Mismatch::BodyMismatch { .. } => "BodyMismatch",
        Mismatch::MetadataMismatch { .. } => "MetadataMismatch"
      }
    }

    /// Returns a summary string for this mismatch
    pub fn summary(&self) -> String {
      match *self {
        Mismatch::MethodMismatch { expected: ref e, .. } => format!("is a {} request", e),
        Mismatch::PathMismatch { expected: ref e, .. } => format!("to path '{}'", e),
        Mismatch::StatusMismatch { expected: ref e, .. } => format!("has status code {}", e),
        Mismatch::QueryMismatch { ref parameter, expected: ref e, .. } => format!("includes parameter '{}' with value '{}'", parameter, e),
        Mismatch::HeaderMismatch { ref key, expected: ref e, .. } => format!("includes header '{}' with value '{}'", key, e),
        Mismatch::BodyTypeMismatch { .. } => s!("has a matching body"),
        Mismatch::BodyMismatch { .. } => s!("has a matching body"),
        Mismatch::MetadataMismatch { .. } => s!("has matching metadata")
      }
    }

    /// Returns a formated string for this mismatch
    pub fn description(&self) -> String {
      match self {
        Mismatch::MethodMismatch { expected: e, actual: a } => format!("expected {} but was {}", e, a),
        Mismatch::PathMismatch { mismatch, .. } => mismatch.clone(),
        Mismatch::StatusMismatch { mismatch, .. } => mismatch.clone(),
        Mismatch::QueryMismatch { mismatch, .. } => mismatch.clone(),
        Mismatch::HeaderMismatch { mismatch, .. } => mismatch.clone(),
        Mismatch::BodyTypeMismatch {  expected: e, actual: a, .. } => format!("expected '{}' body but was '{}'", e, a),
        Mismatch::BodyMismatch { path, mismatch, .. } => format!("{} -> {}", path, mismatch),
        Mismatch::MetadataMismatch { mismatch, .. } => mismatch.clone()
      }
    }

    /// Returns a formatted string with ansi escape codes for this mismatch
    pub fn ansi_description(&self) -> String {
      match self {
        Mismatch::MethodMismatch { expected: e, actual: a } => format!("expected {} but was {}", Red.paint(e.clone()), Green.paint(a.clone())),
        Mismatch::PathMismatch { expected: e, actual: a, .. } => format!("expected '{}' but was '{}'", Red.paint(e.clone()), Green.paint(a.clone())),
        Mismatch::StatusMismatch { expected: e, actual: a, .. } => format!("expected {} but was {}", Red.paint(e.to_string()), Green.paint(a.to_string())),
        Mismatch::QueryMismatch { expected: e, actual: a, parameter: p, .. } => format!("Expected '{}' but received '{}' for query parameter '{}'",
          Red.paint(e.to_string()), Green.paint(a.to_string()), Style::new().bold().paint(p.clone())),
        Mismatch::HeaderMismatch { expected: e, actual: a, key: k, .. } => format!("Expected header '{}' to have value '{}' but was '{}'",
          Style::new().bold().paint(k.clone()), Red.paint(e.to_string()), Green.paint(a.to_string())),
        Mismatch::BodyTypeMismatch {  expected: e, actual: a, .. } => format!("expected '{}' body but was '{}'", Red.paint(e.clone()), Green.paint(a.clone())),
        Mismatch::BodyMismatch { path, mismatch, .. } => format!("{} -> {}", Style::new().bold().paint(path.clone()), mismatch),
        Mismatch::MetadataMismatch { expected: e, actual: a, key: k, .. } => format!("Expected message metadata '{}' to have value '{}' but was '{}'",
          Style::new().bold().paint(k.clone()), Red.paint(e.to_string()), Green.paint(a.to_string()))
      }
    }
}

impl PartialEq for Mismatch {
  fn eq(&self, other: &Mismatch) -> bool {
    match (self, other) {
      (Mismatch::MethodMismatch { expected: e1, actual: a1 },
        Mismatch::MethodMismatch { expected: e2, actual: a2 }) => {
        e1 == e2 && a1 == a2
      },
      (Mismatch::PathMismatch { expected: e1, actual: a1, .. },
        Mismatch::PathMismatch { expected: e2, actual: a2, .. }) => {
        e1 == e2 && a1 == a2
      },
      (Mismatch::StatusMismatch { expected: e1, actual: a1, .. },
        Mismatch::StatusMismatch { expected: e2, actual: a2, .. }) => {
        e1 == e2 && a1 == a2
      },
      (Mismatch::BodyTypeMismatch { expected: e1, actual: a1, .. },
        Mismatch::BodyTypeMismatch { expected: e2, actual: a2, .. }) => {
        e1 == e2 && a1 == a2
      },
      (Mismatch::QueryMismatch { parameter: p1, expected: e1, actual: a1, .. },
        Mismatch::QueryMismatch { parameter: p2, expected: e2, actual: a2, .. }) => {
        p1 == p2 && e1 == e2 && a1 == a2
      },
      (Mismatch::HeaderMismatch { key: p1, expected: e1, actual: a1, .. },
        Mismatch::HeaderMismatch { key: p2, expected: e2, actual: a2, .. }) => {
        p1 == p2 && e1 == e2 && a1 == a2
      },
      (Mismatch::BodyMismatch { path: p1, expected: e1, actual: a1, .. },
        Mismatch::BodyMismatch { path: p2, expected: e2, actual: a2, .. }) => {
        p1 == p2 && e1 == e2 && a1 == a2
      },
      (Mismatch::MetadataMismatch { key: p1, expected: e1, actual: a1, .. },
        Mismatch::MetadataMismatch { key: p2, expected: e2, actual: a2, .. }) => {
        p1 == p2 && e1 == e2 && a1 == a2
      },
      (_, _) => false
    }
  }
}

impl Display for Mismatch {
  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self.description())
  }
}

fn merge_result(res1: Result<(), Vec<Mismatch>>, res2: Result<(), Vec<Mismatch>>) -> Result<(), Vec<Mismatch>> {
  match (&res1, &res2) {
    (Ok(_), Ok(_)) => res1.clone(),
    (Err(_), Ok(_)) => res1.clone(),
    (Ok(_), Err(_)) => res2.clone(),
    (Err(m1), Err(m2)) => {
      let mut mismatches = m1.clone();
      mismatches.extend_from_slice(&*m2);
      Err(mismatches)
    }
  }
}

/// Result of matching a request body
#[derive(Debug, Clone, PartialEq)]
pub enum BodyMatchResult {
  /// Matched OK
  Ok,
  /// Mismatch in the content type of the body
  BodyTypeMismatch {
    /// Expected content type
    expected_type: String,
    /// Actual content type
    actual_type: String,
    /// Message
    message: String,
    /// Expected body
    expected: Option<Bytes>,
    /// Actual body
    actual: Option<Bytes>
  },
  /// Mismatches with the body contents
  BodyMismatches(HashMap<String, Vec<Mismatch>>)
}

impl BodyMatchResult {
  /// Returns all the mismatches
  pub fn mismatches(&self) -> Vec<Mismatch> {
    match self {
      BodyMatchResult::BodyTypeMismatch { expected_type, actual_type, message, expected, actual } => {
        vec![Mismatch::BodyTypeMismatch {
          expected: expected_type.clone(),
          actual: actual_type.clone(),
          mismatch: message.clone(),
          expected_body: expected.clone(),
          actual_body: actual.clone()
        }]
      },
      BodyMatchResult::BodyMismatches(results) =>
        results.values().flatten().cloned().collect(),
      _ => vec![]
    }
  }

  /// If all the things matched OK
  pub fn all_matched(&self) -> bool {
    match self {
      BodyMatchResult::BodyTypeMismatch { .. } => false,
      BodyMatchResult::BodyMismatches(results) =>
        results.values().all(|m| m.is_empty()),
      _ => true
    }
  }
}

/// Result of matching a request
#[derive(Debug, Clone, PartialEq)]
pub struct RequestMatchResult {
  /// Method match result
  pub method: Option<Mismatch>,
  /// Path match result
  pub path: Option<Vec<Mismatch>>,
  /// Body match result
  pub body: BodyMatchResult,
  /// Query parameter result
  pub query: HashMap<String, Vec<Mismatch>>,
  /// Headers result
  pub headers: HashMap<String, Vec<Mismatch>>
}

impl RequestMatchResult {
  /// Returns all the mismatches
  pub fn mismatches(&self) -> Vec<Mismatch> {
    let mut m = vec![];

    if let Some(ref mismatch) = self.method {
      m.push(mismatch.clone());
    }
    if let Some(ref mismatches) = self.path {
      m.extend_from_slice(mismatches.as_slice());
    }
    for mismatches in self.query.values() {
      m.extend_from_slice(mismatches.as_slice());
    }
    for mismatches in self.headers.values() {
      m.extend_from_slice(mismatches.as_slice());
    }
    m.extend_from_slice(self.body.mismatches().as_slice());

    m
  }

  /// Returns a score based on what was matched
  pub fn score(&self) -> i8 {
    let mut score = 0;
    if self.method.is_none() {
      score += 1;
    } else {
      score -= 1;
    }
    if self.path.is_none() {
      score += 1
    } else {
      score -= 1
    }
    for mismatches in self.query.values() {
      if mismatches.is_empty() {
        score += 1;
      } else {
        score -= 1;
      }
    }
    for mismatches in self.headers.values() {
      if mismatches.is_empty() {
        score += 1;
      } else {
        score -= 1;
      }
    }
    match &self.body {
      BodyMatchResult::BodyTypeMismatch { .. } => {
        score -= 1;
      },
      BodyMatchResult::BodyMismatches(results) => {
        for mismatches in results.values() {
          if mismatches.is_empty() {
            score += 1;
          } else {
            score -= 1;
          }
        }
      },
      _ => ()
    }
    score
  }

  /// If all the things matched OK
  pub fn all_matched(&self) -> bool {
    self.method.is_none() && self.path.is_none() &&
      self.query.values().all(|m| m.is_empty()) &&
      self.headers.values().all(|m| m.is_empty()) &&
      self.body.all_matched()
  }

  /// If there was a mismatch with the method or path
  pub fn method_or_path_mismatch(&self) -> bool {
    self.method.is_some() || self.path.is_some()
  }
}

/// Enum that defines the configuration options for performing a match.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DiffConfig {
    /// If unexpected keys are allowed and ignored during matching.
    AllowUnexpectedKeys,
    /// If unexpected keys cause a mismatch.
    NoUnexpectedKeys
}

/// Matches the actual text body to the expected one.
pub fn match_text(expected: &Option<Bytes>, actual: &Option<Bytes>, context: &dyn MatchingContext) -> Result<(), Vec<Mismatch>> {
  let path = DocPath::root();
  if context.matcher_is_defined(&path) {
    let mut mismatches = vec![];
    let empty = Bytes::default();
    let expected_str = match from_utf8(expected.as_ref().unwrap_or(&empty)) {
      Ok(expected) => expected,
      Err(err) => {
        mismatches.push(Mismatch::BodyMismatch {
          path: "$".to_string(),
          expected: expected.clone(),
          actual: actual.clone(),
          mismatch: format!("Could not parse expected value as UTF-8 text: {}", err)
        });
        ""
      }
    };
    let actual_str = match from_utf8(actual.as_ref().unwrap_or(&empty)) {
      Ok(actual) => actual,
      Err(err) => {
        mismatches.push(Mismatch::BodyMismatch {
          path: "$".to_string(),
          expected: expected.clone(),
          actual: actual.clone(),
          mismatch: format!("Could not parse actual value as UTF-8 text: {}", err)
        });
        ""
      }
    };
    if let Err(messages) = match_values(&path, &context.select_best_matcher(&path), expected_str, actual_str) {
      for message in messages {
        mismatches.push(Mismatch::BodyMismatch {
          path: "$".to_string(),
          expected: expected.clone(),
          actual: actual.clone(),
          mismatch: message.clone()
        })
      }
    };
    if mismatches.is_empty() {
      Ok(())
    } else {
      Err(mismatches)
    }
  } else if expected != actual {
    Err(vec![ Mismatch::BodyMismatch { path: "$".to_string(), expected: expected.clone(),
      actual: actual.clone(),
      mismatch: format!("Expected text '{:?}' but received '{:?}'", expected, actual) } ])
  } else {
    Ok(())
  }
}

/// Matches the actual request method to the expected one.
pub fn match_method(expected: &str, actual: &str) -> Result<(), Mismatch> {
  if expected.to_lowercase() != actual.to_lowercase() {
    Err(Mismatch::MethodMismatch { expected: expected.to_string(), actual: actual.to_string() })
  } else {
    Ok(())
  }
}

/// Matches the actual request path to the expected one.
pub fn match_path(expected: &str, actual: &str, context: &(dyn MatchingContext + Send + Sync)) -> Result<(), Vec<Mismatch>> {
  let path = DocPath::empty();
  let matcher_result = if context.matcher_is_defined(&path) {
    match_values(&path, &context.select_best_matcher(&path), expected.to_string(), actual.to_string())
  } else {
    expected.matches_with(actual, &MatchingRule::Equality, false).map_err(|err| vec![err])
      .map_err(|errors| errors.iter().map(|err| err.to_string()).collect())
  };
  matcher_result.map_err(|messages| messages.iter().map(|message| {
    Mismatch::PathMismatch {
      expected: expected.to_string(),
      actual: actual.to_string(), mismatch: message.clone()
    }
  }).collect())
}

fn compare_query_parameter_value(
  key: &str,
  expected: &str,
  actual: &str,
  index: usize,
  context: &dyn MatchingContext
) -> Result<(), Vec<Mismatch>> {
  let index = index.to_string();
  let path = DocPath::root().join(key).join(index.as_str());
  let matcher_result = if context.matcher_is_defined(&path) {
    matchers::match_values(&path, &context.select_best_matcher(&path), expected.to_string(), actual.to_string())
  } else {
    expected.matches_with(actual, &MatchingRule::Equality, false)
      .map_err(|error| vec![error.to_string()])
  };
  matcher_result.map_err(|messages| {
    messages.iter().map(|message| {
      Mismatch::QueryMismatch {
        parameter: key.to_string(),
        expected: expected.to_string(),
        actual: actual.to_string(),
        mismatch: message.clone(),
      }
    }).collect()
  })
}

fn compare_query_parameter_values(
  key: &str,
  expected: &[String],
  actual: &[String],
  context: &dyn MatchingContext
) -> Result<(), Vec<Mismatch>> {
  let result: Vec<Mismatch> = expected.iter().enumerate().flat_map(|(index, val)| {
    if index < actual.len() {
      match compare_query_parameter_value(key, val, &actual[index], index, context) {
        Ok(_) => vec![],
        Err(errors) => errors
      }
    } else {
      vec![ Mismatch::QueryMismatch {
        parameter: key.to_string(),
        expected: format!("{:?}", expected),
        actual: format!("{:?}", actual),
        mismatch: format!("Expected query parameter '{}' value '{}' but was missing", key, val)
      } ]
    }
  }).collect();

  if result.is_empty() {
    Ok(())
  } else {
    Err(result)
  }
}

fn match_query_values(
  key: &str,
  expected: &[String],
  actual: &[String],
  context: &dyn MatchingContext
) -> Result<(), Vec<Mismatch>> {
  if expected.is_empty() && !actual.is_empty() {
    Err(vec![ Mismatch::QueryMismatch {
      parameter: key.to_string(),
      expected: format!("{:?}", expected),
      actual: format!("{:?}", actual),
      mismatch: format!("Expected an empty parameter list for '{}' but received {:?}", key, actual)
    } ])
  } else {
    let mismatch = if expected.len() != actual.len() {
      Err(vec![ Mismatch::QueryMismatch {
        parameter: key.to_string(),
        expected: format!("{:?}", expected),
        actual: format!("{:?}", actual),
        mismatch: format!(
          "Expected query parameter '{}' with {} value(s) but received {} value(s)",
          key, expected.len(), actual.len())
      } ])
    } else {
      Ok(())
    };
    merge_result(compare_query_parameter_values(key, expected, actual, context), mismatch)
  }
}

fn match_query_maps(
  expected: HashMap<String, Vec<String>>,
  actual: HashMap<String, Vec<String>>,
  context: &dyn MatchingContext
) -> HashMap<String, Vec<Mismatch>> {
  let mut result: HashMap<String, Vec<Mismatch>> = hashmap!{};
  for (key, value) in &expected {
    match actual.get(key) {
      Some(actual_value) => {
        let matches = match_query_values(key, value, actual_value, context);
        let v = result.entry(key.clone()).or_default();
        v.extend(matches.err().unwrap_or_default());
      },
      None => result.entry(key.clone()).or_default().push(Mismatch::QueryMismatch {
        parameter: key.clone(),
        expected: format!("{:?}", value),
        actual: "".to_string(),
        mismatch: format!("Expected query parameter '{}' but was missing", key)
      })
    }
  }
  for (key, value) in &actual {
    match expected.get(key) {
      Some(_) => (),
      None => result.entry(key.clone()).or_default().push(Mismatch::QueryMismatch {
        parameter: key.clone(),
        expected: "".to_string(),
        actual: format!("{:?}", value),
        mismatch: format!("Unexpected query parameter '{}' received", key)
      })
    }
  }
  result
}

/// Matches the actual query parameters to the expected ones.
pub fn match_query(
  expected: Option<HashMap<String, Vec<String>>>,
  actual: Option<HashMap<String, Vec<String>>>,
  context: &(dyn MatchingContext + Send + Sync)
) -> HashMap<String, Vec<Mismatch>> {
  match (actual, expected) {
    (Some(aqm), Some(eqm)) => match_query_maps(eqm, aqm, context),
    (Some(aqm), None) => aqm.iter().map(|(key, value)| {
      (key.clone(), vec![Mismatch::QueryMismatch {
        parameter: key.clone(),
        expected: "".to_string(),
        actual: format!("{:?}", value),
        mismatch: format!("Unexpected query parameter '{}' received", key)
      }])
    }).collect(),
    (None, Some(eqm)) => eqm.iter().map(|(key, value)| {
      (key.clone(), vec![Mismatch::QueryMismatch {
        parameter: key.clone(),
        expected: format!("{:?}", value),
        actual: "".to_string(),
        mismatch: format!("Expected query parameter '{}' but was missing", key)
      }])
    }).collect(),
    (None, None) => hashmap!{}
  }
}

fn group_by<I, F, K>(items: I, f: F) -> HashMap<K, Vec<I::Item>>
  where I: IntoIterator, F: Fn(&I::Item) -> K, K: Eq + Hash {
  let mut m = hashmap!{};
  for item in items {
    let key = f(&item);
    let values = m.entry(key).or_insert_with(Vec::new);
    values.push(item);
  }
  m
}

async fn compare_bodies(
  content_type: &ContentType,
  expected: &(dyn HttpPart + Send + Sync),
  actual: &(dyn HttpPart + Send + Sync),
  context: &(dyn MatchingContext + Send + Sync)
) -> BodyMatchResult {
  let mut mismatches = vec![];
  match find_content_matcher(content_type) {
    Some(matcher) => {
      debug!("Using content matcher {} for content type '{}'", matcher.catalogue_entry_key(), content_type);
      if matcher.is_core() {
        if let Err(m) = match matcher.catalogue_entry_key().as_str() {
          // TODO: "core/content-matcher/form-urlencoded" => ,
          "core/content-matcher/json" => match_json(expected, actual, context),
          "core/content-matcher/multipart-form-data" => binary_utils::match_mime_multipart(expected, actual, context),
          "core/content-matcher/text" => match_text(&expected.body().value(), &actual.body().value(), context),
          "core/content-matcher/xml" => xml::match_xml(expected, actual, context),
          "core/content-matcher/binary" => binary_utils::match_octet_stream(expected, actual, context),
          _ => {
            warn!("There is no core content matcher for entry {}", matcher.catalogue_entry_key());
            match_text(&expected.body().value(), &actual.body().value(), context)
          }
        } {
          mismatches.extend_from_slice(&*m);
        }
      } else {
        let plugin_config = context.plugin_configuration().get(&matcher.plugin_name()).cloned();
        if let Err(map) = matcher.match_contents(expected.body(), actual.body(), &context.matchers(),
          context.config() == DiffConfig::AllowUnexpectedKeys, plugin_config).await {
          // TODO: group the mismatches by key
          for (_key, list) in map {
            for mismatch in list {
              mismatches.push(Mismatch::BodyMismatch {
                path: mismatch.path.clone(),
                expected: Some(Bytes::from(mismatch.expected)),
                actual: Some(Bytes::from(mismatch.actual)),
                mismatch: mismatch.mismatch.clone()
              });
            }
          }
        }
      }
    }
    None => {
      debug!("No content matcher defined for content type '{}', using core matcher implementation", content_type);
      mismatches.extend(compare_bodies_core(content_type, expected, actual, context));
    }
  }
  if mismatches.is_empty() {
    BodyMatchResult::Ok
  } else {
    BodyMatchResult::BodyMismatches(group_by(mismatches, |m| match m {
      Mismatch::BodyMismatch { path: m, ..} => m.to_string(),
      _ => String::default()
    }))
  }
}

fn compare_bodies_core(
  content_type: &ContentType,
  expected: &dyn HttpPart,
  actual: &dyn HttpPart,
  context: &dyn MatchingContext
) -> Vec<Mismatch> {
  let mut mismatches = vec![];
  match BODY_MATCHERS.iter().find(|mt| mt.0(content_type)) {
    Some(match_fn) => {
      debug!("Using body matcher for content type '{}'", content_type);
      if let Err(m) = match_fn.1(expected, actual, context) {
        mismatches.extend_from_slice(&*m);
      }
    },
    None => {
      debug!("No body matcher defined for content type '{}', using plain text matcher", content_type);
      if let Err(m) = match_text(&expected.body().value(), &actual.body().value(), context) {
        mismatches.extend_from_slice(&*m);
      }
    }
  };
  mismatches
}

async fn match_body_content(
  content_type: &ContentType,
  expected: &(dyn HttpPart + Send + Sync),
  actual: &(dyn HttpPart + Send + Sync),
  context: &(dyn MatchingContext + Send + Sync)
) -> BodyMatchResult {
  let expected_body = expected.body();
  let actual_body = actual.body();
  match (expected_body, actual_body) {
    (&OptionalBody::Missing, _) => BodyMatchResult::Ok,
    (&OptionalBody::Null, &OptionalBody::Present(ref b, _, _)) => {
      BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch { expected: None, actual: Some(b.clone()),
        mismatch: format!("Expected empty body but received {}", actual_body),
        path: s!("/")}]})
    },
    (&OptionalBody::Empty, &OptionalBody::Present(ref b, _, _)) => {
      BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch { expected: None, actual: Some(b.clone()),
        mismatch: format!("Expected empty body but received {}", actual_body),
        path: s!("/")}]})
    },
    (&OptionalBody::Null, _) => BodyMatchResult::Ok,
    (&OptionalBody::Empty, _) => BodyMatchResult::Ok,
    (e, &OptionalBody::Missing) => {
      BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch {
        expected: e.value(),
        actual: None,
        mismatch: format!("Expected body {} but was missing", e),
        path: s!("/")}]})
    },
    (e, &OptionalBody::Empty) => {
      BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch {
        expected: e.value(),
        actual: None,
        mismatch: format!("Expected body {} but was empty", e),
        path: s!("/")}]})
    },
    (_, _) => compare_bodies(content_type, expected, actual, context).await
  }
}

/// Matches the actual body to the expected one. This takes into account the content type of each.
pub async fn match_body(
  expected: &(dyn HttpPart + Send + Sync),
  actual: &(dyn HttpPart + Send + Sync),
  context: &(dyn MatchingContext + Send + Sync),
  header_context: &(dyn MatchingContext + Send + Sync)
) -> BodyMatchResult {
  let expected_content_type = expected.content_type().unwrap_or_default();
  let actual_content_type = actual.content_type().unwrap_or_default();
  debug!("expected content type = '{}', actual content type = '{}'", expected_content_type,
         actual_content_type);
  let content_type_matcher = header_context.select_best_matcher(&DocPath::root().join("Content-Type"));
  debug!("content type header matcher = '{:?}'", content_type_matcher);
  if expected_content_type.is_unknown() || actual_content_type.is_unknown() ||
    expected_content_type.is_equivalent_to(&actual_content_type) ||
    (!content_type_matcher.is_empty() &&
      match_header_value("Content-Type", expected_content_type.to_string().as_str(),
                         actual_content_type.to_string().as_str(), header_context).is_ok()) {
    match_body_content(&expected_content_type, expected, actual, context).await
  } else if expected.body().is_present() {
    BodyMatchResult::BodyTypeMismatch {
      expected_type: expected_content_type.to_string(),
      actual_type: actual_content_type.to_string(),
      message: format!("Expected body with content type {} but was {}", expected_content_type,
                       actual_content_type),
      expected: expected.body().value(),
      actual: actual.body().value()
    }
  } else {
    BodyMatchResult::Ok
  }
}

/// Matches the expected and actual requests
pub async fn match_request<'a>(
  expected: HttpRequest,
  actual: HttpRequest,
  pact: &Box<dyn Pact + Send + Sync + 'a>,
  interaction: &Box<dyn Interaction + Send + Sync>
) -> RequestMatchResult {
  info!("comparing to expected {}", expected);
  debug!("     body: '{}'", expected.body.str_value());
  debug!("     matching_rules: {:?}", expected.matching_rules);
  debug!("     generators: {:?}", expected.generators);

  let plugin_data = setup_plugin_config(pact, interaction);
  let path_context = CoreMatchingContext::new(DiffConfig::NoUnexpectedKeys,
    &expected.matching_rules.rules_for_category("path").unwrap_or_default(),
    &plugin_data);
  let body_context = CoreMatchingContext::new(DiffConfig::NoUnexpectedKeys,
    &expected.matching_rules.rules_for_category("body").unwrap_or_default(),
    &plugin_data);
  let query_context = CoreMatchingContext::new(DiffConfig::NoUnexpectedKeys,
    &expected.matching_rules.rules_for_category("query").unwrap_or_default(),
    &plugin_data);
  let header_context = CoreMatchingContext::new(DiffConfig::NoUnexpectedKeys,
    &expected.matching_rules.rules_for_category("header").unwrap_or_default(),
    &plugin_data);
  let result = RequestMatchResult {
    method: match_method(&expected.method, &actual.method).err(),
    path: match_path(&expected.path, &actual.path, &path_context).err(),
    body: match_body(&expected, &actual, &body_context, &header_context).await,
    query: match_query(expected.query, actual.query, &query_context),
    headers: match_headers(expected.headers, actual.headers, &header_context)
  };

  debug!("--> Mismatches: {:?}", result.mismatches());
  result
}

/// Matches the actual response status to the expected one.
pub fn match_status(expected: u16, actual: u16, context: &dyn MatchingContext) -> Result<(), Vec<Mismatch>> {
  let path = DocPath::empty();
  if context.matcher_is_defined(&path) {
    match_values(&path, &context.select_best_matcher(&path), expected, actual)
      .map_err(|messages| messages.iter().map(|message| {
        Mismatch::StatusMismatch {
          expected,
          actual,
          mismatch: message.clone()
        }
      }).collect())
  } else if expected != actual {
    Err(vec![Mismatch::StatusMismatch {
      expected,
      actual,
      mismatch: format!("expected {} but was {}", expected, actual)
    }])
  } else {
    Ok(())
  }
}

/// Matches the actual and expected responses.
pub async fn match_response<'a>(
  expected: HttpResponse,
  actual: HttpResponse,
  pact: &Box<dyn Pact + Send + Sync + 'a>,
  interaction: &Box<dyn Interaction + Send + Sync>
) -> Vec<Mismatch> {
  let mut mismatches = vec![];

  info!("comparing to expected response: {}", expected);
  let plugin_data = setup_plugin_config(pact, interaction);

  let status_context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
    &expected.matching_rules.rules_for_category("status").unwrap_or_default(),
    &plugin_data);
  let body_context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
    &expected.matching_rules.rules_for_category("body").unwrap_or_default(),
    &plugin_data);
  let header_context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
    &expected.matching_rules.rules_for_category("header").unwrap_or_default(),
    &plugin_data);

  mismatches.extend_from_slice(match_body(&expected, &actual, &body_context, &header_context).await
    .mismatches().as_slice());
  if let Err(m) = match_status(expected.status, actual.status, &status_context) {
    mismatches.extend_from_slice(&m);
  }
  let result = match_headers(expected.headers, actual.headers,
                             &header_context);
  for values in result.values() {
    mismatches.extend_from_slice(values.as_slice());
  }

  mismatches
}

fn setup_plugin_config<'a>(
  pact: &Box<dyn Pact + Send + Sync + 'a>,
  interaction: &Box<dyn Interaction + Send + Sync>
) -> HashMap<String, PluginInteractionConfig> {
  pact.plugin_data().iter().map(|data| {
    let interaction_config = if let Some(v4_interaction) = interaction.as_v4() {
      v4_interaction.plugin_config().get(&data.name).cloned().unwrap_or_default()
    } else {
      hashmap! {}
    };
    (data.name.clone(), PluginInteractionConfig {
      pact_configuration: data.configuration.clone(),
      interaction_configuration: interaction_config
    })
  }).collect()
}

/// Matches the actual message contents to the expected one. This takes into account the content type of each.
pub async fn match_message_contents(
  expected: &MessageContents,
  actual: &MessageContents,
  context: &(dyn MatchingContext + Send + Sync)
) -> Result<(), Vec<Mismatch>> {
  let expected_content_type = expected.message_content_type().unwrap_or_default();
  let actual_content_type = actual.message_content_type().unwrap_or_default();
  debug!("expected content type = '{}', actual content type = '{}'", expected_content_type,
         actual_content_type);
  if expected_content_type.is_equivalent_to(&actual_content_type) {
    let result = match_body_content(&expected_content_type, expected, actual, context).await;
    match result {
      BodyMatchResult::BodyTypeMismatch { expected_type, actual_type, message, expected, actual } => {
        Err(vec![ Mismatch::BodyTypeMismatch {
          expected: expected_type,
          actual: actual_type,
          mismatch: message,
          expected_body: expected,
          actual_body: actual
        } ])
      },
      BodyMatchResult::BodyMismatches(results) => {
        Err(results.values().flat_map(|values| values.iter().cloned()).collect())
      },
      _ => Ok(())
    }
  } else if expected.contents.is_present() {
    Err(vec![ Mismatch::BodyTypeMismatch {
      expected: expected_content_type.to_string(),
      actual: actual_content_type.to_string(),
      mismatch: format!("Expected message with content type {} but was {}",
                        expected_content_type, actual_content_type),
      expected_body: expected.contents.value(),
      actual_body: actual.contents.value()
    } ])
  } else {
    Ok(())
  }
}

/// Matches the actual message metadata to the expected one.
pub fn match_message_metadata(
  expected: &MessageContents,
  actual: &MessageContents,
  context: &dyn MatchingContext
) -> HashMap<String, Vec<Mismatch>> {
  debug!("Matching message metadata");
  let mut result = hashmap!{};
  let expected_metadata = &expected.metadata;
  let actual_metadata = &actual.metadata;
  debug!("Matching message metadata. Expected '{:?}', Actual '{:?}'", expected_metadata, actual_metadata);

  if !expected_metadata.is_empty() || context.config() == DiffConfig::NoUnexpectedKeys {
    for (key, value) in expected_metadata {
      match actual_metadata.get(key) {
        Some(actual_value) => {
          result.insert(key.clone(), match_metadata_value(key, value,
            actual_value, context).err().unwrap_or_default());
        },
        None => {
          result.insert(key.clone(), vec![Mismatch::MetadataMismatch { key: key.clone(),
            expected: json_to_string(&value),
            actual: "".to_string(),
            mismatch: format!("Expected message metadata '{}' but was missing", key) }]);
        }
      }
    }
  }
  result
}

fn match_metadata_value(
  key: &str,
  expected: &Value,
  actual: &Value,
  context: &dyn MatchingContext
) -> Result<(), Vec<Mismatch>> {
  debug!("Comparing metadata values for key '{}'", key);
  let path = DocPath::empty().join(key);
  let matcher_result = if context.matcher_is_defined(&path) {
    matchers::match_values(&path, &context.select_best_matcher(&path), expected, actual)
  } else if key.to_ascii_lowercase() == "contenttype" || key.to_ascii_lowercase() == "content-type" {
    debug!("Comparing message context type '{}' => '{}'", expected, actual);
    headers::match_parameter_header(expected.as_str().unwrap_or_default(),
                                    actual.as_str().unwrap_or_default(), key, "metadata")
  } else {
    expected.matches_with(actual, &MatchingRule::Equality, false).map_err(|err| vec![err.to_string()])
  };
  matcher_result.map_err(|messages| {
    messages.iter().map(|message| {
      Mismatch::MetadataMismatch {
        key: key.to_string(),
        expected: expected.to_string(),
        actual: actual.to_string(),
        mismatch: format!("Expected metadata key '{}' to have value '{}' but was '{}' - {}", key, expected, actual, message)
      }
    }).collect()
  })
}

/// Matches the actual and expected messages.
pub async fn match_message<'a>(
  expected: &Box<dyn Interaction + Send + Sync>,
  actual: &Box<dyn Interaction + Send + Sync>,
  pact: &Box<dyn Pact + Send + Sync + 'a>) -> Vec<Mismatch> {
  let mut mismatches = vec![];

  if expected.is_message() && actual.is_message() {
    info!("comparing to expected message: {:?}", expected);
    let expected_message = expected.as_message().unwrap();
    let actual_message = actual.as_message().unwrap();

    let matching_rules = &expected_message.matching_rules;
    let plugin_data = setup_plugin_config(pact, expected);

    let body_context = if expected.is_v4() {
      CoreMatchingContext {
        matchers: matching_rules.rules_for_category("content").unwrap_or_default(),
        config: DiffConfig::AllowUnexpectedKeys,
        matching_spec: PactSpecification::V4,
        plugin_configuration: plugin_data.clone()
      }
    } else {
      CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
                           &matching_rules.rules_for_category("body").unwrap_or_default(),
                           &plugin_data)
    };

    let metadata_context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
                                                &matching_rules.rules_for_category("metadata").unwrap_or_default(),
                                                &plugin_data);
    let contents = match_message_contents(&expected_message.as_message_content(), &actual_message.as_message_content(), &body_context).await;

    mismatches.extend_from_slice(contents.err().unwrap_or_default().as_slice());
    for values in match_message_metadata(&expected_message.as_message_content(), &actual_message.as_message_content(), &metadata_context).values() {
      mismatches.extend_from_slice(values.as_slice());
    }
  } else {
    mismatches.push(Mismatch::BodyTypeMismatch {
      expected: "message".into(),
      actual: actual.type_of(),
      mismatch: format!("Cannot compare a {} with a {}", expected.type_of(), actual.type_of()),
      expected_body: None,
      actual_body: None
    });
  }

  mismatches
}

/// Matches synchronous request/response messages
pub async fn match_sync_message<'a>(expected: SynchronousMessage, actual: SynchronousMessage, pact: &Box<dyn Pact + Send + Sync + 'a>) -> Vec<Mismatch> {
  let mut mismatches = match_sync_message_request(&expected, &actual, pact).await;
  let response_result = match_sync_message_response(&expected, &expected.response, &actual.response, pact).await;
  mismatches.extend_from_slice(&*response_result);
  mismatches
}

/// Match the request part of a synchronous request/response message
pub async fn match_sync_message_request<'a>(
  expected: &SynchronousMessage,
  actual: &SynchronousMessage,
  pact: &Box<dyn Pact + Send + Sync + 'a>
) -> Vec<Mismatch> {
  info!("comparing to expected message request: {:?}", expected);

  let matching_rules = &expected.request.matching_rules;
  let plugin_data = setup_plugin_config(pact, &expected.boxed());

  let body_context = CoreMatchingContext {
    matchers: matching_rules.rules_for_category("content").unwrap_or_default(),
    config: DiffConfig::AllowUnexpectedKeys,
    matching_spec: PactSpecification::V4,
    plugin_configuration: plugin_data.clone()
  };

  let metadata_context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
                                              &matching_rules.rules_for_category("metadata").unwrap_or_default(),
                                              &plugin_data);
  let contents = match_message_contents(&expected.request, &actual.request, &body_context).await;

  let mut mismatches = vec![];
  mismatches.extend_from_slice(contents.err().unwrap_or_default().as_slice());
  for values in match_message_metadata(&expected.request, &actual.request, &metadata_context).values() {
    mismatches.extend_from_slice(values.as_slice());
  }
  mismatches
}

/// Match the response part of a synchronous request/response message
pub async fn match_sync_message_response<'a>(
  expected: &SynchronousMessage,
  expected_responses: &[MessageContents],
  actual_responses: &[MessageContents],
  pact: &Box<dyn Pact + Send + Sync + 'a>
) -> Vec<Mismatch> {
  info!("comparing to expected message responses: {:?}", expected_responses);

  let mut mismatches = vec![];

  if expected_responses.len() != actual_responses.len() {
    if !expected_responses.is_empty() && actual_responses.is_empty() {
      mismatches.push(Mismatch::BodyTypeMismatch {
        expected: "message response".into(),
        actual: "".into(),
        mismatch: "Expected a message with a response, but the actual response was empty".into(),
        expected_body: None,
        actual_body: None
      });
    } else if !expected_responses.is_empty() {
      mismatches.push(Mismatch::BodyTypeMismatch {
        expected: "message response".into(),
        actual: "".into(),
        mismatch: format!("Expected a message with {} responses, but the actual response had {}",
                          expected_responses.len(), actual_responses.len()),
        expected_body: None,
        actual_body: None
      });
    }
  } else {
    let plugin_data = setup_plugin_config(pact, &expected.boxed());
    for (expected_response, actual_response) in expected_responses.iter().zip(actual_responses) {
      let matching_rules = &expected_response.matching_rules;
      let body_context = CoreMatchingContext {
        matchers: matching_rules.rules_for_category("content").unwrap_or_default(),
        config: DiffConfig::AllowUnexpectedKeys,
        matching_spec: PactSpecification::V4,
        plugin_configuration: plugin_data.clone()
      };

      let metadata_context = CoreMatchingContext::new(DiffConfig::AllowUnexpectedKeys,
                                                  &matching_rules.rules_for_category("metadata").unwrap_or_default(),
                                                  &plugin_data);
      let contents = match_message_contents(expected_response, actual_response, &body_context).await;

      mismatches.extend_from_slice(contents.err().unwrap_or_default().as_slice());
      for values in match_message_metadata(expected_response, actual_response, &metadata_context).values() {
        mismatches.extend_from_slice(values.as_slice());
      }
    }
  }
  mismatches
}

/// Generates the request by applying any defined generators
pub async fn generate_request(request: &HttpRequest, mode: &GeneratorTestMode, context: &HashMap<&str, Value>) -> HttpRequest {
  let mut request = request.clone();

  let generators = request.build_generators(&GeneratorCategory::PATH);
  if !generators.is_empty() {
    debug!("Applying path generator...");
    apply_generators(mode, &generators, &mut |_, generator| {
      if let Ok(v) = generator.generate_value(&request.path, context, &DefaultVariantMatcher.boxed()) {
        request.path = v;
      }
    });
  }

  let generators = request.build_generators(&GeneratorCategory::HEADER);
  if !generators.is_empty() {
    debug!("Applying header generators...");
    apply_generators(mode, &generators, &mut |key, generator| {
      if let Some(header) = key.first_field() {
        if let Some(ref mut headers) = request.headers {
          if headers.contains_key(header) {
            if let Ok(v) = generator.generate_value(&headers.get(header).unwrap().clone(), context, &DefaultVariantMatcher.boxed()) {
              headers.insert(header.to_string(), v);
            }
          }
        }
      }
    });
  }

  let generators = request.build_generators(&GeneratorCategory::QUERY);
  if !generators.is_empty() {
    debug!("Applying query generators...");
    apply_generators(mode, &generators, &mut |key, generator| {
      if let Some(param) = key.first_field() {
        if let Some(ref mut parameters) = request.query {
          if let Some(parameter) = parameters.get_mut(param) {
            let mut generated = parameter.clone();
            for (index, val) in parameter.iter().enumerate() {
              if let Ok(v) = generator.generate_value(val, context, &DefaultVariantMatcher.boxed()) {
                generated[index] = v;
              }
            }
            *parameter = generated;
          }
        }
      }
    });
  }

  let generators = request.build_generators(&GeneratorCategory::BODY);
  if !generators.is_empty() && request.body.is_present() {
    debug!("Applying body generators...");
    match generators_process_body(mode, &request.body, request.content_type(),
                                  context, &generators, &DefaultVariantMatcher{}).await {
      Ok(body) => request.body = body,
      Err(err) => error!("Failed to generate the body, will use the original: {}", err)
    }
  }

  request
}

/// Generates the response by applying any defined generators
pub async fn generate_response(response: &HttpResponse, mode: &GeneratorTestMode, context: &HashMap<&str, Value>) -> HttpResponse {
  let mut response = response.clone();
  let generators = response.build_generators(&GeneratorCategory::STATUS);
  if !generators.is_empty() {
    debug!("Applying status generator...");
    apply_generators(mode, &generators, &mut |_, generator| {
      if let Ok(v) = generator.generate_value(&response.status, context, &DefaultVariantMatcher.boxed()) {
        debug!("Generated value for status: {}", v);
        response.status = v;
      }
    });
  }
  let generators = response.build_generators(&GeneratorCategory::HEADER);
  if !generators.is_empty() {
    debug!("Applying header generators...");
    apply_generators(mode, &generators, &mut |key, generator| {
      if let Some(header) = key.first_field() {
        if let Some(ref mut headers) = response.headers {
          if headers.contains_key(header) {
            match generator.generate_value(&headers.get(header).unwrap().clone(), context, &DefaultVariantMatcher.boxed()) {
              Ok(v) => {
                debug!("Generated value for header: {} -> {:?}", header, v);
                headers.insert(header.to_string(), v)
              },
              Err(_) => None
            };
          }
        }
      }
    });
  }
  let generators = response.build_generators(&GeneratorCategory::BODY);
  if !generators.is_empty() && response.body.is_present() {
    debug!("Applying body generators...");
    match generators_process_body(mode, &response.body, response.content_type(),
      context, &generators, &DefaultVariantMatcher{}).await {
      Ok(body) => response.body = body,
      Err(err) => error!("Failed to generate the body, will use the original: {}", err)
    }
  }
  response
}

/// Matches the request part of the interaction
pub async fn match_interaction_request(
  expected: Box<dyn Interaction + Send + Sync>,
  actual: Box<dyn Interaction + Send + Sync>,
  pact: Box<dyn Pact + Send + Sync>,
  _spec_version: &PactSpecification
) -> anyhow::Result<RequestMatchResult> {
  if let Some(http_interaction) = expected.as_v4_http() {
    let request = actual.as_v4_http()
      .ok_or_else(|| anyhow!("Could not unpack actual request as a V4 Http Request"))?.request;
    Ok(match_request(http_interaction.request, request, &pact, &expected).await)
  } else {
    Err(anyhow!("match_interaction_request must be called with HTTP request/response interactions, got {}", expected.type_of()))
  }
}

/// Matches the response part of the interaction
pub async fn match_interaction_response(
  expected: Box<dyn Interaction + Sync>,
  actual: Box<dyn Interaction + Sync>,
  pact: Box<dyn Pact + Send + Sync>,
  _spec_version: &PactSpecification
) -> anyhow::Result<Vec<Mismatch>> {
  if let Some(expected) = expected.as_v4_http() {
    let expected_response = expected.response.clone();
    let expected = expected.boxed();
    let response = actual.as_v4_http()
      .ok_or_else(|| anyhow!("Could not unpack actual response as a V4 Http Response"))?.response;
    Ok(match_response(expected_response, response, &pact, &expected).await)
  } else {
    Err(anyhow!("match_interaction_response must be called with HTTP request/response interactions, got {}", expected.type_of()))
  }
}

/// Matches an interaction
pub async fn match_interaction(
  expected: Box<dyn Interaction + Send + Sync>,
  actual: Box<dyn Interaction + Send + Sync>,
  pact: Box<dyn Pact + Send + Sync>,
  _spec_version: &PactSpecification
) -> anyhow::Result<Vec<Mismatch>> {
  if let Some(expected) = expected.as_v4_http() {
    let expected_request = expected.request.clone();
    let expected_response = expected.response.clone();
    let expected = expected.boxed();
    let request = actual.as_v4_http()
      .ok_or_else(|| anyhow!("Could not unpack actual request as a V4 Http Request"))?.request;
    let request_result = match_request(expected_request, request, &pact, &expected).await;
    let response = actual.as_v4_http()
      .ok_or_else(|| anyhow!("Could not unpack actual response as a V4 Http Response"))?.response;
    let response_result = match_response(expected_response, response, &pact, &expected).await;
    let mut mismatches = request_result.mismatches();
    mismatches.extend_from_slice(&*response_result);
    Ok(mismatches)
  } else if expected.is_message() || expected.is_v4() {
    Ok(match_message(&expected, &actual, &pact).await)
  } else {
    Err(anyhow!("match_interaction must be called with either an HTTP request/response interaction or a Message, got {}", expected.type_of()))
  }
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod generator_tests;