1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
use std::collections::HashMap;
use futures::stream::*;
use itertools::Itertools;
use log::*;
use maplit::*;
use pact_models::http_utils::HttpAuth;
use pact_models::pact::{load_pact_from_json, Pact};
use pact_models::PACT_RUST_VERSION;
use regex::{Captures, Regex};
use reqwest::{Method, RequestBuilder};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use serde_with::skip_serializing_none;
use tokio::time::{Duration, sleep};
use pact_matching::Mismatch;
use crate::MismatchResult;
use super::provider_client::join_paths;
fn is_true(object: &serde_json::Map<String, serde_json::Value>, field: &str) -> bool {
match object.get(field) {
Some(json) => match *json {
serde_json::Value::Bool(b) => b,
_ => false
},
None => false
}
}
fn as_string(json: &serde_json::Value) -> String {
match *json {
serde_json::Value::String(ref s) => s.clone(),
_ => format!("{}", json)
}
}
fn content_type(response: &reqwest::Response) -> String {
match response.headers().get("content-type") {
Some(value) => value.to_str().unwrap_or("text/plain").into(),
None => "text/plain".to_string()
}
}
fn json_content_type(response: &reqwest::Response) -> bool {
match content_type(response).parse::<mime::Mime>() {
Ok(mime) => {
match (mime.type_().as_str(), mime.subtype().as_str(), mime.suffix()) {
("application", "json", None) => true,
("application", "hal", Some(mime::JSON)) => true,
_ => false
}
}
Err(_) => false
}
}
fn find_entry(map: &serde_json::Map<String, serde_json::Value>, key: &str) -> Option<(String, serde_json::Value)> {
match map.keys().find(|k| k.to_lowercase() == key.to_lowercase() ) {
Some(k) => map.get(k).map(|v| (key.to_string(), v.clone()) ),
None => None
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum PactBrokerError {
#[error("Error with a HAL link - {0}")]
LinkError(String),
#[error("Error with the content of a HAL resource - {0}")]
ContentError(String),
#[error("IO Error - {0}")]
IoError(String),
#[error("Link/Resource was not found - {0}")]
NotFound(String),
#[error("Invalid URL - {0}")]
UrlError(String)
}
impl PartialEq<String> for PactBrokerError {
fn eq(&self, other: &String) -> bool {
let message = match *self {
PactBrokerError::LinkError(ref s) => s.clone(),
PactBrokerError::ContentError(ref s) => s.clone(),
PactBrokerError::IoError(ref s) => s.clone(),
PactBrokerError::NotFound(ref s) => s.clone(),
PactBrokerError::UrlError(ref s) => s.clone()
};
message == *other
}
}
impl <'a> PartialEq<&'a str> for PactBrokerError {
fn eq(&self, other: &&str) -> bool {
let message = match *self {
PactBrokerError::LinkError(ref s) => s.clone(),
PactBrokerError::ContentError(ref s) => s.clone(),
PactBrokerError::IoError(ref s) => s.clone(),
PactBrokerError::NotFound(ref s) => s.clone(),
PactBrokerError::UrlError(ref s) => s.clone()
};
message.as_str() == *other
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Link {
pub name: String,
pub href: Option<String>,
pub templated: bool,
pub title: Option<String>
}
impl Link {
pub fn from_json(link: &str, link_data: &serde_json::Map<String, serde_json::Value>) -> Link {
Link {
name: link.to_string(),
href: find_entry(link_data, &"href".to_string())
.map(|(_, href)| as_string(&href)),
templated: is_true(link_data, "templated"),
title: link_data.get("title").map(|title| as_string(title))
}
}
pub fn as_json(&self) -> serde_json::Value {
match (self.href.clone(), self.title.clone()) {
(Some(href), Some(title)) => json!({
"href": href,
"title": title,
"templated": self.templated
}),
(Some(href), None) => json!({
"href": href,
"templated": self.templated
}),
(None, Some(title)) => json!({
"title": title,
"templated": self.templated
}),
(None, None) => json!({
"templated": self.templated
})
}
}
}
impl Default for Link {
fn default() -> Self {
Link {
name: "link".to_string(),
href: None,
templated: false,
title: None
}
}
}
#[derive(Clone)]
pub struct HALClient {
client: reqwest::Client,
url: String,
path_info: Option<serde_json::Value>,
auth: Option<HttpAuth>,
retries: u8
}
impl HALClient {
pub fn with_url(url: &str, auth: Option<HttpAuth>) -> HALClient {
HALClient { url: url.to_string(), auth, ..HALClient::default() }
}
fn update_path_info(self, path_info: serde_json::Value) -> HALClient {
HALClient {
client: self.client.clone(),
url: self.url.clone(),
path_info: Some(path_info),
auth: self.auth,
retries: self.retries
}
}
pub async fn navigate(
self,
link: &'static str,
template_values: &HashMap<String, String>
) -> Result<HALClient, PactBrokerError> {
trace!("navigate(link='{}', template_values={:?})", link, template_values);
let client = if self.path_info.is_none() {
let path_info = self.clone().fetch("/".into()).await?;
self.update_path_info(path_info)
} else {
self
};
let path_info = client.clone().fetch_link(link, template_values).await?;
let client = client.update_path_info(path_info);
Ok(client)
}
fn find_link(&self, link: &'static str) -> Result<Link, PactBrokerError> {
match self.path_info {
None => Err(PactBrokerError::LinkError(format!("No previous resource has been fetched from the pact broker. URL: '{}', LINK: '{}'",
self.url, link))),
Some(ref json) => match json.get("_links") {
Some(json) => match json.get(link) {
Some(link_data) => link_data.as_object()
.map(|link_data| Link::from_json(&link.to_string(), &link_data))
.ok_or_else(|| PactBrokerError::LinkError(format!("Link is malformed, expected an object but got {}. URL: '{}', LINK: '{}'",
link_data, self.url, link))),
None => Err(PactBrokerError::LinkError(format!("Link '{}' was not found in the response, only the following links where found: {:?}. URL: '{}', LINK: '{}'",
link, json.as_object().unwrap_or(&json!({}).as_object().unwrap()).keys().join(", "), self.url, link)))
},
None => Err(PactBrokerError::LinkError(format!("Expected a HAL+JSON response from the pact broker, but got a response with no '_links'. URL: '{}', LINK: '{}'",
self.url, link)))
}
}
}
async fn fetch_link(
self,
link: &'static str,
template_values: &HashMap<String, String>
) -> Result<serde_json::Value, PactBrokerError> {
trace!("fetch_link(link='{}', template_values={:?})", link, template_values);
let link_data = self.find_link(link)?;
self.fetch_url(&link_data, template_values).await
}
pub async fn fetch_url(
self,
link: &Link,
template_values: &HashMap<String, String>
) -> Result<serde_json::Value, PactBrokerError> {
trace!("fetch_url(link={:?}, template_values={:?})", link, template_values);
let link_url = if link.templated {
log::debug!("Link URL is templated");
self.clone().parse_link_url(&link, &template_values)
} else {
link.href.clone()
.ok_or_else(|| PactBrokerError::LinkError(
format!("Link is malformed, there is no href. URL: '{}', LINK: '{}'",
self.url, link.name
)
))
}?;
let base_url = self.url.parse::<reqwest::Url>()
.map_err(|err| PactBrokerError::UrlError(format!("{}", err)))?;
let joined_url = base_url.join(&link_url)
.map_err(|err| PactBrokerError::UrlError(format!("{}", err)))?;
self.fetch(joined_url.path().into()).await
}
async fn fetch(self, path: &str) -> Result<serde_json::Value, PactBrokerError> {
info!("Fetching path '{}' from pact broker", path);
let url = join_paths(&self.url, path).parse::<reqwest::Url>()
.map_err(|err| PactBrokerError::UrlError(format!("{}", err)))?;
let request_builder = match self.auth {
Some(ref auth) => match auth {
HttpAuth::User(username, password) => self.client.get(url).basic_auth(username, password.clone()),
HttpAuth::Token(token) => self.client.get(url).bearer_auth(token),
_ => self.client.get(url)
},
None => self.client.get(url)
}.header("accept", "application/hal+json, application/json");
let response = with_retries(self.retries, request_builder).await
.map_err(|err| {
PactBrokerError::IoError(format!("Failed to access pact broker path '{}' - {}. URL: '{}'",
&path,
err,
&self.url,
))
})?;
self.parse_broker_response(path.to_string(), response)
.await
}
async fn parse_broker_response(
&self,
path: String,
response: reqwest::Response,
) -> Result<serde_json::Value, PactBrokerError> {
let is_json_content_type = json_content_type(&response);
let content_type = content_type(&response);
if response.status().is_success() {
let body = response.bytes()
.await
.map_err(|_| PactBrokerError::IoError(
format!("Failed to download response body for path '{}'. URL: '{}'", &path, self.url)
))?;
if is_json_content_type {
serde_json::from_slice(&body)
.map_err(|err| PactBrokerError::ContentError(
format!("Did not get a valid HAL response body from pact broker path '{}' - {}. URL: '{}'",
path, err, self.url)
))
} else {
Err(PactBrokerError::ContentError(
format!("Did not get a HAL response from pact broker path '{}', content type is '{}'. URL: '{}'",
path, content_type, self.url
)
))
}
} else if response.status() == reqwest::StatusCode::NOT_FOUND {
Err(PactBrokerError::NotFound(
format!("Request to pact broker path '{}' failed: {}. URL: '{}'", path,
response.status(), self.url
)
))
} else {
Err(PactBrokerError::IoError(
format!("Request to pact broker path '{}' failed: {}. URL: '{}'", path,
response.status(), self.url
)
))
}
}
fn parse_link_url(self, link: &Link, values: &HashMap<String, String>) -> Result<String, PactBrokerError> {
match link.href {
Some(ref href) => {
debug!("templated URL = {}", href);
let re = Regex::new(r"\{(\w+)}").unwrap();
let final_url = re.replace_all(href, |caps: &Captures| {
let lookup = caps.get(1).unwrap().as_str();
trace!("Looking up value for key '{}'", lookup);
match values.get(lookup) {
Some(val) => urlencoding::encode(val.as_str()).to_string(),
None => {
warn!("No value was found for key '{}', mapped values are {:?}", lookup, values);
format!("{{{}}}", lookup)
}
}
});
debug!("final URL = {}", final_url);
Ok(final_url.to_string())
},
None => Err(PactBrokerError::LinkError(
format!("Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', LINK: '{}'",
self.url, link.name)))
}
}
pub fn iter_links(&self, link: &str) -> Result<Vec<Link>, PactBrokerError> {
match self.path_info {
None => Err(PactBrokerError::LinkError(format!("No previous resource has been fetched from the pact broker. URL: '{}', LINK: '{}'",
self.url, link))),
Some(ref json) => match json.get("_links") {
Some(json) => match json.get(&link) {
Some(link_data) => link_data.as_array()
.map(|link_data| link_data.iter().map(|link_json| match link_json {
Value::Object(data) => Link::from_json(&link, data),
Value::String(s) => Link { name: link.to_string(), href: Some(s.clone()), templated: false, title: None },
_ => Link { name: link.to_string(), href: Some(link_json.to_string()), templated: false, title: None }
}).collect())
.ok_or_else(|| PactBrokerError::LinkError(format!("Link is malformed, expected an object but got {}. URL: '{}', LINK: '{}'",
link_data, self.url, link))),
None => Err(PactBrokerError::LinkError(format!("Link '{}' was not found in the response, only the following links where found: {:?}. URL: '{}', LINK: '{}'",
link, json.as_object().unwrap_or(&json!({}).as_object().unwrap()).keys().join(", "), self.url, link)))
},
None => Err(PactBrokerError::LinkError(format!("Expected a HAL+JSON response from the pact broker, but got a response with no '_links'. URL: '{}', LINK: '{}'",
self.url, link)))
}
}
}
async fn post_json(&self, url: &str, body: &str) -> Result<serde_json::Value, PactBrokerError> {
trace!("post_json(url='{}', body='{}')", url, body);
self.send_document(url, body, Method::POST).await
}
async fn put_json(&self, url: &str, body: &str) -> Result<serde_json::Value, PactBrokerError> {
trace!("put_json(url='{}', body='{}')", url, body);
self.send_document(url, body, Method::PUT).await
}
async fn send_document(&self, url: &str, body: &str, method: Method) -> Result<serde_json::Value, PactBrokerError> {
debug!("Sending JSON to {} using {}: {}", url, method, body);
let url = url.parse::<reqwest::Url>()
.map_err(|err| PactBrokerError::UrlError(format!("{}", err)))?;
let base_url = self.url.parse::<reqwest::Url>()
.map_err(|err| PactBrokerError::UrlError(format!("{}", err)))?;
let url = base_url.join(&url.path())
.map_err(|err| PactBrokerError::UrlError(format!("{}", err)))?;
let request_builder = match self.auth {
Some(ref auth) => match auth {
HttpAuth::User(username, password) => self.client
.request(method, url.clone())
.basic_auth(username, password.clone()),
HttpAuth::Token(token) => self.client
.request(method, url.clone())
.bearer_auth(token),
_ => self.client.request(method, url.clone())
},
None => self.client.request(method, url.clone())
}
.header("Content-Type", "application/json")
.header("Accept", "application/hal+json")
.header("Accept", "application/json")
.body(body.to_string());
let response = with_retries(self.retries, request_builder)
.await
.map_err(|err| PactBrokerError::IoError(
format!("Failed to send JSON to the pact broker URL '{}' - {}", url, err)
))?
.error_for_status()
.map_err(|err| PactBrokerError::ContentError(
format!("Request to pact broker URL '{}' failed - {}", url, err)
));
match response {
Ok(res) => {
let res = self.parse_broker_response(url.path().to_string(), res).await;
Ok(res.unwrap_or_default())
},
Err(err) => Err(err)
}
}
fn with_doc_context(self, doc_attributes: &[Link]) -> Result<HALClient, PactBrokerError> {
let links: serde_json::Map<String, serde_json::Value> = doc_attributes.iter()
.map(|link| (link.name.clone(), link.as_json())).collect();
let links_json = json!({
"_links": json!(links)
});
Ok(self.update_path_info(links_json))
}
}
async fn with_retries(retries: u8, request: RequestBuilder) -> Result<reqwest::Response, reqwest::Error> {
match &request.try_clone() {
None => {
warn!("with_retries: Could not retry the request as it is not cloneable");
request.send().await
}
Some(rb) => {
futures::stream::iter((1..=retries).step_by(1))
.fold((None::<Result<reqwest::Response, reqwest::Error>>, rb.try_clone()), |(response, request), attempt| {
async move {
match request {
Some(request_builder) => match response {
None => {
let next = request_builder.try_clone();
(Some(request_builder.send().await), next)
},
Some(response) => {
trace!("with_retries: attempt {}/{} is {:?}", attempt, retries, response);
match response {
Ok(ref res) => if res.status().is_server_error() {
match request_builder.try_clone() {
None => (Some(response), None),
Some(rb) => {
sleep(Duration::from_millis(10_u64.pow(attempt as u32))).await;
(Some(request_builder.send().await), Some(rb))
}
}
} else {
(Some(response), None)
},
Err(ref err) => if err.is_status() {
if err.status().unwrap_or_default().is_server_error() {
match request_builder.try_clone() {
None => (Some(response), None),
Some(rb) => {
sleep(Duration::from_millis(10_u64.pow(attempt as u32))).await;
(Some(request_builder.send().await), Some(rb))
}
}
} else {
(Some(response), None)
}
} else {
(Some(response), None)
}
}
}
}
None => (response, None)
}
}
}).await.0.unwrap()
}
}
}
impl Default for HALClient {
fn default() -> Self {
HALClient {
client: reqwest::ClientBuilder::new()
.build()
.unwrap(),
url: "".to_string(),
path_info: None,
auth: None,
retries: 3
}
}
}
fn links_from_json(json: &serde_json::Value) -> Vec<Link> {
match json.get("_links") {
Some(json) => match *json {
serde_json::Value::Object(ref v) => {
v.iter().map(|(link, json)| match *json {
serde_json::Value::Object(ref attr) => Link::from_json(link, attr),
_ => Link { name: link.clone(), .. Link::default() }
}).collect()
},
_ => vec![]
},
None => vec![]
}
}
pub async fn fetch_pacts_from_broker(
broker_url: &str,
provider_name: &str,
auth: Option<HttpAuth>
) -> anyhow::Result<Vec<anyhow::Result<(Box<dyn Pact + Send + Sync>, Option<PactVerificationContext>, Vec<Link>)>>> {
trace!("fetch_pacts_from_broker(broker_url='{}', provider_name='{}', auth={})", broker_url,
provider_name, auth.clone().unwrap_or_default());
let mut hal_client = HALClient::with_url(broker_url, auth);
let template_values = hashmap!{ "provider".to_string() => provider_name.to_string() };
hal_client = hal_client.navigate("pb:latest-provider-pacts", &template_values)
.await
.map_err(move |err| {
match err {
PactBrokerError::NotFound(_) =>
PactBrokerError::NotFound(
format!("No pacts for provider '{}' where found in the pact broker. URL: '{}'",
provider_name, broker_url)),
_ => err
}
})?;
let pact_links = hal_client.clone().iter_links("pacts")?;
let results: Vec<_> = futures::stream::iter(pact_links)
.map(|ref pact_link| {
match pact_link.href {
Some(_) => Ok((hal_client.clone(), pact_link.clone())),
None => Err(
PactBrokerError::LinkError(
format!(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', LINK: '{:?}'",
&hal_client.url,
pact_link
)
)
)
}
})
.and_then(|(hal_client, pact_link)| async {
let pact_json = hal_client.fetch_url(
&pact_link.clone(),
&template_values.clone()
).await?;
Ok((pact_link, pact_json))
})
.map(|result| {
match result {
Ok((pact_link, pact_json)) => {
let href = pact_link.href.unwrap_or_default();
let links = links_from_json(&pact_json);
load_pact_from_json(href.as_str(), &pact_json)
.map(|pact| (pact, None, links))
},
Err(err) => Err(err.into())
}
})
.into_stream()
.collect()
.await;
Ok(results)
}
pub async fn fetch_pacts_dynamically_from_broker(
broker_url: &str,
provider_name: String,
pending: bool,
include_wip_pacts_since: Option<String>,
provider_tags: Vec<String>,
provider_branch: Option<String>,
consumer_version_selectors: Vec<ConsumerVersionSelector>,
auth: Option<HttpAuth>
) -> Result<Vec<Result<(Box<dyn Pact + Send + Sync>, Option<PactVerificationContext>, Vec<Link>), PactBrokerError>>, PactBrokerError> {
trace!("fetch_pacts_dynamically_from_broker(broker_url='{}', provider_name='{}', pending={}, \
include_wip_pacts_since={:?}, provider_tags: {:?}, consumer_version_selectors: {:?}, auth={})",
broker_url, provider_name, pending, include_wip_pacts_since, provider_tags,
consumer_version_selectors, auth.clone().unwrap_or_default());
let mut hal_client = HALClient::with_url(broker_url, auth);
let template_values = hashmap!{ "provider".to_string() => provider_name.clone() };
hal_client = hal_client.navigate("pb:provider-pacts-for-verification", &template_values)
.await
.map_err(move |err| {
match err {
PactBrokerError::NotFound(_) =>
PactBrokerError::NotFound(
format!("No pacts for provider '{}' were found in the pact broker. URL: '{}'",
provider_name.clone(), broker_url)),
_ => err
}
})?;
let pacts_for_verification = PactsForVerificationRequest {
provider_version_tags: provider_tags,
provider_version_branch: provider_branch,
include_wip_pacts_since,
consumer_version_selectors,
include_pending_status: pending,
};
let request_body = serde_json::to_string(&pacts_for_verification).unwrap();
let response = match hal_client.find_link("self") {
Ok(link) => {
let link = hal_client.clone().parse_link_url(&link, &hashmap!{})?;
match hal_client.clone().post_json(link.as_str(), request_body.as_str()).await {
Ok(res) => Some(res),
Err(err) => {
debug!("error Response for pacts for verification {:?} ", err);
return Err(err)
}
}
},
Err(e) => return Err(e)
};
let pact_links = match response {
Some(v) => {
let pfv: PactsForVerificationResponse = serde_json::from_value(v)
.unwrap_or(PactsForVerificationResponse { embedded: PactsForVerificationBody { pacts: vec!() } });
if pfv.embedded.pacts.len() == 0 {
return Err(PactBrokerError::NotFound(format!("No pacts were found for this provider")))
};
let links: Result<Vec<(Link, PactVerificationContext)>, PactBrokerError> = pfv.embedded.pacts.iter().map(| p| {
match p.links.get("self") {
Some(l) => Ok((l.clone(), PactVerificationContext{
short_description: p.short_description.clone(),
verification_properties: PactVerificationProperties {
pending: p.verification_properties.pending,
notices: p.verification_properties.notices.clone(),
}
})),
None => Err(
PactBrokerError::LinkError(
format!(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', PATH: '{:?}'",
&hal_client.url,
&p.links,
)
)
)
}
}).collect();
links
},
None => Err(PactBrokerError::NotFound(format!("No pacts were found for this provider")))
}?;
let results: Vec<_> = futures::stream::iter(pact_links)
.map(|(ref pact_link, ref context)| {
match pact_link.href {
Some(_) => Ok((hal_client.clone(), pact_link.clone(), context.clone())),
None => Err(
PactBrokerError::LinkError(
format!(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '{}', LINK: '{:?}'",
&hal_client.url,
pact_link
)
)
)
}
})
.and_then(|(hal_client, pact_link, context)| async {
let pact_json = hal_client.fetch_url(
&pact_link.clone(),
&template_values.clone()
).await?;
Ok((pact_link, pact_json, context))
})
.map(|result| {
match result {
Ok((pact_link, pact_json, context)) => {
let href = pact_link.href.unwrap_or_default();
let links = links_from_json(&pact_json);
load_pact_from_json(href.as_str(), &pact_json)
.map(|pact| (pact, Some(context), links))
.map_err(|err| PactBrokerError::ContentError(format!("{}", err)))
},
Err(err) => Err(err)
}
})
.into_stream()
.collect()
.await;
Ok(results)
}
pub enum TestResult {
Ok(Vec<Option<String>>),
Failed(Vec<(Option<String>, Option<MismatchResult>)>)
}
impl TestResult {
pub fn to_bool(&self) -> bool {
match self {
TestResult::Ok(_) => true,
_ => false
}
}
}
pub async fn publish_verification_results(
links: Vec<Link>,
broker_url: &str,
auth: Option<HttpAuth>,
result: TestResult,
version: String,
build_url: Option<String>,
provider_tags: Vec<String>,
branch: Option<String>
) -> Result<serde_json::Value, PactBrokerError> {
let hal_client = HALClient::with_url(broker_url, auth.clone());
if branch.is_some() {
publish_provider_branch(&hal_client, &links, &branch.unwrap(), &version).await?;
}
if !provider_tags.is_empty() {
publish_provider_tags(&hal_client, &links, provider_tags, &version).await?;
}
let publish_link = links
.iter()
.cloned()
.find(|item| item.name.to_ascii_lowercase() == "pb:publish-verification-results")
.ok_or_else(|| PactBrokerError::LinkError(
"Response from the pact broker has no 'pb:publish-verification-results' link".into()
))?;
let json = build_payload(result, version, build_url);
hal_client.post_json(publish_link.href.unwrap_or_default().as_str(), json.to_string().as_str()).await
}
fn build_payload(result: TestResult, version: String, build_url: Option<String>) -> serde_json::Value {
let mut json = json!({
"success": result.to_bool(),
"providerApplicationVersion": version,
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
});
let json_obj = json.as_object_mut().unwrap();
if build_url.is_some() {
json_obj.insert("buildUrl".into(), json!(build_url.unwrap()));
}
match result {
TestResult::Failed(mismatches) => {
let values = mismatches.iter()
.group_by(|(id, _)| id.clone().unwrap_or_default())
.into_iter()
.map(|(key, mismatches)| {
let acc: (Vec<serde_json::Value>, Vec<serde_json::Value>) = (vec![], vec![]);
let values = mismatches.fold(acc, |mut acc, (_, result)| {
if let Some(mismatch) = result {
match mismatch {
MismatchResult::Mismatches { mismatches, .. } => {
for mismatch in mismatches {
match mismatch {
Mismatch::MethodMismatch { expected, actual } => acc.0.push(json!({
"attribute": "method",
"description": format!("Expected method of {} but received {}", expected, actual)
})),
Mismatch::PathMismatch { mismatch, .. } => acc.0.push(json!({
"attribute": "path",
"description": mismatch
})),
Mismatch::StatusMismatch { mismatch, .. } => acc.0.push(json!({
"attribute": "status",
"description": mismatch
})),
Mismatch::QueryMismatch { parameter, mismatch, .. } => acc.0.push(json!({
"attribute": "query",
"identifier": parameter,
"description": mismatch
})),
Mismatch::HeaderMismatch { key, mismatch, .. } => acc.0.push(json!({
"attribute": "header",
"identifier": key,
"description": mismatch
})),
Mismatch::BodyTypeMismatch { expected, actual, .. } => acc.0.push(json!({
"attribute": "body",
"identifier": "$",
"description": format!("Expected body type of '{}' but received '{}'", expected, actual)
})),
Mismatch::BodyMismatch { path, mismatch, .. } => acc.0.push(json!({
"attribute": "body",
"identifier": path,
"description": mismatch
})),
Mismatch::MetadataMismatch { key, mismatch, .. } => acc.0.push(json!({
"attribute": "metadata",
"identifier": key,
"description": mismatch
}))
}
}
},
MismatchResult::Error(err, _) => acc.1.push(json!({ "message": err }))
};
};
acc
});
let mut json = json!({
"interactionId": key,
"success": values.0.is_empty() && values.1.is_empty()
});
if !values.0.is_empty() {
json.as_object_mut().unwrap().insert("mismatches".into(), json!(values.0));
}
if !values.1.is_empty() {
json.as_object_mut().unwrap().insert("exceptions".into(), json!(values.1));
}
json
}).collect::<Vec<serde_json::Value>>();
json_obj.insert("testResults".into(), serde_json::Value::Array(values));
}
TestResult::Ok(ids) => {
let values = ids.iter().filter(|id| id.is_some())
.map(|id| json!({
"interactionId": id.clone().unwrap_or_default(),
"success": true
})).collect();
json_obj.insert("testResults".into(), serde_json::Value::Array(values));
}
}
json
}
async fn publish_provider_tags(
hal_client: &HALClient,
links: &[Link],
provider_tags: Vec<String>,
version: &str) -> Result<(), PactBrokerError> {
let hal_client = hal_client.clone().with_doc_context(links)?
.navigate("pb:provider", &hashmap!{}).await?;
match hal_client.find_link("pb:version-tag") {
Ok(link) => {
for tag in &provider_tags {
let template_values = hashmap! {
"version".to_string() => version.to_string(),
"tag".to_string() => tag.clone()
};
match hal_client.clone().put_json(hal_client.clone().parse_link_url(&link, &template_values)?.as_str(), "{}").await {
Ok(_) => debug!("Pushed tag {} for provider version {}", tag, version),
Err(err) => {
error!("Failed to push tag {} for provider version {}", tag, version);
return Err(err);
}
}
};
Ok(())
},
Err(_) => Err(PactBrokerError::LinkError("Can't publish provider tags as there is no 'pb:version-tag' link".to_string()))
}
}
async fn publish_provider_branch(
hal_client: &HALClient,
links: &[Link],
branch: &str,
version: &str) -> Result<(), PactBrokerError> {
let hal_client = hal_client.clone().with_doc_context(links)?
.navigate("pb:provider", &hashmap!{}).await?;
match hal_client.find_link("pb:branch-version") {
Ok(link) => {
let template_values = hashmap! {
"branch".to_string() => branch.to_string(),
"version".to_string() => version.to_string(),
};
match hal_client.clone().put_json(hal_client.clone().parse_link_url(&link, &template_values)?.as_str(), "{}").await {
Ok(_) => debug!("Pushed branch {} for provider version {}", branch, version),
Err(err) => {
error!("Failed to push branch {} for provider version {}", branch, version);
return Err(err);
}
}
Ok(())
},
Err(_) => Err(PactBrokerError::LinkError("Can't publish provider branch as there is no 'pb:branch-version' link. Please ugrade to Pact Broker version 2.86.0 or later for branch support".to_string()))
}
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ConsumerVersionSelector {
pub consumer: Option<String>,
pub tag: Option<String>,
pub fallback_tag: Option<String>,
pub latest: Option<bool>,
pub deployed_or_released: Option<bool>,
pub deployed: Option<bool>,
pub released: Option<bool>,
pub environment: Option<String>,
pub main_branch: Option<bool>,
pub branch: Option<String>,
pub matching_branch: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
struct PactsForVerificationResponse {
#[serde(rename(deserialize = "_embedded"))]
pub embedded: PactsForVerificationBody
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
struct PactsForVerificationBody {
pub pacts: Vec<PactForVerification>
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
struct PactForVerification {
pub short_description: String,
#[serde(rename(deserialize = "_links"))]
pub links: HashMap<String, Link>,
pub verification_properties: PactVerificationProperties,
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PactsForVerificationRequest {
pub provider_version_tags: Vec<String>,
pub include_pending_status: bool,
pub include_wip_pacts_since: Option<String>,
pub consumer_version_selectors: Vec<ConsumerVersionSelector>,
pub provider_version_branch: Option<String>
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PactVerificationContext {
pub short_description: String,
pub verification_properties: PactVerificationProperties,
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PactVerificationProperties {
#[serde(default)]
pub pending: bool,
pub notices: Vec<HashMap<String, String>>,
}
#[cfg(test)]
mod tests {
use env_logger::*;
use expectest::expect;
use expectest::prelude::*;
use pact_models::{Consumer, PactSpecification, Provider};
use pact_models::prelude::RequestResponsePact;
use pact_models::sync_interaction::RequestResponseInteraction;
use pact_consumer::*;
use pact_consumer::prelude::*;
use pact_matching::Mismatch::MethodMismatch;
use super::*;
use super::{content_type, json_content_type};
#[tokio::test]
async fn fetch_returns_an_error_if_there_is_no_pact_broker() {
let client = HALClient::with_url("http://idont.exist:6666", None);
expect!(client.fetch("/").await).to(be_err());
}
#[tokio::test]
async fn fetch_returns_an_error_if_it_does_not_get_a_success_response() {
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBroker")
.interaction("a request to a non-existant path", "", |mut i| {
i.given("the pact broker has a valid pact");
i.request.path("/hello");
i.response.status(404);
futures::future::ready(i)
})
.await
.start_mock_server();
let client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.fetch("/hello").await;
expect!(result).to(be_err().value(format!("Request to pact broker path \'/hello\' failed: 404 Not Found. URL: '{}'",
pact_broker.url())));
}
#[tokio::test]
async fn fetch_returns_an_error_if_it_does_not_get_a_hal_response() {
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a non-json resource", "", |mut i| {
i.request.path("/nonjson");
i.response
.header("Content-Type", "text/html")
.body("<html></html>");
futures::future::ready(i)
})
.await
.start_mock_server();
let client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.fetch("/nonjson").await;
expect!(result).to(be_err().value(format!("Did not get a HAL response from pact broker path \'/nonjson\', content type is 'text/html'. URL: '{}'",
pact_broker.url())));
}
#[test]
fn content_type_test() {
let response = reqwest::Response::from(
http::response::Builder::new()
.header("content-type", "application/hal+json; charset=utf-8")
.body("null")
.unwrap()
);
expect!(content_type(&response)).to(be_equal_to("application/hal+json; charset=utf-8".to_string()));
}
#[test]
fn json_content_type_test() {
let response = reqwest::Response::from(
http::response::Builder::new()
.header("content-type", "application/json")
.body("null")
.unwrap()
);
expect!(json_content_type(&response)).to(be_true());
}
#[test]
fn json_content_type_utf8_test() {
let response = reqwest::Response::from(
http::response::Builder::new()
.header("content-type", "application/hal+json;charset=utf-8")
.body("null")
.unwrap()
);
expect!(json_content_type(&response)).to(be_true());
}
#[tokio::test]
async fn fetch_returns_an_error_if_it_does_not_get_a_valid_hal_response() {
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a non-hal resource", "", |mut i| {
i.request.path("/nonhal");
i.response.header("Content-Type", "application/hal+json");
futures::future::ready(i)
})
.await
.interaction("a request to a non-hal resource 2", "", |mut i| {
i.request.path("/nonhal2");
i.response
.header("Content-Type", "application/hal+json")
.body("<html>This is not JSON</html>");
futures::future::ready(i)
})
.await
.start_mock_server();
let client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/nonhal").await;
expect!(result).to(be_err().value(format!("Did not get a valid HAL response body from pact broker path \'/nonhal\' - EOF while parsing a value at line 1 column 0. URL: '{}'",
pact_broker.url())));
let result = client.clone().fetch("/nonhal2").await;
expect!(result).to(be_err().value(format!("Did not get a valid HAL response body from pact broker path \'/nonhal2\' - expected value at line 1 column 1. URL: '{}'",
pact_broker.url())));
}
#[tokio::test]
async fn fetch_retries_the_request_on_50x_errors() {
let _ = env_logger::try_init();
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a hal resource", "", |mut i| async move {
i.given("server returns a gateway error");
i.request.path("/");
i.response.status(503);
i
})
.await
.start_mock_server();
let client = HALClient::with_url(pact_broker.url().as_str(), None);
let expected_requests = client.retries as usize;
let result = client.fetch("/").await;
expect!(result).to(be_err());
expect!(pact_broker.metrics().requests).to(be_equal_to(expected_requests ));
}
#[tokio::test]
async fn post_json_retries_the_request_on_50x_errors() {
let _ = env_logger::try_init();
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a POST request", "", |mut i| async move {
i.given("server returns a gateway error");
i.request.path("/").method("POST");
i.response.status(503);
i
})
.await
.start_mock_server();
let client = HALClient::with_url(pact_broker.url().as_str(), None);
let expected_requests = client.retries as usize;
let result = client.post_json(pact_broker.url().as_str(), "{}").await;
expect!(result.clone()).to(be_err());
expect!(pact_broker.metrics().requests).to(be_equal_to(expected_requests ));
}
#[tokio::test]
async fn put_json_retries_the_request_on_50x_errors() {
let _ = env_logger::try_init();
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a PUT request", "", |mut i| async move {
i.given("server returns a gateway error");
i.request.path("/").method("PUT");
i.response.status(503);
i
})
.await
.start_mock_server();
let client = HALClient::with_url(pact_broker.url().as_str(), None);
let expected_requests = client.retries as usize;
let result = client.put_json(pact_broker.url().as_str(), "{}").await;
expect!(result.clone()).to(be_err());
expect!(pact_broker.metrics().requests).to(be_equal_to(expected_requests ));
}
#[test]
fn parse_link_url_returns_error_if_there_is_no_href() {
let client = HALClient::default();
let link = Link { name: "link".to_string(), href: None, templated: false, title: None };
expect!(client.parse_link_url(&link, &hashmap!{})).to(be_err().value(
"Expected a HAL+JSON response from the pact broker, but got a link with no HREF. URL: '', LINK: 'link'"));
}
#[test]
fn parse_link_url_replaces_all_tokens_in_href() {
let client = HALClient::default();
let values = hashmap!{ "valA".to_string() => "A".to_string(), "valB".to_string() => "B".to_string() };
let link = Link { name: "link".to_string(), href: Some("http://localhost".to_string()), templated: false, title: None };
expect!(client.clone().parse_link_url(&link, &values)).to(be_ok().value("http://localhost"));
let link = Link { name: "link".to_string(), href: Some("http://{valA}/{valB}".to_string()), templated: false, title: None };
expect!(client.clone().parse_link_url(&link, &values)).to(be_ok().value("http://A/B"));
let link = Link { name: "link".to_string(), href: Some("http://{valA}/{valC}".to_string()), templated: false, title: None };
expect!(client.clone().parse_link_url(&link, &values)).to(be_ok().value("http://A/{valC}"));
}
#[test]
fn parse_link_url_encodes_the_tokens_in_href() {
let client = HALClient::default();
let values = hashmap!{ "valA".to_string() => "A".to_string(), "valB".to_string() => "B/C".to_string() };
let link = Link { name: "link".to_string(), href: Some("http://{valA}/{valB}".to_string()), templated: false, title: None };
expect!(client.clone().parse_link_url(&link, &values)).to(be_ok().value("http://A/B%2FC"));
}
#[tokio::test]
async fn fetch_link_returns_an_error_if_a_previous_resource_has_not_been_fetched() {
let client = HALClient::with_url("http://localhost", None);
let result = client.fetch_link("anything_will_do", &hashmap!{}).await;
expect!(result).to(be_err().value("No previous resource has been fetched from the pact broker. URL: 'http://localhost', LINK: 'anything_will_do'".to_string()));
}
#[tokio::test]
async fn fetch_link_returns_an_error_if_the_previous_resource_was_not_hal() {
try_init().unwrap_or(());
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a non-hal json resource", "", |mut i| async move {
i.request.path("/");
i.response
.header("Content-Type", "application/hal+json")
.body("{}");
i
})
.await
.start_mock_server();
let mut client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/").await;
expect!(result.clone()).to(be_ok());
client.path_info = result.ok();
let result = client.clone().fetch_link("hal2", &hashmap!{}).await;
expect!(result).to(be_err().value(format!("Expected a HAL+JSON response from the pact broker, but got a response with no '_links'. URL: '{}', LINK: 'hal2'",
pact_broker.url())));
}
#[tokio::test]
async fn fetch_link_returns_an_error_if_the_previous_resource_links_are_not_correctly_formed() {
try_init().unwrap_or(());
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a hal resource with invalid links", "", |mut i| async move {
i.request.path("/");
i.response
.header("Content-Type", "application/hal+json")
.body("{\"_links\":[{\"next\":{\"href\":\"abc\"}},{\"prev\":{\"href\":\"def\"}}]}");
i
})
.await
.start_mock_server();
let mut client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/").await;
expect!(result.clone()).to(be_ok());
client.path_info = result.ok();
let result = client.clone().fetch_link("any", &hashmap!{}).await;
expect!(result).to(be_err().value(format!("Link 'any' was not found in the response, only the following links where found: \"\". URL: '{}', LINK: 'any'",
pact_broker.url())));
}
#[tokio::test]
async fn fetch_link_returns_an_error_if_the_previous_resource_does_not_have_the_link() {
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a hal resource", "", |mut i| async move {
i.request.path("/");
i.response
.header("Content-Type", "application/hal+json")
.body("{\"_links\":{\"next\":{\"href\":\"/abc\"},\"prev\":{\"href\":\"/def\"}}}");
i
})
.await
.start_mock_server();
let mut client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/").await;
expect!(result.clone()).to(be_ok());
client.path_info = result.ok();
let result = client.clone().fetch_link("any", &hashmap!{}).await;
expect!(result).to(be_err().value(format!("Link 'any' was not found in the response, only the following links where found: \"next, prev\". URL: '{}', LINK: 'any'",
pact_broker.url())));
}
#[tokio::test]
async fn fetch_link_returns_the_resource_for_the_link() {
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a hal resource", "", |mut i| async move {
i.request.path("/");
i.response
.header("Content-Type", "application/hal+json")
.body("{\"_links\":{\"next\":{\"href\":\"/abc\"},\"prev\":{\"href\":\"/def\"}}}");
i
})
.await
.interaction("a request to next", "", |mut i| async move {
i.request.path("/abc");
i.response
.header("Content-Type", "application/json")
.json_body(json_pattern!("Yay! You found your way here"));
i
})
.await
.start_mock_server();
let mut client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/").await;
expect!(result.clone()).to(be_ok());
client.path_info = result.ok();
let result = client.clone().fetch_link("next", &hashmap!{}).await;
expect!(result).to(be_ok().value(serde_json::Value::String("Yay! You found your way here".to_string())));
}
#[tokio::test]
async fn fetch_link_returns_handles_absolute_resource_links() {
try_init().unwrap_or(());
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a hal resource with absolute paths", "", |mut i| async move {
i.request.path("/");
i.response
.header("Content-Type", "application/hal+json")
.body("{\"_links\":{\"next\":{\"href\":\"http://localhost/abc\"},\"prev\":{\"href\":\"http://localhost/def\"}}}");
i
})
.await
.interaction("a request to next", "", |mut i| async move {
i.request.path("/abc");
i.response
.header("Content-Type", "application/json")
.json_body(json_pattern!("Yay! You found your way here"));
i
})
.await
.start_mock_server();
let mut client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/").await;
expect!(result.clone()).to(be_ok());
client.path_info = result.ok();
let result = client.clone().fetch_link("next", &hashmap!{}).await;
expect!(result).to(be_ok().value(serde_json::Value::String("Yay! You found your way here".to_string())));
}
#[tokio::test]
async fn fetch_link_returns_the_resource_for_the_templated_link() {
try_init().unwrap_or(());
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBrokerStub")
.interaction("a request to a templated hal resource", "", |mut i| async move {
i.request.path("/");
i.response
.header("Content-Type", "application/hal+json")
.body("{\"_links\":{\"document\":{\"href\":\"/doc/{id}\",\"templated\":true}}}");
i
})
.await
.interaction("a request for a document", "", |mut i| async move {
i.request.path("/doc/abc");
i.response
.header("Content-Type", "application/json")
.json_body(json_pattern!("Yay! You found your way here"));
i
})
.await
.start_mock_server();
let mut client = HALClient::with_url(pact_broker.url().as_str(), None);
let result = client.clone().fetch("/").await;
expect!(result.clone()).to(be_ok());
client.path_info = result.ok();
let result = client.clone().fetch_link("document", &hashmap!{ "id".to_string() => "abc".to_string() }).await;
expect!(result).to(be_ok().value(serde_json::Value::String("Yay! You found your way here".to_string())));
}
#[tokio::test]
async fn fetch_pacts_from_broker_returns_empty_list_if_there_are_no_pacts() {
try_init().unwrap_or(());
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBroker")
.interaction("a request to the pact broker root", "", |mut i| async move {
i.request
.path("/")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"pb:latest-provider-pacts": {
"href": "http://localhost/pacts/provider/{provider}/latest",
"templated": true,
}
}
}));
i
})
.await
.interaction("a request for a providers pacts", "", |mut i| async move {
i.given("There are no pacts in the pact broker");
i.request
.path("/pacts/provider/sad_provider/latest")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response.status(404);
i
})
.await
.start_mock_server();
let result = fetch_pacts_from_broker(pact_broker.url().as_str(),
"sad_provider", None).await;
match result {
Ok(_) => {
panic!("Expected an error result, but got OK");
},
Err(err) => {
println!("err: {}", err);
expect!(err.to_string().starts_with("Link/Resource was not found - No pacts for provider 'sad_provider' where found in the pact broker")).to(be_true());
}
}
}
#[tokio::test]
async fn fetch_pacts_from_broker_returns_a_list_of_pacts() {
try_init().unwrap_or(());
let pact = RequestResponsePact { consumer: Consumer { name: "Consumer".to_string() },
provider: Provider { name: "happy_provider".to_string() },
.. RequestResponsePact::default() }
.to_json(PactSpecification::V3).unwrap().to_string();
let pact2 = RequestResponsePact { consumer: Consumer { name: "Consumer2".to_string() },
provider: Provider { name: "happy_provider".to_string() },
interactions: vec![ RequestResponseInteraction { description: "a request friends".to_string(), .. RequestResponseInteraction::default() } ],
.. RequestResponsePact::default() }
.to_json(PactSpecification::V3).unwrap().to_string();
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBroker")
.interaction("a request to the pact broker root", "", |mut i| async move {
i.request
.path("/")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"pb:latest-provider-pacts": {
"href": "http://localhost/pacts/provider/{provider}/latest",
"templated": true,
}
}
}));
i
})
.await
.interaction("a request for a providers pacts", "", |mut i| async move {
i.given("There are two pacts in the pact broker");
i.request
.path("/pacts/provider/happy_provider/latest")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links":{
"pacts":[
{"href":"http://localhost/pacts/provider/happy_provider/consumer/Consumer/version/1.0.0"},
{"href":"http://localhost/pacts/provider/happy_provider/consumer/Consumer2/version/1.0.0"}
]
}
}));
i
})
.await
.interaction("a request for the first provider pact", "", |mut i| async move {
i.given("There are two pacts in the pact broker");
i.request
.path("/pacts/provider/happy_provider/consumer/Consumer/version/1.0.0")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/json")
.body(pact.clone());
i
})
.await
.interaction("a request for the second provider pact", "", |mut i| async move {
i.given("There are two pacts in the pact broker");
i.request
.path("/pacts/provider/happy_provider/consumer/Consumer2/version/1.0.0")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/json")
.body(pact2.clone());
i
})
.await
.start_mock_server();
let result = fetch_pacts_from_broker(pact_broker.url().as_str(),
"happy_provider", None).await;
match &result {
Ok(_) => (),
Err(err) => panic!("Expected an Ok result, got a error {}", err)
}
let pacts = &result.unwrap();
expect!(pacts.len()).to(be_equal_to(2));
for pact in pacts {
match pact {
Ok(_) => (),
Err(err) => panic!("Expected an Ok result, got a error {}", err)
}
}
}
#[tokio::test]
async fn fetch_pacts_for_verification_from_broker_returns_a_list_of_pacts() {
try_init().unwrap_or(());
let pact = RequestResponsePact { consumer: Consumer { name: "Consumer".to_string() },
provider: Provider { name: "happy_provider".to_string() },
.. RequestResponsePact::default() }
.to_json(PactSpecification::V3).unwrap().to_string();
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBroker")
.interaction("a request to the pact broker root", "", |mut i| async move {
i.given("Pacts for verification is enabled");
i.request
.path("/")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"pb:provider-pacts-for-verification": {
"href": like!("http://localhost/pacts/provider/{provider}/for-verification"),
"title": like!("Pact versions to be verified for the specified provider"),
"templated": like!(true)
}
}
}));
i
})
.await
.interaction("a request to the pacts for verification endpoint", "", |mut i| async move {
i.given("There are pacts to be verified");
i.request
.get()
.path("/pacts/provider/happy_provider/for-verification")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"self": {
"href": like!("http://localhost/pacts/provider/happy_provider/for-verification"),
"title": like!("Pacts to be verified")
}
}
}));
i
})
.await
.interaction("a request to fetch pacts to be verified", "", |mut i| async move {
i.given("There are pacts to be verified");
i.request
.post()
.path("/pacts/provider/happy_provider/for-verification")
.header("Accept", "application/hal+json")
.header("Accept", "application/json")
.json_body(json_pattern!({
"consumerVersionSelectors": each_like!({
"tag": "prod"
}),
"providerVersionTags": each_like!("master"),
"includePendingStatus": like!(false),
"providerVersionBranch": like!("main")
}));
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_embedded": {
"pacts": each_like!({
"shortDescription": "latest prod",
"verificationProperties": {
"pending": false,
"notices": [
{
"when": "before_verification",
"text": "The pact at http://localhost/pacts/provider/happy_provider/consumer/Consumer/pact-version/12345678 is being verified because it matches the following configured selection criterion: latest pact for a consumer version tagged 'prod'"
},
{
"when": "before_verification",
"text": "This pact has previously been successfully verified by a version of happy_provider with tag 'master'. If this verification fails, it will fail the build. Read more at https://pact.io/pending"
}
]
},
"_links": {
"self": {
"href": "http://localhost/pacts/provider/happy_provider/consumer/Consumer/pact-version/12345678",
"name": "Pact between Consumer (239aa5048a7de54fe5f231116c6d603eab0c6fde) and happy_provider"
}
}
})
},
"_links": {
"self": {
"href": like!("http://localhost/pacts/provider/happy_provider/for-verification"),
"title":like!("Pacts to be verified")
}
}
}));
i
})
.await
.interaction("a request for a pact by version", "", |mut i| async move {
i.given("There is a pact with version 12345678");
i.request
.path("/pacts/provider/happy_provider/consumer/Consumer/pact-version/12345678")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/json")
.body(pact.clone());
i
})
.await
.start_mock_server();
let result = fetch_pacts_dynamically_from_broker(pact_broker.url().as_str(), "happy_provider".to_string(), false, None, vec!("master".to_string()), Some("main".to_string()), vec!(ConsumerVersionSelector {
consumer: None,
tag: Some("prod".to_string()),
fallback_tag: None,
latest: None,
branch: None,
deployed_or_released: None,
deployed: None,
released: None,
main_branch: None,
matching_branch: None,
environment: None,
}), None).await;
match &result {
Ok(_) => (),
Err(err) => panic!("Expected an Ok result, got a error {}", err)
}
let pacts = &result.unwrap();
expect!(pacts.len()).to(be_equal_to(1));
for pact in pacts {
match pact {
Ok(_) => (),
Err(err) => panic!("Expected an Ok result, got a error {}", err)
}
}
}
#[tokio::test]
async fn fetch_pacts_for_verification_from_broker_returns_empty_list_if_there_are_no_pacts() {
try_init().unwrap_or(());
let pact_broker = PactBuilder::new("RustPactVerifier", "PactBroker")
.interaction("a request to the pact broker root", "", |mut i| async move {
i.given("Pacts for verification is enabled");
i.request
.path("/")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"pb:provider-pacts-for-verification": {
"href": like!("http://localhost/pacts/provider/{provider}/for-verification"),
"title": like!("Pact versions to be verified for the specified provider"),
"templated": like!(true)
}
}
}));
i
})
.await
.interaction("a request to the pacts for verification endpoint", "", |mut i| async move {
i.request
.get()
.path("/pacts/provider/sad_provider/for-verification")
.header("Accept", "application/hal+json")
.header("Accept", "application/json");
i.response
.header("Content-Type", "application/hal+json")
.json_body(json_pattern!({
"_links": {
"self": {
"href": like!("http://localhost/pacts/provider/sad_provider/for-verification"),
"title": like!("Pacts to be verified")
}
}
}));
i
})
.await
.interaction("a request to fetch pacts to be verified", "", |mut i| async move {
i.given("There are no pacts to be verified");
i.request
.post()
.path("/pacts/provider/sad_provider/for-verification")
.header("Accept", "application/hal+json")
.header("Accept", "application/json")
.json_body(json_pattern!({
"consumerVersionSelectors": each_like!({
"tag": "prod"
}),
"providerVersionTags": each_like!("master"),
"includePendingStatus": like!(false),
"providerVersionBranch": like!("main")
}));
i.response
.json_body(json_pattern!({
"_embedded": {
"pacts": []
}
}));
i
})
.await
.start_mock_server();
let result = fetch_pacts_dynamically_from_broker(pact_broker.url().as_str(), "sad_provider".to_string(), false, None, vec!("master".to_string()), Some("main".to_string()), vec!(ConsumerVersionSelector {
consumer: None,
tag: Some("prod".to_string()),
fallback_tag: None,
latest: None,
branch: None,
deployed_or_released: None,
deployed: None,
released: None,
main_branch: None,
matching_branch: None,
environment: None,
}), None).await;
match result {
Ok(_) => {
panic!("Expected an error result, but got OK");
},
Err(err) => {
println!("err: {}", err);
expect!(err.to_string().starts_with("Link/Resource was not found - No pacts were found for this provider")).to(be_true());
}
}
}
#[test]
fn test_build_payload_with_success() {
let result = TestResult::Ok(vec![]);
let payload = super::build_payload(result, "1".to_string(), None);
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": true,
"testResults": [],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn test_build_payload_adds_the_build_url_if_provided() {
let result = TestResult::Ok(vec![]);
let payload = super::build_payload(result, "1".to_string(), Some("http://build-url".to_string()));
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": true,
"buildUrl": "http://build-url",
"testResults": [],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn test_build_payload_adds_a_result_for_each_interaction() {
let result = TestResult::Ok(vec![Some("1".to_string()), Some("2".to_string()), Some("3".to_string()), None]);
let payload = super::build_payload(result, "1".to_string(), Some("http://build-url".to_string()));
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": true,
"buildUrl": "http://build-url",
"testResults": [
{ "interactionId": "1", "success": true },
{ "interactionId": "2", "success": true },
{ "interactionId": "3", "success": true }
],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn test_build_payload_with_failure() {
let result = TestResult::Failed(vec![]);
let payload = super::build_payload(result, "1".to_string(), None);
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": false,
"testResults": [],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn test_build_payload_with_failure_with_mismatches() {
let result = TestResult::Failed(vec![
(Some("1234abc".to_string()), Some(MismatchResult::Mismatches {
mismatches: vec![
MethodMismatch { expected: "PUT".to_string(), actual: "POST".to_string() }
],
expected: Box::new(RequestResponseInteraction::default()),
actual: Box::new(RequestResponseInteraction::default()),
interaction_id: Some("1234abc".to_string())
}))
]);
let payload = super::build_payload(result, "1".to_string(), None);
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": false,
"testResults": [
{
"interactionId": "1234abc",
"mismatches": [
{
"attribute": "method", "description": "Expected method of PUT but received POST"
}
],
"success": false
}
],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn test_build_payload_with_failure_with_exception() {
let result = TestResult::Failed(vec![
(Some("1234abc".to_string()), Some(MismatchResult::Error("Bang".to_string(), Some("1234abc".to_string()))))
]);
let payload = super::build_payload(result, "1".to_string(), None);
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": false,
"testResults": [
{
"exceptions": [
{
"message": "Bang"
}
],
"interactionId": "1234abc",
"success": false
}
],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn test_build_payload_with_mixed_results() {
let result = TestResult::Failed(vec![
(Some("1234abc".to_string()), Some(MismatchResult::Mismatches {
mismatches: vec![
MethodMismatch { expected: "PUT".to_string(), actual: "POST".to_string() }
],
expected: Box::new(RequestResponseInteraction::default()),
actual: Box::new(RequestResponseInteraction::default()),
interaction_id: Some("1234abc".to_string())
})),
(Some("12345678".to_string()), Some(MismatchResult::Error("Bang".to_string(), Some("1234abc".to_string())))),
(Some("abc123".to_string()), None)
]);
let payload = super::build_payload(result, "1".to_string(), None);
expect!(payload).to(be_equal_to(json!({
"providerApplicationVersion": "1",
"success": false,
"testResults": [
{
"interactionId": "1234abc",
"mismatches": [
{
"attribute": "method", "description": "Expected method of PUT but received POST"
}
],
"success": false
},
{
"exceptions": [
{
"message": "Bang"
}
],
"interactionId": "12345678",
"success": false
},
{
"interactionId": "abc123",
"success": true
}
],
"verifiedBy": {
"implementation": "Pact-Rust",
"version": PACT_RUST_VERSION
}
})));
}
#[test]
fn build_link_from_json() {
let json = json!({
"href": "localhost"
});
let link = Link::from_json(&"link name".to_string(), json.as_object().unwrap());
expect!(link.name).to(be_equal_to("link name"));
expect!(link.href).to(be_some().value("localhost"));
expect!(link.templated).to(be_false());
let json2 = json!({
"templated": true
});
let link2 = Link::from_json(&"link name".to_string(), json2.as_object().unwrap());
expect!(link2.name).to(be_equal_to("link name"));
expect!(link2.href).to(be_none());
expect!(link2.templated).to(be_true());
}
#[test]
fn build_json_from_link() {
let link = Link {
name: "Link Name".to_string(),
href: Some("1234".to_string()),
templated: true,
title: None
};
let json = link.as_json();
expect!(json.to_string()).to(be_equal_to(
"{\"href\":\"1234\",\"templated\":true}"));
let link = Link {
name: "Link Name".to_string(),
href: Some("1234".to_string()),
templated: true,
title: Some("title".to_string())
};
let json = link.as_json();
expect!(json.to_string()).to(be_equal_to(
"{\"href\":\"1234\",\"templated\":true,\"title\":\"title\"}"));
}
}