Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# pact-python specific ignores
e2e/pacts
userserviceclient-userservice.json
detectcontentlambda-contentprovider.json
pact/bin

# Byte-compiled / optimized / DLL files
Expand Down
6 changes: 2 additions & 4 deletions examples/message/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class MessageHandler(object):
```

Below is a snippet from a test where the message handler has no error.
Since the expected event contains a key `documentType` with value `microsoft-word`, message handler does not throw an error and a pact file `f"pacts/{expected_json}"` is expected to be generated.
Since the expected event contains a key `documentType` with value `microsoft-word`, message handler does not throw an error and a pact file `f"{PACT_FILE}""` is expected to be generated.

```python
def test_generate_new_pact_file(pact):
Expand Down Expand Up @@ -69,7 +69,7 @@ def test_generate_new_pact_file(pact):
assert isfile(f"{PACT_FILE}") == 1
```

For a similar test where the event does not contain a key `documentType` with value `microsoft-word`, a `CustomError` is generated and there there is no generated json file `f"pacts/{expected_json}"`.
For a similar test where the event does not contain a key `documentType` with value `microsoft-word`, a `CustomError` is generated and there there is no generated json file `f"{PACT_FILE}"`.

```python
def test_throw_exception_handler(pact):
Expand Down Expand Up @@ -97,8 +97,6 @@ def test_throw_exception_handler(pact):
assert isfile(f"{PACT_FILE}") == 0
```

Otherwise, no pact file is generated.

## Provider

Note: The current example only tests the consumer side.
Expand Down
64 changes: 34 additions & 30 deletions examples/message/tests/consumer/test_message_consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,17 @@
PACT_BROKER_URL = "http://localhost"
PACT_BROKER_USERNAME = "pactbroker"
PACT_BROKER_PASSWORD = "pactbroker"
PACT_DIR = 'pacts'
PACT_DIR = "pacts"

CONSUMER_NAME = 'DetectContentLambda'
PROVIDER_NAME = 'ContentProvider'
PACT_FILE = (f"{PACT_DIR}/{CONSUMER_NAME.lower().replace(' ', '_')}_message-"
+ f"{PROVIDER_NAME.lower().replace(' ', '_')}_message.json")
CONSUMER_NAME = "DetectContentLambda"
PROVIDER_NAME = "ContentProvider"
PACT_FILE = (f"{PACT_DIR}/{CONSUMER_NAME.lower().replace(' ', '_')}-"
+ f"{PROVIDER_NAME.lower().replace(' ', '_')}.json")

@pytest.fixture(scope='session')

@pytest.fixture(scope="session")
def pact(request):
version = request.config.getoption('--publish-pact')
version = request.config.getoption("--publish-pact")
publish = True if version else False

