Skip to content

Instantly share code, notes, and snippets.

@hartror
Last active August 29, 2015 14:09
Show Gist options
  • Save hartror/5beea8e46c7b5283a37d to your computer and use it in GitHub Desktop.
Save hartror/5beea8e46c7b5283a37d to your computer and use it in GitHub Desktop.
import pytest
import pypact
# 1. Start with your model
class Something(object):
def __init__(self, name):
self.name = name
def __eq__(self, other):
return isinstance(other, self.__class__) and self.name == other.name
# 2. Create a skeleton client class
class MyServiceProviderClient(object):
def __init__(self, base_uri):
self.base_uri = base_uri
def get_something(self):
# Yet to be implemented because we're doing Test First Development...
pass
# 3. Configure the mock server
@pytest.fixture(scope="session")
def my_consumer(request):
consumer = pypact.Consumer("My Service Consumer")
@pytest.fixture(scope="session")
def my_service_provider(consumer):
return pypact.Service("My Service Provider")
# 4. Write a failing spec for the client
@pytest.fixture
def subject(my_service_provider):
subject = MyServiceProviderClient(my_service_provider.base_uri)
return subject
@pytest.fixture
def mock_service(request, my_consumer, my_service_provider):
return my_consumer.has_pact_with(my_service_provider)
def test_returns_something(subject, mock_service):
"""
Subject returns a Something
"""
(mock_service
.given("something exists")
.upon_receiving("a request for something")
.with_request(method="get", path="/something")
.will_respond_with(
status=200,
headers={'Content=Type': 'application/json'},
body={'name': 'A small something'}))
with mock_service:
something = subject.get_something()
assert something == Something(name='A small something')
@bethesque
Copy link

  (mock_service
        .given("a something exists")
        .upon_receiving("a request for something")
        .with_request(method="get", path="/something")
        .will_respond_with(
            status=200,
            headers={'Content=Type': 'application/json'},
            body={'rel': 'http://localhost:1234:/something/child'}))
        .given("something has a child")
        .upon_receiving("a request for something")
        .with_request(method="get", path="/something/child")
        .will_respond_with(
            status=200,
            headers={'Content=Type': 'application/json'},
            body={'name': 'A small something'}))

@thetrav
Copy link

thetrav commented Nov 15, 2014

I also assume you're not running tests in parallel, otherwise the subject probably shouldn't be a fixture

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment