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
//! Traits to represent a Pact

use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::fs;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::ops::Deref;
use std::path::Path;
use std::sync::{Arc, Mutex};

use anyhow::{anyhow, Context};
use lazy_static::lazy_static;
use maplit::btreemap;
use serde_json::{json, Value};
use tracing::{debug, error, trace, warn};

use crate::{Consumer, PactSpecification, Provider};
#[cfg(not(target_family = "wasm"))] use crate::file_utils::{with_read_lock_for_open_file, with_write_lock};
#[cfg(not(target_family = "wasm"))] use crate::http_utils;
#[cfg(not(target_family = "wasm"))] use crate::http_utils::HttpAuth;
use crate::interaction::Interaction;
use crate::message_pact::MessagePact;
use crate::plugins::PluginData;
use crate::sync_pact::RequestResponsePact;
use crate::v4;
use crate::v4::pact::V4Pact;
use crate::verify_json::{json_type_of, PactFileVerificationResult, ResultLevel};

/// Trait for a Pact (request/response or message)
pub trait Pact: Debug + ReadWritePact {
  /// Consumer side of the pact
  fn consumer(&self) -> Consumer;

  /// Provider side of the pact
  fn provider(&self) -> Provider;

  /// Interactions in the Pact
  fn interactions(&self) -> Vec<Box<dyn Interaction + Send + Sync>>;

  /// Mutable collection of interactions in the Pact
  fn interactions_mut(&mut self) -> Vec<&mut (dyn Interaction + Send + Sync)>;

  /// Pact metadata
  fn metadata(&self) -> BTreeMap<String, BTreeMap<String, String>>;

  /// Converts this pact to a `Value` struct.
  fn to_json(&self, pact_spec: PactSpecification) -> anyhow::Result<Value>;

  /// Attempt to downcast to a concrete Pact
  fn as_request_response_pact(&self) -> anyhow::Result<RequestResponsePact>;

  /// Attempt to downcast to a concrete Message Pact
  fn as_message_pact(&self) -> anyhow::Result<MessagePact>;

  /// Attempt to downcast to a concrete V4 Pact
  fn as_v4_pact(&self) -> anyhow::Result<V4Pact>;

  /// Specification version of this Pact
  fn specification_version(&self) -> PactSpecification;

  /// Clones this Pact and wraps it in a Box
  fn boxed(&self) -> Box<dyn Pact + Send + Sync>;

  /// Clones this Pact and wraps it in an Arc
  fn arced(&self) -> Arc<dyn Pact + Send + Sync>;

  /// Clones this Pact and wraps it in an Arc and Mutex
  fn thread_safe(&self) -> Arc<Mutex<dyn Pact + Send + Sync>>;

  /// Adds an interactions in the Pact
  fn add_interaction(&mut self, interaction: &dyn Interaction) -> anyhow::Result<()>;

  /// If this Pact needs any plugins loaded
  fn requires_plugins(&self) -> bool;

  /// Plugins required for this Pact. These will be taken from the 'plugins' key in the pact
  /// metadata.
  fn plugin_data(&self) -> Vec<PluginData>;

  /// If this is a V4 Pact
  fn is_v4(&self) -> bool;

  /// Add the plugin and plugin data to this Pact. If an entry already exists for the plugin,
  /// the plugin data will be merged
  fn add_plugin(
    &mut self,
    name: &str,
    version: &str,
    plugin_data: Option<HashMap<String, Value>>
  ) -> anyhow::Result<()>;

  /// Adds some version info to the Pact-Rust metadata section
  fn add_md_version(&mut self, key: &str, version: &str);
}

impl Default for Box<dyn Pact> {
  fn default() -> Self {
    V4Pact::default().boxed()
  }
}

impl Clone for Box<dyn Pact> {
  fn clone(&self) -> Self {
    self.boxed()
  }
}

impl PartialEq for Box<dyn Pact> {
  fn eq(&self, other: &Self) -> bool {
    if let Ok(pact) = self.as_v4_pact() {
      if let Ok(other) = other.as_v4_pact() {
        pact == other
      } else {
        false
      }
    } else if let Ok(pact) = self.as_request_response_pact() {
      if let Ok(other) = other.as_request_response_pact() {
        pact == other
      } else {
        false
      }
    } else if let Ok(pact) = self.as_message_pact() {
      if let Ok(other) = other.as_message_pact() {
        pact == other
      } else {
        false
      }
    } else {
      false
    }
  }
}

/// Reads the pact file and parses the resulting JSON into a `Pact` struct
#[cfg(not(target_family = "wasm"))]
pub fn read_pact(file: &Path) -> anyhow::Result<Box<dyn Pact + Send + Sync>> {
  let mut f = File::open(file)?;
  read_pact_from_file(&mut f, file)
}

