Wing SDK 数学模块实战:math.combinations 组合数计算与 Hangar 快照验证
Wing SDK 数学模块实战:math.combinations 组合数计算与 Hangar 快照验证
math.combinations(n, r) 是 Wing 标准库数学模块(@winglang/sdk)提供的组合数计算函数,用于计算从 n 个元素中选取 r 个元素的不同组合数量。本文以仓库中真实的 SDK 测试用例 combinations.test.w 及其 Hangar 快照 combinations.test.w_test_sim.md 为主线,讲解该函数的数学语义、底层实现原理、preflight 与 inflight 双阶段使用方式,以及 Wing 官方测试框架 Hangar 如何对该功能进行自动化验证。读完本文,你将掌握 math.combinations 的完整用法,并理解 Wing SDK 测试快照的生成与解读方法。
一、测试用例全景:组合数在 Wing 中的真实用法
仓库中的 SDK 测试用例 tests/sdk_tests/math/combinations.test.w 是 math.combinations 最直接的使用范例,全文如下:
bring math;
let population = 5;
let subset = 3;
assert(math.combinations(population, subset) == 10);
test "inflight combinations" {
assert(math.combinations(population, subset) == 10);
}
这个测试用例展示了两个关键事实:
- 组合数的数学含义:
math.combinations(5, 3)计算从 5 个元素中选取 3 个元素的组合数,根据组合公式C(5,3) = 5! / (3! * 2!) = 120 / (6 * 2) = 10,结果恰为 10,与断言完全一致; - 双阶段可调用:该函数既可以在 preflight(预飞,即基础设施定义阶段)中直接调用(文件顶部的
assert(...)),也可以在 inflight(飞行中,即运行时阶段)中通过test块调用(test "inflight combinations" { ... })。这正是 Wing 语言"统一编程模型"的体现——同一个数学函数在基础设施编排阶段与业务运行阶段均可使用。
二、底层实现原理:基于阶乘的组合数公式
math.combinations 的实现位于 packages/@winglang/sdk/src/math/math.ts,源码如下:
/**
* Calculates the number of combinations for choosing r items from a total of n items.
* @param n - The total number of items.
* @param r - The number of items to be chosen.
*/
public static combinations(n: number, r: number): number {
if (r > n) {
return 0;
}
const numerator = this.factorial(n);
const denominator = this.factorial(r) * this.factorial(n - r);
return numerator / denominator;
}
实现要点:
- 边界保护:当选取数量
r大于总数n时,直接返回0。从组合数学的角度看,从n个元素中选取r > n个元素不存在任何合法组合,返回 0 是正确语义; - 公式实现:组合数
C(n, r) = n! / (r! * (n - r)!),源码中的numerator与denominator正是该公式的分子与分母; - 依赖阶乘函数:组合数计算依赖同模块的
math.factorial。factorial的实现同样位于 math.ts,采用经典递归写法:
public static factorial(n: number): number {
if (n === 0 || n === 1) {
return 1;
}
return n * this.factorial(n - 1);
}
值得说明的是,math.factorial 自身在仓库中有独立的测试用例 tests/sdk_tests/math/factorial.test.w,覆盖了 0! 到 5! 的取值(1, 1, 2, 6, 24, 120),同样以 preflight assert 加 inflight test 块的双阶段形式验证,是理解组合数计算正确性的底层支撑。
组合数的数值特性与适用前提
从源码结构可以推断,当前实现属于直接基于阶乘的朴素实现:当 n 较大时,n! 会以超指数速度增长,可能超出 num(浮点数)的精确表示范围。因此该实现更适合组合数规模适中的场景(如 C(5,3) 这类小规模计算);对于超大 n 的场景,需要考虑基于乘除累积或查表的优化算法。这一点在官方文档中未做额外承诺,属于实现层面的客观特性。
三、Hangar 快照解析:test_sim 与 compile_tf-aws 双视角
Hangar 是 Wing 工具链的官方端到端测试套件(见 tools/hangar/README.md),它会为每个 SDK 测试用例自动生成两类 Markdown 快照:compile_tf-aws(编译目标快照)与 test_sim(模拟器运行快照)。本次关联文档 combinations.test.w_test_sim.md 正是后者,内容如下:
# <a href="https://link.gitcode.com/i/028e3e0813c20dca1d873fd4a866fe5d" target="_blank">combinations.test.w</a> | test | sim
## stdout.log
```log
pass ─ combinations.test.wsim » root/Default/test:inflight combinations
Tests 1 passed (1)
Snapshots 1 skipped
Test Files 1 passed (1)
Duration <DURATION>
快照解读要点:
- **标题语义**:`| test | sim` 表明这是 `wing test -t sim`(sim 模拟器目标)的测试运行快照;标题中指向 <a href="https://link.gitcode.com/i/bbd2615d06e1867cfab8e845fbdc227b" target="_blank">tests/sdk_tests/math/combinations.test.w</a> 的相对链接,正是前文分析的测试用例文件;
- **运行结果**:`pass ─ combinations.test.wsim » root/Default/test:inflight combinations` 表示名为 `inflight combinations` 的测试在模拟器中执行通过,作用域路径为 `root/Default/test:inflight combinations`;
- **统计信息**:`Tests 1 passed (1)` 表明 1 个测试全部通过,`Duration <DURATION>` 是 Hangar 对输出中运行时长的**统一脱敏占位符**(见下文"快照稳定性机制"),并非真实值。
与此对应,编译快照 <a href="https://link.gitcode.com/i/7cbc9084ae83de25aa06b0f724956b86" target="_blank">combinations.test.w_compile_tf-aws.md</a> 则记录了 `wing compile -t tf-aws` 的产物 `main.tf.json`——由于本用例只包含数学计算与断言、不涉及任何云资源,生成的 Terraform 模板中仅有一个空的 `aws` provider 配置,没有任何 `resource` 条目。这从侧面印证:`math.combinations` 是纯函数式计算,不产生基础设施副作用。
### 快照稳定性机制:Duration 为何是 `<DURATION>`
Hangar 在生成快照前会对命令输出进行脱敏处理,相关实现位于 <a href="https://link.gitcode.com/i/a142fa79820b75e5253b3dbe368408e5" target="_blank">tools/hangar/src/utils.ts</a> 的 `sanitizeOutput` 函数。它对输出依次执行多种规范化与脱敏替换,包括:
- 统一换行符、规范化 Windows 路径分隔符;
- 移除 Rust 源码中的行列号(替换为 `LINE:COL`);
- 移除绝对堆栈路径、绝对路径与随机状态文件引用;
- 将 `Duration 0m10.5s` 一类的测试耗时替换为 `Duration <DURATION>`(这正是快照中该占位符的来源);
- 将端口号、带端口的 IP、时间戳等易变内容替换为 `<PORT>`、`<IP>:<PORT>`、`<TIMESTAMP>` 等占位符。
这套脱敏机制保证了快照在不同机器、不同时间重复运行时保持一致,使快照对比具备确定性——这也是本次快照中看不到具体耗时数字的原因。
## 四、快照背后的测试链路:从 `.w` 源文件到快照文件
了解 Hangar 如何从测试源文件生成快照,有助于准确解读 `combinations.test.w_test_sim.md` 的来龙去脉。其核心链路如下:
1. **测试发现与代码生成**:<a href="https://link.gitcode.com/i/e6fc8e9d8a6aab5c890df16a84dce78b" target="_blank">tools/hangar/src/generate_tests.ts</a> 会递归扫描 `tests/sdk_tests` 目录下的所有 `.w` 文件(`generateTests({ sourceDir: sdkTestsDir, ... })`),为每个文件生成对应的 Vitest 测试脚本。每个 `.w` 文件会生成两个测试用例:`wing compile -t tf-aws`(调用 `compileTest`)与 `wing test -t sim`(调用 `testTest`);
2. **实际执行**:<a href="https://link.gitcode.com/i/64b98634a6b85d6d7157e758b6e81b2e" target="_blank">tools/hangar/src/generated_test_targets.ts</a> 中的 `compileTest` 与 `testTest` 通过 `runWingCommand`(见 <a href="https://link.gitcode.com/i/f049cfb41440d68284dc70a762d7178b" target="_blank">utils.ts</a>)调用 `wing` 二进制,分别以 `-t tf-aws` 与 `-t sim` 平台参数执行编译与测试;
3. **快照写入**:执行结果(stdout/stderr 或 `main.tf.json` 等产物文件)经脱敏后,由 `createMarkdownSnapshot`(<a href="https://link.gitcode.com/i/790859aa8c76307fd9a00cb2678a4f4c" target="_blank">utils.ts</a>)写入 `tools/hangar/__snapshots__/test_corpus/` 对应目录,文件命名规则为 `<wingFile>_<testCase>_<target>.md`——例如 `combinations.test.w_test_sim.md` 即 `combinations.test.w` + `test` + `sim` 的组合;
4. **跳过机制**:如需跳过某测试,可在 `.w` 源文件头部通过 YAML 格式的特殊注释控制(`skip`、`skipPlatforms`、`env`、`args` 等,见 <a href="https://link.gitcode.com/i/b2fdd8d676f52ae3ff960b14673506ca" target="_blank">tools/hangar/src/meta_comment.ts</a>)。`combinations.test.w` 未包含此类注释,因此默认全量执行。
## 五、实战:如何在本仓库中亲自运行验证
若想亲自复现该快照结果,可按以下步骤在本仓库环境下操作:
### 运行 sim 目标测试
在包含 `combinations.test.w` 的目录下执行:
```bash
wing test -t sim combinations.test.w
预期输出与快照中的 stdout.log 一致:pass ─ combinations.test.wsim » root/Default/test:inflight combinations,并显示 Tests 1 passed (1)。
运行 tf-aws 编译
wing compile -t tf-aws combinations.test.w
产物位于 target/ 目录下的 main.tf.json,内容应与编译快照 combinations.test.w_compile_tf-aws.md 中展示的 Terraform 模板一致(仅含空 aws provider,无资源定义)。
运行完整 Hangar 套件
如需执行 Hangar 对 sdk_tests 目录的完整验证,可参考 tools/hangar/src/generate_tests.ts 的生成逻辑运行对应测试入口;由于 Hangar 依赖仓库构建出的 wing 二进制与 SDK 依赖,建议遵循 docs/contributing/01-start-here/05-development.md 中的开发环境搭建流程后执行。
六、横向参考:math 模块中的关联函数
math.combinations 并非孤立存在,它所在的 Util 工具类(见 packages/@winglang/sdk/src/math/math.ts)还提供了与之密切相关的数学函数,完整 API 清单见官方文档 docs/api/04-standard-library/math/api-reference.md:
| 函数 | 说明 | 与 combinations 的关系 |
|---|---|---|
math.factorial(n) |
计算 n 的阶乘 | combinations 的直接依赖,两者测试模式相同 |
math.isPrime(n) |
判断素数 | 同属数论类函数,测试用例为 prime.test.w |
math.fibonacci(n) |
计算第 n 个斐波那契数 | 同为递归实现的数值函数 |
math.round(value, options?) |
四舍五入,支持 RoundingOptions.decimalPlaces |
与组合数的浮点结果配合使用的常见取舍工具 |
math.min/max/median/mode |
数组统计函数 | 组合数结果常用于统计场景 |
所有函数均支持 preflight 与 inflight 双阶段调用,这也是 tests/sdk_tests/math/ 目录下 33 个测试用例的统一模式——每个用例都在文件顶部用 assert 做 preflight 验证,再用 test "inflight ..." 块做 inflight 验证,对应的 Hangar 快照则分 compile_tf-aws 与 test_sim 两种形态归档于 tools/hangar/snapshots/test_corpus/sdk_tests/math/。
结语
math.combinations 是 Wing 标准库数学模块中"小而完整"的代表:它以标准的阶乘公式实现组合数计算,正确处理了 r > n 的边界语义,并且凭借 Wing 统一的执行模型,同一份代码可在 preflight 与 inflight 两个阶段运行。而 combinations.test.w 与其对应的 Hangar 快照(test_sim 与 compile_tf-aws 两种形态)则完整演示了 Wing 官方"测试用例 + 脱敏快照 + 确定性对比"的质量保障链路。理解这条链路,既能掌握 math.combinations 的正确用法,也能举一反三地读懂仓库中数百份 Hangar 快照的生成逻辑与解读方法。