1

我正在尝试使用pytest编写我的第一个 Pact-python 测试,有人可以告诉我我的代码有什么问题吗?

import unittest

import requests

import json

import pytest

import atexit

from pact import Consumer, Provider

pact = Consumer('Consumer').has_pact_with(Provider('Provider'), host_name='mockservice', port=8080)
pact.start_service()
atexit.register(pact.stop_service)

class InterviewDetails(unittest.TestCase):

    def test_candidate_report_api(self):
        candidate_report_payload = {}
        resp = requests.post("http://localhost:1234/users/",data=json.dumps(candidate_report_payload))
        response = json.loads(resp.text)
        return response

    @pytest.mark.health1
    def test_candidate_report(self):
        expected = {}
        (pact.given('Comment')
         .upon_receiving('comment')
         .with_request(method='POST', path="http://localhost:1234/users/", headers={})
         .will_respond_with(200, body=expected))
        with pact:
            pact.setup()
            result = self.test_candidate_report_api()
            self.assertEqual(result, expected)
            pact.verify()

来自堆栈跟踪的错误:

AttributeError:模块 'pact' 没有属性 'Like'

4

1 回答 1

0

您能否确认您使用pact-python的是https://github.com/pact-foundation/pact-python/(而不是 pactman,不是由 Pact 基金会维护的项目)?

这可能与您设置测试的方式有关?

这是一个可以用作参考的示例项目:https ://github.com/pactflow/example-consumer-python/

相关测试代码:

"""pact test for product service client"""

import json
import logging
import os
import requests
from requests.auth import HTTPBasicAuth

import pytest
from pact import Consumer, Like, Provider, Term, Format

from src.consumer import ProductConsumer

log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
print(Format().__dict__)

PACT_MOCK_HOST = 'localhost'
PACT_MOCK_PORT = 1234
PACT_DIR = os.path.dirname(os.path.realpath(__file__))


@pytest.fixture
def consumer():
    return ProductConsumer(
        'http://{host}:{port}'
        .format(host=PACT_MOCK_HOST, port=PACT_MOCK_PORT)
    )


@pytest.fixture(scope='session')
def pact(request):
    pact = Consumer('pactflow-example-consumer-python').has_pact_with(
        Provider('pactflow-example-provider-python'), 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 test_get_product(pact, consumer):
    expected = {
        'id': "27",
        'name': 'Margharita',
        'type': 'Pizza'
    }

    (pact
     .given('a product with ID 10 exists')
     .upon_receiving('a request to get a product')
     .with_request('GET', '/product/10')
     .will_respond_with(200, body=Like(expected)))

    with pact:
        user = consumer.get_product('10')
        assert user.name == 'Margharita'
于 2020-09-25T01:10:01.987 回答