【Python】pact-python模块进行契约测试

2023-11-10 18:52

本文主要是介绍【Python】pact-python模块进行契约测试,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Pact是一个契约测试框架,有多种语言实现,本文主要介绍模块pact-python进行契约测。
官网:https://docs.pact.io/implementation_guides/python/readme

安装命令:pip install pact-python  
安装过程中如果报错,安装失败,需要进如pact包下载官网,找到对应的ZIP包自行下载,
https://github.com/pact-foundation/pact-ruby-standalone/releases 
放到pact\bin目录下,再重新用命令pip install pact-python  安装

此外需要安装另外两个依赖包:pip install requests 和pip install Flask

Step 1: 写一个 customer:customer_success.py

import requestsheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0',"Content-Type": "application/json",
}
data={"data": {"transactionType": "C",  # "brnNo": "9998199930",   #"taxInvoiceNumber": "202106161221150000000001", "supplierBrnNo":"9998199954","creationDate": "20210616",     #"taxInvoiceType": "11",  # "supplyPrice": 75000000000,     #"taxAmount": 320000000,         # "buyerBrnNo": "9998199916",# 非必填"mainItems": "전산장비","remark1": "하드웨어 10종","remark2": "소프트웨어 30종","supplierCmpName": "서울데이터시스템","buyerCmpName": "종각은행"},"header": {"chanlId": "IDC","grpId": "GROUPID001","messageTimeStamp": '2021-05-17T20:00:20.123Z',"trackingId": "ABC123DEF456"}
}
url = 'http://127.0.0.1:8080'def OLTP_inquiry():api = '/api/v2/coperator/taxInvoice'f_url = url + apiprint("请求接口:",f_url)json_data = dataprint("请求参数:",json_data)resp = requests.post(f_url, json=json_data,headers=headers)print("响应参数:",resp.json())if __name__ == '__main__':OLTP_inquiry()


Step 2: 写一个 customer:customer_error.py

import requestsheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0',"Content-Type": "application/json",
}
data={"data": {"transactionType": "C",  # C-create,目前只支持C"brnNo": "9998199930",   # BRN"taxInvoiceNumber": "202106161221150000000000",  # BRN"supplierBrnNo":"9998199954","creationDate": "20210616",     #"taxInvoiceType": "11",  # 11-Electronic Tax Invoice,21-Electronic Tax Invoice(Exempt from taxation),31-Electronic Tax Invoice(Customs)"supplyPrice": 75000000000,     # Supply Price in KRW"taxAmount": 320000000,         # Tax Amount in KRW"buyerBrnNo": "9998199916",# 非必填"mainItems": "전산장비","remark1": "하드웨어 10종","remark2": "소프트웨어 30종","supplierCmpName": "서울데이터시스템","buyerCmpName": "종각은행"},"header": {"chanlId": "IDC","grpId": "GROUPID001","messageTimeStamp": '2021-05-17T20:00:20.123Z',"trackingId": "ABC123DEF456"}
}
url = 'http://127.0.0.1:8080'def OLTP_inquiry_error():api = '/api/v2/coperator/taxInvoice'f_url = url + apiprint("请求接口:",f_url)json_data = dataprint("请求参数:",json_data)resp = requests.post(f_url, json=json_data,headers=headers)print("响应参数:",resp.json())if __name__ == '__main__':OLTP_inquiry_error()


Step 3: 写一个 provider:oltp_service.py

from flask import Flask,request
app = Flask(__name__)@app.route('/api/v2/coperator/taxInvoice',methods=["POST"])
def create_tax_invoice():resp_success  ={"result": {"trackingId": "test","messageTimeStamp": "2021-06-16T15:45:59.123Z","chanlId": "IDC","grpId": "group id"},"data": {"ackSignal": "0"}}resp_error ={"result": {"trackingId": "test","messageTimeStamp": "2021-06-16T15:45:59.123Z","chanlId": "IDC","grpId": "group id"},"data": {},"error": {"code": "1234modulenm","description": "사업자번호가 존재 하지 않습니다.","descriptionKr": "Not Exist Business Registration Number"}}data = request.get_json()print(data)resp_success['result'] = data['header']resp_error['result'] = data['header']tax_no = data['data']['taxInvoiceNumber']if tax_no[-1:]=='0':return resp_errorelse:return resp_successif __name__ == '__main__':app.run(port=8080)


Step 4: 获取预期结果
先运行oltp_service.py文件启动provider服务,然后分别运行customer_success.py和customer_error.py
最终得到正常类和异常类两种预期结果。
Step 5: 写一个正常类和一个错误类案例
根据上面两个预期结果编写两个对应的测试用例
正常类测试用例:invoice_tax_pact.py

import atexit
import requests
import unittest
from pact.consumer import Consumer
from pact.provider import Provider
from pact import Like# 定义一个pact,消费者是ModuleB,生产者是ModuleA,契约文件存放在pacts文件夹下
pact = Consumer('customer_success').has_pact_with(Provider('oltp_service'), pact_dir='../pacts')
# 启动服务
pact.start_service()
atexit.register(pact.stop_service)# 测试用例
class UserTesting(unittest.TestCase):def test_service(self):post_data = {"data": {"transactionType": "C","brnNo": "9998199930","taxInvoiceNumber": "202106161221150000000001","supplierBrnNo": "9998199954","creationDate": "20210616",  #"taxInvoiceType": "11","supplyPrice": 75000000000,"taxAmount": 320000000,"buyerBrnNo": "9998199916","mainItems": "전산장비","remark1": "하드웨어 10종","remark2": "소프트웨어 30종","supplierCmpName": "서울데이터시스템","buyerCmpName": "종각은행"},"header": {"chanlId": "IDC","grpId": "GROUPID001","messageTimeStamp": '2021-05-17T20:00:20.123Z',"trackingId": "ABC123DEF456"}}# 消费者定义的期望结果expected = {"result": {"trackingId": "test","messageTimeStamp": "2021-06-16T15:45:59.123Z","chanlId": "IDC","grpId": "group id"},"data": {"ackSignal": "0"}}# 消费者定义的契约的实际内容。包括请求参数、请求方法、请求头、响应值等(pact.given('test service.').upon_receiving('post request for oltp_service').with_request(method='post', path='/api/v2/coperator/taxInvoice',body=post_data,headers={'Content-Type': 'application/json'})# 具体校验内容.will_respond_with(200, body={'data': {"ackSignal": "0"},"result": {"trackingId": Like('hello world'),  # string类型"chanlId": "IDC","grpId": "GROUPID001"},}))# pact自带一个mock服务,端口 1234,用requests向mock接口发送请求,验证mock的结果是否正确with pact:res = requests.post("http://localhost:1234/api/v2/coperator/taxInvoice",json=post_data).json()self.assertEqual(res['data'], expected['data'])if __name__ == "__main__":ut = UserTesting()ut.test_service()


Step 5: 运行测试案例获取契约文件
运行上面的invoice_tax_pact.py文件后,会在对应pacts目录生成契约文件
Step 6: 运行服务和测试案例
先启动第三步创建的服务oltp_service.py
然后打开终端,进入契约文件目录,运行命令
pact-verifier --provider-base-url=http://127.0.0.1:8080 --pact-url=customer_success-oltp_service.json

这篇关于【Python】pact-python模块进行契约测试的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/384625

相关文章

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

Python Websockets库的使用指南

《PythonWebsockets库的使用指南》pythonwebsockets库是一个用于创建WebSocket服务器和客户端的Python库,它提供了一种简单的方式来实现实时通信,支持异步和同步... 目录一、WebSocket 简介二、python 的 websockets 库安装三、完整代码示例1.

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

Python使用自带的base64库进行base64编码和解码

《Python使用自带的base64库进行base64编码和解码》在Python中,处理数据的编码和解码是数据传输和存储中非常普遍的需求,其中,Base64是一种常用的编码方案,本文我将详细介绍如何使... 目录引言使用python的base64库进行编码和解码编码函数解码函数Base64编码的应用场景注意

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

Java进行文件格式校验的方案详解

《Java进行文件格式校验的方案详解》这篇文章主要为大家详细介绍了Java中进行文件格式校验的相关方案,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、背景异常现象原因排查用户的无心之过二、解决方案Magandroidic Number判断主流检测库对比Tika的使用区分zip

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3