-
Notifications
You must be signed in to change notification settings - Fork 16
/
PactContractTests.swift
737 lines (667 loc) · 23.1 KB
/
PactContractTests.swift
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
//
// Created by Marko Justinek on 15/5/21.
// Copyright © 2020 Marko Justinek. All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import XCTest
@testable import PactSwift
private class MockServiceWrapper {
static let shared = MockServiceWrapper()
let errorCapture = ErrorCapture()
let consumer = "sanity-consumer"
let provider = "sanity-provider"
var mockService: MockService
init() {
mockService = MockService(consumer: consumer, provider: provider, merge: false, errorReporter: errorCapture)
}
}
class PactContractTests: XCTestCase {
var mockService = MockServiceWrapper.shared.mockService
let session = URLSession(configuration: .ephemeral)
static var errorCapture = MockServiceWrapper.shared.errorCapture
static let pactContractFileName = "\(MockServiceWrapper.shared.consumer)-\(MockServiceWrapper.shared.provider).json"
// MARK: - Validate Pact contract at the end
override class func setUp() {
super.setUp()
// Remove any previously generated Pact contracts for this test case
PactContractTests.removeFile(pactContractFileName)
}
override class func tearDown() {
do {
let fileContents = try XCTUnwrap(FileManager.default.contents(atPath: PactFileManager.pactDirectoryPath + "/" + self.pactContractFileName))
let jsonObject = try JSONSerialization.jsonObject(with: fileContents, options: []) as! [String: Any]
// Validate the final Pact contract file contains values that were specified in tests' expectations
// MARK: - Validate Interactions
let interactions = try XCTUnwrap(jsonObject["interactions"] as? [Any])
let numOfExpectedInteractions = 11
assert(
interactions.count == numOfExpectedInteractions,
"Expected \(numOfExpectedInteractions) interactions in Pact contract but got \(interactions.count)!"
)
// MARK: - Validate Matchers for Interactions
// Validate interaction "bug example"
let bugExampleInteraction = try PactContractTests.extract(.matchingRules, in: .response, interactions: interactions, description: "bug example")
// print("\nMATCHERS:\n\(matchersOne)")
let expectedMatchersOne = [
"$.array_of_objects",
"$.array_of_objects[*].key_for_explicit_array[0]",
"$.array_of_objects[*].key_for_explicit_array[1]",
"$.array_of_objects[*].key_for_explicit_array[2]",
"$.array_of_objects[*].key_for_explicit_array[3]",
"$.array_of_objects[*].key_for_explicit_array[4]",
"$.array_of_objects[*].key_for_matcher_array",
"$.array_of_objects[*].key_for_matcher_array[*]",
"$.array_of_objects[*].key_int",
"$.array_of_objects[*].key_string",
"$.array_of_strings",
"$.array_of_strings[*]",
"$.includes_like",
]
assert(
expectedMatchersOne.allSatisfy { expectedKey -> Bool in
bugExampleInteraction.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
},
"Not all expected generators found in Pact contract file"
)
// Validate interaction "a request for roles with sub-roles"
let arrayOnRootInteraction = try PactContractTests.extract(.matchingRules, in: .response, interactions: interactions, description: "a request for roles with sub-roles")
let expectedNodesForArrayOnRoot = [
"$[*].id"
]
assert(
expectedNodesForArrayOnRoot.allSatisfy { expectedKey -> Bool in
arrayOnRootInteraction.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
},
"Not all expected generators found in Pact contract file"
)
// Validate interaction "Request for animals with children"
let animalsWithChildrenInteraction = try PactContractTests.extract(.matchingRules, in: .response, interactions: interactions, description: "a request for animals with children")
let expectedNodesForAnimalsWithChildren = [
"$.animals",
"$.animals[*].children",
"$.animals[*].children[*]",
]
assert(
expectedNodesForAnimalsWithChildren.allSatisfy { expectedKey -> Bool in
animalsWithChildrenInteraction.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
}
)
// Validate interaction "Request for list of users in state"
let requestMatchers = try PactContractTests.extract(.matchingRules, in: .request, interactions: interactions, description: "Request for list of users in state")
let expectedMatchersTwo = [
"$.foo"
]
assert(
expectedMatchersTwo.allSatisfy { expectedKey -> Bool in
requestMatchers.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
}
, "Not all expected generators found in Pact contract file"
)
// Validate eachKeyLike matcher from interaction
let eachKeyLikeInteraction = try PactContractTests.extract(.matchingRules, in: .response, interactions: interactions, description: "Request for an object with wildcard matchers")
// print("\nMATCHERS:\n\(matchersOne)")
let expectedEachKeyLikePaths = [
"$.articles",
"$.articles[*].variants.*",
"$.articles[*].variants.*.bundles.*",
"$.articles[*].variants.*.bundles.*.description",
"$.articles[*].variants.*.bundles.*.referencedArticles",
"$.articles[*].variants.*.bundles.*.referencedArticles[*].bundleId",
]
assert(
expectedEachKeyLikePaths.allSatisfy { expectedKey -> Bool in
eachKeyLikeInteraction.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
},
"Not all expected generators found in Pact contract file for eachKeyLike matcher"
)
// Validate eachKeyLike matcher from interaction
let eachKeyLikeSimplerInteraction = try PactContractTests.extract(.matchingRules, in: .response, interactions: interactions, description: "Request for a simpler object with wildcard matchers")
// print("\nMATCHERS:\n\(matchersOne)")
let expectedSimplerEachKeyLikePaths = [
"$.*",
"$.*.field1",
"$.*.field2",
]
assert(
expectedSimplerEachKeyLikePaths.allSatisfy { expectedKey -> Bool in
eachKeyLikeSimplerInteraction.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
},
"Not all expected generators found in Pact contract file for eachKeyLike matcher"
)
// MARK: - Validate Generators
let responseGenerators = try extract(.generators, in: .response, interactions: interactions, description: "Request for list of users")
let expectedGeneratorsType = [
"$.array_of_arrays[*][2]": [
"type": "Uuid",
"format": "upper-case-hyphenated"
]
]
assert(
expectedGeneratorsType.allSatisfy { expectedKey, expectedValue -> Bool in
responseGenerators.contains { generatedKey, generatedValue -> Bool in
expectedKey == generatedKey
&& expectedValue["type"] == (generatedValue as? [String: String])?["type"]
&& expectedValue["format"] == (generatedValue as? [String: String])?["format"]
}
},
"Not all expected generators found in Pact contract file"
)
// MARK: - Test two of same matchers used
let twoMatchersTest = try PactContractTests.extract(.matchingRules, in: .response, interactions: interactions, description: "Request for a simple object")
let expectedTwoMatchers = [
"$.identifier",
"$.group_identifier",
]
assert(expectedTwoMatchers.allSatisfy { expectedKey -> Bool in
twoMatchersTest.contains { generatedKey, _ -> Bool in
expectedKey == generatedKey
}
},
"Not all expected matchers are found in Pact interaction"
)
} catch {
XCTFail(error.localizedDescription)
}
super.tearDown()
}
// MARK: - Tests that write the Pact contract
func testBugExample() {
mockService
.uponReceiving("bug example")
.given("some state")
.withRequest(method: .GET, path: "/bugfix")
.willRespondWith(
status: 200,
body: [
"array_of_objects": Matcher.EachLike(
[
"key_string": Matcher.SomethingLike("String value"),
"key_int": Matcher.IntegerLike(123),
"key_for_matcher_array": Matcher.EachLike(
Matcher.SomethingLike("matcher_array_value")
),
"key_for_explicit_array": [
Matcher.SomethingLike("explicit_array_value_one"),
Matcher.SomethingLike(1),
Matcher.IntegerLike(936),
Matcher.DecimalLike(123.23),
Matcher.RegexLike(value: "2021-05-17", pattern: #"\d{4}-\d{2}-\d{2}"#),
Matcher.IncludesLike("in", "array", generate: "Included in explicit array")
] as [Any],
"key_for_datetime_expression": ExampleGenerator.DateTimeExpression(expression: "today +1 day", format: "yyyy-MM-dd")
] as [String : Any]
),
"array_of_strings": Matcher.EachLike(
Matcher.SomethingLike("A string")
),
"includes_like": Matcher.IncludesLike("included", generate: "Value _included_ is included in this string")
] as [String : Any]
)
mockService.run { [unowned self] baseURL, completed in
let url = URL(string: "\(baseURL)/bugfix")!
self.session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testExample_AnimalsWithChildren() {
mockService
.uponReceiving("a request for animals with children")
.given("animals have children")
.withRequest(method: .GET, path: "/animals")
.willRespondWith(
status: 200,
body: [
"animals": Matcher.EachLike(
[
"children": Matcher.EachLike(
Matcher.SomethingLike("Mary"),
min: 0
),
]
)
]
)
mockService.run { [unowned self] baseURL, completed in
let url = URL(string: "\(baseURL)/animals")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testExample_AnimalsWithChildrenMultipleInteractionsInOneTest() {
let firstInteraction = mockService
.uponReceiving("a request for animals with children")
.given("animals have children")
.withRequest(method: .GET, path: "/animals1")
.willRespondWith(
status: 200,
body: [
"animals": Matcher.EachLike(
[
"children": Matcher.EachLike(
Matcher.SomethingLike("Mary"),
min: 0
),
]
)
]
)
let secondInteraction = mockService
.uponReceiving("a request for animals with Children")
.given("animals have children")
.withRequest(method: .GET, path: "/animals2")
.willRespondWith(
status: 200,
body: [
"animals": Matcher.EachLike(
[
"children": Matcher.EachLike(
Matcher.SomethingLike("Mary"),
min: 0
),
]
)
]
)
mockService.run(verify: [firstInteraction, secondInteraction]) { [unowned self] baseURL, completed in
let urlOne = URL(string: "\(baseURL)/animals1")!
let urlTwo = URL(string: "\(baseURL)/animals2")!
let expOne = expectation(description: "one")
let expTwo = expectation(description: "two")
session
.dataTask(with: urlOne) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: urlOne.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
expOne.fulfill()
}
.resume()
session
.dataTask(with: urlTwo) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: urlOne.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
expTwo.fulfill()
}
.resume()
waitForExpectations(timeout: 5) { _ in
completed()
}
}
}
func testExample_ArrayOnRoot() {
mockService
.uponReceiving("a request for roles with sub-roles")
.given("roles have sub-rules")
.withRequest(method: .GET, path: "/roles")
.willRespondWith(
status: 200,
body:
Matcher.EachLike(
[
"id": Matcher.RegexLike(
value: "1234abcd-1234-abcf-12ab-abcdef1234567",
pattern: #"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"#
)
]
)
)
mockService.run { [unowned self] baseURL, completed in
let url = URL(string: "\(baseURL)/roles")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testPactContract_WritesMatchersAndGenerators() {
mockService
.uponReceiving("Request for list of users")
.given("users exist")
.withRequest(method: .GET, path: "/users")
.willRespondWith(
status: 200,
body: [
"foo": Matcher.SomethingLike("bar"),
"baz": Matcher.EachLike(123, min: 1, max: 5, count: 3),
"array_of_arrays": Matcher.EachLike(
[
Matcher.SomethingLike("array_value"),
Matcher.RegexLike(value: "2021-05-15", pattern: #"\d{4}-\d{2}-\d{2}"#),
ExampleGenerator.RandomUUID(format: .uppercaseHyphenated),
Matcher.EachLike(
[
"3rd_level_nested": Matcher.EachLike(Matcher.IntegerLike(369), count: 2)
]
)
] as [Any]
),
"regex_array": Matcher.EachLike(
[
"regex_key": Matcher.EachLike(
Matcher.RegexLike(value: "1235", pattern: #"\d{4}"#),
min: 2
),
"regex_nested_object": Matcher.EachLike(
[
"regex_nested_key": Matcher.RegexLike(value: "12345678", pattern: #"\d{8}"#)
]
)
]
),
"enum_value": Matcher.OneOf("night", "morning", "mid-day", "afternoon", "evening")
] as [String : Any]
)
mockService.run { [unowned self] baseURL, completed in
let url = URL(string: "\(baseURL)/users")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testPactContract_ArrayAsRoot() {
mockService
.uponReceiving("Request for an explicit array")
.given("array exist")
.withRequest(
method: .GET,
path: Matcher.RegexLike(value: "/arrays/explicit", pattern: #"^/arrays/e\w+$"#)
)
.willRespondWith(
status: 200,
body:
[
[
"id": Matcher.SomethingLike(19231421)
],
[
"id": Matcher.SomethingLike(49817231)
]
]
)
mockService.run { [unowned self] baseURL, completed in
let url = URL(string: "\(baseURL)/arrays/explicit")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testPactContract_WithMatcherInRequestBody() {
mockService
.uponReceiving("Request for list of users in state")
.given("users in that state exist")
.withRequest(
method: .POST,
path: Matcher.FromProviderState(parameter: "/users/state/${stateIdentifier}", value: .string("/users/state/nsw")),
body: ["foo": Matcher.SomethingLike("bar")]
)
.willRespondWith(
status: 200,
body: [
"identifier": Matcher.FromProviderState(parameter: "userId", value: .int(100)),
"randomCode": Matcher.FromProviderState(parameter: "rndCode", value: .string("some-random-code")),
"foo": Matcher.SomethingLike("bar"),
"baz": Matcher.SomethingLike("qux")
] as [String : Any]
)
mockService.run { [unowned self] baseURL, completed in
var request = URLRequest(url: URL(string: "\(baseURL)/users/state/nsw")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = #"{"foo": "bar"}"#.data(using: .utf8)
session
.dataTask(with: request) { _, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: request.debugDescription, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testPactContract_WithTwoMatchersOfSameType() {
mockService
.uponReceiving("Request for a simple object")
.given("data exists")
.withRequest(method: .GET, path: "/users/data")
.willRespondWith(
status: 200,
body: [
"identifier": Matcher.SomethingLike(1),
"group_identifier": Matcher.SomethingLike(1)
]
)
mockService.run { [unowned self] baseURL, completed in
let url = URL(string: "\(baseURL)/users/data")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
// We don't care about the network response here, so we tell PactSwift we're done with the Pact test
// This is tested in `MockServiceTests.swift`
completed()
}
.resume()
}
}
func testPactContract_WithEachKeyLikeMatcher() {
mockService
.uponReceiving("Request for an object with wildcard matchers")
.given("keys in response itself are ignored")
.withRequest(method: .GET, path: "/articles/nested/keyLikeMatcher")
.willRespondWith(
status: 200,
body: [
"articles": Matcher.EachLike(
[
"variants": [
"001": Matcher.EachKeyLike([
"bundles": [
"001-A": Matcher.EachKeyLike([
"description": Matcher.SomethingLike("someDescription"),
"referencedArticles": Matcher.EachLike([
"bundleId": Matcher.SomethingLike("someId")
])
] as [String : Any])
]
])
]
]
)
]
)
mockService.run { [unowned self] baseURL, done in
let url = URL(string: "\(baseURL)/articles/nested/keyLikeMatcher")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
done()
}
.resume()
}
}
func testPactContract_WithSimplerEachKeyLikeMatcher() {
mockService
.uponReceiving("Request for a simpler object with wildcard matchers")
.given("keys in response itself are ignored")
.withRequest(method: .GET, path: "/articles/simpler/keyLikeMatcher")
.willRespondWith(
status: 200,
body: [
"abc": Matcher.EachKeyLike([
"field1": Matcher.SomethingLike("value1"),
"field2": Matcher.IntegerLike(123)
] as [String : Any]),
"xyz": Matcher.EachKeyLike([
"field1": Matcher.SomethingLike("value2"),
"field2": Matcher.IntegerLike(456)
] as [String : Any])
]
)
mockService.run { [unowned self] baseURL, done in
let url = URL(string: "\(baseURL)/articles/simpler/keyLikeMatcher")!
session
.dataTask(with: url) { data, response, error in
guard
error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else {
self.fail(function: #function, request: url.absoluteString, response: response.debugDescription, error: error)
return
}
done()
}
.resume()
}
}
}
private extension PactContractTests {
enum PactNode: String {
case matchingRules
case generators
}
enum Direction: String {
case request
case response
}
func fail(function: String, request: String? = nil, response: String? = nil, error: Error? = nil) {
XCTFail(
"""
Expected network request to succeed in \(function)!
Request URL: \t\(String(describing: request))
Response:\t\(String(describing: response))
Reason: \t\(String(describing: error?.localizedDescription))
"""
)
}
static func extract(_ type: PactNode, in direction: Direction, interactions: [Any], description: String) throws -> [String: Any] {
let interaction = interactions.first { interaction -> Bool in
(interaction as! [String: Any])["description"] as! String == description
}
return try XCTUnwrap((((interaction as? [String: Any])?[direction.rawValue] as? [String: Any])?[type.rawValue] as? [String: Any])?["body"] as? [String: Any])
}
@discardableResult
static func fileExists(_ filename: String) -> Bool {
FileManager.default.fileExists(atPath: PactFileManager.pactDirectoryPath + "/\(filename)")
}
@discardableResult
static func removeFile(_ filename: String) -> Bool {
if fileExists(filename) {
do {
try FileManager.default.removeItem(at: URL(fileURLWithPath: PactFileManager.pactDirectoryPath + "/\(filename)"))
return true
} catch {
debugPrint("Could not remove file \(PactFileManager.pactDirectoryPath + "/\(filename)")")
return false
}
}
return false
}
}