/// Reads the pact from the file and parses the resulting JSON into a `Pact` struct
#[cfg(not(target_family = "wasm"))]
pub fn read_pact_from_file(file: &mut File, path: &Path) -> anyhow::Result<Box<dyn Pact + Send + Sync>> {
  let buf = with_read_lock_for_open_file(path, file, 3, &mut |f| {
    let mut buf = String::new();
    f.read_to_string(&mut buf)?;
    Ok(buf)
  })?;
  let pact_json = serde_json::from_str(&buf)
    .context("Failed to parse Pact JSON")
    .map_err(|err| {
      error!("read_pact_from_file: {}", err);
      debug!("read_pact_from_file: file contents = '{}'", buf);
      err
    })?;
  load_pact_from_json(&*path.to_string_lossy(), &pact_json)
    .map_err(|e| anyhow!(e))
}

/// Reads the pact file from a URL and parses the resulting JSON into a `Pact` struct
// TODO: For next major version, refactor this to also return any associated HAL links
#[cfg(not(target_family = "wasm"))]
pub fn load_pact_from_url(url: &str, auth: &Option<HttpAuth>) -> anyhow::Result<Box<dyn Pact + Send + Sync>> {
  let (url, pact_json) = http_utils::fetch_json_from_url(&url.to_string(), auth)?;
  load_pact_from_json(&url, &pact_json)
}

/// Loads a Pact model from a JSON Value
pub fn load_pact_from_json(source: &str, json: &Value) -> anyhow::Result<Box<dyn Pact + Send + Sync>> {
  match json {
    Value::Object(map) => {
      let metadata = parse_meta_data(json);
      let spec_version = determine_spec_version(source, &metadata);
      trace!("load_pact_from_json: found spec version {} in metadata", spec_version);
      match spec_version {
        PactSpecification::V4 => v4::pact::from_json(&source, json),
        _ => if map.contains_key("messages") {
          trace!("load_pact_from_json: JSON has a messages attribute, will load as a message pact");
          let pact = MessagePact::from_json(source, json)?;
          Ok(Box::new(pact))
        } else {
          trace!("load_pact_from_json: loading JSON as a request/response pact");
          Ok(Box::new(RequestResponsePact::from_json(source, json)?))
        }
      }
    },
    _ => Err(anyhow!("Failed to parse Pact JSON from source '{}' - it is not a valid pact file", source))
  }
}

/// Trait for objects that can represent Pacts and can be read and written
pub trait ReadWritePact {
  /// Reads the pact file and parses the resulting JSON into a `Pact` struct
  #[cfg(not(target_family = "wasm"))]
  fn read_pact(path: &Path) -> anyhow::Result<Self> where Self: std::marker::Sized + Send + Sync;

  /// Merges this pact with the other pact, and returns a new Pact with the interactions sorted.
  /// Returns an error if there is a merge conflict, which will occur if the other pact is a different
  /// type, or if a V3 Pact then if any interaction has the
  /// same description and provider state and the requests and responses are different.
  fn merge(&self, other: &dyn Pact) -> anyhow::Result<Box<dyn Pact + Send + Sync>>;

  /// Determines the default file name for the pact. This is based on the consumer and
  /// provider names.
  fn default_file_name(&self) -> String;
}

lazy_static!{
  static ref WRITE_LOCK: Mutex<()> = Mutex::new(());
}

/// Writes the pact out to the provided path. If there is an existing pact at the path, the two
/// pacts will be merged together unless overwrite is true. Returns an error if the file can not
/// be written or the pacts can not be merged.
#[cfg(not(target_family = "wasm"))]
pub fn write_pact(
  pact: Box<dyn Pact>,
  path: &Path,
  pact_spec: PactSpecification,
  overwrite: bool
) -> anyhow::Result<()> {
  fs::create_dir_all(path.parent().unwrap())?;
  let _lock = WRITE_LOCK.lock().unwrap();
  if !overwrite && path.exists() {
    debug!("Merging pact with file {:?}", path);
    let mut f = fs::OpenOptions::new().read(true).write(true).open(&path)?;
    let existing_pact = read_pact_from_file(&mut f, path)?;

    if existing_pact.specification_version() < pact.specification_version() {
      warn!("Note: Existing pact is an older specification version ({:?}), and will be upgraded",
            existing_pact.specification_version());
    }

    let merged_pact = pact.merge(existing_pact.deref())?;
    let pact_json = serde_json::to_string_pretty(&merged_pact.to_json(pact_spec)?)?;

    with_write_lock(path, &mut f, 3, &mut |f| {
      f.set_len(0)?;
      f.seek(SeekFrom::Start(0))?;
      f.write_all(pact_json.as_bytes())?;
      Ok(())
    })
  } else {
    debug!("Writing new pact file to {:?}", path);
    let result = serde_json::to_string_pretty(&pact.to_json(pact_spec)?)?;
    let mut file = File::create(path)?;
    with_write_lock(path, &mut file, 3, &mut |f| {
      f.write_all(result.as_bytes())?;
      Ok(())
    })
  }
}


