如何使用Pact测试键为字符串、值为浮点数的字典对象?
问题描述
当前测试代码通过Like({"key": 1.23})定义请求体,当提交{"a different key": 4.56}这类请求时会失败——因为契约强制要求键必须为"key",仅浮点数值可灵活变化。需要修改Pact契约定义,仅校验请求体是键为字符串、值为浮点数的字典,不限制具体键名。
测试代码示例:
def test_case_1(pact, client): ( pact.given("object does not exist") .upon_receiving("a new post request") .with_request( "post", "/url/post/endpoint", body=Like({"key": 1.23}) ) .will_respond_with(200, body={}) ) with pact: client.post(body={"key": 4.56})
解决方案
要实现仅校验字典键值类型的需求,需使用Pact-python的匹配器组合,核心是定义"任意字符串键+浮点数值"的结构:
单键值对场景
如果请求体是单个键值对(键任意、值为浮点数),可以用Term(匹配任意字符串键)结合FloatMatcher(校验浮点数值类型):
from pact import Like, Term, FloatMatcher def test_case_1(pact, client): ( pact.given("object does not exist") .upon_receiving("a new post request") .with_request( "post", "/url/post/endpoint", body=Like({ # 用正则匹配任意字符串键,第二个参数是契约文档的示例键名 Term(".*", "any_string_key"): FloatMatcher(1.23) }) ) .will_respond_with(200, body={}) ) with pact: # 任意字符串键+浮点数值的请求都会通过校验 client.post(body={"a different key": 4.56})
多键值对场景
如果允许请求体包含多个任意键值对,可使用EachLike匹配至少1组(或更多)符合要求的键值结构:
from pact import EachLike, Term, FloatMatcher def test_case_1(pact, client): ( pact.given("object does not exist") .upon_receiving("a new post request") .with_request( "post", "/url/post/endpoint", # 匹配至少1组键为字符串、值为浮点数的键值对 body=EachLike( {Term(".*", "any_string_key"): FloatMatcher(1.23)}, min=1 ) ) .will_respond_with(200, body={}) ) with pact: # 多键值对请求也能通过校验 client.post(body={"key1": 1.23, "key2": 4.56})
关键细节
Term(".*", "any_string_key"):通过正则.*匹配任意字符串类型的键,第二个参数是生成契约文档时展示的示例键名FloatMatcher(1.23):确保请求体对应值为浮点数类型,1.23是契约文档中展示的示例值- 若允许空字典,可将
EachLike的min参数设为0,或直接用Like({})结合类型校验逻辑
内容的提问来源于stack exchange,提问作者Conor
相关产品推荐
相关产品推荐

