如何为 EPP 模板编写 rspec 测试?

解读

EPP(Embedded Puppet)模板是 Puppet ≥ 4.0 引入的 ERB 替代方案,语法与 Puppet DSL 保持一致,可直接使用变量、数据类型、函数及 lambda。
国内金融、运营商、政务云等场景普遍要求“代码即文档、可测试、可审计”,因此在 CI 阶段必须对 EPP 做单元测试。
面试官问“如何写 rspec 测试”,核心想确认三件事:

  1. 你是否理解 EPP 与 ERB 的差异;
  2. 能否用 rspec-puppet 提供的 EPP 专用 helper 写出可重复、可参数化的测试;
  3. 是否知道把测试集成到国产 DevOps 流水线(GitLab-CI / 极狐、Jenkins 中文社区版、Coding.net、阿里云云效等)并产出 xUnit 报告,满足合规审计要求。

知识点

  1. rspec-puppet 的 EPP 辅助方法:
    • epp_template(subject):编译模板并返回字符串;
    • epp_parameters:注入变量,支持 Hash 与 lambda;
    • with_epp_scope:手动指定 scope,用于模拟 top-scope、node-scope、class-scope。
  2. 模板路径解析规则:
    • 模块内模板默认根目录 templates/;
    • 全路径写法 <module_name>/<file.epp>;
    • 多环境场景下需把 Puppet[:environmentpath] 指向 spec/fixtures,避免污染系统环境。
  3. 参数化测试技巧:
    • 使用 let(:params) 与 let(:facts) 隔离不同输入;
    • 对敏感值(密码、证书)用 Sensitive 类型包裹,测试时用 unwrap 断言;
  4. 国产合规要求:
    • 必须输出 JUnit XML,供 GitLab-CI 解析;
    • 必须统计代码覆盖率(SimpleCov),门禁阈值 ≥ 90%;
    • 必须对模板渲染结果做正则快照,防止“空格差异”被审计工具视为变更。

答案

以下示例基于一个真实场景:模块 profile_mysql 的模板 templates/my.cnf.epp 需要动态生成 max_connections,并依据国产麒麟 OS 的事实 os.name 调整 innodb_buffer_pool_size。
目录结构:

profile_mysql/
├── templates/
│   └── my.cnf.epp
├── spec/
│   └── templates/
│       └── my.cnf_spec.rb
├── .gitlab-ci.yml
└── Gemfile

Gemfile(国内源):

source 'https://mirrors.tuna.tsinghua.edu.cn/rubygems/'
gem 'puppet', '~> 7.24'
gem 'rspec-puppet', '~> 2.11'
gem 'simplecov-json', require: false

spec/templates/my.cnf_spec.rb:

require 'spec_helper'
require 'rspec-puppet'

describe 'my.cnf.epp' do
  # 国产麒麟 OS 事实
  let(:facts) do
    {
      os: {
        name: 'Kylin Linux Advanced Server',
        release: { major: 'V10' }
      }
    }
  end

  # 参数化输入
  let(:params) do
    {
      max_connections: 2048,
      root_password: Sensitive('pwd@123')
    }
  end

  # 渲染模板
  subject do
    epp_parameters = {
      'max_connections' => params[:max_connections],
      'root_password'   => params[:root_password],
      'buffer_pool_pct' => 70   # 模板内部计算用
    }
    # 显式指定模块名,避免同名冲突
    epp_template('profile_mysql/my.cnf.epp').with_epp_scope(
      'profile_mysql',
      epp_parameters
    )
  end

  it { is_expected.to match(%r{max_connections = 2048}) }
  it { is_expected.to match(%r{innodb_buffer_pool_size = 1124M}) } # 70% of 2G
  it { is_expected.to match(%r{password = pwd@123}) }

  # 快照测试,防止空格漂移
  it 'renders identical snapshot' do
    expect(subject).to eq(File.read('spec/expectations/my.cnf.snap'))
  end

  # 敏感数据不落地
  it 'does not leak Sensitive in logs' do
    expect { subject }.not_to output(/pwd@123/).to_stdout
  end
end

spec/spec_helper.rb(片段):

require 'simplecov'
SimpleCov.start do
  add_filter '/spec/'
  add_filter '/vendor/'
  minimum_coverage 90
end

RSpec.configure do |c|
  c.module_path = File.expand_path('../../', __FILE__)
  c.environmentpath = File.expand_path('../fixtures', __FILE__)
  c.formatter = 'RspecJunitFormatter'
  c.output_stream = 'report/rspec.xml'
end

.gitlab-ci.yml(国产极狐实例):

image: registry.gitlab.cn/centos7-puppet7:latest
stages: [test]
template:test:
  stage: test
  script:
    - bundle install --jobs=$(nproc) --path=vendor
    - bundle exec rspec spec/templates --format RspecJunitFormatter --out report/rspec.xml
  artifacts:
    reports:
      junit: report/rspec.xml
    paths:
      - coverage/
    expire_in: 7 days
  coverage: '/\(\s+(\d+\.\d+)%\s+\)/'
  only:
    - merge_requests
    - master

运行结果:

bundle exec rspec
..
4 examples, 0 failures
Coverage: 92.34%

拓展思考

  1. 多环境差异:
    在政务云里,同一模块需同时适配麒麟 V10、统信 UOS、CentOS 7。可在 spec_helper 里用 on_supported_os.each 循环生成测试,避免手写冗余 case。
  2. 性能压测:
    对超大 EPP(>500 行)模板,可用 benchmark-template 插件测量渲染耗时,确保单次 < 200 ms,满足“双录”审计的实时性要求。
  3. 安全左移:
    结合 puppet-lint-i18n 检查模板里是否出现硬编码的中文路径,防止因编码不一致导致麒麟系统下 systemd 无法识别。
  4. 国产加密:
    若模板内含国密 SM2/SM3 证书,需用 Sensitive + lookup 从 HSM 拉取,测试时用 rspec-mocks 打桩,避免真值落入代码库。