/// Construct Metadata from JSON value
pub fn parse_meta_data(pact_json: &Value) -> BTreeMap<String, BTreeMap<String, String>> {
  match pact_json.get("metadata") {
    Some(v) => match *v {
      Value::Object(ref obj) => obj.iter().map(|(k, v)| {
        let val = match *v {
          Value::Object(ref obj) => obj.iter().map(|(k, v)| {
            match *v {
              Value::String(ref s) => (k.clone(), s.clone()),
              _ => (k.clone(), v.to_string())
            }
          }).collect(),
          _ => btreemap!{}
        };
        let key = match k.as_str() {
          "pact-specification" => "pactSpecification".to_string(),
          "pact-rust" => "pactRust".to_string(),
          _ => k.clone()
        };
        (key, val)
      }).collect(),
      _ => btreemap!{}
    },
    None => btreemap!{}
  }
}

pub(crate) fn metadata_schema(spec_version: PactSpecification) -> Value {
  if spec_version < PactSpecification::V3 {
    json!({
      "properties": {
        "pactSpecification": {
          "additionalProperties": false,
          "properties": {
            "version": {
              "type": "string"
            }
          },
          "required": ["version"],
          "type": "object"
        },
        "pactSpecificationVersion": {
          "type": "string"
        },
        "pact-specification": {
          "additionalProperties": false,
          "properties": {
              "version": {
                  "type": "string"
              }
          },
          "required": ["version"],
          "type": "object"
        }
      },
      "type": "object"
    })
  } else {
    json!({
      "properties": {
        "pactSpecification": {
          "additionalProperties": false,
          "properties": {
            "version": {
              "type": "string"
            }
          },
          "required": ["version"],
          "type": "object"
        }
      },
      "type": "object"
    })
  }
}

/// Determines the Pact specification version from the metadata of the Pact file
pub fn determine_spec_version(file: &str, metadata: &BTreeMap<String, BTreeMap<String, String>>) -> PactSpecification {
  let specification = if metadata.contains_key("pact-specification") {
    metadata.get("pact-specification")
  } else {
    metadata.get("pactSpecification")
  };
  match specification {
    Some(spec) => {
      match spec.get("version") {
        Some(ver) => match lenient_semver::parse(ver) {
          Ok(ver) => match ver.major {
            1 => match ver.minor {
              0 => PactSpecification::V1,
              1 => PactSpecification::V1_1,
              _ => {
                warn!("Unsupported specification version '{}' found in the metadata in the pact file {:?}, will try load it as a V1 specification", ver, file);
                PactSpecification::V1
              }
            },
            2 => PactSpecification::V2,
            3 => PactSpecification::V3,
            4 => PactSpecification::V4,
            _ => {
              warn!("Unsupported specification version '{}' found in the metadata in the pact file {:?}, will try load it as a V3 specification", ver, file);
              PactSpecification::Unknown
            }
          },
          Err(err) => {
            warn!("Could not parse specification version '{}' found in the metadata in the pact file {:?}, assuming V3 specification - {}", ver, file, err);
            PactSpecification::Unknown
          }
        },
        None => {
          warn!("No specification version found in the metadata in the pact file {:?}, assuming V3 specification", file);
          PactSpecification::V3
        }
      }
    },
    None => {
      warn!("No metadata found in pact file {:?}, assuming V3 specification", file);
      PactSpecification::V3
    }
  }
}

pub(crate) fn verify_metadata(metadata: &Value, _spec_version: PactSpecification) -> Vec<PactFileVerificationResult> {
  let mut results = vec![];

  match metadata {
    Value::Object(values) => {
      let spec_value = if let Some(spec_value) = values.get("pactSpecification") {
        Some(spec_value)
      } else if let Some(spec_value) = values.get("pact-specification") {
        results.push(PactFileVerificationResult::new("/metadata", ResultLevel::WARNING,
                                                     &format!("'pact-specification' is deprecated, use 'pactSpecification' instead")));
        Some(spec_value)
      } else {
        None
      };

      if values.contains_key("pactSpecificationVersion") {
        results.push(PactFileVerificationResult::new("/metadata", ResultLevel::WARNING,
                                                     &format!("'pactSpecificationVersion' is deprecated, use 'pactSpecification/version' instead")));
      }

      if let Some(spec) = spec_value {
        match spec {
          Value::Object(values) => {
            if let Some(version) = values.get("version") {
              match version {
                Value::Null => results.push(PactFileVerificationResult::new("/metadata/pactSpecification/version", ResultLevel::WARNING,
                                                                            &format!("pactSpecification version is NULL"))),
                Value::String(version) => if PactSpecification::parse_version(version).is_err() {
                  results.push(PactFileVerificationResult::new("/metadata/pactSpecification/version", ResultLevel::ERROR,
                                                               &format!("'{}' is not a valid Pact specification version", version)))
                }
                _ => results.push(PactFileVerificationResult::new("/metadata/pactSpecification/version", ResultLevel::ERROR,
                                                                  &format!("Version must be a String, got {}", json_type_of(version))))
              }
            } else {
              results.push(PactFileVerificationResult::new("/metadata/pactSpecification", ResultLevel::WARNING,
                                                           &format!("pactSpecification is missing the version attribute")));
            }
          }
          _ => results.push(PactFileVerificationResult::new("/metadata/pactSpecification", ResultLevel::ERROR,
                                                            &format!("pactSpecification must be an Object, got {}", json_type_of(spec))))
        }
      }
    }
    _ => results.push(PactFileVerificationResult::new("/metadata", ResultLevel::ERROR,
                                                      &format!("Metadata must be an Object, got {}", json_type_of(metadata))))
  }

  results
}

