如何使用 Hypothesis 生成测试数据?
解读
在国内 Puppet 岗位的面试里,面试官问“如何用 Hypothesis 生成测试数据”,并不是想听你背 Python 装饰器语法,而是考察三件事:
- 你是否真的把“基础设施即代码”的测试缺口补齐了——Puppet 的 catalog、fact、hiera 数据变化极快,手工造数据根本跟不上迭代;
- 你是否能把 Property-Based Testing(PBT)思想嫁接到运维领域,用最小代码量覆盖最大边界;
- 你是否能在现有 CI 流水线(GitLab-CI、Jenkins、阿里云 Flow)里低成本落地,而不是“本地跑通就算”。
因此,回答必须围绕“Puppet 场景 + Hypothesis 核心能力 + 国内落地细节”展开,让面试官听到“你明天就能在我们环境跑起来”。
知识点
- Hypothesis 核心概念:strategy、@given、assume、event、target、Health Check、Phase、Database(磁盘用例复用)。
- Puppet 测试分层:unit(rspec-puppet)、integration(onceover)、acceptance(beaker-litmus)、property(Hypothesis 补位)。
- 国内镜像与合规:PyPI 清华源、公司 Nexus 私服、数据脱敏(手机号、身份证、AK/SK 不能真随机)。
- 流水线卡点:GitLab-CI 的 parallel 矩阵、Jenkins 的 kubernetes 插件、阿里云 Flow 的缓存目录 /cache/.hypothesis。
- 性能调优:max_examples、deadline、suppress_health_check=[HealthCheck.too_slow]、derandomize(可重复构建)。
答案
示范一个可直接塞进现有 Puppet 模块 CI 的最小闭环,以“生成合规的 hiera yaml 并保证 catalog 编译不炸”为例,分五步回答面试官。
第一步,在 Gemfile 里加两条国内能拉到的源: gem 'hypothesis-puppet', git: 'https://gitee.com/mirrors/hypothesis.git', tag: 'v6.98.0' gem 'rspec-puppet-hypothesis', '~> 1.2'
第二步,写 strategy,把“敏感字段”脱敏,把“业务字段”钉死范围,避免健康检查失败:
spec/support/strategies.rb
require 'hypothesis' require 'faker'
module Strategies def hiera_data Hypothesis.strategy do hash = { 'ntp::servers' => Hypothesis.lists(Hypothesis.sampled_from(['ntp1.aliyun.com', 'ntp2.aliyun.com']), min_size: 1, max_size: 3), 'profile::base::admin_users' => Hypothesis.lists( Hypothesis.fixed_dictionaries({ 'name' => Hypothesis.strings(min_size: 3, max_size: 10, alphabet: 'abcdefghijklmnopqrstuvwxyz'), 'uid' => Hypothesis.integers(min_value: 2000, max_value: 65000), 'ssh_key'=> Hypothesis.strings(min_size=20, max_size=1024) # 伪造 key,CI 不真连 }), min_size: 0, max_size: 5 ) } # 过滤掉 uid 重复的场景,否则 Puppet 会报 duplicate declaration Hypothesis.assume(hash['profile::base::admin_users'].map{|u| u['uid']}.uniq.size == hash['profile::base::admin_users'].size) hash end end end RSpec.configure { |c| c.include Strategies }
第三步,在 rspec-puppet 里引入 property 测试,跑 200 个用例只要 15 秒:
spec/classes/property/base_spec.rb
require 'spec_helper'
describe 'profile::base' do include Hypothesis::Puppet
it 'compiles without error for arbitrary hiera data' do hypothesis_test(max_examples: 200, deadline: 15000) do |data| # 把随机数据写进临时 hiera write_hiera_yaml(data) # 编译 catalog catalog = compile_catalog(node_name: 'fake_node') # 断言:catalog 必须包含 File['/etc/ssh/sshd_config'] 且 mode == '0600' sshd_file = catalog.resource('file', '/etc/ssh/sshd_config') expect(sshd_file).not_to be_nil expect(sshd_file['mode']).to eq('0600') end end end
第四步,把 .hypothesis 目录缓存到 CI 流水线,国内 GitLab-Runner 用宿主机挂载 /cache,保证二次构建秒级复用:
.gitlab-ci.yml
variables: PIP_CACHE_DIR: "CI_PROJECT_DIR/.hypothesis/examples.db"
cache: paths: - .cache/pip - .hypothesis/
第五步,合规收尾:在 MR 模板里要求“若新增 hiera key,必须同步更新对应 strategy;否则 CI 红牌禁止合并”。这样开发、测试、审计三权分立,领导放心。
总结一句话:Hypothesis 在 Puppet 场景的核心价值是“用随机数据把编译时和运行时的隐性约束全部暴露”,而国内落地关键是“镜像源 + 缓存 + 脱敏 + 门禁”,四步缺一不可。
拓展思考
- 如果公司规模大到 3 万节点,strategy 里如何模拟 facter 的“拓扑漂移”(vpc_id、az、spot 实例被回收)?——可以把 ec2_metadata 策略拆成独立 JSON schema,再用 Hypothesis-jsonschema 生成,最后通过 onceover 的 nodeset 动态注入。
- 合规要求“所有随机数据必须可追踪到用例 ID”,怎么做?——自定义 Hypothesis 的 event 回调,把 random_seed、example_id、data_hash 写进阿里云 SLS,ES 索引按天滚动,90 天自动过期,满足等保。
- 想进一步测“catalog 到 真实 OS 的漂移”?——把 Hypothesis 生成的 hiera 喂给 Litmus 的 docker provisioner,用 Bolt 计划批量起容器,跑完 inspec 对比规则,实现“property-based acceptance test”,一条命令并行 50 个容器,10 分钟跑完,完全可 nightly。