Man*_*r S 0 python-3.x pact pact-python
我是 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)
Run Code Online (Sandbox Code Playgroud)
在这里,我试图点击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
Run Code Online (Sandbox Code Playgroud)
我已经尝试过pact.setup(),pact.verify()但仍然遇到同样的错误。有人可以帮我解决这个问题吗?
它也不会创建 pactfile。我必须设置哪些东西?
断言错误:实际交互与模拟 MockService 的预期交互不匹配。
^ 此错误表示协议模拟未收到协议测试中描述的交互。
E Missing requests:
E GET /posts/1
Run Code Online (Sandbox Code Playgroud)
^这部分说,模拟未收到GET的请求/posts/1。如果模拟服务器收到了其他请求(例如POST它不期望的请求),它们也会在此处列出。
因此,我们知道在测试期间没有请求命中模拟服务器。
阅读测试类的其余部分,我们有:
with pact:
result = requests.get('https://jsonplaceholder.typicode.com/posts/1')
Run Code Online (Sandbox Code Playgroud)
这表明测试正在击中jsonplaceholder.typicode.com而不是在测试期间设置的模拟。所以,错误是正确的 - 要修复它,我们需要点击模拟服务器:
要解决您的问题,您需要改为联系协议模拟服务器:
with pact:
result = requests.get('https://localhost:1234/posts/1')
Run Code Online (Sandbox Code Playgroud)
(或您配置 Pact 侦听的任何端口)。
您也可以直接从 Pact 获取此信息:
with pact:
result = requests.get(pact.uri + '/posts/1')
Run Code Online (Sandbox Code Playgroud)
您可能会发现此消费者测试图很有用(取自Pact 文档的How Pact Works部分):
您的消费者代码是橙色部分,蓝色部分是 Pact 提供的模拟。
在 Pact 测试期间,消费者不会联系实际的提供者,它只会联系模拟提供者。提供者验证的情况正好相反——只有模拟消费者联系真正的提供者。
这意味着您不需要将使用者和提供者一起启动以进行测试。这一优势是合约测试的一个主要卖点。
| 归档时间: |
|
| 查看次数: |
2898 次 |
| 最近记录: |