pact = MessageConsumer(CONSUMER_NAME, version=version).has_pact_with(
Expand Down Expand Up @@ -54,57 +55,59 @@ def progressive_delay(file, time_to_wait=10, second_interval=0.5, verbose=False)
time.sleep(second_interval)
time_counter += 1
if verbose:
print(f'Trying for {time_counter*second_interval} seconds')
print(f"Trying for {time_counter*second_interval} seconds")
if time_counter > time_to_wait:
if verbose:
print(f'Already waited {time_counter*second_interval} seconds')
print(f"Already waited {time_counter*second_interval} seconds")
break


def test_throw_exception_handler(pact):
cleanup_json(PACT_FILE)

wrong_event = {
'documentName': 'spreadsheet.xls',
'creator': 'WI',
'documentType': 'microsoft-excel'
"event": "ObjectCreated:Put",
"documentName": "spreadsheet.xls",
"creator": "WI",
"documentType": "microsoft-excel"
}

(pact
.given('Another document in Document Service')
.expects_to_receive('Description')
.given("Document unsupported type")
.expects_to_receive("Description")
.with_content(wrong_event)
.with_metadata({
'Content-Type': 'application/json'
"Content-Type": "application/json"
}))

with pytest.raises(CustomError):
with pact:
# handler needs 'documentType' == 'microsoft-word'
# handler needs "documentType" == "microsoft-word"
MessageHandler(wrong_event)

progressive_delay(f"{PACT_FILE}")
assert isfile(f"{PACT_FILE}") == 0


def test_generate_new_pact_file(pact):
def test_put_file(pact):
cleanup_json(PACT_FILE)

expected_event = {
'documentName': 'document.doc',
'creator': 'TP',
'documentType': 'microsoft-word'
"event": "ObjectCreated:Put",
"documentName": "document.doc",
"creator": "TP",
"documentType": "microsoft-word"
}

(pact
.given('A document create in Document Service')
.expects_to_receive('Description')
.given("A document created successfully")
.expects_to_receive("Description")
.with_content(expected_event)
.with_metadata({
'Content-Type': 'application/json'
"Content-Type": "application/json"
}))

with pact:
# handler needs 'documentType' == 'microsoft-word'
MessageHandler(expected_event)

progressive_delay(f"{PACT_FILE}")
Expand All @@ -121,17 +124,18 @@ def test_publish_to_broker(pact):
`pytest tests/consumer/test_message_consumer.py::test_publish_pact_to_broker --publish-pact 2`
"""
expected_event = {
'documentName': 'document.doc',
'creator': 'TP',
'documentType': 'microsoft-word'
"event": "ObjectCreated:Delete",
"documentName": "document.doc",
"creator": "TP",
"documentType": "microsoft-word"
}

(pact
.given('A document create in Document Service with broker')
.expects_to_receive('Description with broker')
.given("A document deleted successfully")
.expects_to_receive("Description with broker")
.with_content(expected_event)
.with_metadata({
'Content-Type': 'application/json'
"Content-Type": "application/json"
}))

with pact:
Expand Down
Empty file.
51 changes: 51 additions & 0 deletions examples/message/tests/provider/test_message_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import pytest
from pact import MessageProvider


def document_created_handler():
return {
"event": "ObjectCreated:Put",
"documentName": "document.doc",
"creator": "TP",
"documentType": "microsoft-word"
}


def document_deleted_handler():
return {
"event": "ObjectCreated:Delete",
"documentName": "document.doc",
"creator": "TP",
"documentType": "microsoft-word"
}


def test_verify_success():
provider = MessageProvider(
message_providers={
'A document created successfully': document_created_handler,
'A document deleted successfully': document_deleted_handler
},
provider='ContentProvider',
consumer='DetectContentLambda',
pact_dir='pacts'

)
with provider:
provider.verify()


def test_verify_failure_when_a_provider_missing():
provider = MessageProvider(
message_providers={
'A document created successfully': document_created_handler,
},
provider='ContentProvider',
consumer='DetectContentLambda',
pact_dir='pacts'

)

with pytest.raises(AssertionError):
with provider:
provider.verify()
6 changes: 4 additions & 2 deletions pact/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
from .broker import Broker
from .consumer import Consumer
from .matchers import EachLike, Like, SomethingLike, Term, Format
from .message_pact import MessagePact
from .message_consumer import MessageConsumer
from .message_pact import MessagePact
from .message_provider import MessageProvider
from .pact import Pact
from .provider import Provider
from .verifier import Verifier

from .__version__ import __version__ # noqa: F401

__all__ = ('Broker', 'Consumer', 'EachLike', 'Like', 'MessageConsumer', 'MessagePact',
__all__ = ('Broker', 'Consumer', 'EachLike', 'Like',
'MessageConsumer', 'MessagePact', 'MessageProvider',
'Pact', 'Provider', 'SomethingLike', 'Term', 'Format', 'Verifier')
2 changes: 1 addition & 1 deletion pact/__version__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Pact version info."""

__version__ = '1.3.9'
__version__ = '1.3.0'
4 changes: 2 additions & 2 deletions pact/broker.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def publish(self, consumer_name, version, pact_dir=None,
os.listdir(pact_dir),
self._normalize_consumer_name(consumer_name) + '*.json'
)
pact_files = list(map(lambda pact_file: f'{pact_dir}/{pact_file}', pact_files))
pact_files[0] = f'{pact_dir}/{pact_files[0]}'
command = [
BROKER_CLIENT_PATH,
'publish',
Expand All @@ -85,7 +85,7 @@ def publish(self, consumer_name, version, pact_dir=None,
for tag in consumer_tags:
command.extend(['-t', tag])

print(f"PactBroker command: {command}")
log.debug(f"PactBroker publish command: {command}")

publish_process = Popen(command)
publish_process.wait()
Expand Down
9 changes: 4 additions & 5 deletions pact/consumer.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ def has_pact_with(self, provider, host_name='localhost', port=1234,
cors=False, publish_to_broker=False,
broker_base_url=None, broker_username=None,
broker_password=None, broker_token=None, pact_dir=None,
specification_version='2.0.0',
file_write_mode='overwrite'):
version='2.0.0', file_write_mode='overwrite'):
"""
Create a contract between the `provider` and this consumer.

Expand Down Expand Up @@ -109,8 +108,8 @@ def has_pact_with(self, provider, host_name='localhost', port=1234,
:param pact_dir: Directory where the resulting pact files will be
written. Defaults to the current directory.
:type pact_dir: str
:param specification_version: The Pact Specification version to use.
Defaults to '2.0.0'.
:param version: The Pact Specification version to use, defaults to
'2.0.0'.
:type version: str
:param file_write_mode: How the mock service should apply multiple
calls to .verify(). Pass 'overwrite' to overwrite the generated
Expand Down Expand Up @@ -143,5 +142,5 @@ def has_pact_with(self, provider, host_name='localhost', port=1234,
cors=cors,
pact_dir=pact_dir,
publish_to_broker=publish_to_broker,
specification_version=specification_version,
version=version,
file_write_mode=file_write_mode)
Loading