# -3.50 的退款通过了所有测试，结果却是错的

> Hypothesis 能生成数百行订单，但只有对照独立计算而不是靠往返测试，bug 才会暴露。

原文: https://fdetimes.net/zh/guides/hypothesis-property-testing-customer-data-parser/

设想客户发来一个订单文件，其中有一行退款写的是 `-3.50`，你的解析器却把它读成 -2.50。手写的测试通过了，往返测试也通过了。直到月底客户的会计对账，这个 bug 才暴露出来。

客户数据解析器看起来简单，实际需要的测试比外表复杂得多。你可能只凭几份样例文件就写出了它，但之后它每个月都要处理你从没见过的数据。

Hypothesis 是一个用于基于属性的测试的 Python 库。你不必事先逐个猜测样例，只需描述一整类场景，让机器去探索各种可能。

下文从头到尾只用一个例子。你会写一个订单行解析器，生成几百行结构化数据，看到一条看似无懈可击的属性如何仍然漏掉 bug，最后把客户真实出错的那一行固定到测试里。

## 开始之前需要准备什么？

需要在 virtualenv 中安装 Python 3、pytest 和 Hypothesis（通常是 `pip install hypothesis pytest`）。本文的数据格式是假设的：每行包含订单 ID、日期和金额，用分号分隔，例如 `ORD-00042;2024-03-07;12.50`。代码为演示做了简化，并不是生产环境的解析器。

## 第 1 步：一个看起来正确的解析器

```python
# parser.py — 为演示做了简化
from dataclasses import dataclass

@dataclass
class Order:
    order_id: str
    date: str
    amount_cents: int

def parse_line(line: str) -> Order:
    order_id, date, amount = line.strip().split(";")
    whole, _, frac = amount.partition(".")
    cents = int(whole) * 100 + int((frac + "00")[:2])
    return Order(order_id, date, cents)

def format_line(o: Order) -> str:
    return f"{o.order_id};{o.date};{o.amount_cents // 100}.{o.amount_cents % 100:02d}"
```

输入 `12.50`，函数返回 1250；输入 `12`，返回 1200。针对几行样例写的单元测试都会通过，陷阱恰恰就在这里。

## 第 2 步：用策略而不是样例来描述数据

基于属性的测试中最难的部分是生成复杂输入。Hillel Wayne 指出，PBT 相关文献很少讨论这一部分。

要组合多个策略，可以用 `@composite`：带这个装饰器的函数以 `draw` 作为第一个参数，调用它从各个更小的策略中取值。

每个字段都用 `st.from_regex` 配合 `fullmatch=True` 生成，这样生成的整个字符串都符合模式。

```python
# test_parser.py
from hypothesis import given, settings, strategies as st
from parser import Order, parse_line, format_line

@st.composite
def orders(draw):
    order_id = draw(st.from_regex(r"ORD-[0-9]{5}", fullmatch=True))
    date = draw(st.from_regex(r"20[0-9]{2}-[01][0-9]-[0-3][0-9]", fullmatch=True))
    cents = draw(st.integers(min_value=-10_000_000, max_value=10_000_000))
    return Order(order_id, date, cents)

@settings(max_examples=500)
@given(orders())
def test_round_trip(order):
    assert parse_line(format_line(order)) == order
```

`@given` 装饰器把普通函数变成 Hypothesis 测试。默认每个测试运行 100 个样例，`max_examples=500` 可以提高这个数量。运行 `pytest`，测试通过。

如果想要一个现成的测试骨架来修改，`hypothesis write` 命令（Ghostwriter）可以帮你生成。Ghostwriter 文档称往返是一条非常强的属性，尤其是在配置选项随对象一起变化的时候。

## 第 3 步：解析器明明有错，测试为什么会通过？

让 -250 分走一遍这个循环。Python 的 `//` 向下取整，所以 -250 // 100 得到 -3；而 `%` 的符号跟随除数，所以 -250 % 100 得到 50。结果是 `format_line` 写出 `-3.50`，`parse_line` 再把它读回 -300 + 50 = -250。两个方向错得一模一样，因此结果仍然一致；可在人看来，`-3.50` 表示的是 -350。

**要点:** 往返测试只能证明两个方向彼此一致，不能证明两个方向都正确。

解决办法是增加一条带独立校验的属性：按客户的写法直接生成金额字符串，再把结果与 `Decimal` 对比，这种计算与解析器没有任何共享逻辑：

```python
from decimal import Decimal

@st.composite
def raw_lines(draw):
    order_id = draw(st.from_regex(r"ORD-[0-9]{5}", fullmatch=True))
    date = draw(st.from_regex(r"20[0-9]{2}-[01][0-9]-[0-3][0-9]", fullmatch=True))
    amount = draw(st.from_regex(r"-?[0-9]{1,6}\.[0-9]{2}", fullmatch=True))
    return f"{order_id};{date};{amount}", amount

@settings(max_examples=500)
@given(raw_lines())
def test_amount_matches_decimal(case):
    line, amount = case
    assert parse_line(line).amount_cents == int(Decimal(amount) * 100)
```

