-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathverifier.py
881 lines (732 loc) · 26.6 KB
/
verifier.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
"""
Verifier for Pact.
The Verifier is used to verify that a provider meets the expectations of a
consumer. This is done by replaying interactions from the consumer against the
provider, and ensuring that the provider's responses match the expectations set
by the consumer.
"""
from __future__ import annotations
import json
from datetime import date
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, overload
from typing_extensions import Self
from yarl import URL
import pact.v3.ffi
if TYPE_CHECKING:
from collections.abc import Iterable
class Verifier:
"""
A Verifier between a consumer and a provider.
This class encapsulates the logic for verifying that a provider meets the
expectations of a consumer. This is done by replaying interactions from the
consumer against the provider, and ensuring that the provider's responses
match the expectations set by the consumer.
"""
def __init__(self) -> None:
"""
Create a new Verifier.
"""
self._handle: pact.v3.ffi.VerifierHandle = (
pact.v3.ffi.verifier_new_for_application()
)
# In order to provide a fluent interface, we remember some options which
# are set using the same FFI method.
self._disable_ssl_verification = False
self._request_timeout = 5000
def __str__(self) -> str:
"""
Informal string representation of the Verifier.
"""
return "Verifier"
def __repr__(self) -> str:
"""
Information-rish string representation of the Verifier.
"""
return f"<Verifier: {self._handle}>"
def set_info( # noqa: PLR0913
self,
name: str,
*,
url: str | URL | None = None,
scheme: str | None = None,
host: str | None = None,
port: int | None = None,
path: str | None = None,
) -> Self:
"""
Set the provider information.
This sets up information about the provider as well as the way it
communicates with the consumer. Note that for historical reasons, a
HTTP(S) transport method is always added.
For a provider which uses other protocols (such as message queues), the
[`add_provider_transport`][pact.v3.verifier.Verifier.add_provider_transport]
must be used. This method can be called multiple times to add multiple
transport methods.
Args:
name:
A user-friendly name for the provider.
url:
The URL on which requests are made to the provider by Pact.
It is recommended to use this parameter to set the provider URL.
If the port is not explicitly set, the default port for the
scheme will be used.
This parameter is mutually exclusive with the individual
parameters.
scheme:
The provider scheme. This must be one of `http` or `https`.
host:
The provider hostname or IP address. If the provider is running
on the same machine as the verifier, `localhost` can be used.
port:
The provider port. If not specified, the default port for the
schema will be used.
path:
The provider context path. If not specified, the root path will
be used.
If a non-root path is used, the path given here will be
prepended to the path in the interaction. For example, if the
path is `/api`, and the interaction path is `/users`, the
request will be made to `/api/users`.
"""
if url is not None:
if any(param is not None for param in (scheme, host, port, path)):
msg = "Cannot specify both `url` and individual parameters"
raise ValueError(msg)
url = URL(url)
scheme = url.scheme
host = url.host
port = url.explicit_port
path = url.path
if port is None:
msg = "Unable to determine default port for scheme {scheme}"
raise ValueError(msg)
pact.v3.ffi.verifier_set_provider_info(
self._handle,
name,
scheme,
host,
port,
path,
)
return self
url = URL.build(
scheme=scheme or "http",
host=host or "localhost",
port=port,
path=path or "",
)
return self.set_info(name, url=url)
def add_transport(
self,
*,
protocol: str,
port: int | None = None,
path: str | None = None,
scheme: str | None = None,
) -> Self:
"""
Add a provider transport method.
If the provider supports multiple transport methods, or non-HTTP(S)
methods, this method allows these additional transport methods to be
added. It can be called multiple times to add multiple transport methods.
As some transport methods may not use ports, paths or schemes, these
parameters are optional.
Args:
protocol:
The protocol to use. This will typically be one of:
- `http` for communications over HTTP(S). Note that when
setting up the provider information in
[`set_provider_info`][pact.v3.verifier.Verifier.set_provider_info],
a HTTP transport method is always added and it is unlikely
that an additional HTTP transport method will be needed
unless the provider is running on additional ports.
- `message` for non-plugin synchronous message-based
communications.
Any other protocol will be treated as a custom protocol and will
be handled by a plugin.
port:
The provider port.
If the protocol does not use ports, this parameter should be
`None`. If not specified, the default port for the scheme will
be used (provided the scheme is known).
path:
The provider context path.
For protocols which do not use paths, this parameter should be
`None`.
For protocols which do use paths, this parameter should be
specified to avoid any ambiguity, though if left unspecified,
the root path will be used.
If a non-root path is used, the path given here will be
prepended to the path in the interaction. For example, if the
path is `/api`, and the interaction path is `/users`, the
request will be made to `/api/users`.
scheme:
The provider scheme, if applicable to the protocol.
This is typically only used for the `http` protocol, where this
value can either be `http` (the default) or `https`.
"""
if port is None and scheme:
if scheme.lower() == "http":
port = 80
elif scheme.lower() == "https":
port = 443
pact.v3.ffi.verifier_add_provider_transport(
self._handle,
protocol,
port or 0,
path,
scheme,
)
return self
def filter(
self,
description: str | None = None,
*,
state: str | None = None,
no_state: bool = False,
) -> Self:
"""
Set the filter for the interactions.
This method can be used to filter interactions based on their
description and state. Repeated calls to this method will replace the
previous filter.
Args:
description:
The interaction description. This should be a regular
expression. If unspecified, no filtering will be done based on
the description.
state:
The interaction state. This should be a regular expression. If
unspecified, no filtering will be done based on the state.
no_state:
Whether to include interactions with no state.
"""
pact.v3.ffi.verifier_set_filter_info(
self._handle,
description,
state,
filter_no_state=no_state,
)
return self
def set_state(
self,
url: str | URL,
*,
teardown: bool = False,
body: bool = False,
) -> Self:
"""
Set the provider state URL.
The URL is used when the provider's internal state needs to be changed.
For example, a consumer might have an interaction that requires a
specific user to be present in the database. The provider state URL is
used to change the provider's internal state to include the required
user.
Args:
url:
The URL to which a `POST` request will be made to change the
provider's internal state.
teardown:
Whether to teardown the provider state after an interaction is
validated.
body:
Whether to include the state change request in the body (`True`)
or in the query string (`False`).
"""
pact.v3.ffi.verifier_set_provider_state(
self._handle,
url if isinstance(url, str) else str(url),
teardown=teardown,
body=body,
)
return self
def disable_ssl_verification(self) -> Self:
"""
Disable SSL verification.
"""
self._disable_ssl_verification = True
pact.v3.ffi.verifier_set_verification_options(
self._handle,
disable_ssl_verification=self._disable_ssl_verification,
request_timeout=self._request_timeout,
)
return self
def set_request_timeout(self, timeout: int) -> Self:
"""
Set the request timeout.
Args:
timeout:
The request timeout in milliseconds.
"""
if timeout < 0:
msg = "Request timeout must be a positive integer"
raise ValueError(msg)
self._request_timeout = timeout
pact.v3.ffi.verifier_set_verification_options(
self._handle,
disable_ssl_verification=self._disable_ssl_verification,
request_timeout=self._request_timeout,
)
return self
def set_coloured_output(self, *, enabled: bool = True) -> Self:
"""
Toggle coloured output.
"""
pact.v3.ffi.verifier_set_coloured_output(self._handle, enabled=enabled)
return self
def set_error_on_empty_pact(self, *, enabled: bool = True) -> Self:
"""
Toggle error on empty pact.
If enabled, a Pact file with no interactions will cause the verifier to
return an error. If disabled, a Pact file with no interactions will be
ignored.
"""
pact.v3.ffi.verifier_set_no_pacts_is_error(self._handle, enabled=enabled)
return self
def set_publish_options(
self,
version: str,
url: str | None = None,
branch: str | None = None,
tags: list[str] | None = None,
) -> Self:
"""
Set options used when publishing results to the Broker.
Args:
version:
The provider version.
url:
URL to the build which ran the verification.
tags:
Collection of tags for the provider.
branch:
Name of the branch used for verification.
"""
pact.v3.ffi.verifier_set_publish_options(
self._handle,
version,
url,
tags or [],
branch,
)
return self
def filter_consumers(self, *filters: str) -> Self:
"""
Filter the consumers.
Args:
filters:
Filters to apply to the consumers.
"""
pact.v3.ffi.verifier_set_consumer_filters(self._handle, filters)
return self
def add_custom_header(self, name: str, value: str) -> Self:
"""
Add a customer header to the request.
These headers are added to every request made to the provider.
Args:
name:
The key of the header.
value:
The value of the header.
"""
pact.v3.ffi.verifier_add_custom_header(self._handle, name, value)
return self
def add_custom_headers(
self,
headers: dict[str, str] | Iterable[tuple[str, str]],
) -> Self:
"""
Add multiple customer headers to the request.
These headers are added to every request made to the provider.
Args:
headers:
The headers to add. This can be a dictionary or an iterable of
key-value pairs. The iterable is preferred as it ensures that
repeated headers are not lost.
"""
if isinstance(headers, dict):
headers = headers.items()
for name, value in headers:
self.add_custom_header(name, value)
return self
@overload
def add_source(
self,
source: str | URL,
*,
username: str | None = None,
password: str | None = None,
) -> Self: ...
@overload
def add_source(self, source: str | URL, *, token: str | None = None) -> Self: ...
@overload
def add_source(self, source: str | Path) -> Self: ...
def add_source(
self,
source: str | Path | URL,
*,
username: str | None = None,
password: str | None = None,
token: str | None = None,
) -> Self:
"""
Adds a source to the verifier.
This will use one or more Pact files as the source of interactions to
verify.
Args:
source:
The source of the interactions. This may be either of the
following:
- A local file path to a Pact file.
- A local file path to a directory containing Pact files.
- A URL to a Pact file.
If using a URL, the `username` and `password` parameters can be
used to provide basic HTTP authentication, or the `token`
parameter can be used to provide bearer token authentication.
The `username` and `password` parameters can also be passed as
part of the URL.
username:
The username to use for basic HTTP authentication. This is only
used when the source is a URL.
password:
The password to use for basic HTTP authentication. This is only
used when the source is a URL.
token:
The token to use for bearer token authentication. This is only
used when the source is a URL. Note that this is mutually
exclusive with `username` and `password`.
"""
if isinstance(source, Path):
return self._add_source_local(source)
if isinstance(source, URL):
if source.scheme == "file":
return self._add_source_local(source.path)
if source.scheme in ("http", "https"):
return self._add_source_remote(
source,
username=username,
password=password,
token=token,
)
msg = f"Invalid source scheme: {source.scheme}"
raise ValueError(msg)
# Strings are ambiguous, so we need identify them as either local or
# remote.
if "://" in source:
return self._add_source_remote(
URL(source),
username=username,
password=password,
token=token,
)
return self._add_source_local(source)
def _add_source_local(self, source: str | Path) -> Self:
"""
Adds a local source to the verifier.
This will use one or more Pact files as the source of interactions to
verify.
Args:
source:
The source of the interactions. This may be either of the
following:
- A local file path to a Pact file.
- A local file path to a directory containing Pact files.
"""
source = Path(source)
if source.is_dir():
pact.v3.ffi.verifier_add_directory_source(self._handle, str(source))
return self
if source.is_file():
pact.v3.ffi.verifier_add_file_source(self._handle, str(source))
return self
msg = f"Invalid source: {source}"
raise ValueError(msg)
def _add_source_remote(
self,
url: str | URL,
*,
username: str | None = None,
password: str | None = None,
token: str | None = None,
) -> Self:
"""
Add a remote source to the verifier.
This will use a Pact file accessible over HTTP or HTTPS as the source of
interactions to verify.
Args:
url:
The source of the interactions. This must be a URL to a Pact
file. The URL may contain a username and password for basic HTTP
authentication.
username:
The username to use for basic HTTP authentication. If the source
is a URL containing a username, this parameter must be `None`.
password:
The password to use for basic HTTP authentication. If the source
is a URL containing a password, this parameter must be `None`.
token:
The token to use for bearer token authentication. This is
mutually exclusive with `username` and `password` (whether they
be specified through arguments, or embedded in the URL).
"""
url = URL(url)
if url.user and username:
msg = "Cannot specify both `username` and a username in the URL"
raise ValueError(msg)
username = url.user or username
if url.password and password:
msg = "Cannot specify both `password` and a password in the URL"
raise ValueError(msg)
password = url.password or password
if token and (username or password):
msg = "Cannot specify both `token` and `username`/`password`"
raise ValueError(msg)
pact.v3.ffi.verifier_url_source(
self._handle,
str(url.with_user(None).with_password(None)),
username,
password,
token,
)
return self
@overload
def broker_source(
self,
url: str | URL,
*,
username: str | None = None,
password: str | None = None,
selector: Literal[False] = False,
) -> Self: ...
@overload
def broker_source(
self,
url: str | URL,
*,
token: str | None = None,
selector: Literal[False] = False,
) -> Self: ...
@overload
def broker_source(
self,
url: str | URL,
*,
username: str | None = None,
password: str | None = None,
selector: Literal[True],
) -> BrokerSelectorBuilder: ...
@overload
def broker_source(
self,
url: str | URL,
*,
token: str | None = None,
selector: Literal[True],
) -> BrokerSelectorBuilder: ...
def broker_source( # noqa: PLR0913
self,
url: str | URL,
*,
username: str | None = None,
password: str | None = None,
token: str | None = None,
selector: bool = False,
) -> BrokerSelectorBuilder | Self:
"""
Adds a broker source to the verifier.
Args:
url:
The broker URL. TThe URL may contain a username and password for
basic HTTP authentication.
username:
The username to use for basic HTTP authentication. If the source
is a URL containing a username, this parameter must be `None`.
password:
The password to use for basic HTTP authentication. If the source
is a URL containing a password, this parameter must be `None`.
token:
The token to use for bearer token authentication. This is
mutually exclusive with `username` and `password` (whether they
be specified through arguments, or embedded in the URL).
selector:
Whether to return a BrokerSelectorBuilder instance.
"""
url = URL(url)
if url.user and username:
msg = "Cannot specify both `username` and a username in the URL"
raise ValueError(msg)
username = url.user or username
if url.password and password:
msg = "Cannot specify both `password` and a password in the URL"
raise ValueError(msg)
password = url.password or password
if token and (username or password):
msg = "Cannot specify both `token` and `username`/`password`"
raise ValueError(msg)
if selector:
return BrokerSelectorBuilder(
self,
str(url.with_user(None).with_password(None)),
username,
password,
token,
)
pact.v3.ffi.verifier_broker_source(
self._handle,
str(url.with_user(None).with_password(None)),
username,
password,
token,
)
return self
def verify(self) -> Self:
"""
Verify the interactions.
Returns:
Whether the interactions were verified successfully.
"""
pact.v3.ffi.verifier_execute(self._handle)
return self
@property
def logs(self) -> str:
"""
Get the logs.
"""
return pact.v3.ffi.verifier_logs(self._handle)
@classmethod
def logs_for_provider(cls, provider: str) -> str:
"""
Get the logs for a provider.
"""
return pact.v3.ffi.verifier_logs_for_provider(provider)
def output(self, *, strip_ansi: bool = False) -> str:
"""
Get the output.
"""
return pact.v3.ffi.verifier_output(self._handle, strip_ansi=strip_ansi)
@property
def results(self) -> dict[str, Any]:
"""
Get the results.
"""
return json.loads(pact.v3.ffi.verifier_json(self._handle))
class BrokerSelectorBuilder:
"""
A Broker selector.
This class encapsulates the logic for selecting Pacts from a Pact broker.
"""
def __init__( # noqa: PLR0913
self,
verifier: Verifier,
url: str,
username: str | None,
password: str | None,
token: str | None,
) -> None:
"""
Instantiate a new Broker Selector.
This constructor should not be called directly. Instead, use the
`broker_source` method of the `Verifier` class with `selector=True`.
"""
self._verifier = verifier
self._url = url
self._username = username
self._password = password
self._token = token
# If the instance is dropped without having the `build()` method called,
# raise a warning.
self._built = False
self._include_pending: bool = False
"Whether to include pending Pacts."
self._include_wip_since: date | None = None
"Whether to include work in progress Pacts since a given date."
self._provider_tags: list[str] | None = None
"List of provider tags to match."
self._provider_branch: str | None = None
"The provider branch."
self._consumer_versions: list[str] | None = None
"List of consumer version regex patterns."
self._consumer_tags: list[str] | None = None
"List of consumer tags to match."
def include_pending(self) -> Self:
"""
Include pending Pacts.
"""
self._include_pending = True
return self
def exclude_pending(self) -> Self:
"""
Exclude pending Pacts.
"""
self._include_pending = False
return self
def include_wip_since(self, d: str | date) -> Self:
"""
Include work in progress Pacts since a given date.
"""
if isinstance(d, str):
d = date.fromisoformat(d)
self._include_wip_since = d
return self
def exclude_wip(self) -> Self:
"""
Exclude work in progress Pacts.
"""
self._include_wip_since = None
return self
def provider_tags(self, *tags: str) -> Self:
"""
Set the provider tags.
"""
self._provider_tags = list(tags)
return self
def provider_branch(self, branch: str) -> Self:
"""
Set the provider branch.
"""
self._provider_branch = branch
return self
def consumer_versions(self, *versions: str) -> Self:
"""
Set the consumer versions.
"""
self._consumer_versions = list(versions)
return self
def consumer_tags(self, *tags: str) -> Self:
"""
Set the consumer tags.
"""
self._consumer_tags = list(tags)
return self
def build(self) -> Verifier:
"""
Build the Broker Selector.
Returns:
The Verifier instance with the broker source added.
"""
pact.v3.ffi.verifier_broker_source_with_selectors(
self._verifier._handle, # noqa: SLF001
self._url,
self._username,
self._password,
self._token,
self._include_pending,
self._include_wip_since,
self._provider_tags or [],
self._provider_branch,
self._consumer_versions or [],
self._consumer_tags or [],
)
self._built = True
return self._verifier
def __del__(self) -> None:
"""
Destructor for the Broker Selector.
This destructor will raise a warning if the instance is dropped without
having the [`build()`][pact.v3.verifier.BrokerSelectorBuilder.build]
method called.
"""
if not self._built:
msg = "BrokerSelectorBuilder was dropped before being built."
raise Warning(msg)