瀏覽代碼

adjust mkpasswd function to use plain ruby method, add tests for that function

Marcel Haerry 13 年之前
父節點
當前提交
3d913534ce
共有 4 個文件被更改,包括 68 次插入3 次删除
  1. 5 3
      lib/puppet/parser/functions/mkpasswd.rb
  2. 6 0
      spec/spec.opts
  3. 16 0
      spec/spec_helper.rb
  4. 41 0
      spec/unit/parser/functions/mkpasswd.rb

+ 5 - 3
lib/puppet/parser/functions/mkpasswd.rb

@@ -1,6 +1,8 @@
-# needs an 8-char salt *always*
 module Puppet::Parser::Functions
-  newfunction(:mkpasswd, :type => :rvalue) do |args|
-    %x{/usr/bin/mkpasswd -H MD5 #{args[0]} #{args[1]}}.chomp
+  newfunction(:mkpasswd, :type => :rvalue, :doc =>
+    "Returns a salted md5 hash to be used for shadowed passwords") do |args|
+    raise Puppet::ParseError, "Wrong number of arguments" unless args.length == 2
+    raise Puppet::ParseError, "Salt must be 8 characters long" unless args[1].length == 8
+    args[0].crypt('$1$' << args[1] << '$')
   end
 end

+ 6 - 0
spec/spec.opts

@@ -0,0 +1,6 @@
+--format
+s
+--colour
+--loadby
+mtime
+--backtrace

+ 16 - 0
spec/spec_helper.rb

@@ -0,0 +1,16 @@
+require 'pathname'
+dir = Pathname.new(__FILE__).parent
+$LOAD_PATH.unshift(dir, dir + 'lib', dir + '../lib')
+require 'puppet'
+gem 'rspec', '>= 1.2.9'
+require 'spec/autorun'
+
+Dir[File.join(File.dirname(__FILE__), 'support', '*.rb')].each do |support_file|
+  require support_file
+end
+
+# We need this because the RAL uses 'should' as a method.  This
+# allows us the same behaviour but with a different method name.
+class Object
+    alias :must :should
+end

+ 41 - 0
spec/unit/parser/functions/mkpasswd.rb

@@ -0,0 +1,41 @@
+#! /usr/bin/env ruby
+
+
+require File.dirname(__FILE__) + '/../../../spec_helper'
+
+require 'mocha'
+require 'fileutils'
+
+describe "the mkpasswd function" do
+
+  before :each do
+    @scope = Puppet::Parser::Scope.new
+  end
+
+  it "should exist" do
+    Puppet::Parser::Functions.function("mkpasswd").should == "function_mkpasswd"
+  end
+
+  it "should raise a ParseError if less than 2 arguments is passed" do
+    lambda { @scope.function_mkpasswd(['aaa']) }.should( raise_error(Puppet::ParseError))
+  end
+
+  it "should raise a ParseError if there is more than 2 arguments" do
+    lambda { @scope.function_mkpasswd(['foo', 'bar','foo']) }.should( raise_error(Puppet::ParseError))
+  end
+
+  it "should raise a ParseError if the sencond argument is not 8 characters" do
+    lambda { @scope.function_mkpasswd(['foo','aaa']) }.should( raise_error(Puppet::ParseError))
+  end
+
+  describe "when executing properly" do
+    it "should return a salted md5 hash" do
+      res = @scope.function_mkpasswd(['foobar','12345678']).should == "$1$12345678$z10EIqhVCcU9.xpb4navW0"
+    end
+
+    it "should use the crypt string method" do
+      String.any_instance.expects(:crypt).with('$1$' << '12345678' << '$')
+      @scope.function_mkpasswd(['foobar','12345678'])
+    end
+  end
+end