这次测试失败了。Hypothesis 会在后台执行“简化”（shrinking）过程，所以你拿到的反例通常是一行金额为小负数的短数据，而不是它最初碰巧找到的那串杂乱字符。看一眼这个反例，就能发现 bug 出在负号上。

## 第 4 步：修复 bug，固定客户的真实数据行

把金额解析拆成一个独立函数，先处理符号；再让 `format_line` 对称：符号单独写，然后格式化绝对值。

```python
def parse_amount(s: str) -> int:
    sign = -1 if s.startswith("-") else 1
    whole, _, frac = s.lstrip("-").partition(".")
    return sign * (int(whole) * 100 + int((frac + "00")[:2]))

def parse_line(line: str) -> Order:
    order_id, date, amount = line.strip().split(";")
    return Order(order_id, date, parse_amount(amount))

def format_line(o: Order) -> str:
    sign = "-" if o.amount_cents < 0 else ""
    a = abs(o.amount_cents)
    return f"{o.order_id};{o.date};{sign}{a // 100}.{a % 100:02d}"
```

手动验算：-250 分现在写成 `-2.50`，`parse_amount("-2.50")` 返回 -(200 + 50) = -250。往返测试和 Decimal 测试现在都应该通过。

接下来，用 `@example` 把客户发来的那行退款放进测试。Hypothesis 总是先运行这些显式声明的输入，再生成随机数据：

```python
from hypothesis import example

@example(("ORD-00042;2024-03-07;-3.50", "-3.50"))
@settings(max_examples=500)
@given(raw_lines())
def test_amount_matches_decimal(case):
    ...
```

从现在起，客户每发来一个出错的文件，都应该留下一行 `@example`。这些用例合起来就是项目的经验清单，它们活在代码里，即使你转去服务别的客户，也依然留在那里。

## 第 5 步：调整运行次数和时间限制

真实的解析器常常调用复杂的正则、查表或做 Unicode 规范化。Hypothesis 默认给每个样例设定 200 毫秒的 deadline，所以慢速解析器即使输出正确，也会被报告为失败。遇到这种情况，应在 `settings` 中有意识地放宽 deadline 并注明原因，而不是为了让问题消失直接关掉它。

Hypothesis 还会把以往失败的样例保存在当前工作目录下的 `.hypothesis/examples` 目录中，并在下次运行时重放。所以如果某个失败出现后又消失了，不要急着断定它是偶发的，先去看看这个目录。

## 最常见的错误有哪些？

最常见的错误是策略比真实数据窄：客户有退款，却只生成正数；客户姓名带声调符号（越南人名就是典型例子），却只生成 ASCII。策略应当以样例文件和从客户那里了解到的信息为依据，而不是以解析器当前能接受什么为依据。

第二个错误是让断言重复解析器自身的逻辑，这正是第 3 步中的往返陷阱。第三个错误是把 Hypothesis 当作单元测试的替代品。Hypothesis 的文档说得很清楚，它是一种补充，客户确认过的业务用例仍然需要写成显式的样例测试。

## 这项技能在客户现场是什么样子？

拿到客户文件的第一天，在写解析器之前，先问那些之后会变成策略中正则的问题：负数怎么写？日期会不会缺少前导零？订单 ID 的前缀会不会变？每个答案都是 `@composite` 中的一行，每个“不确定”都是应该放进策略的用例。

在简历上，用具体成果描述这项技能，而不是只写“Python”。比如“为客户数据解析器编写基于属性的测试，固定了 N 个来自生产环境的故障用例”，这样一行能让招聘方看到你处理过真实数据，旁边还可以附上一个演示仓库。

面试时，复述第 3 步中的往返陷阱，能快速表明你理解一个测试到底证明了什么。

解析器迟早会遇到你没见过的数据。你的工作是确保在客户的会计碰到它之前，先让几百行生成的数据碰到它。

**本周动手试试:**

- 挑一个你维护的 CSV 或日志解析器，写一个生成合法数据行的 @composite 策略，用 max_examples=500 运行。
- 找出三行曾在客户那里导致数据管道出错的数据，用 @example 把它们固定到测试中。
- 为每个现有的往返测试加一条断言，与独立计算的结果对比（Decimal、标准库，或客户确认过的值）。

## 信源

- [What is Hypothesis? (hypothesis.works)](https://hypothesis.works/articles/what-is-hypothesis/)

- [Introduction to Hypothesis (tutorial)](https://hypothesis.readthedocs.io/en/latest/tutorial/introduction.html)

- [Hypothesis API reference](https://hypothesis.readthedocs.io/en/latest/reference/api.html)

- [Hypothesis strategies reference](https://hypothesis.readthedocs.io/en/latest/reference/strategies.html)

- [Hypothesis integrations reference (Ghostwriter)](https://hypothesis.readthedocs.io/en/latest/reference/integrations.html)

- [Property Testing with Complex Inputs (Hillel Wayne)](https://www.hillelwayne.com/post/property-testing-complex-inputs/)
