Skip to content

Commit 23faa7c

Browse files
author
Travis Fields
committed
Add function to test for uniq values in hash
1 parent a3c800c commit 23faa7c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# === Defined Parser Function: sqlserver_validate_hash_uniq_values
2+
#
3+
# [args*] A hash, that contains string or string[] for values
4+
#
5+
# @raise [Puppet::ParserError] When duplicates are found
6+
#
7+
module Puppet::Parser::Functions
8+
newfunction(:sqlserver_validate_hash_uniq_values) do |arguments|
9+
10+
raise(Puppet::ParseError, 'Expect a Hash as an argument') unless arguments[0].is_a?(Hash)
11+
12+
value = arguments[0].each_value.collect { |v| v }.flatten
13+
14+
total_count = value.count
15+
uniq_count = value.uniq.count
16+
msg = arguments[1] ? arguments[1] : "Duplicate values passed to hash #{value}"
17+
if uniq_count != total_count
18+
raise(Puppet::ParseError, msg)
19+
end
20+
end
21+
end
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#! /usr/bin/env ruby -S rspec
2+
require 'spec_helper'
3+
4+
describe "the sqlserver_validate_hash_uniq_values" do
5+
let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
6+
7+
it "should exist" do
8+
expect(Puppet::Parser::Functions.function("sqlserver_validate_hash_uniq_values")).to eq("function_sqlserver_validate_hash_uniq_values")
9+
end
10+
11+
it "should accept mixed value types of string and string[]" do
12+
expect {
13+
scope.function_sqlserver_validate_hash_uniq_values([{'test' => 'this', 'and' => ['test', 'this']}])
14+
}.to raise_error
15+
end
16+
17+
it "should pass validation" do
18+
expect {
19+
scope.function_sqlserver_validate_hash_uniq_values([{'test' => 'this', 'and' => ['test', 'another']}])
20+
}.to_not raise_error
21+
end
22+
23+
it "should require a hash" do
24+
expect {
25+
scope.function_sqlserver_validate_hash_uniq_values(["MyString"])
26+
}.to raise_error
27+
end
28+
end

0 commit comments

Comments
 (0)