我是python和合同测试的新手。我正在尝试使用pact-python
测试我的消费者应用程序。
这是测试文件test_posts_controller.py
import unittest
import atexit
from pact import Consumer, Provider, Term
import requests
pact = Consumer('Consumer').has_pact_with(Provider('Provider'))
pact.start_service()
atexit.register(pact.stop_service)
class GetPostsContract(unittest.TestCase):
def test_get_all_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"
}
(pact
.given('posts exist')
.upon_receiving('a request for post by id')
.with_request('GET', '/posts/1')
.will_respond_with(200, body=expected))
with pact:
result = requests.get('https://jsonplaceholder.typicode.com/posts/1')
self.assertEqual(result.json(), expected)
在这里,我试图击中JSONPlaceholder。
我正在使用pytest
命令来运行测试。
但我得到以下错误。我不知道我错过了什么。
self = <pact.pact.Pact object at 0x10cc8c8d0>
def verify(self):
"""
Have the mock service verify all interactions occurred.
Calls the mock service to verify that all interactions occurred as
expected, and has it write out the contracts to disk.
:raises AssertionError: When not all interactions are found.
"""
self._interactions = []
resp = requests.get(
self.uri + '/interactions/verification',
headers=self.HEADERS)
> assert resp.status_code == 200, resp.text
E AssertionError: Actual interactions do not match expected interactions for mock MockService.
E
E Missing requests:
E GET /posts/1
E
E See pact-mock-service.log for details.
venv/lib/python3.7/site-packages/pact/pact.py:209: AssertionError
我也试过pact.setup()
和pact.verify()
,但我仍然得到同样的错误。有人可以帮我解决这个问题吗?
并且它也不会创建pactfile。我需要设置什么?
AssertionError:实际交互与模拟MockService的预期交互不匹配。
^此错误表示pact mock未收到Pact测试中描述的交互。
E Missing requests:
E GET /posts/1
^这部分说模拟没有收到GET
请求/posts/1
。如果模拟服务器已收到其他请求(例如,它没有预期的POST
),它们也将在此处列出。
因此,我们知道在测试期间没有请求到达模拟服务器。
阅读其他测试课程,我们有:
with pact:
result = requests.get('https://jsonplaceholder.typicode.com/posts/1')
这表明测试是在测试期间击中jsonplaceholder.typicode.com
而不是模拟设置。所以,错误是正确的 - 要修复它我们需要点击模拟服务器:
要修复您的案例,您需要联系pact模拟服务器:
with pact:
result = requests.get('https://localhost:1234/posts/1')
(或者您已配置Pact监听的任何端口)。
您也可以直接从Pact获取:
with pact:
result = requests.get(pact.uri + '/posts/1')
您可能会发现这个消费者测试图很有用(取自Pact文档的How Pact Works部分):
您的消费者代码是橙色部分,蓝色部分是Pact提供的模拟。
在Pact测试期间,消费者不联系实际的提供者,它只联系模拟提供者。对于提供者验证,情况恰恰相反 - 只有模拟消费者才会联系真正的提供者。
这意味着您无需一起启动使用者和提供者以进行测试。这个优势是合同测试的一个主要卖点。
契约告诉你,互动永远不会被触发。你永远不会在pact模拟服务器上调用GET /posts/1
,因此当你尝试验证它时,它会说它缺少交互而不是产生pact文件,因为它失败了。
除非https://jsonplaceholder.typicode.com/posts/1
指向协议模拟服务(我猜它不是),这是行不通的。无论它在哪个端口(它通常在localhost :),都是你需要点击的。
而不是你做的代码,从pact本身获取基URI:
with pact:
result = requests.get(pact.uri + '/posts/1')
self.assertEqual(result.json(), expected)
pact.verify()