契约:尝试设置模拟提供程序时出错

时间:2020-09-24 12:40:18

标签: pact pytest-mock

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

enter code here    

 Blog.ImageIndex = "images.jpg";
                    if (Blog != null)
                    {
                        Blog.ImageIndex = Guid.NewGuid().ToString() + Path.GetExtension(imageblog.FileName);
                        imageblog.SaveAs(Server.MapPath("/Images/ProductImages/" + Blog.ImageIndex));
                        ImageResizer img = new ImageResizer();
                        img.Resize(Server.MapPath("/Images/ProductImages/" + Blog.ImageIndex),
                            Server.MapPath("/Images/ProductImages/Thumb/" + Blog.ImageIndex));
                    }

stacktrace 中的错误:

AttributeError:模块“ pact”没有属性“ Like”

1 个答案:

答案 0 :(得分:0)

能否请您确认您使用的是https://github.com/pact-foundation/pact-python/中的pact-python(而不是pactman,这不是Pact Foundation维护的项目)?

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

这是一个示例项目,您可以参考: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'