介绍 wrapture

Simon Willison's Blog 工具

摘要

介绍 wrapture,一个全新的 Python 库,用于 monkeypatching、测试和追踪,支持 OpenTelemetry,并且其开发完全由 AI 辅助。

暂无内容
查看原文
查看缓存全文

缓存时间: 2026/09/01 13:10

# 介绍 wrapture 来源:https://simonwillison.net/2026/Aug/31/introducing-wrapture/ **介绍 wrapture(https://grahamdumpleton.me/posts/2026/08/introducing-wrapture/)**。这是 Graham Dumpleton(来自 wrapt(https://pypi.org/project/wrapt/)、mod_wsgi 和 New Relic 的 Python agent 系列)的新作,他将 Wrapture 描述为从 wrapt 中借鉴了猴子补丁(monkeypatching)的理念,并将其扩展到同时应用于测试与追踪。 Wrapture(完整文档见此处(https://wrapture.readthedocs.io/))使得包装任何函数或方法变得非常简单,可以追踪其所有访问,或者覆盖其返回值。 它既可以作为 `unittest.mock` 的替代品,也可以用于对现有项目实现追踪: > 对无法控制的代码附加观察,记录流经其中的数据,并且在此过程中不干扰被观察的程序——这是我从未真正停止思考的问题。 Wrapture 包含 OpenTelemetry 支持(https://wrapture.readthedocs.io/en/latest/otel-export.html),甚至提供了一种完全基于配置的机制来为现有的 Python 项目添加追踪,配置示例如下: ``` capture = "summary" [[observe]] target = "domain:Calculator" name = ["outer", "inner"] [[sink]] type = "jsonlines" path = "trace.jsonl" ``` 这仍然是一个非常年轻的项目——才几周大——但其起步非常有前途。 有趣的是,这也是 Graham 首次尝试打造一个完全由智能体驱动的大型项目: > wrapture 中的每一行代码和文档都是由人工智能助手在我的指导下编写的。我对此开诚布公,也同样坦诚地说明它不是什么。这不是那种“氛围编码”——即一次提示生成一堆代码,驱动者因为缺乏判断能力而只能寄希望于结果。“氛围编码”已声名狼藉。我从一开始就精心设计了 wrapture。我在这个 Python 的特定领域深耕多年,完全清楚最终成果应该是什么,人工智能只是实现它的工具,而非设计的源头。 在后续文章《使用 wrapture 进行单元测试》(https://grahamdumpleton.me/posts/2026/09/unit-testing-with-wrapture/)中,Graham 展示了这个新库支持的测试模式: ``` def test_stub_with_wrapture(): with wrapture.binding( Gateway, "charge" ).on_call.returns({ "id": "stub", "amount": 0} ): assert OrderService().place( 500 )["id"] == "stub" ``` 以及这个巧妙的测试示例,它调用原始方法后修改其返回值: ``` def test_pinned_result_with_wrapture(): charge = wrapture.binding( Gateway, "charge" ) charge.on_call.transforms_result( lambda r: {**r, "id": "ch_TEST"} ) with charge: assert OrderService().place( 500 ) == { "id": "ch_TEST", "amount": 500 } ``` (在这两个示例中,`OrderService().place(...)` 方法都调用了 `Gateway().charge(...)`。)

相似文章