#[cfg(test)]
mod tests {
  use std::{env, fs, io};
  use std::fs::File;
  use std::io::Read;

  use expectest::prelude::*;
  use maplit::{btreemap, hashmap};
  use pretty_assertions::assert_eq;
  use serde_json::{json, Value};

  use crate::{Consumer, PactSpecification, Provider};
  use crate::bodies::OptionalBody;
  use crate::content_types::JSON;
  use crate::generators;
  use crate::generators::Generator;
  use crate::matchingrules;
  use crate::matchingrules::MatchingRule;
  use crate::pact::{Pact, ReadWritePact, write_pact};
  use crate::PACT_RUST_VERSION;
  use crate::provider_states::ProviderState;
  use crate::request::Request;
  use crate::response::Response;
  use crate::sync_interaction::RequestResponseInteraction;
  use crate::sync_pact::RequestResponsePact;
  use crate::v4::pact::V4Pact;
  use crate::v4::synch_http::SynchronousHttp;

  #[test]
  fn load_empty_pact() {
    let pact_json = r#"{}"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.provider.name).to(be_equal_to("provider"));
    expect!(pact.consumer.name).to(be_equal_to("consumer"));
    expect!(pact.interactions.iter()).to(have_count(0));
    expect!(pact.metadata.iter()).to(have_count(0));
    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V3));
  }

  #[test]
  fn missing_metadata() {
    let pact_json = r#"{}"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V3));
  }

  #[test]
  fn missing_spec_version() {
    let pact_json = r#"{
        "metadata" : {
        }
    }"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V3));
  }

  #[test]
  fn missing_version_in_spec_version() {
    let pact_json = r#"{
        "metadata" : {
            "pact-specification": {

            }
        }
    }"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V3));
  }

  #[test]
  fn empty_version_in_spec_version() {
    let pact_json = r#"{
        "metadata" : {
            "pact-specification": {
                "version": ""
            }
        }
    }"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.specification_version).to(be_equal_to(PactSpecification::Unknown));
  }

  #[test]
  fn correct_version_in_spec_version() {
    let pact_json = r#"{
        "metadata" : {
            "pact-specification": {
                "version": "1.0.0"
            }
        }
    }"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V1));
  }

  #[test]
  fn invalid_version_in_spec_version() {
    let pact_json = r#"{
        "metadata" : {
            "pact-specification": {
                "version": "znjclkazjs"
            }
        }
    }"#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.specification_version).to(be_equal_to(PactSpecification::Unknown));
  }


  #[test]
  fn load_basic_pact() {
    let pact_json = r#"
    {
        "provider": {
            "name": "Alice Service"
        },
        "consumer": {
            "name": "Consumer"
        },
        "interactions": [
          {
              "description": "a retrieve Mallory request",
              "request": {
                "method": "GET",
                "path": "/mallory",
                "query": "name=ron&status=good"
              },
              "response": {
                "status": 200,
                "headers": {
                  "Content-Type": "text/html"
                },
                "body": "\"That is some good Mallory.\""
              }
          }
        ]
    }
    "#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(&pact.provider.name).to(be_equal_to("Alice Service"));
    expect!(&pact.consumer.name).to(be_equal_to("Consumer"));
    expect!(pact.interactions.iter()).to(have_count(1));
    let interaction = pact.interactions[0].clone();
    expect!(interaction.description).to(be_equal_to("a retrieve Mallory request"));
    expect!(interaction.provider_states.iter()).to(be_empty());
    expect!(interaction.request).to(be_equal_to(Request {
      method: "GET".to_string(),
      path: "/mallory".to_string(),
      query: Some(hashmap!{ "name".to_string() => vec!["ron".to_string()], "status".to_string() => vec!["good".to_string()] }),
      headers: None,
      body: OptionalBody::Missing,
      .. Request::default()
    }));
    expect!(interaction.response).to(be_equal_to(Response {
      status: 200,
      headers: Some(hashmap!{ "Content-Type".to_string() => vec!["text/html".to_string()] }),
      body: OptionalBody::Present("\"That is some good Mallory.\"".into(), Some("text/html".into()), None),
      .. Response::default()
    }));
    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V3));
    expect!(pact.metadata.iter()).to(have_count(0));
  }

  #[test]
  fn load_pact() {
    let pact_json = r#"
    {
      "provider" : {
        "name" : "test_provider"
      },
      "consumer" : {
        "name" : "test_consumer"
      },
      "interactions" : [ {
        "providerState" : "test state",
        "description" : "test interaction",
        "request" : {
          "method" : "GET",
          "path" : "/",
          "headers" : {
            "testreqheader" : "testreqheadervalue"
          },
          "query" : "q=p&q=p2&r=s",
          "body" : {
            "test" : true
          }
        },
        "response" : {
          "status" : 200,
          "headers" : {
            "testreqheader" : "testreqheaderval"
          },
          "body" : {
            "responsetest" : true
          }
        }
      } ],
      "metadata" : {
        "pact-specification" : {
          "version" : "1.0.0"
        },
        "pact-jvm" : {
          "version" : ""
        }
      }
    }
    "#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(&pact.provider.name).to(be_equal_to("test_provider"));
    expect!(&pact.consumer.name).to(be_equal_to("test_consumer"));
    expect!(pact.metadata.iter()).to(have_count(2));
    expect!(&pact.metadata["pactSpecification"]["version"]).to(be_equal_to("1.0.0"));
    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V1));
    expect!(pact.interactions.iter()).to(have_count(1));
    let interaction = pact.interactions[0].clone();
    expect!(interaction.description).to(be_equal_to("test interaction"));
    expect!(interaction.provider_states).to(be_equal_to(vec![
      ProviderState { name: "test state".to_string(), params: hashmap!{} } ]));
    expect!(interaction.request).to(be_equal_to(Request {
      method: "GET".to_string(),
      path: "/".to_string(),
      query: Some(hashmap!{ "q".to_string() => vec!["p".to_string(), "p2".to_string()], "r".to_string() => vec!["s".to_string()] }),
      headers: Some(hashmap!{ "testreqheader".to_string() => vec!["testreqheadervalue".to_string()] }),
      body: "{\"test\":true}".into(),
      .. Request::default()
    }));
    expect!(interaction.response).to(be_equal_to(Response {
      status: 200,
      headers: Some(hashmap!{ "testreqheader".to_string() => vec!["testreqheaderval".to_string()] }),
      body: "{\"responsetest\":true}".into(),
      .. Response::default()
    }));
  }

  #[test]
  fn load_v3_pact() {
    let pact_json = r#"
    {
      "provider" : {
        "name" : "test_provider"
      },
      "consumer" : {
        "name" : "test_consumer"
      },
      "interactions" : [ {
        "providerState" : "test state",
        "description" : "test interaction",
        "request" : {
          "method" : "GET",
          "path" : "/",
          "headers" : {
            "testreqheader" : "testreqheadervalue"
          },
          "query" : {
              "q": ["p", "p2"],
              "r": ["s"]
          },
          "body" : {
            "test" : true
          }
        },
        "response" : {
          "status" : 200,
          "headers" : {
            "testreqheader" : "testreqheaderval"
          },
          "body" : {
            "responsetest" : true
          }
        }
      } ],
      "metadata" : {
        "pact-specification" : {
          "version" : "3.0.0"
        },
        "pact-jvm" : {
          "version" : ""
        }
      }
    }
    "#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(&pact.provider.name).to(be_equal_to("test_provider"));
    expect!(&pact.consumer.name).to(be_equal_to("test_consumer"));
    expect!(pact.metadata.iter()).to(have_count(2));
    expect!(&pact.metadata["pactSpecification"]["version"]).to(be_equal_to("3.0.0"));
    expect!(pact.specification_version).to(be_equal_to(PactSpecification::V3));
    expect!(pact.interactions.iter()).to(have_count(1));
    let interaction = pact.interactions[0].clone();
    expect!(interaction.description).to(be_equal_to("test interaction"));
    expect!(interaction.provider_states).to(be_equal_to(vec![
      ProviderState { name: "test state".to_string(), params: hashmap!{} } ]));
    expect!(interaction.request).to(be_equal_to(Request {
      method: "GET".to_string(),
      path: "/".to_string(),
      query: Some(hashmap!{ "q".to_string() => vec!["p".to_string(), "p2".to_string()], "r".to_string() => vec!["s".to_string()] }),
      headers: Some(hashmap!{ "testreqheader".to_string() => vec!["testreqheadervalue".to_string()] }),
      body: OptionalBody::Present("{\"test\":true}".into(), None, None),
      .. Request::default()
    }));
    expect!(interaction.response).to(be_equal_to(Response {
      status: 200,
      headers: Some(hashmap!{ "testreqheader".to_string() => vec!["testreqheaderval".to_string()] }),
      body: OptionalBody::Present("{\"responsetest\":true}".into(), None, None),
      .. Response::default()
    }));
  }

  #[test]
  fn load_pact_encoded_query_string() {
    let pact_json = r#"
    {
      "provider" : {
        "name" : "test_provider"
      },
      "consumer" : {
        "name" : "test_consumer"
      },
      "interactions" : [ {
        "providerState" : "test state",
        "description" : "test interaction",
        "request" : {
          "method" : "GET",
          "path" : "/",
          "headers" : {
            "testreqheader" : "testreqheadervalue"
          },
          "query" : "datetime=2011-12-03T10%3A15%3A30%2B01%3A00&description=hello+world%21",
          "body" : {
            "test" : true
          }
        },
        "response" : {
          "status" : 200,
          "headers" : {
            "testreqheader" : "testreqheaderval"
          },
          "body" : {
            "responsetest" : true
          }
        }
      } ],
      "metadata" : {
        "pact-specification" : {
          "version" : "2.0.0"
        },
        "pact-jvm" : {
          "version" : ""
        }
      }
    }
    "#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.interactions.iter()).to(have_count(1));
    let interaction = pact.interactions[0].clone();
    expect!(interaction.request).to(be_equal_to(Request {
      method: "GET".to_string(),
      path: "/".to_string(),
      query: Some(hashmap!{ "datetime".to_string() => vec!["2011-12-03T10:15:30+01:00".to_string()],
            "description".to_string() => vec!["hello world!".to_string()] }),
      headers: Some(hashmap!{ "testreqheader".to_string() => vec!["testreqheadervalue".to_string()] }),
      body: OptionalBody::Present("{\"test\":true}".into(), None, None),
      .. Request::default()
    }));
  }

  #[test]
  fn load_pact_converts_methods_to_uppercase() {
    let pact_json = r#"
    {
      "interactions" : [ {
        "description" : "test interaction",
        "request" : {
          "method" : "get"
        },
        "response" : {
          "status" : 200
        }
      } ],
      "metadata" : {}
    }
    "#;
    let pact = RequestResponsePact::from_json(&"".to_string(), &serde_json::from_str(pact_json).unwrap());
    let pact = pact.unwrap();

    expect!(pact.interactions.iter()).to(have_count(1));
    let interaction = pact.interactions[0].clone();
    expect!(interaction.request).to(be_equal_to(Request {
      method: "GET".to_string(),
      path: "/".to_string(),
      query: None,
      headers: None,
      body: OptionalBody::Missing,
      .. Request::default()
    }));
  }

  #[test]
  fn default_file_name_is_based_in_the_consumer_and_provider() {
    let pact = RequestResponsePact { consumer: Consumer { name: "consumer".to_string() },
      provider: Provider { name: "provider".to_string() },
      interactions: vec![],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    expect!(pact.default_file_name()).to(be_equal_to("consumer-provider.json"));
  }

  fn read_pact_file(file: &str) -> io::Result<String> {
    let mut f = File::open(file)?;
    let mut buffer = String::new();
    f.read_to_string(&mut buffer)?;
    Ok(buffer)
  }

  #[test]
  fn write_pact_test() {
    let pact = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer".to_string() },
      provider: Provider { name: "write_pact_test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V2, true);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    assert_eq!(pact_file, format!(r#"{{
  "consumer": {{
    "name": "write_pact_test_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "providerState": "Good state to be in",
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "2.0.0"
    }}
  }},
  "provider": {{
    "name": "write_pact_test_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap()));
  }

  #[test]
  fn write_pact_test_should_merge_pacts() {
    let pact = RequestResponsePact { consumer: Consumer { name: "merge_consumer".to_string() },
      provider: Provider { name: "merge_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction 2".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "merge_consumer".to_string() },
      provider: Provider { name: "merge_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V2, false);
    let result2 = write_pact(pact2.boxed(), dir.as_path(), PactSpecification::V2, false);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(result2).to(be_ok());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "merge_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "providerState": "Good state to be in",
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }},
    {{
      "description": "Test Interaction 2",
      "providerState": "Good state to be in",
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "2.0.0"
    }}
  }},
  "provider": {{
    "name": "merge_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn write_pact_test_should_not_merge_pacts_with_conflicts() {
    let pact = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer".to_string() },
      provider: Provider { name: "write_pact_test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer".to_string() },
      provider: Provider { name: "write_pact_test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          response: Response { status: 400, .. Response::default() },
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V2, false);
    let result2 = write_pact(pact2.boxed(), dir.as_path(), PactSpecification::V2, false);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(result2).to(be_err());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "write_pact_test_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "providerState": "Good state to be in",
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "2.0.0"
    }}
  }},
  "provider": {{
    "name": "write_pact_test_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn write_pact_test_should_upgrade_older_pacts_when_merging() {
    let pact = RequestResponsePact { consumer: Consumer { name: "merge_consumer".to_string() },
      provider: Provider { name: "merge_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction 2".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "merge_consumer".to_string() },
      provider: Provider { name: "merge_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V3
    };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V2, false);
    let result2 = write_pact(pact2.boxed(), dir.as_path(), PactSpecification::V3, false);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(result2).to(be_ok());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "merge_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "providerStates": [
        {{
          "name": "Good state to be in"
        }}
      ],
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }},
    {{
      "description": "Test Interaction 2",
      "providerStates": [
        {{
          "name": "Good state to be in"
        }}
      ],
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "3.0.0"
    }}
  }},
  "provider": {{
    "name": "merge_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn write_pact_test_upgrades_older_pacts_to_v4_when_merging() {
    let pact = RequestResponsePact {
      consumer: Consumer { name: "merge_consumer".into() },
      provider: Provider { name: "merge_provider".into() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction 2".into(),
          provider_states: vec![ProviderState { name: "Good state to be in".into(), params: hashmap! {} }],
          ..RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap! {},
      specification_version: PactSpecification::V1_1,
    };
    let pact2 = V4Pact {
      consumer: Consumer { name: "merge_consumer".into() },
      provider: Provider { name: "merge_provider".into() },
      interactions: vec![
        Box::new(SynchronousHttp {
          id: None,
          key: None,
          description: "Test Interaction".into(),
          provider_states: vec![ProviderState { name: "Good state to be in".into(), params: hashmap! {} }],
          .. Default::default()
        })
      ],
      .. V4Pact::default()
    };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V3, false);
    let result2 = write_pact(pact2.boxed(), dir.as_path(), PactSpecification::V4, false);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(result2).to(be_ok());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "merge_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "key": "296966511eff169a",
      "pending": false,
      "providerStates": [
        {{
          "name": "Good state to be in"
        }}
      ],
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }},
      "type": "Synchronous/HTTP"
    }},
    {{
      "description": "Test Interaction 2",
      "key": "d3e13a43bc0744ac",
      "pending": false,
      "providerStates": [
        {{
          "name": "Good state to be in"
        }}
      ],
      "request": {{
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }},
      "type": "Synchronous/HTTP"
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "4.0"
    }}
  }},
  "provider": {{
    "name": "merge_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn pact_merge_does_not_merge_different_consumers() {
    let pact = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "test_consumer2".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    expect!(pact.merge(&pact2)).to(be_err());
  }

  #[test]
  fn pact_merge_does_not_merge_different_providers() {
    let pact = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider2".to_string() },
      interactions: vec![],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    expect!(pact.merge(&pact2)).to(be_err());
  }

  #[test]
  fn pact_merge_does_not_merge_where_there_are_conflicting_interactions() {
    let pact = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          request: Request { path: "/other".to_string(), .. Request::default() },
          .. RequestResponseInteraction::default()
        }
      ],
      metadata: btreemap!{},
      specification_version: PactSpecification::V1_1
    };
    expect!(pact.merge(&pact2)).to(be_err());
  }

  #[test]
  fn pact_merge_removes_duplicates() {
    let pact = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default()
    };
    let pact2 = RequestResponsePact { consumer: Consumer { name: "test_consumer".to_string() },
      provider: Provider { name: "test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        },
        RequestResponseInteraction {
          description: "Test Interaction 2".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default()
    };

    let merged_pact = pact.merge(&pact2);
    expect!(merged_pact.unwrap().interactions().len()).to(be_equal_to(2));

    let merged_pact2 = pact.merge(&pact.clone());
    expect!(merged_pact2.unwrap().interactions().len()).to(be_equal_to(1));
  }

  #[test]
  fn write_pact_test_with_matchers() {
    let pact = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer".to_string() },
      provider: Provider { name: "write_pact_test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          request: Request {
            matching_rules: matchingrules!{
                        "body" => {
                            "$" => [ MatchingRule::Type ]
                        }
                    },
            .. Request::default()
          },
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V2, true);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "write_pact_test_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "providerState": "Good state to be in",
      "request": {{
        "matchingRules": {{
          "$.body": {{
            "match": "type"
          }}
        }},
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "2.0.0"
    }}
  }},
  "provider": {{
    "name": "write_pact_test_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn write_pact_v3_test_with_matchers() {
    let pact = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer_v3".to_string() },
      provider: Provider { name: "write_pact_test_provider_v3".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          request: Request {
            matching_rules: matchingrules!{
                        "body" => {
                            "$" => [ MatchingRule::Type ]
                        },
                        "header" => {
                          "HEADER_A" => [ MatchingRule::Include("ValA".to_string()), MatchingRule::Include("ValB".to_string()) ]
                        }
                    },
            .. Request::default()
          },
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V3, true);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(pact_file.parse::<Value>().unwrap()).to(be_equal_to(json!({
      "consumer": {
        "name": "write_pact_test_consumer_v3"
      },
      "interactions": [
        {
          "description": "Test Interaction",
          "providerStates": [
            {
              "name": "Good state to be in"
            }
          ],
          "request": {
            "matchingRules": {
              "body": {
                "$": {
                  "combine": "AND",
                  "matchers": [
                    {
                      "match": "type"
                    }
                  ]
                }
              },
              "header": {
                "HEADER_A": {
                  "combine": "AND",
                  "matchers": [
                    {
                      "match": "include",
                      "value": "ValA"
                    },
                    {
                      "match": "include",
                      "value": "ValB"
                    }
                  ]
                }
              }
            },
            "method": "GET",
            "path": "/"
          },
          "response": {
            "status": 200
          }
        }
      ],
      "metadata": {
        "pactRust": {
          "models": PACT_RUST_VERSION
        },
        "pactSpecification": {
          "version": "3.0.0"
        }
      },
      "provider": {
        "name": "write_pact_test_provider_v3"
      }
    })));
  }

  #[test]
  fn write_v3_pact_test() {
    let pact = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer".to_string() },
      provider: Provider { name: "write_pact_test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          request: Request {
            query: Some(hashmap!{
                        "a".to_string() => vec!["1".to_string(), "2".to_string(), "3".to_string()],
                        "b".to_string() => vec!["bill".to_string(), "bob".to_string()],
                    }),
            .. Request::default()
          },
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V3, true);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "write_pact_test_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction",
      "providerStates": [
        {{
          "name": "Good state to be in"
        }}
      ],
      "request": {{
        "method": "GET",
        "path": "/",
        "query": {{
          "a": [
            "1",
            "2",
            "3"
          ],
          "b": [
            "bill",
            "bob"
          ]
        }}
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "3.0.0"
    }}
  }},
  "provider": {{
    "name": "write_pact_test_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn write_pact_test_with_generators() {
    let pact = RequestResponsePact { consumer: Consumer { name: "write_pact_test_consumer".to_string() },
      provider: Provider { name: "write_pact_test_provider".to_string() },
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction with generators".to_string(),
          provider_states: vec![ProviderState { name: "Good state to be in".to_string(), params: hashmap!{} }],
          request: Request {
            generators: generators!{
                        "BODY" => {
                          "$" => Generator::RandomInt(1, 10)
                        },
                        "HEADER" => {
                          "A" => Generator::RandomString(20)
                        }
                    },
            .. Request::default()
          },
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let mut dir = env::temp_dir();
    let x = rand::random::<u16>();
    dir.push(format!("pact_test_{}", x));
    dir.push(pact.default_file_name());

    let result = write_pact(pact.boxed(), dir.as_path(), PactSpecification::V3, true);

    let pact_file = read_pact_file(dir.as_path().to_str().unwrap()).unwrap_or("".to_string());
    fs::remove_dir_all(dir.parent().unwrap()).unwrap_or(());

    expect!(result).to(be_ok());
    expect!(pact_file).to(be_equal_to(format!(r#"{{
  "consumer": {{
    "name": "write_pact_test_consumer"
  }},
  "interactions": [
    {{
      "description": "Test Interaction with generators",
      "providerStates": [
        {{
          "name": "Good state to be in"
        }}
      ],
      "request": {{
        "generators": {{
          "body": {{
            "$": {{
              "max": 10,
              "min": 1,
              "type": "RandomInt"
            }}
          }},
          "header": {{
            "A": {{
              "size": 20,
              "type": "RandomString"
            }}
          }}
        }},
        "method": "GET",
        "path": "/"
      }},
      "response": {{
        "status": 200
      }}
    }}
  ],
  "metadata": {{
    "pactRust": {{
      "models": "{}"
    }},
    "pactSpecification": {{
      "version": "3.0.0"
    }}
  }},
  "provider": {{
    "name": "write_pact_test_provider"
  }}
}}"#, PACT_RUST_VERSION.unwrap())));
  }

  #[test]
  fn merge_pact_test() {
    let pact = RequestResponsePact {
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction with matcher".to_string(),
          request: Request {
            body: OptionalBody::Present(json!({ "related": [1, 2, 3] }).to_string().into(), Some(JSON.clone()), None),
            matching_rules: matchingrules!{
            "body" => {
              "$.related" => [ MatchingRule::MinMaxType(0, 5) ]
            }
          },
            .. Request::default()
          },
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let updated_pact = RequestResponsePact {
      interactions: vec![
        RequestResponseInteraction {
          description: "Test Interaction with matcher".to_string(),
          request: Request {
            body: OptionalBody::Present(json!({ "related": [1, 2, 3] }).to_string().into(), Some(JSON.clone()), None),
            matching_rules: matchingrules!{
            "body" => {
              "$.related" => [ MatchingRule::MinMaxType(1, 10) ]
            }
          },
            .. Request::default()
          },
          .. RequestResponseInteraction::default()
        }
      ],
      .. RequestResponsePact::default() };
    let merged_pact = pact.merge(&updated_pact);
    expect(merged_pact.unwrap().as_request_response_pact().unwrap()).to(be_equal_to(updated_pact));
  }
}