如何为Chef Nginx Cookbook中的编译命令编写测试?
嘿,我明白你在Chef测试里遇到的难题了——针对bash资源里的编译命令写测试确实有点棘手,毕竟不像Chef原生资源那样有现成的匹配器。这里有几个实用的思路,帮你验证./autogen.sh、./configure --enable-standalone-module和make install这些命令是否正确执行:
1. 验证命令执行的痕迹(文件生成)
bash命令执行后通常会留下可追踪的文件,你可以通过检查这些文件的存在性来间接验证命令是否成功:
- 针对
./autogen.sh:这个脚本通常会生成或更新configure脚本、aclocal.m4这类自动构建相关文件。你可以测试这些文件是否在编译目录下生成:# ChefSpec示例 it 'generates configure script via autogen.sh' do expect(chef_run.file("#{modsec_compile_path}/configure")).to exist end - 针对
./configure:执行configure后会生成Makefile、config.log或config.h文件。你可以检查这些文件是否存在,甚至验证配置参数是否正确传入:# 验证configure参数是否正确写入Makefile it 'uses the standalone module flag in configure' do expect(chef_run.file("#{modsec_compile_path}/Makefile").content).to match(/--enable-standalone-module/) end
2. 验证make install的实际结果
make install的核心是把编译好的文件复制到系统路径,直接检查这些目标文件的存在性是最直接的验证方式:
# 检查ModSecurity模块是否安装到Nginx模块目录 it 'installs modsecurity module to nginx modules dir' do expect(chef_run.file('/usr/lib/nginx/modules/mod_security2.so')).to exist end # 或者检查头文件/库文件的安装 it 'installs modsecurity header files' do expect(chef_run.file('/usr/include/modsecurity/modsecurity.h')).to exist end
3. 用ChefSpec直接匹配bash资源的代码内容
如果只是想验证bash资源里包含了目标命令(而不关心实际执行结果),可以直接检查code片段:
it 'includes all required compilation commands' do bash_resource = chef_run.bash('compile_modsecurity') expect(bash_resource.code).to include('./autogen.sh') expect(bash_resource.code).to include('./configure --enable-standalone-module') expect(bash_resource.code).to include('make install') end
4. 集成测试层面的验证(InSpec)
比起单元测试的ChefSpec,用InSpec做端到端测试能更真实地验证编译安装的效果:
# InSpec示例 describe file('/usr/lib/nginx/modules/mod_security2.so') do it { should exist } it { should be_file } end # 验证Nginx是否能识别模块(如果已经配置加载的话) describe command('nginx -V 2>&1') do its('stdout') { should match(/modsecurity/) } end
小提示
- 如果你的编译目录是临时路径(比如
/tmp下的目录),记得在测试环境中保留这个路径,或者指定固定的编译目录方便测试。 - 确保测试环境预装了autotools(
autoconf、automake等),否则./autogen.sh会执行失败,影响测试结果。
内容的提问来源于stack exchange,提问作者user9753902
相关产品推荐
相关产品推荐

