Skip to content

版本、契约测试与平台差异:练习答案 ​

练习解答 ​

以下是完整离线文件,保存为answer.py后运行python answer.py;先建立与正文一致的初始状态,再验证变体。

只有产品明确保证每箱固定 10 本、允许改变数量且不会超旧数量范围时,转换才可能成立;不同商品包装不能用全局常数猜测。保守方案继续拒绝 box:

python
def upgrade_v1(v):
    if set(v)!={'quantity'} or type(v['quantity']) is not int:
        raise ValueError('invalid v1')
    return {'version':2,'quantity':v['quantity'],'unit':'book'}
def downgrade_v2(v):
    if v['unit']!='book':raise ValueError('cannot represent v2 unit in v1')
    return {'quantity':v['quantity']}
assert downgrade_v2(upgrade_v1({'quantity':2}))=={'quantity':2}
try:downgrade_v2({'version':2,'quantity':2,'unit':'box'})
except ValueError:pass
else:raise AssertionError('lossy conversion accepted')
print('compatibility passed')

assert downgrade_v2({'version':2,'quantity':2,'unit':'book'})=={'quantity':2}
try:downgrade_v2({'version':2,'quantity':2,'unit':'box'})
except ValueError:pass
else:raise AssertionError('unit silently erased')

此测试防止适配器为了“兼容成功率”静默丢语义。

用心记录每一步成长