def __init__(self, service, log_dir='contract_logs/consumer'): config = SERVICES[service] self.pact = Consumer(BASE_CONFIG['consumer']).has_pact_with( Provider(service), host_name=BASE_CONFIG['host'], port=config['port'], pact_dir=BASE_CONFIG['path_to_pacts'], log_dir=log_dir) for interaction in config['interactions']: (self.pact.given(interaction['GIVEN']).upon_receiving( interaction['UPON_RECEIVING']).with_request( **interaction['REQUEST']).will_respond_with( **interaction['RESPONSE']))
def _pact_mock_server(): port = 3141 pact_address = socket.gethostbyname(socket.gethostname()) pact = Consumer('TestConsumer').has_pact_with( Provider('TestProvider'), host_name='0.0.0.0', port=port, log_dir="/app" ) pact.start_service() atexit.register(pact.stop_service) server_address_pair = pact, "http://{}:{}".format(pact_address, port) return server_address_pair
def test_get_user(): pact = Consumer("UserClient").has_pact_with(Provider("UserProvider")) # pact.start_service expected_body = {"email": "admin@localhost", "id": 42, "username": "******"} (pact.given("admin user exists").upon_receiving( "a request for admin user").with_request( "get", "users/admin").will_respond_with(200, Like(expected_body))) with pact: user = consumer.get_user_by_name("admin") assert user.username == "admin" pact.stop_service
class MockApiServer: def __init__(self, service, log_dir='contract_logs/consumer'): config = SERVICES[service] self.pact = Consumer(BASE_CONFIG['consumer']).has_pact_with( Provider(service), host_name=BASE_CONFIG['host'], port=config['port'], pact_dir=BASE_CONFIG['path_to_pacts'], log_dir=log_dir) for interaction in config['interactions']: (self.pact.given(interaction['GIVEN']).upon_receiving( interaction['UPON_RECEIVING']).with_request( **interaction['REQUEST']).will_respond_with( **interaction['RESPONSE'])) def stop(self): self.pact.stop_service() return self def start(self): self.pact.start_service() self.pact.setup() return self def safe_start(self): self.start() atexit.register(self.stop) return self.pact
def pact(request): pact = Consumer('UserServiceClient').has_pact_with( Provider('UserService'), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT, pact_dir=PACT_DIR) pact.start_service() yield pact pact.stop_service() version = request.config.getoption('--publish-pact') if not request.node.testsfailed and version: push_to_broker(version)
def pact(): pact = Consumer(CONSUMER_NAME, tags=['master', 'consumer-py'], version='1.0.0') \ .has_pact_with(Provider(PROVIDER_NAME), # pact_dir=PACT_DIR, //https://github.com/pact-foundation/pact-python/issues/128 version='2.0.0', publish_to_broker=True, broker_base_url=PACT_BROKER_URL) try: pact.start_service() yield pact finally: pact.stop_service()
def pact(request): pact = Consumer('consumer-in-python').has_pact_with( Provider('provider-in-dotnet'), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT, pact_dir="./pacts", log_dir="./logs") try: print('start service') pact.start_service() yield pact finally: print('stop service') pact.stop_service()
def pact(request): version = request.config.getoption('--publish-pact') publish = True if version else False pact = Consumer('UserServiceClient', version=version).has_pact_with( Provider('UserService'), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT, pact_dir=PACT_DIR, publish_to_broker=publish, broker_base_url=PACT_BROKER_URL, broker_username=PACT_BROKER_USERNAME, broker_password=PACT_BROKER_PASSWORD) print('start service') pact.start_service() yield pact print('stop service') pact.stop_service()
def pact(request): pact = Consumer('UserServiceClient').has_pact_with( Provider('UserService'), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT, pact_dir=PACT_DIR, publish_to_broker=False, broker_base_url=PACT_BROKER_URL, broker_username=PACT_BROKER_USERNAME, broker_password=PACT_BROKER_USERNAME) pact.start_service() atexit.register(pact.stop_service) yield pact pact.stop_service() version = request.config.getoption('--publish-pact') if not request.node.testsfailed and version: push_to_broker(version) print('not handcraft')
def pact(request): """Setup a Pact Consumer, which provides the Provider mock service. This will generate and optionally publish Pacts to the Pact Broker""" # When publishing a Pact to the Pact Broker, a version number of the Consumer # is required, to be able to construct the compatability matrix between the # Consumer versions and Provider versions version = request.config.getoption("--publish-pact") publish = True if version else False pact = Consumer("UserServiceClient", version=version).has_pact_with( Provider("UserService"), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT, pact_dir=PACT_DIR, publish_to_broker=publish, broker_base_url=PACT_BROKER_URL, broker_username=PACT_BROKER_USERNAME, broker_password=PACT_BROKER_PASSWORD, ) pact.start_service() # Make sure the Pact mocked provider is stopped when we finish, otherwise # port 1234 may become blocked atexit.register(pact.stop_service) yield pact # This will stop the Pact mock server, and if publish is True, submit Pacts # to the Pact Broker pact.stop_service() # Given we have cleanly stopped the service, we do not want to re-submit the # Pacts to the Pact Broker again atexit, since the Broker may no longer be # available if it has been started using the --run-broker option, as it will # have been torn down at that point pact.publish_to_broker = False
def pact(request): pact = Consumer('PythonConzoomer').has_pact_with( Provider('AccountJSService'), host_name=PROVIDER_HOST, port=PROVIDER_PORT, pact_dir=PACT_DIR) # V: Provider port must align with inner Consumer call setup! (Might be python thing) # V: Therefore I'm pulling definition for local development from Consumer directly try: print('start service') pact.start_service() yield pact finally: print('stop service') pact.stop_service() # version = request.config.getoption('--publish-pact') version = CONSUMER_VERSION # version = False if not request.node.testsfailed and version: push_to_broker(version)
import unittest import atexit from pact import Consumer, Provider from consumer3 import getCustomer pact = Consumer('Consumer 3').has_pact_with(Provider('Provider'), host_name='localhost', port=7070) pact.start_service() atexit.register(pact.stop_service) class GetCustomersContract(unittest.TestCase): def test_get_customer(self): expected = { 'name': 'Alice', 'financialProducts': [{ 'name': 'Share', 'balance': 4, 'productCode': 'ABC1', 'interestRate': 1.2 }, { 'name': 'Bond', 'balance': 5, 'productCode': 'ABC2', 'interestRate': 1.3 }] } (pact.given('customer 1 exists and has financialProducts').
import atexit from mock import patch from unittest import TestCase import requests from pact import Consumer from pact import Provider pact = Consumer('failing-consumer').has_pact_with(Provider('provider'), pact_dir='./pacts', port=1235) pact.start_service() atexit.register(pact.stop_service) class FailingVerification(TestCase): def setUp(self): super(FailingVerification, self).setUp() self.addCleanup(patch.stopall) def test_post_user_wrong_response(self): expected = {'name': 'Robert'} (pact.given('the user Bob is returned instead of Robert'). upon_receiving('a query for the user Robert').with_request( 'post', '/users/', body={ 'kind': 'name' },
import atexit import http import unittest import requests from pact import Consumer, Provider from requests.auth import HTTPBasicAuth from client import get_inventory_details, save_inventory_details pact = Consumer('consumer').has_pact_with(Provider('python-producer'), pact_dir='./pacts') pact.start_service() atexit.register(pact.stop_service) host = 'https://yourpactbroker.domain.com:8443' broker_url = '{host}/pacts/provider/{provider}/consumer/{consumer}/version/{consumerApplicationVersion}'.format(host=host, provider='python-producer', consumer='consumer', consumerApplicationVersion='1.0.0') def _publish_to_broker(pactfile): headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} resp = requests.put(broker_url, data=open(pactfile, 'rb'), headers=headers, auth=HTTPBasicAuth('uname', 'password'), verify=False) if resp.status_code == http.HTTPStatus.OK: print('Template has been published.') else: print('Unable to publish template.') print(resp.status_code) class GetPipelineInfoContract(unittest.TestCase): def test_get_inventory(self): expected = dict(productName="Laptops", locationName="Bangalore", quantity=1000)
import atexit import json import unittest from pact import Consumer, Provider from client.authenthicate import AuthenticateRequest from configurations.consumer_configurations import ConsumerConfig pact = Consumer('consumer_app').has_pact_with(Provider('provider_api'), host_name='localhost', port=9191, pact_dir='./consumer_app_and_api_contracts') pact.start_service() atexit.register(pact.stop_service) class UserContract(unittest.TestCase): def test_admin_user_authentication(self): (pact .given('An administrator user') .upon_receiving('an authentication request') .with_request('post', ConsumerConfig.authenticate['path']) .will_respond_with(status=200, body=ConsumerConfig.authenticate['response_body_matcher']) ) with pact: request = AuthenticateRequest() result = request.authenticate_request("http://localhost:9191") self.assertEqual(result.json(), json.loads('{"token":"edff372c-55de-11e7-907b-a6006ad3dba0"}'))
import atexit import unittest from consumer_app import get_item from pact import Consumer, Provider pact = Consumer('consumer_app').has_pact_with(Provider('provider_app'), port=5000) pact.start_service() atexit.register(pact.stop_service) class GetItemContract(unittest.TestCase): def test_get_item(self): expected = { 'name': 'Strawberries', 'id': 1, 'count': 2, } (pact.given( 'Item exists').upon_receiving('a request for id 1').with_request( 'get', '/provider/api/items/1').will_respond_with(200, body=expected)) with pact: result = get_item('1') self.assertEqual(result, expected)
import atexit import unittest import requests from pact import Consumer, Provider pact = Consumer('Translator').has_pact_with(Provider('Translate Service'), pact_dir='./pacts') pact.start_service() atexit.register(pact.stop_service) class TranslateServiceContract(unittest.TestCase): mock_host = "http://localhost:1234" def _request_helper(self, path): return requests.get(self.mock_host + path) def test_get_translation_existing(self): path = '/translate/1' expected_body = {"en": "one", "de": "eins"} expected_status = 200 (pact.given('translation for number 1').upon_receiving( 'a request to get translation for 1').with_request( 'get', path).will_respond_with(expected_status, body=expected_body)) with pact:
import os import unittest from unittest import mock from pact import Consumer, Provider from main import user PACT_HOST = "localhost" PACT_PORT = 2345 pact = Consumer("MyConsumer").has_pact_with(Provider("MyProvider"), host_name=PACT_HOST, port=PACT_PORT) class GetUserInfoContract(unittest.TestCase): @classmethod def setUpClass(cls): pact.start_service() @classmethod def tearDownClass(cls): pact.stop_service() @mock.patch.dict(os.environ, { "SERVER_HOST": PACT_HOST, "SERVER_PORT": str(PACT_PORT) }) def test_get_user(self): expected = {"username": "******", "id": 123, "groups": ["Editors"]}
import requests import atexit import time import unittest from pact import Consumer, Provider def generation(generation_id): """Fetch a generation by generationid from the server.""" uri = 'http://maxbill-docker03-dc2.maxbilldev.impello.co.uk:13200/maxbill__billing--sensibility-api/v1/sensibility_result?generationId=' + generation_id return requests.get(uri).json() pact = Consumer('Consumer').has_pact_with(Provider('Provider'), pact_dir='./pacts') # pact.start_service() atexit.register(pact.stop_service) class GetUserInfoContract(unittest.TestCase): def test_get_user(self): expected = { 'username': '******', 'id': 123, 'groups': ['Editors'] } (pact .given('UserA exists and is not an administrator') .upon_receiving('a request for UserA') .with_request('get', '/users/UserA') .will_respond_with(200, body=expected))
import atexit import unittest from pact import Consumer, Provider import requests import ipdb from shutil import copy pact = Consumer('My Consumer').has_pact_with( Provider('My Provider') ) #default port of pact-python is 1234, we can change by adding arg port=port# pact.start_service() atexit.register(pact.stop_service) def posts(): """Fetch a user object by user_name from the server.""" uri = 'http://localhost:1234/posts' return requests.get(uri).json() class GetPostsInfo(unittest.TestCase): def test_get_posts(self): expected = { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
import atexit import unittest from pact import Consumer, Provider from consumer import get_user class GetUserInfoContract(unittest.TestCase): def test_get_user(self): expected = { "username": "******", "email": "*****@*****.**" } (pact .given('admin exists and is not an administrator') .upon_receiving('a request for admin') .with_request('get', '/users/1') .will_respond_with(200, body=expected)) with pact: result = get_user(1, 'http://localhost:1234') self.assertEqual(result, expected) #requests.put('http://192.168.99.100/pacts/provider/UsersProvider/consumer/UsersConsumer/latest', ) pact = Consumer('UsersConsumer').has_pact_with(Provider('UsersProvider'), port=1234) pact.start_service() unittest.main() atexit.register(pact.stop_service)
import atexit import unittest from unittest.mock import patch from pact import Consumer, Provider from user import get_user pact = Consumer('LoginService').has_pact_with(Provider('UserService'), host_name='localhost', port=1234, pact_dir='pacts') pact.start_service() atexit.register(pact.stop_service) class TestGetUserInfoContract(unittest.TestCase): def test_get_user(self): expected = {"data": ["User1", 123, "Editor"]} (pact.given('User1 exists and is not an administrator').upon_receiving( 'a request for User1').with_request( 'get', '/users/User1').will_respond_with(200, body=expected)) pact.setup() # Patch USERS_URL so that the service uses the mock server URL instead of the real URL. with patch.dict('user.__dict__', {'USERS_URL': 'http://localhost:1234/users/'}): result = get_user('User1') pact.verify() self.assertEqual(result, expected)
import requests import atexit import unittest from pact import Consumer, Provider def user(user_name): uri = 'http://localhost:1235/users/' + user_name return requests.get(uri).json() pact = Consumer('Consumer').has_pact_with(Provider('Provider'), host_name='localhost', port=1235, pact_dir='/home') pact.start_service() atexit.register(pact.stop_service) class GetUserInfoContract(unittest.TestCase): def test_get_user(self): expected = {'username': '******', 'id': 123, 'groups': ['Editors']} (pact.given("UserA exits and is not an administrator").upon_receiving( 'a requests for UserA').with_request( 'get', '/users/UserA').will_respond_with(200, body=expected)) with pact: result = user('UserA') self.assertEqual(result, expected) if __name__ == '__main__':
import json, requests, atexit, pytest, os from pact import Consumer, Like, Provider, Term, Format, Verifier #initalize pact object be defining the Consumer and Provider objects as well as the pact and log directories pact = Consumer('Problem Service').has_pact_with( Provider('Image Upload Service'), pact_dir="./pacts", log_dir="./logs") #Start pact VM pact.start_service() #Register observer to notify vm to stop when python exits atexit.register(pact.stop_service) def test_get_product(): #Get the expected response from petstore api expected = "eef74ecc-38b9-493f-a854-a65c64846b32" body = files = [('image', ('Capture.PNG', open('../Capture.PNG', 'rb'), 'application/octet-stream'))] #Create pact file given=Description, uponReceiving=the state the provider is in, Request=Expected Request, Response=The expected response (pact.given('the image upload service is available').upon_receiving( 'a successful insert into the problem db').with_request( 'POST', '/image/v1/Problem/1', body).will_respond_with(200, body=expected)) #In the pact context with pact: #create Petstore consumer object and set endpoint to pact VM (defaults to actual if uri not specified) consumer = PetstoreConsumer(uri=pact.uri) print(pact.uri) #call get pet by id 1 pet = consumer.get_pet(1) verifier = Verifier(provider="Petstore Provider Spring",
import atexit import unittest from ..consumer import consumer from pact import Consumer, Provider PACT_MOCK_HOST = "localhost" PACT_MOCK_PORT = "1234" BASE_URL = "http://" + PACT_MOCK_HOST + ":" + PACT_MOCK_PORT pact = Consumer("Consumer").has_pact_with( Provider("Provider"), host_name=PACT_MOCK_HOST, port=PACT_MOCK_PORT, ) pact.start_service() atexit.register(pact.stop_service) class GetUserInfoContract(unittest.TestCase): def test_get_user(self): expected_body = { "email": "userA@localhost", "id": 42, "username": "******" } (pact.given("userA exists in the system").upon_receiving(
import atexit import unittest from pact import Consumer, Provider, Term from .consumer import user pact = Consumer('Consumer').has_pact_with(Provider('Provider')) pact.start_service() atexit.register(pact.stop_service) class GetUserInfoContract(unittest.TestCase): def test_get_user(self): expected = { 'username': '******', 'id': 123, 'groups': ['Editors'], 'last_modified': Term(r'\d+-\d+-\d+T\d+:\d+:\d+', '2016-12-15T20:16:01'), } (pact .given('UserA exists and is not an administrator') .upon_receiving('a request for UserA') .with_request('get', '/users/UserA') .will_respond_with(200, body=expected)) with pact: result = user('UserA') expected_result = expected.copy()
# 将项目路径保存至环境变量 # sys.path.append('/Users/yang/PycharmProjects/Test0402_git') # 必须的操作!否则提示 No module named 'MicroService' ******* sys.path.append(os.getcwd()) # 注意:如果要导入该项目其他模块的包名,应将导入的方法写在上面方法的后面 import atexit # 退出时资源自动释放,一般用来做一些资源清理的操作 from atexit import register # 有时候重启pycharm后会找不到atexit模块,也搜不到,需要重新安装一下register import unittest from pact import Consumer, Provider from MicroService.Contract_test.query import get_cartoon_characters import pytest # 构造pact对象,定义消费者服务的名字并给它绑定一个生产者服务 pact = Consumer('Consumer Miku').has_pact_with( Provider('Provider')) # 为消费者绑定一个生产者,名字可随便取 pact.start_service() # 启动pact服务(Start the external Mock Service.) atexit.register(pact.stop_service) # 注册退出时,关闭pact服务,stop_service不能要括号,固定写法 # pact.stop_service() # 由于atexit经常出错,可以不用 class TestGetMikuInfoContract(): def test_miku(self): # 定义响应的期望结果 expected = { "salary": 45000, "name": "Hatsune Miku", "nationality": "Japan", "contact": { "Email": "*****@*****.**",
import atexit import unittest from pact import Consumer, Provider from consumer.fetcher import Fetcher # Configure your environment variables here: # Note, by default, a mock server will spin up on localhost:1234 BASE_URI = 'http://localhost:1234' LOG_DIR = '../logs/' PACT_DIR = '../pacts/' pact = Consumer('Consumer').has_pact_with(provider=Provider('Provider'), log_dir=LOG_DIR, pact_dir=PACT_DIR) pact.start_service() atexit.register(pact.stop_service) class GetAddContract(unittest.TestCase): @classmethod def setUpClass(self): self.fetcher = Fetcher(BASE_URI) def test_request_add(self): expected = { 'sum': 27, } (pact.upon_receiving('a request to add 20 and 7').with_request( method='get', path='/add',