-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathpact.py
1561 lines (1304 loc) · 48.4 KB
/
pact.py
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
"""
Pact between a consumer and a provider.
This module defines the classes that are used to define a Pact between a
consumer and a provider. It defines the interactions between the two parties,
and provides the functionality to verify that the interactions are satisfied.
For the roles of consumer and provider, see the documentation for the
`pact.v3.service` module.
"""
from __future__ import annotations
import abc
import json
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable, Literal, Set, overload
from yarl import URL
import pact.v3.ffi
if TYPE_CHECKING:
from types import TracebackType
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class Interaction(abc.ABC):
"""
Interaction between a consumer and a provider.
This abstract class defines an interaction between a consumer and a
provider. The concrete subclasses define the type of interaction, and include:
- [`HttpInteraction`][pact.v3.pact.HttpInteraction]
- [`AsyncMessageInteraction`][pact.v3.pact.AsyncMessageInteraction]
- [`SyncMessageInteraction`][pact.v3.pact.SyncMessageInteraction]
A set of interactions between a consumer and a provider is called a Pact.
"""
def __init__(self, description: str) -> None:
"""
Create a new Interaction.
As this class is abstract, this function should not be called directly
but should instead be called through one of the concrete subclasses.
Args:
description:
Description of the interaction. This must be unique within the
Pact.
"""
self._description = description
def __str__(self) -> str:
"""
Nice representation of the Interaction.
"""
return f"{self.__class__.__name__}({self._description})"
def __repr__(self) -> str:
"""
Debugging representation of the Interaction.
"""
return f"{self.__class__.__name__}({self._handle!r})"
@property
@abc.abstractmethod
def _handle(self) -> pact.v3.ffi.InteractionHandle:
"""
Handle for the Interaction.
This is used internally by the library to pass the Interaction to the
underlying Pact library.
"""
@property
@abc.abstractmethod
def _interaction_part(self) -> pact.v3.ffi.InteractionPart:
"""
Interaction part.
Where interactions have multiple parts, this property keeps track
of which part is currently being set.
"""
def _parse_interaction_part(
self,
part: Literal["Request", "Response", None],
) -> pact.v3.ffi.InteractionPart:
"""
Convert the input into an InteractionPart.
"""
if part == "Request":
return pact.v3.ffi.InteractionPart.REQUEST
if part == "Response":
return pact.v3.ffi.InteractionPart.RESPONSE
if part is None:
return self._interaction_part
msg = f"Invalid part: {part}"
raise ValueError(msg)
@overload
def given(self, state: str) -> Self: ...
@overload
def given(self, state: str, *, name: str, value: str) -> Self: ...
@overload
def given(self, state: str, *, parameters: dict[str, Any] | str) -> Self: ...
def given(
self,
state: str,
*,
name: str | None = None,
value: str | None = None,
parameters: dict[str, Any] | str | None = None,
) -> Self:
"""
Set the provider state.
This is the state that the provider should be in when the Interaction is
executed. When the provider is being verified, the provider state is
passed to the provider so that its internal state can be set to match
the provider state.
In its simplest form, the provider state is a string. For example, to
match a provider state of `a user exists`, you would use:
```python
pact.upon_receiving("a request").given("a user exists")
```
It is also possible to specify a parameter that will be used to match
the provider state. For example, to match a provider state of `a user
exists` with a parameter `id` that has the value `123`, you would use:
```python
(
pact.upon_receiving("a request").given(
"a user exists", name="id", value="123"
)
)
```
Lastly, it is possible to specify multiple parameters that will be used
to match the provider state. For example, to match a provider state of
`a user exists` with a parameter `id` that has the value `123` and a
parameter `name` that has the value `John`, you would use:
```python
(
pact.upon_receiving("a request").given(
"a user exists",
parameters={
"id": "123",
"name": "John",
},
)
)
```
This function can be called repeatedly to specify multiple provider
states for the same Interaction. If the same `state` is specified with
different parameters, then the parameters are merged together. The above
example with multiple parameters can equivalently be specified as:
```python
(
pact.upon_receiving("a request")
.given("a user exists", name="id", value="123")
.given("a user exists", name="name", value="John")
)
```
Args:
state:
Provider state for the Interaction.
name:
Name of the parameter. This must be specified in conjunction
with `value`.
value:
Value of the parameter. This must be specified in conjunction
with `name`.
parameters:
Key-value pairs of parameters to use for the provider state.
These must be encodable using [`json.dumps(...)`][json.dumps].
Alternatively, a string contained the JSON object can be passed
directly.
If the string does not contain a valid JSON object, then the
string is passed directly as follows:
```python
(
pact.upon_receiving("a request").given(
"a user exists", name="value", value=parameters
)
)
```
Raises:
ValueError:
If the combination of arguments is invalid or inconsistent.
"""
if name is not None and value is not None and parameters is None:
pact.v3.ffi.given_with_param(self._handle, state, name, value)
elif name is None and value is None and parameters is not None:
if isinstance(parameters, dict):
pact.v3.ffi.given_with_params(
self._handle,
state,
json.dumps(parameters),
)
else:
pact.v3.ffi.given_with_params(self._handle, state, parameters)
elif name is None and value is None and parameters is None:
pact.v3.ffi.given(self._handle, state)
else:
msg = "Invalid combination of arguments."
raise ValueError(msg)
return self
def with_body(
self,
body: str | None = None,
content_type: str | None = None,
part: Literal["Request", "Response"] | None = None,
) -> Self:
"""
Set the body of the request or response.
Args:
body:
Body of the request. If this is `None`, then the body is
empty.
content_type:
Content type of the body. This is ignored if the `Content-Type`
header has already been set.
part:
Whether the body should be added to the request or the response.
If `None`, then the function intelligently determines whether
the body should be added to the request or the response, based
on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
pact.v3.ffi.with_body(
self._handle,
self._parse_interaction_part(part),
content_type,
body,
)
return self
def with_binary_body(
self,
body: bytes | None,
content_type: str | None = None,
part: Literal["Request", "Response"] | None = None,
) -> Self:
"""
Adds a binary body to the request or response.
Note that for HTTP interactions, this function will overwrite the body
if it has been set using
[`with_body(...)`][pact.v3.Interaction.with_body].
Args:
part:
Whether the body should be added to the request or the response.
If `None`, then the function intelligently determines whether
the body should be added to the request or the response, based
on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
content_type:
Content type of the body. This is ignored if the `Content-Type`
header has already been set.
body:
Body of the request.
"""
pact.v3.ffi.with_binary_file(
self._handle,
self._parse_interaction_part(part),
content_type,
body,
)
return self
def with_multipart_file( # noqa: PLR0913
self,
part_name: str,
path: Path | None,
content_type: str | None = None,
part: Literal["Request", "Response"] | None = None,
boundary: str | None = None,
) -> Self:
"""
Adds a binary file as the body of a multipart request or response.
The content type of the body will be set to a MIME multipart message.
"""
pact.v3.ffi.with_multipart_file_v2(
self._handle,
self._parse_interaction_part(part),
content_type,
path,
part_name,
boundary,
)
return self
def set_key(self, key: str | None) -> Self:
"""
Sets the key for the interaction.
This is used by V4 interactions to set the key of the interaction, which
can subsequently used to reference the interaction.
"""
pact.v3.ffi.set_key(self._handle, key)
return self
def set_pending(self, *, pending: bool) -> Self:
"""
Mark the interaction as pending.
This is used by V4 interactions to mark the interaction as pending, in
which case the provider is not expected to honour the interaction.
"""
pact.v3.ffi.set_pending(self._handle, pending=pending)
return self
def set_comment(self, key: str, value: Any | None) -> Self: # noqa: ANN401
"""
Set a comment for the interaction.
This is used by V4 interactions to set a comment for the interaction. A
comment consists of a key-value pair, where the key is a string and the
value is anything that can be encoded as JSON.
Args:
key:
Key for the comment.
value:
Value for the comment. This must be encodable using
[`json.dumps(...)`][json.dumps], or an existing JSON string. The
value of `None` will remove the comment with the given key.
"""
if isinstance(value, str) or value is None:
pact.v3.ffi.set_comment(self._handle, key, value)
else:
pact.v3.ffi.set_comment(self._handle, key, json.dumps(value))
return self
def test_name(
self,
name: str,
) -> Self:
"""
Set the test name annotation for the interaction.
This is used by V4 interactions to set the name of the test.
Args:
name:
Name of the test.
"""
pact.v3.ffi.interaction_test_name(self._handle, name)
return self
def with_plugin_contents(
self,
contents: dict[str, Any] | str,
content_type: str,
part: Literal["Request", "Response"] | None = None,
) -> Self:
"""
Set the interaction content using a plugin.
The value of `contents` is passed directly to the plugin as a JSON
string. The plugin will document the format of the JSON content.
Args:
contents:
Body of the request. If this is `None`, then the body is empty.
content_type:
Content type of the body. This is ignored if the `Content-Type`
header has already been set.
part:
Whether the body should be added to the request or the response.
If `None`, then the function intelligently determines whether
the body should be added to the request or the response, based
on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
if isinstance(contents, dict):
contents = json.dumps(contents)
pact.v3.ffi.interaction_contents(
self._handle,
self._parse_interaction_part(part),
content_type,
contents,
)
return self
def with_matching_rules(
self,
rules: dict[str, Any] | str,
part: Literal["Request", "Response"] | None = None,
) -> Self:
"""
Add matching rules to the interaction.
Matching rules are used to specify how the request or response should be
matched. This is useful for specifying that certain parts of the request
or response are flexible, such as the date or time.
Args:
rules:
Matching rules to add to the interaction. This must be
encodable using [`json.dumps(...)`][json.dumps], or a string.
part:
Whether the matching rules should be added to the request or the
response. If `None`, then the function intelligently determines
whether the matching rules should be added to the request or the
response, based on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
if isinstance(rules, dict):
rules = json.dumps(rules)
pact.v3.ffi.with_matching_rules(
self._handle,
self._parse_interaction_part(part),
rules,
)
return self
class HttpInteraction(Interaction):
"""
A synchronous HTTP interaction.
This class defines a synchronous HTTP interaction between a consumer and a
provider. It defines a specific request that the consumer makes to the
provider, and the response that the provider should return.
"""
def __init__(self, pact_handle: pact.v3.ffi.PactHandle, description: str) -> None:
"""
Initialise a new HTTP Interaction.
This function should not be called directly. Instead, an Interaction
should be created using the
[`upon_receiving(...)`][pact.v3.Pact.upon_receiving] method of a
[`Pact`][pact.v3.Pact] instance.
"""
super().__init__(description)
self.__handle = pact.v3.ffi.new_interaction(pact_handle, description)
self.__interaction_part = pact.v3.ffi.InteractionPart.REQUEST
self._request_indices: dict[
tuple[pact.v3.ffi.InteractionPart, str],
int,
] = defaultdict(int)
self._parameter_indices: dict[str, int] = defaultdict(int)
@property
def _handle(self) -> pact.v3.ffi.InteractionHandle:
"""
Handle for the Interaction.
This is used internally by the library to pass the Interaction to the
underlying Pact library.
"""
return self.__handle
@property
def _interaction_part(self) -> pact.v3.ffi.InteractionPart:
"""
Interaction part.
Keeps track whether we are setting by default the request or the
response in the HTTP interaction.
"""
return self.__interaction_part
def with_request(self, method: str, path: str) -> Self:
"""
Set the request.
This is the request that the consumer will make to the provider.
Args:
method:
HTTP method for the request.
path:
Path for the request.
"""
pact.v3.ffi.with_request(self._handle, method, path)
return self
def with_header(
self,
name: str,
value: str,
part: Literal["Request", "Response"] | None = None,
) -> Self:
r"""
Add a header to the request.
# Repeated Headers
If the same header has multiple values ([see RFC9110
§5.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.2)), then
the same header must be specified multiple times with _order being
preserved_. For example
```python
(
pact.upon_receiving("a request")
.with_header("X-Foo", "bar")
.with_header("X-Foo", "baz")
)
```
will expect a request with the following headers:
```http
X-Foo: bar
X-Foo: baz
# Or, equivalently:
X-Foo: bar, baz
```
Note that repeated headers are _case insensitive_ in accordance with
[RFC 9110
§5.1](https://www.rfc-editor.org/rfc/rfc9110.html#section-5.1).
# JSON Matching
Pact's matching rules are defined in the [upstream
documentation](https://github.com/pact-foundation/pact-reference/blob/libpact_ffi-v0.4.18/rust/pact_ffi/IntegrationJson.md)
and support a wide range of matching rules. These can be specified
using a JSON object as a strong using `json.dumps(...)`. For example,
the above rule whereby the `X-Foo` header has multiple values can be
specified as:
```python
(
pact.upon_receiving("a request")
.with_header(
"X-Foo",
json.dumps({
"value": ["bar", "baz"],
}),
)
)
```
It is also possible to have a more complicated Regex pattern for the
header. For example, a pattern for an `Accept-Version` header might be
specified as:
```python
(
pact.upon_receiving("a request").with_header(
"Accept-Version",
json.dumps({
"value": "1.2.3",
"pact:matcher:type": "regex",
"regex": r"\d+\.\d+\.\d+",
}),
)
)
```
If the value of the header is expected to be a JSON object and clashes
with the above syntax, then it is recommended to make use of the
[`set_header(...)`][pact.v3.Interaction.set_header] method instead.
Args:
name:
Name of the header.
value:
Value of the header.
part:
Whether the header should be added to the request or the
response. If `None`, then the function intelligently determines
whether the header should be added to the request or the
response, based on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
interaction_part = self._parse_interaction_part(part)
name_lower = name.lower()
index = self._request_indices[(interaction_part, name_lower)]
self._request_indices[(interaction_part, name_lower)] += 1
pact.v3.ffi.with_header_v2(
self._handle,
interaction_part,
name,
index,
value,
)
return self
def with_headers(
self,
headers: dict[str, str] | Iterable[tuple[str, str]],
part: Literal["Request", "Response"] | None = None,
) -> Self:
"""
Add multiple headers to the request.
Note that due to the requirement of Python dictionaries to
have unique keys, it is _not_ possible to specify a header multiple
times to create a multi-valued header. Instead, you may:
- Use an alternative data structure. Any iterable of key-value pairs
is accepted, including a list of tuples, a list of lists, or a
dictionary view.
- Make multiple calls to
[`with_header(...)`][pact.v3.Interaction.with_header] or
[`with_headers(...)`][pact.v3.Interaction.with_headers].
- Specify the multiple values in a JSON object of the form:
```python
(
pact.upon_receiving("a request")
.with_headers({
"X-Foo": json.dumps({
"value": ["bar", "baz"],
}),
)
)
```
See [`with_header(...)`][pact.v3.Interaction.with_header] for more
information.
Args:
headers:
Headers to add to the request.
part:
Whether the header should be added to the request or the
response. If `None`, then the function intelligently determines
whether the header should be added to the request or the
response, based on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
if isinstance(headers, dict):
headers = headers.items()
for name, value in headers:
self.with_header(name, value, part)
return self
def set_header(
self,
name: str,
value: str,
part: Literal["Request", "Response"] | None = None,
) -> Self:
r"""
Add a header to the request.
Unlike [`with_header(...)`][pact.v3.Interaction.with_header], this
function does no additional processing of the header value. This is
useful for headers that contain a JSON object.
Args:
name:
Name of the header.
value:
Value of the header.
part:
Whether the header should be added to the request or the
response. If `None`, then the function intelligently determines
whether the header should be added to the request or the
response, based on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
pact.v3.ffi.set_header(
self._handle,
self._parse_interaction_part(part),
name,
value,
)
return self
def set_headers(
self,
headers: dict[str, str] | Iterable[tuple[str, str]],
part: Literal["Request", "Response"] | None = None,
) -> Self:
"""
Add multiple headers to the request.
This function intelligently determines whether the header should be
added to the request or the response, based on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with] method
has been called.
See [`set_header(...)`][pact.v3.Interaction.set_header] for more
information.
Args:
headers:
Headers to add to the request.
part:
Whether the headers should be added to the request or the
response. If `None`, then the function intelligently determines
whether the header should be added to the request or the
response, based on whether the
[`will_respond_with(...)`][pact.v3.Interaction.will_respond_with]
method has been called.
"""
if isinstance(headers, dict):
headers = headers.items()
for name, value in headers:
self.set_header(name, value, part)
return self
def with_query_parameter(self, name: str, value: str) -> Self:
r"""
Add a query to the request.
This is the query parameter(s) that the consumer will send to the
provider.
If the same parameter can support multiple values, then the same
parameter can be specified multiple times:
```python
(
pact.upon_receiving("a request")
.with_query_parameter("name", "John")
.with_query_parameter("name", "Mary")
)
```
The above can equivalently be specified as:
```python
(
pact.upon_receiving("a request").with_query_parameter(
"name",
json.dumps({
"value": ["John", "Mary"],
}),
)
)
```
It is also possible to have a more complicated Regex pattern for the
paramater. For example, a pattern for an `version` parameter might be
specified as:
```python
(
pact.upon_receiving("a request").with_query_parameter(
"version",
json.dumps({
"value": "1.2.3",
"pact:matcher:type": "regex",
"regex": r"\d+\.\d+\.\d+",
}),
)
)
```
For more information on the format of the JSON object, see the [upstream
documentation](https://github.com/pact-foundation/pact-reference/blob/libpact_ffi-v0.4.18/rust/pact_ffi/IntegrationJson.md).
Args:
name:
Name of the query parameter.
value:
Value of the query parameter.
"""
index = self._parameter_indices[name]
self._parameter_indices[name] += 1
pact.v3.ffi.with_query_parameter_v2(
self._handle,
name,
index,
value,
)
return self
def with_query_parameters(
self,
parameters: dict[str, str] | Iterable[tuple[str, str]],
) -> Self:
"""
Add multiple query parameters to the request.
See [`with_query_parameter(...)`][pact.v3.Interaction.with_query_parameter]
for more information.
Args:
parameters:
Query parameters to add to the request.
"""
if isinstance(parameters, dict):
parameters = parameters.items()
for name, value in parameters:
self.with_query_parameter(name, value)
return self
def will_respond_with(self, status: int) -> Self:
"""
Set the response status.
Ideally, this function is called once all of the request information has
been set. This allows functions such as
[`with_header(...)`][pact.v3.Interaction.with_header] to intelligently
determine whether this is a request or response header.
Alternatively, the `part` argument can be used to explicitly specify
whether the header should be added to the request or the response.
Args:
status:
Status for the response.
"""
pact.v3.ffi.response_status(self._handle, status)
self.__interaction_part = pact.v3.ffi.InteractionPart.RESPONSE
return self
class AsyncMessageInteraction(Interaction):
"""
An asynchronous message interaction.
This class defines an asynchronous message interaction between a consumer
and a provider. It defines the kind of messages a consumer can accept, and
the is agnostic of the underlying protocol, be it a message queue, Apache
Kafka, or some other asynchronous protocol.
"""
def __init__(self, pact_handle: pact.v3.ffi.PactHandle, description: str) -> None:
"""
Initialise a new Asynchronous Message Interaction.
This function should not be called directly. Instead, an
AsyncMessageInteraction should be created using the
[`upon_receiving(...)`][pact.v3.Pact.upon_receiving] method of a
[`Pact`][pact.v3.Pact] instance using the `"Async"` interaction type.
Args:
pact_handle:
Handle for the Pact.
description:
Description of the interaction. This must be unique within the
Pact.
"""
super().__init__(description)
self.__handle = pact.v3.ffi.new_message_interaction(pact_handle, description)
@property
def _handle(self) -> pact.v3.ffi.InteractionHandle:
"""
Handle for the Interaction.
This is used internally by the library to pass the Interaction to the
underlying Pact library.
"""
return self.__handle
@property
def _interaction_part(self) -> pact.v3.ffi.InteractionPart:
return pact.v3.ffi.InteractionPart.REQUEST
class SyncMessageInteraction(Interaction):
"""
A synchronous message interaction.
This class defines a synchronous message interaction between a consumer and
a provider. As with [`HttpInteraction`][pact.v3.pact.HttpInteraction], it
defines a specific request that the consumer makes to the provider, and the
response that the provider should return.
"""
def __init__(self, pact_handle: pact.v3.ffi.PactHandle, description: str) -> None:
"""
Initialise a new Synchronous Message Interaction.
This function should not be called directly. Instead, an
AsyncMessageInteraction should be created using the
[`upon_receiving(...)`][pact.v3.Pact.upon_receiving] method of a
[`Pact`][pact.v3.Pact] instance using the `"Sync"` interaction type.
Args:
pact_handle:
Handle for the Pact.
description:
Description of the interaction. This must be unique within the
Pact.
"""
super().__init__(description)
self.__handle = pact.v3.ffi.new_sync_message_interaction(
pact_handle,
description,
)
self.__interaction_part = pact.v3.ffi.InteractionPart.REQUEST
@property
def _handle(self) -> pact.v3.ffi.InteractionHandle:
"""
Handle for the Interaction.
This is used internally by the library to pass the Interaction to the
underlying Pact library.
"""
return self.__handle
@property
def _interaction_part(self) -> pact.v3.ffi.InteractionPart:
return self.__interaction_part
class Pact:
"""
A Pact between a consumer and a provider.
This class defines a Pact between a consumer and a provider. It is the
central class in Pact's framework, and is responsible for defining the
interactions between the two parties.
One Pact instance should be created for each provider that a consumer
interacts with. This instance can then be used to define the interactions
between the two parties.
"""
def __init__(
self,
consumer: str,
provider: str,
) -> None:
"""
Initialise a new Pact.
Args:
consumer:
Name of the consumer.
provider:
Name of the provider.
"""
if not consumer:
msg = "Consumer name cannot be empty."
raise ValueError(msg)
if not provider:
msg = "Provider name cannot be empty."
raise ValueError(msg)
self._consumer = consumer
self._provider = provider
self._interactions: Set[Interaction] = set()
self._handle: pact.v3.ffi.PactHandle = pact.v3.ffi.new_pact(
consumer,
provider,
)