Serverspec(Specinfra)にcheck_is_installed_by_pip2を実装しました


TL;DR

serverspecでは、pip2コマンドでモジュールをチェックする機能が実装されていないので、独自でリソースを実装し、以下のように利用できるようにする。

describe package(module_name) do
  it { should be_installed.by('pip2') }
  it { should be_installed.by('pip2').with_version(version) }
end

追記

check_is_installed_by_pip2を実装して、SpecinfraのGitHubにPull requestを出したらマージされたので、独自実装する必要がなくなりました。
https://github.com/mizzy/specinfra/pull/688

経緯

serverspecで、pip2, pip3のモジュールをそれぞれチェックしたかった。
チェック対象のサーバーは、pippip3コマンドではpip3が呼ばれ、pip2コマンドではpip2が呼ばれるようにしている。

しかし、serverspecでは、以下のように、pip、pip3コマンドでのチェックしかできない。

# check_is_installed_by_pip
it { should be_installed.by('pip') }
# check_is_installed_by_pip3
it { should be_installed.by('pip3') }

理由は、specinfraでは、check_is_installed_by_pipcheck_is_installed_by_pip3しか用意されていないからだ。

これではpip2のチェックができない。

そこで、check_is_installed_by_pip2を独自で用意し、serverspecで以下のように定義できるようにする。

it { should be_installed.by('pip2') }

独自リソースを作成する

packageリソースを拡張するため、check_is_installed_by_pip2を定義する。

参考:specinfra/lib/specinfra/command/base/package.rb

check_is_installed_by_pip2を定義

以下のファイルにcheck_is_installed_by_pip2を定義する。
spec/lib/extension/specinfra/command/base/package.rb

spec/lib/extension/specinfra/command/base/package.rb
class Specinfra::Command::Base::Package < Specinfra::Command::Base
  class << self
    def check_is_installed_by_pip2(name, version=nil)
      regexp = "^#{name}"
      cmd = "pip2 freeze | grep -iw -- #{escape(regexp)}"
      cmd = "#{cmd} | grep -w -- #{escape(version)}" if version
      cmd
    end
  end
end

spec/lib以下のファイルがautoloadされるようにする

spec/libの*.rbのファイルがautoloadされるように、以下の一行をspec/spec_helper.rbに追加する。

spec/spec_helper.rb
Dir[File.expand_path "#{__dir__}/lib/**/*.rb"].each{|f| require(f)}

specファイルで呼び出す

be_installed.by('pip2')とすることで、check_is_installed_by_pip2が呼び出される。

spec/sample/sample_spec.rb
require 'spec_helper'

describe package('boto3') do
  it { should be_installed.by('pip2') }
  it { should be_installed.by('pip2').with_version('1.9.156') }
end

追記

check_is_installed_by_pip2を実装して、SpecinfraのGitHubにPull requestを出したらマージされたので、独自実装する必要がなくなりました。
https://github.com/mizzy/specinfra/pull/688

参考にしたserverspec, specinfraのファイル

その他参考記事