pax_global_header00006660000000000000000000000064121320402540014503gustar00rootroot0000000000000052 comment=bebecd33783b483f6af059e311b9631d3a3336cc puppetlabs-stdlib-4.0.2/000077500000000000000000000000001213204025400151445ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/.gemspec000066400000000000000000000034201213204025400165670ustar00rootroot00000000000000# # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "puppetmodule-stdlib" s.version = "4.0.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Puppet Labs"] s.date = "2013-04-12" s.description = [ 'This Gem format of the stdlib module is intended to make', 'it easier for _module authors_ to resolve dependencies', 'using a Gemfile when running automated testing jobs like', 'Travis or Jenkins. The recommended best practice for', 'installation by end users is to use the `puppet module', 'install` command to install stdlib from the [Puppet', 'Forge](http://forge.puppetlabs.com/puppetlabs/stdlib).' ].join(' ') s.email = "puppet-dev@puppetlabs.com" s.executables = [] s.files = [ 'CHANGELOG', 'CONTRIBUTING.md', 'Gemfile', 'LICENSE', 'Modulefile', 'README.markdown', 'README_DEVELOPER.markdown', 'RELEASE_PROCESS.markdown', 'Rakefile', 'spec/spec.opts' ] s.files += Dir['lib/**/*.rb'] + Dir['manifests/**/*.pp'] + Dir['tests/**/*.pp'] + Dir['spec/**/*.rb'] s.homepage = "http://forge.puppetlabs.com/puppetlabs/stdlib" s.rdoc_options = ["--title", "Puppet Standard Library Development Gem", "--main", "README.markdown", "--line-numbers"] s.require_paths = ["lib"] s.rubyforge_project = "puppetmodule-stdlib" s.rubygems_version = "1.8.24" s.summary = "This gem provides a way to make the standard library available for other module spec testing tasks." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end puppetlabs-stdlib-4.0.2/.gitignore000066400000000000000000000001331213204025400171310ustar00rootroot00000000000000pkg/ .DS_Store metadata.json coverage/ spec/fixtures/ Gemfile.lock .bundle/ vendor/bundle/ puppetlabs-stdlib-4.0.2/.project000066400000000000000000000011051213204025400166100ustar00rootroot00000000000000 stdlib org.cloudsmith.geppetto.pp.dsl.ui.modulefileBuilder org.eclipse.xtext.ui.shared.xtextBuilder org.cloudsmith.geppetto.pp.dsl.ui.puppetNature org.eclipse.xtext.ui.shared.xtextNature puppetlabs-stdlib-4.0.2/.rspec000066400000000000000000000000461213204025400162610ustar00rootroot00000000000000--color --format progress --backtrace puppetlabs-stdlib-4.0.2/.travis.yml000066400000000000000000000010211213204025400172470ustar00rootroot00000000000000language: ruby bundler_args: --without development script: "bundle exec rake spec SPEC_OPTS='--color --format documentation'" rvm: - 1.8.7 - 1.9.3 - 2.0.0 - ruby-head env: - PUPPET_GEM_VERSION=">= 3.0.0" matrix: allow_failures: - rvm: 2.0.0 - rvm: ruby-head include: - rvm: 1.8.7 env: PUPPET_GEM_VERSION="~> 2.7" notifications: email: false webhooks: urls: - https://puppet-dev-community.herokuapp.com/event/travis-ci/ on_success: always on_failure: always on_start: yes puppetlabs-stdlib-4.0.2/CHANGELOG000066400000000000000000000231341213204025400163610ustar00rootroot000000000000002013-04-12 - Jeff McCune - 4.0.2 * Update user information in gemspec to make the intent of the Gem clear. 2013-04-11 - Jeff McCune - 4.0.1 * Fix README function documentation (ab3e30c) 2013-04-11 - Jeff McCune - 4.0.0 * stdlib 4.0 drops support with Puppet 2.7 * stdlib 4.0 preserves support with Puppet 3 2013-04-11 - Jeff McCune - 4.0.0 * Add ability to use puppet from git via bundler (9c5805f) 2013-04-10 - Jeff McCune - 4.0.0 * (maint) Make stdlib usable as a Ruby GEM (e81a45e) 2013-04-10 - Erik Dalén - 4.0.0 * Add a count function (f28550e) 2013-03-31 - Amos Shapira - 4.0.0 * (#19998) Implement any2array (7a2fb80) 2013-03-29 - Steve Huff - 4.0.0 * (19864) num2bool match fix (8d217f0) 2013-03-20 - Erik Dalén - 4.0.0 * Allow comparisons of Numeric and number as String (ff5dd5d) 2013-03-26 - Richard Soderberg - 4.0.0 * add suffix function to accompany the prefix function (88a93ac) 2013-03-19 - Kristof Willaert - 4.0.0 * Add floor function implementation and unit tests (0527341) 2012-04-03 - Eric Shamow - 4.0.0 * (#13610) Add is_function_available to stdlib (961dcab) 2012-12-17 - Justin Lambert - 4.0.0 * str2bool should return a boolean if called with a boolean (5d5a4d4) 2012-10-23 - Uwe Stuehler - 4.0.0 * Fix number of arguments check in flatten() (e80207b) 2013-03-11 - Jeff McCune - 4.0.0 * Add contributing document (96e19d0) 2013-03-04 - Raphaël Pinson - 4.0.0 * Add missing documentation for validate_augeas and validate_cmd to README.markdown (a1510a1) 2013-02-14 - Joshua Hoblitt - 4.0.0 * (#19272) Add has_element() function (95cf3fe) 2013-02-07 - Raphaël Pinson - 4.0.0 * validate_cmd(): Use Puppet::Util::Execution.execute when available (69248df) 2012-12-06 - Raphaël Pinson - 4.0.0 * Add validate_augeas function (3a97c23) 2012-12-06 - Raphaël Pinson - 4.0.0 * Add validate_cmd function (6902cc5) 2013-01-14 - David Schmitt - 4.0.0 * Add geppetto project definition (b3fc0a3) 2013-01-02 - Jaka Hudoklin - 4.0.0 * Add getparam function to get defined resource parameters (20e0e07) 2013-01-05 - Jeff McCune - 4.0.0 * (maint) Add Travis CI Support (d082046) 2012-12-04 - Jeff McCune - 4.0.0 * Clarify that stdlib 3 supports Puppet 3 (3a6085f) 2012-11-30 - Erik Dalén - 4.0.0 * maint: style guideline fixes (7742e5f) 2012-11-09 - James Fryman - 4.0.0 * puppet-lint cleanup (88acc52) 2012-11-06 - Joe Julian - 4.0.0 * Add function, uriescape, to URI.escape strings. Redmine #17459 (fd52b8d) 2012-09-18 - Chad Metcalf - 3.2.0 * Add an ensure_packages function. (8a8c09e) 2012-11-23 - Erik Dalén - 3.2.0 * (#17797) min() and max() functions (9954133) 2012-05-23 - Peter Meier - 3.2.0 * (#14670) autorequire a file_line resource's path (dfcee63) 2012-11-19 - Joshua Harlan Lifton - 3.2.0 * Add join_keys_to_values function (ee0f2b3) 2012-11-17 - Joshua Harlan Lifton - 3.2.0 * Extend delete function for strings and hashes (7322e4d) 2012-08-03 - Gary Larizza - 3.2.0 * Add the pick() function (ba6dd13) 2012-03-20 - Wil Cooley - 3.2.0 * (#13974) Add predicate functions for interface facts (f819417) 2012-11-06 - Joe Julian - 3.2.0 * Add function, uriescape, to URI.escape strings. Redmine #17459 (70f4a0e) 2012-10-25 - Jeff McCune - 3.1.1 * (maint) Fix spec failures resulting from Facter API changes (97f836f) 2012-10-23 - Matthaus Owens - 3.1.0 * Add PE facts to stdlib (cdf3b05) 2012-08-16 - Jeff McCune - 3.0.1 * Fix accidental removal of facts_dot_d.rb in 3.0.0 release 2012-08-16 - Jeff McCune - 3.0.0 * stdlib 3.0 drops support with Puppet 2.6 * stdlib 3.0 preserves support with Puppet 2.7 2012-08-07 - Dan Bode - 3.0.0 * Add function ensure_resource and defined_with_params (ba789de) 2012-07-10 - Hailee Kenney - 3.0.0 * (#2157) Remove facter_dot_d for compatibility with external facts (f92574f) 2012-04-10 - Chris Price - 3.0.0 * (#13693) moving logic from local spec_helper to puppetlabs_spec_helper (85f96df) 2012-10-25 - Jeff McCune - 2.5.1 * (maint) Fix spec failures resulting from Facter API changes (97f836f) 2012-10-23 - Matthaus Owens - 2.5.0 * Add PE facts to stdlib (cdf3b05) 2012-08-15 - Dan Bode - 2.5.0 * Explicitly load functions used by ensure_resource (9fc3063) 2012-08-13 - Dan Bode - 2.5.0 * Add better docs about duplicate resource failures (97d327a) 2012-08-13 - Dan Bode - 2.5.0 * Handle undef for parameter argument (4f8b133) 2012-08-07 - Dan Bode - 2.5.0 * Add function ensure_resource and defined_with_params (a0cb8cd) 2012-08-20 - Jeff McCune - 2.5.0 * Disable tests that fail on 2.6.x due to #15912 (c81496e) 2012-08-20 - Jeff McCune - 2.5.0 * (Maint) Fix mis-use of rvalue functions as statements (4492913) 2012-08-20 - Jeff McCune - 2.5.0 * Add .rspec file to repo root (88789e8) 2012-06-07 - Chris Price - 2.4.0 * Add support for a 'match' parameter to file_line (a06c0d8) 2012-08-07 - Erik Dalén - 2.4.0 * (#15872) Add to_bytes function (247b69c) 2012-07-19 - Jeff McCune - 2.4.0 * (Maint) use PuppetlabsSpec::PuppetInternals.scope (master) (deafe88) 2012-07-10 - Hailee Kenney - 2.4.0 * (#2157) Make facts_dot_d compatible with external facts (5fb0ddc) 2012-03-16 - Steve Traylen - 2.4.0 * (#13205) Rotate array/string randomley based on fqdn, fqdn_rotate() (fef247b) 2012-05-22 - Peter Meier - 2.3.3 * fix regression in #11017 properly (f0a62c7) 2012-05-10 - Jeff McCune - 2.3.3 * Fix spec tests using the new spec_helper (7d34333) 2012-05-10 - Puppet Labs - 2.3.2 * Make file_line default to ensure => present (1373e70) * Memoize file_line spec instance variables (20aacc5) * Fix spec tests using the new spec_helper (1ebfa5d) * (#13595) initialize_everything_for_tests couples modules Puppet ver (3222f35) * (#13439) Fix MRI 1.9 issue with spec_helper (15c5fd1) * (#13439) Fix test failures with Puppet 2.6.x (665610b) * (#13439) refactor spec helper for compatibility with both puppet 2.7 and master (82194ca) * (#13494) Specify the behavior of zero padded strings (61891bb) 2012-03-29 Puppet Labs - 2.1.3 * (#11607) Add Rakefile to enable spec testing * (#12377) Avoid infinite loop when retrying require json 2012-03-13 Puppet Labs - 2.3.1 * (#13091) Fix LoadError bug with puppet apply and puppet_vardir fact 2012-03-12 Puppet Labs - 2.3.0 * Add a large number of new Puppet functions * Backwards compatibility preserved with 2.2.x 2011-12-30 Puppet Labs - 2.2.1 * Documentation only release for the Forge 2011-12-30 Puppet Labs - 2.1.2 * Documentation only release for PE 2.0.x 2011-11-08 Puppet Labs - 2.2.0 * #10285 - Refactor json to use pson instead. * Maint - Add watchr autotest script * Maint - Make rspec tests work with Puppet 2.6.4 * #9859 - Add root_home fact and tests 2011-08-18 Puppet Labs - 2.1.1 * Change facts.d paths to match Facter 2.0 paths. * /etc/facter/facts.d * /etc/puppetlabs/facter/facts.d 2011-08-17 Puppet Labs - 2.1.0 * Add R.I. Pienaar's facts.d custom facter fact * facts defined in /etc/facts.d and /etc/puppetlabs/facts.d are automatically loaded now. 2011-08-04 Puppet Labs - 2.0.0 * Rename whole_line to file_line * This is an API change and as such motivating a 2.0.0 release according to semver.org. 2011-08-04 Puppet Labs - 1.1.0 * Rename append_line to whole_line * This is an API change and as such motivating a 1.1.0 release. 2011-08-04 Puppet Labs - 1.0.0 * Initial stable release * Add validate_array and validate_string functions * Make merge() function work with Ruby 1.8.5 * Add hash merging function * Add has_key function * Add loadyaml() function * Add append_line native 2011-06-21 Jeff McCune - 0.1.7 * Add validate_hash() and getvar() functions 2011-06-15 Jeff McCune - 0.1.6 * Add anchor resource type to provide containment for composite classes 2011-06-03 Jeff McCune - 0.1.5 * Add validate_bool() function to stdlib 0.1.4 2011-05-26 Jeff McCune * Move most stages after main 0.1.3 2011-05-25 Jeff McCune * Add validate_re() function 0.1.2 2011-05-24 Jeff McCune * Update to add annotated tag 0.1.1 2011-05-24 Jeff McCune * Add stdlib::stages class with a standard set of stages puppetlabs-stdlib-4.0.2/CONTRIBUTING.md000066400000000000000000000060141213204025400173760ustar00rootroot00000000000000# How to contribute Third-party patches are essential for keeping stdlib great. We simply can't access the huge number of platforms and myriad configurations for running stdlib. We want to keep it as easy as possible to contribute changes that get things working in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. ## Getting Started * Make sure you have a [Redmine account](http://projects.puppetlabs.com) * Make sure you have a [GitHub account](https://github.com/signup/free) * Submit a ticket for your issue, assuming one does not already exist. * Clearly describe the issue including steps to reproduce when it is a bug. * Make sure you fill in the earliest version that you know has the issue. * Fork the repository on GitHub ## Making Changes * Create a topic branch from where you want to base your work. * This is usually the master branch. * Only target release branches if you are certain your fix must be on that branch. * To quickly create a topic branch based on master; `git branch fix/master/my_contribution master` then checkout the new branch with `git checkout fix/master/my_contribution`. Please avoid working directly on the `master` branch. * Make commits of logical units. * Check for unnecessary whitespace with `git diff --check` before committing. * Make sure your commit messages are in the proper format. ```` (#99999) Make the example in CONTRIBUTING imperative and concrete Without this patch applied the example commit message in the CONTRIBUTING document is not a concrete example. This is a problem because the contributor is left to imagine what the commit message should look like based on a description rather than an example. This patch fixes the problem by making the example concrete and imperative. The first line is a real life imperative statement with a ticket number from our issue tracker. The body describes the behavior without the patch, why this is a problem, and how the patch fixes the problem when applied. ```` * Make sure you have added the necessary tests for your changes. * Run _all_ the tests to assure nothing else was accidentally broken. ## Submitting Changes * Sign the [Contributor License Agreement](http://links.puppetlabs.com/cla). * Push your changes to a topic branch in your fork of the repository. * Submit a pull request to the repository in the puppetlabs organization. * Update your Redmine ticket to mark that you have submitted code and are ready for it to be reviewed. * Include a link to the pull request in the ticket # Additional Resources * [More information on contributing](http://links.puppetlabs.com/contribute-to-puppet) * [Bug tracker (Redmine)](http://projects.puppetlabs.com) * [Contributor License Agreement](http://links.puppetlabs.com/cla) * [General GitHub documentation](http://help.github.com/) * [GitHub pull request documentation](http://help.github.com/send-pull-requests/) * #puppet-dev IRC channel on freenode.org puppetlabs-stdlib-4.0.2/Gemfile000066400000000000000000000015601213204025400164410ustar00rootroot00000000000000source "https://rubygems.org" def location_for(place, fake_version = nil) mdata = /^(git:[^#]*)#(.*)/.match(place) if mdata [fake_version, { :git => mdata[1], :branch => mdata[2], :require => false }].compact elsif place =~ /^file:\/\/(.*)/ ['>= 0', { :path => File.expand_path(mdata[1]), :require => false }] else [place, { :require => false }] end end group :development do gem 'watchr' end group :development, :test do gem 'rake' gem 'puppetmodule-stdlib', ">= 1.0.0", :path => File.expand_path("..", __FILE__) gem 'rspec', "~> 2.11.0", :require => false gem 'mocha', "~> 0.10.5", :require => false gem 'puppetlabs_spec_helper', :require => false gem 'rspec-puppet', :require => false end if puppetversion = ENV['PUPPET_GEM_VERSION'] gem 'puppet', *location_for(puppetversion) else gem 'puppet', :require => false end # vim:ft=ruby puppetlabs-stdlib-4.0.2/LICENSE000066400000000000000000000012401213204025400161460ustar00rootroot00000000000000Copyright (C) 2011 Puppet Labs Inc and some parts: Copyright (C) 2011 Krzysztof Wilczynski Puppet Labs can be contacted at: info@puppetlabs.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. puppetlabs-stdlib-4.0.2/Modulefile000066400000000000000000000005611213204025400171560ustar00rootroot00000000000000name 'puppetlabs-stdlib' version '4.0.2' source 'git://github.com/puppetlabs/puppetlabs-stdlib.git' author 'puppetlabs' license 'Apache 2.0' summary 'Puppet Module Standard Library' description 'Standard Library for Puppet Modules' project_page 'https://github.com/puppetlabs/puppetlabs-stdlib' ## Add dependencies, if any: # dependency 'username/name', '>= 1.2.0' puppetlabs-stdlib-4.0.2/README.markdown000066400000000000000000000620131213204025400176470ustar00rootroot00000000000000# Puppet Labs Standard Library # [![Build Status](https://travis-ci.org/puppetlabs/puppetlabs-stdlib.png?branch=master)](https://travis-ci.org/puppetlabs/puppetlabs-stdlib) This module provides a "standard library" of resources for developing Puppet Modules. This modules will include the following additions to Puppet * Stages * Facts * Functions * Defined resource types * Types * Providers This module is officially curated and provided by Puppet Labs. The modules Puppet Labs writes and distributes will make heavy use of this standard library. To report or research a bug with any part of this module, please go to [http://projects.puppetlabs.com/projects/stdlib](http://projects.puppetlabs.com/projects/stdlib) # Versions # This module follows semver.org (v1.0.0) versioning guidelines. The standard library module is released as part of [Puppet Enterprise](http://puppetlabs.com/puppet/puppet-enterprise/) and as a result older versions of Puppet Enterprise that Puppet Labs still supports will have bugfix maintenance branches periodically "merged up" into master. The current list of integration branches are: * v2.1.x (v2.1.1 released in PE 1) * v2.2.x (Never released as part of PE, only to the Forge) * v2.3.x (Released in PE 2) * v3.0.x (Never released as part of PE, only to the Forge) * v4.0.x (Drops support for Puppet 2.7) * master (mainline development branch) The first Puppet Enterprise version including the stdlib module is Puppet Enterprise 1.2. # Compatibility # Puppet Versions | < 2.6 | 2.6 | 2.7 | 3.x | :---------------|:-----:|:---:|:---:|:----: **stdlib 2.x** | no | **yes** | **yes** | no **stdlib 3.x** | no | no | **yes** | **yes** **stdlib 4.x** | no | no | no | **yes** The stdlib module does not work with Puppet versions released prior to Puppet 2.6.0. ## stdlib 2.x ## All stdlib releases in the 2.0 major version support Puppet 2.6 and Puppet 2.7. ## stdlib 3.x ## The 3.0 major release of stdlib drops support for Puppet 2.6. Stdlib 3.x supports Puppet 2 and Puppet 3. ## stdlib 4.x ## The 4.0 major release of stdlib drops support for Puppet 2.7. Stdlib 4.x supports Puppet 3. Notably, ruby 1.8.5 is no longer supported though ruby 1.8.7, 1.9.3, and 2.0.0 are fully supported. # Functions # abs --- Returns the absolute value of a number, for example -34.56 becomes 34.56. Takes a single integer and float value as an argument. - *Type*: rvalue any2array --------- This converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. - *Type*: rvalue bool2num -------- Converts a boolean to a number. Converts the values: false, f, 0, n, and no to 0 true, t, 1, y, and yes to 1 Requires a single boolean or string as an input. - *Type*: rvalue capitalize ---------- Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. - *Type*: rvalue chomp ----- Removes the record separator from the end of a string or an array of strings, for example `hello\n` becomes `hello`. Requires a single string or array as an input. - *Type*: rvalue chop ---- Returns a new string with the last character removed. If the string ends with `\r\n`, both characters are removed. Applying chop to an empty string returns an empty string. If you wish to merely remove record separators then you should use the `chomp` function. Requires a string or array of strings as input. - *Type*: rvalue concat ------ Appends the contents of array 2 onto array 1. *Example:* concat(['1','2','3'],['4','5','6']) Would result in: ['1','2','3','4','5','6'] - *Type*: rvalue count ----- Takes an array as first argument and an optional second argument. Count the number of elements in array that matches second argument. If called with only an array it counts the number of elements that are not nil/undef. - *Type*: rvalue defined_with_params ------------------- Takes a resource reference and an optional hash of attributes. Returns true if a resource with the specified attributes has already been added to the catalog, and false otherwise. user { 'dan': ensure => present, } if ! defined_with_params(User[dan], {'ensure' => 'present' }) { user { 'dan': ensure => present, } } - *Type*: rvalue delete ------ Deletes all instances of a given element from an array, substring from a string, or key from a hash. *Examples:* delete(['a','b','c','b'], 'b') Would return: ['a','c'] delete({'a'=>1,'b'=>2,'c'=>3}, 'b') Would return: {'a'=>1,'c'=>3} delete('abracadabra', 'bra') Would return: 'acada' - *Type*: rvalue delete_at --------- Deletes a determined indexed value from an array. *Examples:* delete_at(['a','b','c'], 1) Would return: ['a','c'] - *Type*: rvalue downcase -------- Converts the case of a string or all strings in an array to lower case. - *Type*: rvalue empty ----- Returns true if the variable is empty. - *Type*: rvalue ensure_packages --------------- Takes a list of packages and only installs them if they don't already exist. - *Type*: statement ensure_resource --------------- Takes a resource type, title, and a list of attributes that describe a resource. user { 'dan': ensure => present, } This example only creates the resource if it does not already exist: ensure_resource('user, 'dan', {'ensure' => 'present' }) If the resource already exists but does not match the specified parameters, this function will attempt to recreate the resource leading to a duplicate resource definition error. - *Type*: statement flatten ------- This function flattens any deeply nested arrays and returns a single flat array as a result. *Examples:* flatten(['a', ['b', ['c']]]) Would return: ['a','b','c'] - *Type*: rvalue floor ----- Returns the largest integer less or equal to the argument. Takes a single numeric value as an argument. - *Type*: rvalue fqdn_rotate ----------- Rotates an array a random number of times based on a nodes fqdn. - *Type*: rvalue get_module_path --------------- Returns the absolute path of the specified module for the current environment. Example: $module_path = get_module_path('stdlib') - *Type*: rvalue getparam -------- Takes a resource reference and name of the parameter and returns value of resource's parameter. *Examples:* define example_resource($param) { } example_resource { "example_resource_instance": param => "param_value" } getparam(Example_resource["example_resource_instance"], "param") Would return: param_value - *Type*: rvalue getvar ------ Lookup a variable in a remote namespace. For example: $foo = getvar('site::data::foo') # Equivalent to $foo = $site::data::foo This is useful if the namespace itself is stored in a string: $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # Equivalent to $bar = $site::data::bar - *Type*: rvalue grep ---- This function searches through an array and returns any elements that match the provided regular expression. *Examples:* grep(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['aaa','aaaddd'] - *Type*: rvalue has_interface_with ------------------ Returns boolean based on kind and value: * macaddress * netmask * ipaddress * network has_interface_with("macaddress", "x:x:x:x:x:x") has_interface_with("ipaddress", "127.0.0.1") => true etc. If no "kind" is given, then the presence of the interface is checked: has_interface_with("lo") => true - *Type*: rvalue has_ip_address -------------- Returns true if the client has the requested IP address on some interface. This function iterates through the 'interfaces' fact and checks the 'ipaddress_IFACE' facts, performing a simple string comparison. - *Type*: rvalue has_ip_network -------------- Returns true if the client has an IP address within the requested network. This function iterates through the 'interfaces' fact and checks the 'network_IFACE' facts, performing a simple string comparision. - *Type*: rvalue has_key ------- Determine if a hash has a certain key value. Example: $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } - *Type*: rvalue hash ---- This function converts and array into a hash. *Examples:* hash(['a',1,'b',2,'c',3]) Would return: {'a'=>1,'b'=>2,'c'=>3} - *Type*: rvalue is_array -------- Returns true if the variable passed to this function is an array. - *Type*: rvalue is_domain_name -------------- Returns true if the string passed to this function is a syntactically correct domain name. - *Type*: rvalue is_float -------- Returns true if the variable passed to this function is a float. - *Type*: rvalue is_function_available --------------------- This function accepts a string as an argument, determines whether the Puppet runtime has access to a function by that name. It returns a true if the function exists, false if not. - *Type*: rvalue is_hash ------- Returns true if the variable passed to this function is a hash. - *Type*: rvalue is_integer ---------- Returns true if the variable returned to this string is an integer. - *Type*: rvalue is_ip_address ------------- Returns true if the string passed to this function is a valid IP address. - *Type*: rvalue is_mac_address -------------- Returns true if the string passed to this function is a valid mac address. - *Type*: rvalue is_numeric ---------- Returns true if the variable passed to this function is a number. - *Type*: rvalue is_string --------- Returns true if the variable passed to this function is a string. - *Type*: rvalue join ---- This function joins an array into a string using a seperator. *Examples:* join(['a','b','c'], ",") Would result in: "a,b,c" - *Type*: rvalue join_keys_to_values ------------------- This function joins each key of a hash to that key's corresponding value with a separator. Keys and values are cast to strings. The return value is an array in which each element is one joined key/value pair. *Examples:* join_keys_to_values({'a'=>1,'b'=>2}, " is ") Would result in: ["a is 1","b is 2"] - *Type*: rvalue keys ---- Returns the keys of a hash as an array. - *Type*: rvalue loadyaml -------- Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. For example: $myhash = loadyaml('/etc/puppet/data/myhash.yaml') - *Type*: rvalue lstrip ------ Strips leading spaces to the left of a string. - *Type*: rvalue max --- Returns the highest value of all arguments. Requires at least one argument. - *Type*: rvalue member ------ This function determines if a variable is a member of an array. *Examples:* member(['a','b'], 'b') Would return: true member(['a','b'], 'c') Would return: false - *Type*: rvalue merge ----- Merges two or more hashes together and returns the resulting hash. For example: $hash1 = {'one' => 1, 'two', => 2} $hash2 = {'two' => 'dos', 'three', => 'tres'} $merged_hash = merge($hash1, $hash2) # The resulting hash is equivalent to: # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} When there is a duplicate key, the key in the rightmost hash will "win." - *Type*: rvalue min --- Returns the lowest value of all arguments. Requires at least one argument. - *Type*: rvalue num2bool -------- This function converts a number or a string representation of a number into a true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 become true. - *Type*: rvalue parsejson --------- This function accepts JSON as a string and converts into the correct Puppet structure. - *Type*: rvalue parseyaml --------- This function accepts YAML as a string and converts it into the correct Puppet structure. - *Type*: rvalue pick ---- This function is similar to a coalesce function in SQL in that it will return the first value in a list of values that is not undefined or an empty string (two things in Puppet that will return a boolean false value). Typically, this function is used to check for a value in the Puppet Dashboard/Enterprise Console, and failover to a default value like the following: $real_jenkins_version = pick($::jenkins_version, '1.449') The value of $real_jenkins_version will first look for a top-scope variable called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ Enterprise Console are brought into Puppet as top-scope variables), and, failing that, will use a default value of 1.449. - *Type*: rvalue prefix ------ This function applies a prefix to all elements in an array. *Examples:* prefix(['a','b','c'], 'p') Will return: ['pa','pb','pc'] - *Type*: rvalue range ----- When given range in the form of (start, stop) it will extrapolate a range as an array. *Examples:* range("0", "9") Will return: [0,1,2,3,4,5,6,7,8,9] range("00", "09") Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to integers automatically) range("a", "c") Will return: ["a","b","c"] range("host01", "host10") Will return: ["host01", "host02", ..., "host09", "host10"] - *Type*: rvalue reject ------ This function searches through an array and rejects all elements that match the provided regular expression. *Examples:* reject(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['bbb','ccc'] - *Type*: rvalue reverse ------- Reverses the order of a string or array. - *Type*: rvalue rstrip ------ Strips leading spaces to the right of the string. - *Type*: rvalue shuffle ------- Randomizes the order of a string or array elements. - *Type*: rvalue size ---- Returns the number of elements in a string or array. - *Type*: rvalue sort ---- Sorts strings and arrays lexically. - *Type*: rvalue squeeze ------- Returns a new string where runs of the same character that occur in this set are replaced by a single character. - *Type*: rvalue str2bool -------- This converts a string to a boolean. This attempt to convert strings that contain things like: y, 1, t, true to 'true' and strings that contain things like: 0, f, n, false, no to 'false'. - *Type*: rvalue str2saltedsha512 ---------------- This converts a string to a salted-SHA512 password hash (which is used for OS X versions >= 10.7). Given any simple string, you will get a hex version of a salted-SHA512 password hash that can be inserted into your Puppet manifests as a valid password attribute. - *Type*: rvalue strftime -------- This function returns formatted time. *Examples:* To return the time since epoch: strftime("%s") To return the date: strftime("%Y-%m-%d") *Format meaning:* %a - The abbreviated weekday name (``Sun'') %A - The full weekday name (``Sunday'') %b - The abbreviated month name (``Jan'') %B - The full month name (``January'') %c - The preferred local date and time representation %C - Century (20 in 2009) %d - Day of the month (01..31) %D - Date (%m/%d/%y) %e - Day of the month, blank-padded ( 1..31) %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) %h - Equivalent to %b %H - Hour of the day, 24-hour clock (00..23) %I - Hour of the day, 12-hour clock (01..12) %j - Day of the year (001..366) %k - hour, 24-hour clock, blank-padded ( 0..23) %l - hour, 12-hour clock, blank-padded ( 0..12) %L - Millisecond of the second (000..999) %m - Month of the year (01..12) %M - Minute of the hour (00..59) %n - Newline ( ) %N - Fractional seconds digits, default is 9 digits (nanosecond) %3N millisecond (3 digits) %6N microsecond (6 digits) %9N nanosecond (9 digits) %p - Meridian indicator (``AM'' or ``PM'') %P - Meridian indicator (``am'' or ``pm'') %r - time, 12-hour (same as %I:%M:%S %p) %R - time, 24-hour (%H:%M) %s - Number of seconds since 1970-01-01 00:00:00 UTC. %S - Second of the minute (00..60) %t - Tab character ( ) %T - time, 24-hour (%H:%M:%S) %u - Day of the week as a decimal, Monday being 1. (1..7) %U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) %v - VMS date (%e-%b-%Y) %V - Week number of year according to ISO 8601 (01..53) %W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53) %w - Day of the week (Sunday is 0, 0..6) %x - Preferred representation for the date alone, no time %X - Preferred representation for the time alone, no date %y - Year without a century (00..99) %Y - Year with century %z - Time zone as hour offset from UTC (e.g. +0900) %Z - Time zone name %% - Literal ``%'' character - *Type*: rvalue strip ----- This function removes leading and trailing whitespace from a string or from every string inside an array. *Examples:* strip(" aaa ") Would result in: "aaa" - *Type*: rvalue suffix ------ This function applies a suffix to all elements in an array. *Examples:* suffix(['a','b','c'], 'p') Will return: ['ap','bp','cp'] - *Type*: rvalue swapcase -------- This function will swap the existing case of a string. *Examples:* swapcase("aBcD") Would result in: "AbCd" - *Type*: rvalue time ---- This function will return the current time since epoch as an integer. *Examples:* time() Will return something like: 1311972653 - *Type*: rvalue to_bytes -------- Converts the argument into bytes, for example 4 kB becomes 4096. Takes a single string value as an argument. - *Type*: rvalue type ---- Returns the type when passed a variable. Type can be one of: * string * array * hash * float * integer * boolean - *Type*: rvalue unique ------ This function will remove duplicates from strings and arrays. *Examples:* unique("aabbcc") Will return: abc You can also use this with arrays: unique(["a","a","b","b","c","c"]) This returns: ["a","b","c"] - *Type*: rvalue upcase ------ Converts a string or an array of strings to uppercase. *Examples:* upcase("abcd") Will return: ASDF - *Type*: rvalue uriescape --------- Urlencodes a string or array of strings. Requires either a single string or an array as an input. - *Type*: rvalue validate_absolute_path ---------------------- Validate the string represents an absolute path in the filesystem. This function works for windows and unix style paths. The following values will pass: $my_path = "C:/Program Files (x86)/Puppet Labs/Puppet" validate_absolute_path($my_path) $my_path2 = "/var/lib/puppet" validate_absolute_path($my_path2) The following values will fail, causing compilation to abort: validate_absolute_path(true) validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = undef validate_absolute_path($undefined) - *Type*: statement validate_array -------------- Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_array = [ 'one', 'two' ] validate_array($my_array) The following values will fail, causing compilation to abort: validate_array(true) validate_array('some_string') $undefined = undef validate_array($undefined) - *Type*: statement validate_augeas --------------- Perform validation of a string using an Augeas lens The first argument of this function should be a string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation will abort with a parse error. A third argument can be specified, listing paths which should not be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. For example, if you want to make sure your passwd content never contains a user `foo`, you could write: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) Or if you wanted to ensure that no users used the '/bin/barsh' shell, you could use: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] If a fourth argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') - *Type*: statement validate_bool ------------- Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check. The following values will pass: $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) The following values will fail, causing compilation to abort: $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) - *Type*: statement validate_cmd ------------ Perform validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a file as last argument. If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: Example: validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') - *Type*: statement validate_hash ------------- Validate that all passed values are hash data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_hash = { 'one' => 'two' } validate_hash($my_hash) The following values will fail, causing compilation to abort: validate_hash(true) validate_hash('some_string') $undefined = undef validate_hash($undefined) - *Type*: statement validate_re ----------- Perform simple validation of a string against one or more regular expressions. The first argument of this function should be a string to test, and the second argument should be a stringified regular expression (without the // delimiters) or an array of regular expressions. If none of the regular expressions match the string passed in, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. The following strings will validate against the regular expressions: validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) The following strings will fail to validate, causing compilation to abort: validate_re('one', [ '^two', '^three' ]) A helpful error message can be returned like this: validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') - *Type*: statement validate_slength ---------------- Validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. It fails if the first argument is not a string or array of strings, and if arg 2 is not convertable to a number. The following values will pass: validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) The following valueis will not: validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) - *Type*: statement validate_string --------------- Validate that all passed values are string data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_string = "one two" validate_string($my_string, 'three') The following values will fail, causing compilation to abort: validate_string(true) validate_string([ 'some', 'array' ]) $undefined = undef validate_string($undefined) - *Type*: statement values ------ When given a hash this function will return the values of that hash. *Examples:* $hash = { 'a' => 1, 'b' => 2, 'c' => 3, } values($hash) This example would return: [1,2,3] - *Type*: rvalue values_at --------- Finds value inside an array based on location. The first argument is the array you want to analyze, and the second element can be a combination of: * A single numeric index * A range in the form of 'start-stop' (eg. 4-9) * An array combining the above *Examples*: values_at(['a','b','c'], 2) Would return ['c']. values_at(['a','b','c'], ["0-1"]) Would return ['a','b']. values_at(['a','b','c','d','e'], [0, "2-3"]) Would return ['a','c','d']. - *Type*: rvalue zip --- Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. *Example:* zip(['1','2','3'],['4','5','6']) Would result in: ["1", "4"], ["2", "5"], ["3", "6"] - *Type*: rvalue *This page autogenerated on 2013-04-11 13:54:25 -0700* puppetlabs-stdlib-4.0.2/README_DEVELOPER.markdown000066400000000000000000000025411213204025400212540ustar00rootroot00000000000000Puppet Specific Facts ===================== Facter is meant to stand alone and apart from Puppet. However, Facter often runs inside Puppet and all custom facts included in the stdlib module will almost always be evaluated in the context of Puppet and Facter working together. Still, we don't want to write custom facts that blow up in the users face if Puppet is not loaded in memory. This is often the case if the user runs `facter` without also supplying the `--puppet` flag. Ah! But Jeff, the custom fact won't be in the `$LOAD_PATH` unless the user supplies `--facter`! You might say... Not (always) true I say! If the user happens to have a CWD of `/stdlib/lib` then the facts will automatically be evaluated and blow up. In any event, it's pretty easy to write a fact that has no value if Puppet is not loaded. Simply do it like this: Facter.add(:node_vardir) do setcode do # This will be nil if Puppet is not available. Facter::Util::PuppetSettings.with_puppet do Puppet[:vardir] end end end The `Facter::Util::PuppetSettings.with_puppet` method accepts a block and yields to it only if the Puppet library is loaded. If the Puppet library is not loaded, then the method silently returns `nil` which Facter interprets as an undefined fact value. The net effect is that the fact won't be set. puppetlabs-stdlib-4.0.2/README_SPECS.markdown000066400000000000000000000004301213204025400205770ustar00rootroot00000000000000NOTE ==== This project's specs depend on puppet core, and thus they require the `puppetlabs_spec_helper` project. For more information please see the README in that project, which can be found here: [puppetlabs spec helper](https://github.com/puppetlabs/puppetlabs_spec_helper) puppetlabs-stdlib-4.0.2/RELEASE_PROCESS.markdown000066400000000000000000000017431213204025400211730ustar00rootroot00000000000000# Contributing to this module # * Work in a topic branch * Submit a github pull request * Address any comments / feeback * Merge into master using --no-ff # Releasing this module # * This module adheres to http://semver.org/ * Look for API breaking changes using git diff vX.Y.Z..master * If no API breaking changes, the minor version may be bumped. * If there are API breaking changes, the major version must be bumped. * If there are only small minor changes, the patch version may be bumped. * Update the CHANGELOG * Update the Modulefile * Commit these changes with a message along the lines of "Update CHANGELOG and Modulefile for release" * Create an annotated tag with git tag -a vX.Y.Z -m 'version X.Y.Z' (NOTE the leading v as per semver.org) * Push the tag with git push origin --tags * Build a new package with puppet-module or the rake build task if it exists * Publish the new package to the forge * Bonus points for an announcement to puppet-users. puppetlabs-stdlib-4.0.2/Rakefile000066400000000000000000000000771213204025400166150ustar00rootroot00000000000000require 'rubygems' require 'puppetlabs_spec_helper/rake_tasks' puppetlabs-stdlib-4.0.2/lib/000077500000000000000000000000001213204025400157125ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/facter/000077500000000000000000000000001213204025400171565ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/facter/pe_version.rb000066400000000000000000000022241213204025400216540ustar00rootroot00000000000000# Fact: is_pe, pe_version, pe_major_version, pe_minor_version, pe_patch_version # # Purpose: Return various facts about the PE state of the system # # Resolution: Uses a regex match against puppetversion to determine whether the # machine has Puppet Enterprise installed, and what version (overall, major, # minor, patch) is installed. # # Caveats: # Facter.add("pe_version") do setcode do pe_ver = Facter.value("puppetversion").match(/Puppet Enterprise (\d+\.\d+\.\d+)/) pe_ver[1] if pe_ver end end Facter.add("is_pe") do setcode do if Facter.value(:pe_version).to_s.empty? then false else true end end end Facter.add("pe_major_version") do confine :is_pe => true setcode do if pe_version = Facter.value(:pe_version) pe_version.to_s.split('.')[0] end end end Facter.add("pe_minor_version") do confine :is_pe => true setcode do if pe_version = Facter.value(:pe_version) pe_version.to_s.split('.')[1] end end end Facter.add("pe_patch_version") do confine :is_pe => true setcode do if pe_version = Facter.value(:pe_version) pe_version.to_s.split('.')[2] end end end puppetlabs-stdlib-4.0.2/lib/facter/puppet_vardir.rb000066400000000000000000000016511213204025400223720ustar00rootroot00000000000000# This facter fact returns the value of the Puppet vardir setting for the node # running puppet or puppet agent. The intent is to enable Puppet modules to # automatically have insight into a place where they can place variable data, # regardless of the node's platform. # # The value should be directly usable in a File resource path attribute. begin require 'facter/util/puppet_settings' rescue LoadError => e # puppet apply does not add module lib directories to the $LOAD_PATH (See # #4248). It should (in the future) but for the time being we need to be # defensive which is what this rescue block is doing. rb_file = File.join(File.dirname(__FILE__), 'util', 'puppet_settings.rb') load rb_file if File.exists?(rb_file) or raise e end Facter.add(:puppet_vardir) do setcode do # This will be nil if Puppet is not available. Facter::Util::PuppetSettings.with_puppet do Puppet[:vardir] end end end puppetlabs-stdlib-4.0.2/lib/facter/root_home.rb000066400000000000000000000011071213204025400214750ustar00rootroot00000000000000# A facter fact to determine the root home directory. # This varies on PE supported platforms and may be # reconfigured by the end user. module Facter::Util::RootHome class << self def get_root_home root_ent = Facter::Util::Resolution.exec("getent passwd root") # The home directory is the sixth element in the passwd entry # If the platform doesn't have getent, root_ent will be nil and we should # return it straight away. root_ent && root_ent.split(":")[5] end end end Facter.add(:root_home) do setcode { Facter::Util::RootHome.get_root_home } end puppetlabs-stdlib-4.0.2/lib/facter/util/000077500000000000000000000000001213204025400201335ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/facter/util/puppet_settings.rb000066400000000000000000000012241213204025400237140ustar00rootroot00000000000000module Facter module Util module PuppetSettings # This method is intended to provide a convenient way to evaluate a # Facter code block only if Puppet is loaded. This is to account for the # situation where the fact happens to be in the load path, but Puppet is # not loaded for whatever reason. Perhaps the user is simply running # facter without the --puppet flag and they happen to be working in a lib # directory of a module. def self.with_puppet begin Module.const_get("Puppet") rescue NameError nil else yield end end end end end puppetlabs-stdlib-4.0.2/lib/puppet/000077500000000000000000000000001213204025400172275ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/puppet/parser/000077500000000000000000000000001213204025400205235ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/000077500000000000000000000000001213204025400225335ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/abs.rb000066400000000000000000000016161213204025400236310ustar00rootroot00000000000000# # abs.rb # module Puppet::Parser::Functions newfunction(:abs, :type => :rvalue, :doc => <<-EOS Returns the absolute value of a number, for example -34.56 becomes 34.56. Takes a single integer and float value as an argument. EOS ) do |arguments| raise(Puppet::ParseError, "abs(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] # Numbers in Puppet are often string-encoded which is troublesome ... if value.is_a?(String) if value.match(/^-?(?:\d+)(?:\.\d+){1}$/) value = value.to_f elsif value.match(/^-?\d+$/) value = value.to_i else raise(Puppet::ParseError, 'abs(): Requires float or ' + 'integer to work with') end end # We have numeric value to handle ... result = value.abs return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/any2array.rb000066400000000000000000000014011213204025400247640ustar00rootroot00000000000000# # any2array.rb # module Puppet::Parser::Functions newfunction(:any2array, :type => :rvalue, :doc => <<-EOS This converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. EOS ) do |arguments| if arguments.empty? return [] end if arguments.length == 1 if arguments[0].kind_of?(Array) return arguments[0] elsif arguments[0].kind_of?(Hash) result = [] arguments[0].each do |key, value| result << key << value end return result end end return arguments end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/bool2num.rb000066400000000000000000000027071213204025400246230ustar00rootroot00000000000000# # bool2num.rb # module Puppet::Parser::Functions newfunction(:bool2num, :type => :rvalue, :doc => <<-EOS Converts a boolean to a number. Converts the values: false, f, 0, n, and no to 0 true, t, 1, y, and yes to 1 Requires a single boolean or string as an input. EOS ) do |arguments| raise(Puppet::ParseError, "bool2num(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class # We can have either true or false, or string which resembles boolean ... unless [FalseClass, TrueClass, String].include?(klass) raise(Puppet::ParseError, 'bool2num(): Requires either ' + 'boolean or string to work with') end if value.is_a?(String) # We consider all the yes, no, y, n and so on too ... value = case value # # This is how undef looks like in Puppet ... # We yield 0 (or false if you wish) in this case. # when /^$/, '' then false # Empty string will be false ... when /^(1|t|y|true|yes)$/ then true when /^(0|f|n|false|no)$/ then false when /^(undef|undefined)$/ then false # This is not likely to happen ... else raise(Puppet::ParseError, 'bool2num(): Unknown type of boolean given') end end # We have real boolean values as well ... result = value ? 1 : 0 return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/capitalize.rb000066400000000000000000000016011213204025400252030ustar00rootroot00000000000000# # capitalize.rb # module Puppet::Parser::Functions newfunction(:capitalize, :type => :rvalue, :doc => <<-EOS Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. EOS ) do |arguments| raise(Puppet::ParseError, "capitalize(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'capitalize(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.capitalize : i } else result = value.capitalize end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/chomp.rb000066400000000000000000000016261213204025400241730ustar00rootroot00000000000000# # chomp.rb # module Puppet::Parser::Functions newfunction(:chomp, :type => :rvalue, :doc => <<-'EOS' Removes the record separator from the end of a string or an array of strings, for example `hello\n` becomes `hello`. Requires a single string or array as an input. EOS ) do |arguments| raise(Puppet::ParseError, "chomp(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'chomp(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.chomp : i } else result = value.chomp end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/chop.rb000066400000000000000000000020551213204025400240130ustar00rootroot00000000000000# # chop.rb # module Puppet::Parser::Functions newfunction(:chop, :type => :rvalue, :doc => <<-'EOS' Returns a new string with the last character removed. If the string ends with `\r\n`, both characters are removed. Applying chop to an empty string returns an empty string. If you wish to merely remove record separators then you should use the `chomp` function. Requires a string or array of strings as input. EOS ) do |arguments| raise(Puppet::ParseError, "chop(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'chop(): Requires either an ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.chop : i } else result = value.chop end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/concat.rb000066400000000000000000000013631213204025400243320ustar00rootroot00000000000000# # concat.rb # module Puppet::Parser::Functions newfunction(:concat, :type => :rvalue, :doc => <<-EOS Appends the contents of array 2 onto array 1. *Example:* concat(['1','2','3'],['4','5','6']) Would result in: ['1','2','3','4','5','6'] EOS ) do |arguments| # Check that 2 arguments have been given ... raise(Puppet::ParseError, "concat(): Wrong number of arguments " + "given (#{arguments.size} for 2)") if arguments.size != 2 a = arguments[0] b = arguments[1] # Check that both args are arrays. unless a.is_a?(Array) and b.is_a?(Array) raise(Puppet::ParseError, 'concat(): Requires array to work with') end result = a.concat(b) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/count.rb000066400000000000000000000012311213204025400242050ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-EOS Takes an array as first argument and an optional second argument. Count the number of elements in array that matches second argument. If called with only an array it counts the number of elements that are not nil/undef. EOS ) do |args| if (args.size > 2) then raise(ArgumentError, "count(): Wrong number of arguments "+ "given #{args.size} for 1 or 2.") end collection, item = args if item then collection.count item else collection.count { |obj| obj != nil && obj != :undef && obj != '' } end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/defined_with_params.rb000066400000000000000000000020501213204025400270510ustar00rootroot00000000000000# Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:defined_with_params, :type => :rvalue, :doc => <<-'ENDOFDOC' Takes a resource reference and an optional hash of attributes. Returns true if a resource with the specified attributes has already been added to the catalog, and false otherwise. user { 'dan': ensure => present, } if ! defined_with_params(User[dan], {'ensure' => 'present' }) { user { 'dan': ensure => present, } } ENDOFDOC ) do |vals| reference, params = vals raise(ArgumentError, 'Must specify a reference') unless reference if (! params) || params == '' params = {} end ret = false if resource = findresource(reference.to_s) matches = params.collect do |key, value| resource[key] == value end ret = params.empty? || !matches.include?(false) end Puppet.debug("Resource #{reference} was not determined to be defined") ret end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/delete.rb000066400000000000000000000020661213204025400243260ustar00rootroot00000000000000# # delete.rb # # TODO(Krzysztof Wilczynski): We need to add support for regular expression ... module Puppet::Parser::Functions newfunction(:delete, :type => :rvalue, :doc => <<-EOS Deletes all instances of a given element from an array, substring from a string, or key from a hash. *Examples:* delete(['a','b','c','b'], 'b') Would return: ['a','c'] delete({'a'=>1,'b'=>2,'c'=>3}, 'b') Would return: {'a'=>1,'c'=>3} delete('abracadabra', 'bra') Would return: 'acada' EOS ) do |arguments| if (arguments.size != 2) then raise(Puppet::ParseError, "delete(): Wrong number of arguments "+ "given #{arguments.size} for 2.") end collection = arguments[0] item = arguments[1] case collection when Array, Hash collection.delete item when String collection.gsub! item, '' else raise(TypeError, "delete(): First argument must be an Array, " + "String, or Hash. Given an argument of class #{collection.class}.") end collection end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/delete_at.rb000066400000000000000000000022231213204025400250050ustar00rootroot00000000000000# # delete_at.rb # module Puppet::Parser::Functions newfunction(:delete_at, :type => :rvalue, :doc => <<-EOS Deletes a determined indexed value from an array. *Examples:* delete_at(['a','b','c'], 1) Would return: ['a','c'] EOS ) do |arguments| raise(Puppet::ParseError, "delete_at(): Wrong number of arguments " + "given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'delete_at(): Requires array to work with') end index = arguments[1] if index.is_a?(String) and not index.match(/^\d+$/) raise(Puppet::ParseError, 'delete_at(): You must provide ' + 'non-negative numeric index') end result = array.clone # Numbers in Puppet are often string-encoded which is troublesome ... index = index.to_i if index > result.size - 1 # First element is at index 0 is it not? raise(Puppet::ParseError, 'delete_at(): Given index ' + 'exceeds size of array given') end result.delete_at(index) # We ignore the element that got deleted ... return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/downcase.rb000066400000000000000000000014761213204025400246730ustar00rootroot00000000000000# # downcase.rb # module Puppet::Parser::Functions newfunction(:downcase, :type => :rvalue, :doc => <<-EOS Converts the case of a string or all strings in an array to lower case. EOS ) do |arguments| raise(Puppet::ParseError, "downcase(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'downcase(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.downcase : i } else result = value.downcase end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/empty.rb000066400000000000000000000011331213204025400242140ustar00rootroot00000000000000# # empty.rb # module Puppet::Parser::Functions newfunction(:empty, :type => :rvalue, :doc => <<-EOS Returns true if the variable is empty. EOS ) do |arguments| raise(Puppet::ParseError, "empty(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, Hash, String].include?(klass) raise(Puppet::ParseError, 'empty(): Requires either ' + 'array, hash or string to work with') end result = value.empty? return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/ensure_packages.rb000066400000000000000000000014101213204025400262130ustar00rootroot00000000000000# # ensure_packages.rb # require 'puppet/parser/functions' module Puppet::Parser::Functions newfunction(:ensure_packages, :type => :statement, :doc => <<-EOS Takes a list of packages and only installs them if they don't already exist. EOS ) do |arguments| raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 raise(Puppet::ParseError, "ensure_packages(): Requires array " + "given (#{arguments[0].class})") if !arguments[0].kind_of?(Array) Puppet::Parser::Functions.function(:ensure_resource) arguments[0].each { |package_name| function_ensure_resource(['package', package_name, {'ensure' => 'present' } ]) } end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/ensure_resource.rb000066400000000000000000000023301213204025400262660ustar00rootroot00000000000000# Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resource, :type => :statement, :doc => <<-'ENDOFDOC' Takes a resource type, title, and a list of attributes that describe a resource. user { 'dan': ensure => present, } This example only creates the resource if it does not already exist: ensure_resource('user, 'dan', {'ensure' => 'present' }) If the resource already exists but does not match the specified parameters, this function will attempt to recreate the resource leading to a duplicate resource definition error. ENDOFDOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} Puppet::Parser::Functions.function(:defined_with_params) if function_defined_with_params(["#{type}[#{title}]", params]) Puppet.debug("Resource #{type}[#{title}] not created b/c it already exists") else Puppet::Parser::Functions.function(:create_resources) function_create_resources([type.capitalize, { title => params }]) end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/flatten.rb000066400000000000000000000012301213204025400245110ustar00rootroot00000000000000# # flatten.rb # module Puppet::Parser::Functions newfunction(:flatten, :type => :rvalue, :doc => <<-EOS This function flattens any deeply nested arrays and returns a single flat array as a result. *Examples:* flatten(['a', ['b', ['c']]]) Would return: ['a','b','c'] EOS ) do |arguments| raise(Puppet::ParseError, "flatten(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'flatten(): Requires array to work with') end result = array.flatten return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/floor.rb000066400000000000000000000011101213204025400241720ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:floor, :type => :rvalue, :doc => <<-EOS Returns the largest integer less or equal to the argument. Takes a single numeric value as an argument. EOS ) do |arguments| raise(Puppet::ParseError, "floor(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 arg = arguments[0] raise(Puppet::ParseError, "floor(): Wrong argument type " + "given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.floor end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/fqdn_rotate.rb000066400000000000000000000021631213204025400253700ustar00rootroot00000000000000# # fqdn_rotate.rb # module Puppet::Parser::Functions newfunction(:fqdn_rotate, :type => :rvalue, :doc => <<-EOS Rotates an array a random number of times based on a nodes fqdn. EOS ) do |arguments| raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class require 'digest/md5' unless [Array, String].include?(klass) raise(Puppet::ParseError, 'fqdn_rotate(): Requires either ' + 'array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to rotate ... return result if result.size <= 1 # We turn any string value into an array to be able to rotate ... result = string ? result.split('') : result elements = result.size srand(Digest::MD5.hexdigest([lookupvar('::fqdn'),arguments].join(':')).hex) rand(elements).times { result.push result.shift } result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/get_module_path.rb000066400000000000000000000011441213204025400262200ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:get_module_path, :type =>:rvalue, :doc => <<-EOT Returns the absolute path of the specified module for the current environment. Example: $module_path = get_module_path('stdlib') EOT ) do |args| raise(Puppet::ParseError, "get_module_path(): Wrong number of arguments, expects one") unless args.size == 1 if module_path = Puppet::Module.find(args[0], compiler.environment.to_s) module_path.path else raise(Puppet::ParseError, "Could not find module #{args[0]} in environment #{compiler.environment}") end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/getparam.rb000066400000000000000000000016741213204025400246700ustar00rootroot00000000000000# Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:getparam, :type => :rvalue, :doc => <<-'ENDOFDOC' Takes a resource reference and name of the parameter and returns value of resource's parameter. *Examples:* define example_resource($param) { } example_resource { "example_resource_instance": param => "param_value" } getparam(Example_resource["example_resource_instance"], "param") Would return: param_value ENDOFDOC ) do |vals| reference, param = vals raise(ArgumentError, 'Must specify a reference') unless reference raise(ArgumentError, 'Must specify name of a parameter') unless param and param.instance_of? String return '' if param.empty? if resource = findresource(reference.to_s) return resource[param] if resource[param] end return '' end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/getvar.rb000066400000000000000000000012241213204025400243470ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:getvar, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| Lookup a variable in a remote namespace. For example: $foo = getvar('site::data::foo') # Equivalent to $foo = $site::data::foo This is useful if the namespace itself is stored in a string: $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # Equivalent to $bar = $site::data::bar ENDHEREDOC unless args.length == 1 raise Puppet::ParseError, ("getvar(): wrong number of arguments (#{args.length}; must be 1)") end self.lookupvar("#{args[0]}") end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/grep.rb000066400000000000000000000011411213204025400240120ustar00rootroot00000000000000# # grep.rb # module Puppet::Parser::Functions newfunction(:grep, :type => :rvalue, :doc => <<-EOS This function searches through an array and returns any elements that match the provided regular expression. *Examples:* grep(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['aaa','aaaddd'] EOS ) do |arguments| if (arguments.size != 2) then raise(Puppet::ParseError, "grep(): Wrong number of arguments "+ "given #{arguments.size} for 2") end a = arguments[0] pattern = Regexp.new(arguments[1]) a.grep(pattern) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/has_interface_with.rb000066400000000000000000000022361213204025400267110ustar00rootroot00000000000000# # has_interface_with # module Puppet::Parser::Functions newfunction(:has_interface_with, :type => :rvalue, :doc => <<-EOS Returns boolean based on kind and value: * macaddress * netmask * ipaddress * network has_interface_with("macaddress", "x:x:x:x:x:x") has_interface_with("ipaddress", "127.0.0.1") => true etc. If no "kind" is given, then the presence of the interface is checked: has_interface_with("lo") => true EOS ) do |args| raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments " + "given (#{args.size} for 1 or 2)") if args.size < 1 or args.size > 2 interfaces = lookupvar('interfaces') # If we do not have any interfaces, then there are no requested attributes return false if (interfaces == :undefined) interfaces = interfaces.split(',') if args.size == 1 return interfaces.member?(args[0]) end kind, value = args if lookupvar(kind) == value return true end result = false interfaces.each do |iface| if value == lookupvar("#{kind}_#{iface}") result = true break end end result end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/has_ip_address.rb000066400000000000000000000013221213204025400260260ustar00rootroot00000000000000# # has_ip_address # module Puppet::Parser::Functions newfunction(:has_ip_address, :type => :rvalue, :doc => <<-EOS Returns true if the client has the requested IP address on some interface. This function iterates through the 'interfaces' fact and checks the 'ipaddress_IFACE' facts, performing a simple string comparison. EOS ) do |args| raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments " + "given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['ipaddress', args[0]]) end end # vim:sts=2 sw=2 puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/has_ip_network.rb000066400000000000000000000013171213204025400260760ustar00rootroot00000000000000# # has_ip_network # module Puppet::Parser::Functions newfunction(:has_ip_network, :type => :rvalue, :doc => <<-EOS Returns true if the client has an IP address within the requested network. This function iterates through the 'interfaces' fact and checks the 'network_IFACE' facts, performing a simple string comparision. EOS ) do |args| raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments " + "given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['network', args[0]]) end end # vim:sts=2 sw=2 puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/has_key.rb000066400000000000000000000014231213204025400245030ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:has_key, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| Determine if a hash has a certain key value. Example: $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } ENDHEREDOC unless args.length == 2 raise Puppet::ParseError, ("has_key(): wrong number of arguments (#{args.length}; must be 2)") end unless args[0].is_a?(Hash) raise Puppet::ParseError, "has_key(): expects the first argument to be a hash, got #{args[0].inspect} which is of type #{args[0].class}" end args[0].has_key?(args[1]) end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/hash.rb000066400000000000000000000015351213204025400240070ustar00rootroot00000000000000# # hash.rb # module Puppet::Parser::Functions newfunction(:hash, :type => :rvalue, :doc => <<-EOS This function converts and array into a hash. *Examples:* hash(['a',1,'b',2,'c',3]) Would return: {'a'=>1,'b'=>2,'c'=>3} EOS ) do |arguments| raise(Puppet::ParseError, "hash(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'hash(): Requires array to work with') end result = {} begin # This is to make it compatible with older version of Ruby ... array = array.flatten result = Hash[*array] rescue Exception raise(Puppet::ParseError, 'hash(): Unable to compute ' + 'hash from array given') end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_array.rb000066400000000000000000000007051213204025400246730ustar00rootroot00000000000000# # is_array.rb # module Puppet::Parser::Functions newfunction(:is_array, :type => :rvalue, :doc => <<-EOS Returns true if the variable passed to this function is an array. EOS ) do |arguments| raise(Puppet::ParseError, "is_array(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 type = arguments[0] result = type.is_a?(Array) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_domain_name.rb000066400000000000000000000022411213204025400260210ustar00rootroot00000000000000# # is_domain_name.rb # module Puppet::Parser::Functions newfunction(:is_domain_name, :type => :rvalue, :doc => <<-EOS Returns true if the string passed to this function is a syntactically correct domain name. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments "+ "given #{arguments.size} for 1") end domain = arguments[0] # Limits (rfc1035, 3.1) domain_max_length=255 label_min_length=1 label_max_length=63 # Allow ".", it is the top level domain return true if domain == '.' # Remove the final dot, if present. domain.chomp!('.') # Check the whole domain return false if domain.empty? return false if domain.length > domain_max_length # Check each label in the domain labels = domain.split('.') vlabels = labels.each do |label| break if label.length < label_min_length break if label.length > label_max_length break if label[-1..-1] == '-' break if label[0..0] == '-' break unless /^[a-z\d-]+$/i.match(label) end return vlabels == labels end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_float.rb000066400000000000000000000010331213204025400246550ustar00rootroot00000000000000# # is_float.rb # module Puppet::Parser::Functions newfunction(:is_float, :type => :rvalue, :doc => <<-EOS Returns true if the variable passed to this function is a float. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "is_float(): Wrong number of arguments "+ "given #{arguments.size} for 1") end value = arguments[0] if value != value.to_f.to_s and !value.is_a? Float then return false else return true end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_function_available.rb000066400000000000000000000012441213204025400274010ustar00rootroot00000000000000# # is_function_available.rb # module Puppet::Parser::Functions newfunction(:is_function_available, :type => :rvalue, :doc => <<-EOS This function accepts a string as an argument, determines whether the Puppet runtime has access to a function by that name. It returns a true if the function exists, false if not. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments "+ "given #{arguments.size} for 1") end function = Puppet::Parser::Functions.function(arguments[0].to_sym) function.is_a?(String) and not function.empty? end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_hash.rb000066400000000000000000000007001213204025400244730ustar00rootroot00000000000000# # is_hash.rb # module Puppet::Parser::Functions newfunction(:is_hash, :type => :rvalue, :doc => <<-EOS Returns true if the variable passed to this function is a hash. EOS ) do |arguments| raise(Puppet::ParseError, "is_hash(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(Hash) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_integer.rb000066400000000000000000000010451213204025400252100ustar00rootroot00000000000000# # is_integer.rb # module Puppet::Parser::Functions newfunction(:is_integer, :type => :rvalue, :doc => <<-EOS Returns true if the variable returned to this string is an integer. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "is_integer(): Wrong number of arguments "+ "given #{arguments.size} for 1") end value = arguments[0] if value != value.to_i.to_s and !value.is_a? Fixnum then return false else return true end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_ip_address.rb000066400000000000000000000011661213204025400256740ustar00rootroot00000000000000# # is_ip_address.rb # module Puppet::Parser::Functions newfunction(:is_ip_address, :type => :rvalue, :doc => <<-EOS Returns true if the string passed to this function is a valid IP address. EOS ) do |arguments| require 'ipaddr' if (arguments.size != 1) then raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments "+ "given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end if ip.ipv4? or ip.ipv6? then return true else return false end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_mac_address.rb000066400000000000000000000011721213204025400260210ustar00rootroot00000000000000# # is_mac_address.rb # module Puppet::Parser::Functions newfunction(:is_mac_address, :type => :rvalue, :doc => <<-EOS Returns true if the string passed to this function is a valid mac address. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments "+ "given #{arguments.size} for 1") end mac = arguments[0] if /^[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}$/.match(mac) then return true else return false end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_numeric.rb000066400000000000000000000010761213204025400252210ustar00rootroot00000000000000# # is_numeric.rb # module Puppet::Parser::Functions newfunction(:is_numeric, :type => :rvalue, :doc => <<-EOS Returns true if the variable passed to this function is a number. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments "+ "given #{arguments.size} for 1") end value = arguments[0] if value == value.to_f.to_s or value == value.to_i.to_s or value.is_a? Numeric then return true else return false end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/is_string.rb000066400000000000000000000010571213204025400250640ustar00rootroot00000000000000# # is_string.rb # module Puppet::Parser::Functions newfunction(:is_string, :type => :rvalue, :doc => <<-EOS Returns true if the variable passed to this function is a string. EOS ) do |arguments| raise(Puppet::ParseError, "is_string(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 type = arguments[0] result = type.is_a?(String) if result and (type == type.to_f.to_s or type == type.to_i.to_s) then return false end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/join.rb000066400000000000000000000016031213204025400240170ustar00rootroot00000000000000# # join.rb # module Puppet::Parser::Functions newfunction(:join, :type => :rvalue, :doc => <<-EOS This function joins an array into a string using a seperator. *Examples:* join(['a','b','c'], ",") Would result in: "a,b,c" EOS ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "join(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'join(): Requires array to work with') end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a?(String) raise(Puppet::ParseError, 'join(): Requires string to work with') end end result = suffix ? array.join(suffix) : array.join return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/join_keys_to_values.rb000066400000000000000000000024061213204025400271350ustar00rootroot00000000000000# # join.rb # module Puppet::Parser::Functions newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-EOS This function joins each key of a hash to that key's corresponding value with a separator. Keys and values are cast to strings. The return value is an array in which each element is one joined key/value pair. *Examples:* join_keys_to_values({'a'=>1,'b'=>2}, " is ") Would result in: ["a is 1","b is 2"] EOS ) do |arguments| # Validate the number of arguments. if arguments.size != 2 raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two " + "arguments, but #{arguments.size} given.") end # Validate the first argument. hash = arguments[0] if not hash.is_a?(Hash) raise(TypeError, "join_keys_to_values(): The first argument must be a " + "hash, but a #{hash.class} was given.") end # Validate the second argument. separator = arguments[1] if not separator.is_a?(String) raise(TypeError, "join_keys_to_values(): The second argument must be a " + "string, but a #{separator.class} was given.") end # Join the keys to their values. hash.map do |k,v| String(k) + separator + String(v) end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/keys.rb000066400000000000000000000010021213204025400240240ustar00rootroot00000000000000# # keys.rb # module Puppet::Parser::Functions newfunction(:keys, :type => :rvalue, :doc => <<-EOS Returns the keys of a hash as an array. EOS ) do |arguments| raise(Puppet::ParseError, "keys(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'keys(): Requires hash to work with') end result = hash.keys return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/loadyaml.rb000066400000000000000000000007731213204025400246710ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:loadyaml, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. For example: $myhash = loadyaml('/etc/puppet/data/myhash.yaml') ENDHEREDOC unless args.length == 1 raise Puppet::ParseError, ("loadyaml(): wrong number of arguments (#{args.length}; must be 1)") end YAML.load_file(args[0]) end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/lstrip.rb000066400000000000000000000014311213204025400243740ustar00rootroot00000000000000# # lstrip.rb # module Puppet::Parser::Functions newfunction(:lstrip, :type => :rvalue, :doc => <<-EOS Strips leading spaces to the left of a string. EOS ) do |arguments| raise(Puppet::ParseError, "lstrip(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'lstrip(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.lstrip : i } else result = value.lstrip end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/max.rb000066400000000000000000000011661213204025400236510ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:max, :type => :rvalue, :doc => <<-EOS Returns the highest value of all arguments. Requires at least one argument. EOS ) do |args| raise(Puppet::ParseError, "max(): Wrong number of arguments " + "need at least one") if args.size == 0 # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible return args.max do |a,b| if a.to_s =~ /\A-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then a.to_f <=> b.to_f else a.to_s <=> b.to_s end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/member.rb000066400000000000000000000017131213204025400243310ustar00rootroot00000000000000# # member.rb # # TODO(Krzysztof Wilczynski): We need to add support for regular expression ... # TODO(Krzysztof Wilczynski): Support for strings and hashes too ... module Puppet::Parser::Functions newfunction(:member, :type => :rvalue, :doc => <<-EOS This function determines if a variable is a member of an array. *Examples:* member(['a','b'], 'b') Would return: true member(['a','b'], 'c') Would return: false EOS ) do |arguments| raise(Puppet::ParseError, "member(): Wrong number of arguments " + "given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'member(): Requires array to work with') end item = arguments[1] raise(Puppet::ParseError, 'member(): You must provide item ' + 'to search for within array given') if item.empty? result = array.include?(item) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/merge.rb000066400000000000000000000020521213204025400241560ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| Merges two or more hashes together and returns the resulting hash. For example: $hash1 = {'one' => 1, 'two', => 2} $hash2 = {'two' => 'dos', 'three', => 'tres'} $merged_hash = merge($hash1, $hash2) # The resulting hash is equivalent to: # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} When there is a duplicate key, the key in the rightmost hash will "win." ENDHEREDOC if args.length < 2 raise Puppet::ParseError, ("merge(): wrong number of arguments (#{args.length}; must be at least 2)") end # The hash we accumulate into accumulator = Hash.new # Merge into the accumulator hash args.each do |arg| unless arg.is_a?(Hash) raise Puppet::ParseError, "merge: unexpected argument type #{arg.class}, only expects hash arguments" end accumulator.merge!(arg) end # Return the fully merged hash accumulator end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/min.rb000066400000000000000000000011661213204025400236470ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:min, :type => :rvalue, :doc => <<-EOS Returns the lowest value of all arguments. Requires at least one argument. EOS ) do |args| raise(Puppet::ParseError, "min(): Wrong number of arguments " + "need at least one") if args.size == 0 # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible return args.min do |a,b| if a.to_s =~ /\A^-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then a.to_f <=> b.to_f else a.to_s <=> b.to_s end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/num2bool.rb000066400000000000000000000021141213204025400246130ustar00rootroot00000000000000# # num2bool.rb # module Puppet::Parser::Functions newfunction(:num2bool, :type => :rvalue, :doc => <<-EOS This function converts a number or a string representation of a number into a true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 become true. EOS ) do |arguments| raise(Puppet::ParseError, "num2bool(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 number = arguments[0] case number when Numeric # Yay, it's a number when String begin number = Float(number) rescue ArgumentError => ex raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number: #{ex.message}") end else begin number = number.to_s rescue NoMethodError => ex raise(Puppet::ParseError, "num2bool(): Unable to parse argument: #{ex.message}") end end # Truncate Floats number = number.to_i # Return true for any positive number and false otherwise return number > 0 end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/parsejson.rb000066400000000000000000000007771213204025400250770ustar00rootroot00000000000000# # parsejson.rb # module Puppet::Parser::Functions newfunction(:parsejson, :type => :rvalue, :doc => <<-EOS This function accepts JSON as a string and converts into the correct Puppet structure. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "parsejson(): Wrong number of arguments "+ "given #{arguments.size} for 1") end json = arguments[0] # PSON is natively available in puppet PSON.load(json) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/parseyaml.rb000066400000000000000000000007341213204025400250610ustar00rootroot00000000000000# # parseyaml.rb # module Puppet::Parser::Functions newfunction(:parseyaml, :type => :rvalue, :doc => <<-EOS This function accepts YAML as a string and converts it into the correct Puppet structure. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "parseyaml(): Wrong number of arguments "+ "given #{arguments.size} for 1") end require 'yaml' YAML::load(arguments[0]) end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/pick.rb000066400000000000000000000017711213204025400240140ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:pick, :type => :rvalue, :doc => <<-EOS This function is similar to a coalesce function in SQL in that it will return the first value in a list of values that is not undefined or an empty string (two things in Puppet that will return a boolean false value). Typically, this function is used to check for a value in the Puppet Dashboard/Enterprise Console, and failover to a default value like the following: $real_jenkins_version = pick($::jenkins_version, '1.449') The value of $real_jenkins_version will first look for a top-scope variable called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ Enterprise Console are brought into Puppet as top-scope variables), and, failing that, will use a default value of 1.449. EOS ) do |args| args = args.compact args.delete(:undef) args.delete(:undefined) args.delete("") if args[0].to_s.empty? then fail "Must provide non empty value." else return args[0] end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/prefix.rb000066400000000000000000000020621213204025400243550ustar00rootroot00000000000000# # prefix.rb # module Puppet::Parser::Functions newfunction(:prefix, :type => :rvalue, :doc => <<-EOS This function applies a prefix to all elements in an array. *Examples:* prefix(['a','b','c'], 'p') Will return: ['pa','pb','pc'] EOS ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "prefix(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 array = arguments[0] unless array.is_a?(Array) raise Puppet::ParseError, "prefix(): expected first argument to be an Array, got #{array.inspect}" end prefix = arguments[1] if arguments[1] if prefix unless prefix.is_a?(String) raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{suffix.inspect}" end end # Turn everything into string same as join would do ... result = array.collect do |i| i = i.to_s prefix ? prefix + i : i end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/range.rb000066400000000000000000000036271213204025400241640ustar00rootroot00000000000000# # range.rb # # TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ... module Puppet::Parser::Functions newfunction(:range, :type => :rvalue, :doc => <<-EOS When given range in the form of (start, stop) it will extrapolate a range as an array. *Examples:* range("0", "9") Will return: [0,1,2,3,4,5,6,7,8,9] range("00", "09") Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to integers automatically) range("a", "c") Will return: ["a","b","c"] range("host01", "host10") Will return: ["host01", "host02", ..., "host09", "host10"] EOS ) do |arguments| # We support more than one argument but at least one is mandatory ... raise(Puppet::ParseError, "range(): Wrong number of " + "arguments given (#{arguments.size} for 1)") if arguments.size < 1 if arguments.size > 1 start = arguments[0] stop = arguments[1] type = '..' # We select simplest type for Range available in Ruby ... elsif arguments.size > 0 value = arguments[0] if m = value.match(/^(\w+)(\.\.\.?|\-)(\w+)$/) start = m[1] stop = m[3] type = m[2] elsif value.match(/^.+$/) raise(Puppet::ParseError, 'range(): Unable to compute range ' + 'from the value given') else raise(Puppet::ParseError, 'range(): Unknown format of range given') end end # Check whether we have integer value if so then make it so ... if start.match(/^\d+$/) start = start.to_i stop = stop.to_i else start = start.to_s stop = stop.to_s end range = case type when /^(\.\.|\-)$/ then (start .. stop) when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ... end result = range.collect { |i| i } # Get them all ... Pokemon ... return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/reject.rb000066400000000000000000000011151213204025400243320ustar00rootroot00000000000000# # reject.rb # module Puppet::Parser::Functions newfunction(:reject, :type => :rvalue, :doc => <<-EOS) do |args| This function searches through an array and rejects all elements that match the provided regular expression. *Examples:* reject(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['bbb','ccc'] EOS if (args.size != 2) raise Puppet::ParseError, "reject(): Wrong number of arguments given #{args.size} for 2" end ary = args[0] pattern = Regexp.new(args[1]) ary.reject { |e| e =~ pattern } end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/reverse.rb000066400000000000000000000011321213204025400245300ustar00rootroot00000000000000# # reverse.rb # module Puppet::Parser::Functions newfunction(:reverse, :type => :rvalue, :doc => <<-EOS Reverses the order of a string or array. EOS ) do |arguments| raise(Puppet::ParseError, "reverse(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'reverse(): Requires either ' + 'array or string to work with') end result = value.reverse return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/rstrip.rb000066400000000000000000000013201213204025400243770ustar00rootroot00000000000000# # rstrip.rb # module Puppet::Parser::Functions newfunction(:rstrip, :type => :rvalue, :doc => <<-EOS Strips leading spaces to the right of the string. EOS ) do |arguments| raise(Puppet::ParseError, "rstrip(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'rstrip(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) result = value.collect { |i| i.is_a?(String) ? i.rstrip : i } else result = value.rstrip end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/shuffle.rb000066400000000000000000000021461213204025400245170ustar00rootroot00000000000000# # shuffle.rb # module Puppet::Parser::Functions newfunction(:shuffle, :type => :rvalue, :doc => <<-EOS Randomizes the order of a string or array elements. EOS ) do |arguments| raise(Puppet::ParseError, "shuffle(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'shuffle(): Requires either ' + 'array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to shuffle ... return result if result.size <= 1 # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result elements = result.size # Simple implementation of Fisher–Yates in-place shuffle ... elements.times do |i| j = rand(elements - i) + i result[j], result[i] = result[i], result[j] end result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/size.rb000066400000000000000000000022351213204025400240340ustar00rootroot00000000000000# # size.rb # # TODO(Krzysztof Wilczynski): Support for hashes would be nice too ... module Puppet::Parser::Functions newfunction(:size, :type => :rvalue, :doc => <<-EOS Returns the number of elements in a string or array. EOS ) do |arguments| raise(Puppet::ParseError, "size(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 item = arguments[0] if item.is_a?(String) begin # # Check whether your item is a numeric value or not ... # This will take care about positive and/or negative numbers # for both integer and floating-point values ... # # Please note that Puppet has no notion of hexadecimal # nor octal numbers for its DSL at this point in time ... # Float(item) raise(Puppet::ParseError, 'size(): Requires either ' + 'string or array to work with') rescue ArgumentError result = item.size end elsif item.is_a?(Array) result = item.size else raise(Puppet::ParseError, 'size(): Unknown type given') end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/sort.rb000066400000000000000000000007771213204025400240620ustar00rootroot00000000000000# # sort.rb # module Puppet::Parser::Functions newfunction(:sort, :type => :rvalue, :doc => <<-EOS Sorts strings and arrays lexically. EOS ) do |arguments| if (arguments.size != 1) then raise(Puppet::ParseError, "sort(): Wrong number of arguments "+ "given #{arguments.size} for 1") end value = arguments[0] if value.is_a?(Array) then value.sort elsif value.is_a?(String) then value.split("").sort.join("") end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/squeeze.rb000066400000000000000000000014571213204025400245500ustar00rootroot00000000000000# # squeeze.rb # module Puppet::Parser::Functions newfunction(:squeeze, :type => :rvalue, :doc => <<-EOS Returns a new string where runs of the same character that occur in this set are replaced by a single character. EOS ) do |arguments| if ((arguments.size != 2) and (arguments.size != 1)) then raise(Puppet::ParseError, "squeeze(): Wrong number of arguments "+ "given #{arguments.size} for 2 or 1") end item = arguments[0] squeezeval = arguments[1] if item.is_a?(Array) then if squeezeval then item.collect { |i| i.squeeze(squeezeval) } else item.collect { |i| i.squeeze } end else if squeezeval then item.squeeze(squeezeval) else item.squeeze end end end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/str2bool.rb000066400000000000000000000024271213204025400246330ustar00rootroot00000000000000# # str2bool.rb # module Puppet::Parser::Functions newfunction(:str2bool, :type => :rvalue, :doc => <<-EOS This converts a string to a boolean. This attempt to convert strings that contain things like: y, 1, t, true to 'true' and strings that contain things like: 0, f, n, false, no to 'false'. EOS ) do |arguments| raise(Puppet::ParseError, "str2bool(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 string = arguments[0] # If string is already Boolean, return it if !!string == string return string end unless string.is_a?(String) raise(Puppet::ParseError, 'str2bool(): Requires either ' + 'string to work with') end # We consider all the yes, no, y, n and so on too ... result = case string # # This is how undef looks like in Puppet ... # We yield false in this case. # when /^$/, '' then false # Empty string will be false ... when /^(1|t|y|true|yes)$/ then true when /^(0|f|n|false|no)$/ then false when /^(undef|undefined)$/ then false # This is not likely to happen ... else raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given') end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/str2saltedsha512.rb000066400000000000000000000017731213204025400261030ustar00rootroot00000000000000# # str2saltedsha512.rb # module Puppet::Parser::Functions newfunction(:str2saltedsha512, :type => :rvalue, :doc => <<-EOS This converts a string to a salted-SHA512 password hash (which is used for OS X versions >= 10.7). Given any simple string, you will get a hex version of a salted-SHA512 password hash that can be inserted into your Puppet manifests as a valid password attribute. EOS ) do |arguments| require 'digest/sha2' raise(Puppet::ParseError, "str2saltedsha512(): Wrong number of arguments " + "passed (#{arguments.size} but we require 1)") if arguments.size != 1 password = arguments[0] unless password.is_a?(String) raise(Puppet::ParseError, 'str2saltedsha512(): Requires a ' + "String argument, you passed: #{password.class}") end seedint = rand(2**31 - 1) seedstring = Array(seedint).pack("L") saltedpass = Digest::SHA512.digest(seedstring + password) (seedstring + saltedpass).unpack('H*')[0] end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/strftime.rb000066400000000000000000000063771213204025400247320ustar00rootroot00000000000000# # strftime.rb # module Puppet::Parser::Functions newfunction(:strftime, :type => :rvalue, :doc => <<-EOS This function returns formatted time. *Examples:* To return the time since epoch: strftime("%s") To return the date: strftime("%Y-%m-%d") *Format meaning:* %a - The abbreviated weekday name (``Sun'') %A - The full weekday name (``Sunday'') %b - The abbreviated month name (``Jan'') %B - The full month name (``January'') %c - The preferred local date and time representation %C - Century (20 in 2009) %d - Day of the month (01..31) %D - Date (%m/%d/%y) %e - Day of the month, blank-padded ( 1..31) %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) %h - Equivalent to %b %H - Hour of the day, 24-hour clock (00..23) %I - Hour of the day, 12-hour clock (01..12) %j - Day of the year (001..366) %k - hour, 24-hour clock, blank-padded ( 0..23) %l - hour, 12-hour clock, blank-padded ( 0..12) %L - Millisecond of the second (000..999) %m - Month of the year (01..12) %M - Minute of the hour (00..59) %n - Newline (\n) %N - Fractional seconds digits, default is 9 digits (nanosecond) %3N millisecond (3 digits) %6N microsecond (6 digits) %9N nanosecond (9 digits) %p - Meridian indicator (``AM'' or ``PM'') %P - Meridian indicator (``am'' or ``pm'') %r - time, 12-hour (same as %I:%M:%S %p) %R - time, 24-hour (%H:%M) %s - Number of seconds since 1970-01-01 00:00:00 UTC. %S - Second of the minute (00..60) %t - Tab character (\t) %T - time, 24-hour (%H:%M:%S) %u - Day of the week as a decimal, Monday being 1. (1..7) %U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53) %v - VMS date (%e-%b-%Y) %V - Week number of year according to ISO 8601 (01..53) %W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53) %w - Day of the week (Sunday is 0, 0..6) %x - Preferred representation for the date alone, no time %X - Preferred representation for the time alone, no date %y - Year without a century (00..99) %Y - Year with century %z - Time zone as hour offset from UTC (e.g. +0900) %Z - Time zone name %% - Literal ``%'' character EOS ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "strftime(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 format = arguments[0] raise(Puppet::ParseError, 'strftime(): You must provide ' + 'format for evaluation') if format.empty? # The Time Zone argument is optional ... time_zone = arguments[1] if arguments[1] time = Time.new # There is probably a better way to handle Time Zone ... if time_zone and not time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone local_time = local_time.utc ENV['TZ'] = time_zone time = local_time.localtime ENV['TZ'] = original_zone end result = time.strftime(format) return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/strip.rb000066400000000000000000000015001213204025400242150ustar00rootroot00000000000000# # strip.rb # module Puppet::Parser::Functions newfunction(:strip, :type => :rvalue, :doc => <<-EOS This function removes leading and trailing whitespace from a string or from every string inside an array. *Examples:* strip(" aaa ") Would result in: "aaa" EOS ) do |arguments| raise(Puppet::ParseError, "strip(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'strip(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) result = value.collect { |i| i.is_a?(String) ? i.strip : i } else result = value.strip end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/suffix.rb000066400000000000000000000020611213204025400243630ustar00rootroot00000000000000# # suffix.rb # module Puppet::Parser::Functions newfunction(:suffix, :type => :rvalue, :doc => <<-EOS This function applies a suffix to all elements in an array. *Examples:* suffix(['a','b','c'], 'p') Will return: ['ap','bp','cp'] EOS ) do |arguments| # Technically we support two arguments but only first is mandatory ... raise(Puppet::ParseError, "suffix(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 array = arguments[0] unless array.is_a?(Array) raise Puppet::ParseError, "suffix(): expected first argument to be an Array, got #{array.inspect}" end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a? String raise Puppet::ParseError, "suffix(): expected second argument to be a String, got #{suffix.inspect}" end end # Turn everything into string same as join would do ... result = array.collect do |i| i = i.to_s suffix ? i + suffix : i end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/swapcase.rb000066400000000000000000000015511213204025400246700ustar00rootroot00000000000000# # swapcase.rb # module Puppet::Parser::Functions newfunction(:swapcase, :type => :rvalue, :doc => <<-EOS This function will swap the existing case of a string. *Examples:* swapcase("aBcD") Would result in: "AbCd" EOS ) do |arguments| raise(Puppet::ParseError, "swapcase(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'swapcase(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.swapcase : i } else result = value.swapcase end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/time.rb000066400000000000000000000020431213204025400240150ustar00rootroot00000000000000# # time.rb # module Puppet::Parser::Functions newfunction(:time, :type => :rvalue, :doc => <<-EOS This function will return the current time since epoch as an integer. *Examples:* time() Will return something like: 1311972653 EOS ) do |arguments| # The Time Zone argument is optional ... time_zone = arguments[0] if arguments[0] if (arguments.size != 0) and (arguments.size != 1) then raise(Puppet::ParseError, "time(): Wrong number of arguments "+ "given #{arguments.size} for 0 or 1") end time = Time.new # There is probably a better way to handle Time Zone ... if time_zone and not time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone local_time = local_time.utc ENV['TZ'] = time_zone time = local_time.localtime ENV['TZ'] = original_zone end # Calling Time#to_i on a receiver changes it. Trust me I am the Doctor. result = time.strftime('%s') result = result.to_i return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/to_bytes.rb000066400000000000000000000016021213204025400247070ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:to_bytes, :type => :rvalue, :doc => <<-EOS Converts the argument into bytes, for example 4 kB becomes 4096. Takes a single string value as an argument. EOS ) do |arguments| raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 arg = arguments[0] return arg if arg.is_a? Numeric value,prefix = */([0-9.e+-]*)\s*([^bB]?)/.match(arg)[1,2] value = value.to_f case prefix when '' then return value.to_i when 'k' then return (value*(1<<10)).to_i when 'M' then return (value*(1<<20)).to_i when 'G' then return (value*(1<<30)).to_i when 'T' then return (value*(1<<40)).to_i when 'E' then return (value*(1<<50)).to_i else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}" end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/type.rb000066400000000000000000000020711213204025400240410ustar00rootroot00000000000000# # type.rb # module Puppet::Parser::Functions newfunction(:type, :type => :rvalue, :doc => <<-EOS Returns the type when passed a variable. Type can be one of: * string * array * hash * float * integer * boolean EOS ) do |arguments| raise(Puppet::ParseError, "type(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class if not [TrueClass, FalseClass, Array, Bignum, Fixnum, Float, Hash, String].include?(klass) raise(Puppet::ParseError, 'type(): Unknown type') end klass = klass.to_s # Ugly ... # We note that Integer is the parent to Bignum and Fixnum ... result = case klass when /^(?:Big|Fix)num$/ then 'integer' when /^(?:True|False)Class$/ then 'boolean' else klass end if result == "String" then if value == value.to_i.to_s then result = "Integer" elsif value == value.to_f.to_s then result = "Float" end end return result.downcase end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/unique.rb000066400000000000000000000020251213204025400243650ustar00rootroot00000000000000# # unique.rb # module Puppet::Parser::Functions newfunction(:unique, :type => :rvalue, :doc => <<-EOS This function will remove duplicates from strings and arrays. *Examples:* unique("aabbcc") Will return: abc You can also use this with arrays: unique(["a","a","b","b","c","c"]) This returns: ["a","b","c"] EOS ) do |arguments| raise(Puppet::ParseError, "unique(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'unique(): Requires either ' + 'array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result result = result.uniq # Remove duplicates ... result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/upcase.rb000066400000000000000000000015311213204025400243400ustar00rootroot00000000000000# # upcase.rb # module Puppet::Parser::Functions newfunction(:upcase, :type => :rvalue, :doc => <<-EOS Converts a string or an array of strings to uppercase. *Examples:* upcase("abcd") Will return: ASDF EOS ) do |arguments| raise(Puppet::ParseError, "upcase(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'upcase(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? i.upcase : i } else result = value.upcase end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/uriescape.rb000066400000000000000000000016511213204025400250430ustar00rootroot00000000000000# # uriescape.rb # require 'uri' module Puppet::Parser::Functions newfunction(:uriescape, :type => :rvalue, :doc => <<-EOS Urlencodes a string or array of strings. Requires either a single string or an array as an input. EOS ) do |arguments| raise(Puppet::ParseError, "uriescape(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 value = arguments[0] klass = value.class unsafe = ":/?#[]@!$&'()*+,;= " unless [Array, String].include?(klass) raise(Puppet::ParseError, 'uriescape(): Requires either ' + 'array or string to work with') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.collect { |i| i.is_a?(String) ? URI.escape(i,unsafe) : i } else result = URI.escape(value,unsafe) end return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_absolute_path.rb000066400000000000000000000043401213204025400275640ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_absolute_path, :doc => <<-'ENDHEREDOC') do |args| Validate the string represents an absolute path in the filesystem. This function works for windows and unix style paths. The following values will pass: $my_path = "C:/Program Files (x86)/Puppet Labs/Puppet" validate_absolute_path($my_path) $my_path2 = "/var/lib/puppet" validate_absolute_path($my_path2) The following values will fail, causing compilation to abort: validate_absolute_path(true) validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = undef validate_absolute_path($undefined) ENDHEREDOC require 'puppet/util' unless args.length > 0 then raise Puppet::ParseError, ("validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)") end args.each do |arg| # This logic was borrowed from # [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/master/lib/puppet/file_serving/base.rb) # Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise. if Puppet::Util.respond_to?(:absolute_path?) then unless Puppet::Util.absolute_path?(arg, :posix) or Puppet::Util.absolute_path?(arg, :windows) raise Puppet::ParseError, ("#{arg.inspect} is not an absolute path.") end else # This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path? # Determine in a platform-specific way whether a path is absolute. This # defaults to the local platform if none is specified. # Escape once for the string literal, and once for the regex. slash = '[\\\\/]' name = '[^\\\\/]+' regexes = { :windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i, :posix => %r!^/!, } rval = (!!(arg =~ regexes[:posix])) || (!!(arg =~ regexes[:windows])) rval or raise Puppet::ParseError, ("#{arg.inspect} is not an absolute path.") end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_array.rb000066400000000000000000000015621213204025400260530ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_array, :doc => <<-'ENDHEREDOC') do |args| Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_array = [ 'one', 'two' ] validate_array($my_array) The following values will fail, causing compilation to abort: validate_array(true) validate_array('some_string') $undefined = undef validate_array($undefined) ENDHEREDOC unless args.length > 0 then raise Puppet::ParseError, ("validate_array(): wrong number of arguments (#{args.length}; must be > 0)") end args.each do |arg| unless arg.is_a?(Array) raise Puppet::ParseError, ("#{arg.inspect} is not an Array. It looks to be a #{arg.class}") end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_augeas.rb000066400000000000000000000053501213204025400262010ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_augeas, :doc => <<-'ENDHEREDOC') do |args| Perform validation of a string using an Augeas lens The first argument of this function should be a string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation will abort with a parse error. A third argument can be specified, listing paths which should not be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. For example, if you want to make sure your passwd content never contains a user `foo`, you could write: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) Or if you wanted to ensure that no users used the '/bin/barsh' shell, you could use: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] If a fourth argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') ENDHEREDOC unless Puppet.features.augeas? raise Puppet::ParseError, ("validate_augeas(): this function requires the augeas feature. See http://projects.puppetlabs.com/projects/puppet/wiki/Puppet_Augeas#Pre-requisites for how to activate it.") end if (args.length < 2) or (args.length > 4) then raise Puppet::ParseError, ("validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)") end msg = args[3] || "validate_augeas(): Failed to validate content against #{args[1].inspect}" require 'augeas' aug = Augeas::open(nil, nil, Augeas::NO_MODL_AUTOLOAD) begin content = args[0] # Test content in a temporary file tmpfile = Tempfile.new("validate_augeas") begin tmpfile.write(content) ensure tmpfile.close end # Check for syntax lens = args[1] aug.transform( :lens => lens, :name => 'Validate_augeas', :incl => tmpfile.path ) aug.load! unless aug.match("/augeas/files#{tmpfile.path}//error").empty? error = aug.get("/augeas/files#{tmpfile.path}//error/message") msg += " with error: #{error}" raise Puppet::ParseError, (msg) end # Launch unit tests tests = args[2] || [] aug.defvar('file', "/files#{tmpfile.path}") tests.each do |t| msg += " testing path #{t}" raise Puppet::ParseError, (msg) unless aug.match(t).empty? end ensure aug.close tmpfile.unlink end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_bool.rb000066400000000000000000000016551213204025400256730ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_bool, :doc => <<-'ENDHEREDOC') do |args| Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check. The following values will pass: $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) The following values will fail, causing compilation to abort: $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) ENDHEREDOC unless args.length > 0 then raise Puppet::ParseError, ("validate_bool(): wrong number of arguments (#{args.length}; must be > 0)") end args.each do |arg| unless (arg.is_a?(TrueClass) || arg.is_a?(FalseClass)) raise Puppet::ParseError, ("#{arg.inspect} is not a boolean. It looks to be a #{arg.class}") end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_cmd.rb000066400000000000000000000031251213204025400254750ustar00rootroot00000000000000require 'puppet/util/execution' module Puppet::Parser::Functions newfunction(:validate_cmd, :doc => <<-'ENDHEREDOC') do |args| Perform validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a file as last argument. If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: Example: validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') ENDHEREDOC if (args.length < 2) or (args.length > 3) then raise Puppet::ParseError, ("validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)") end msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}" content = args[0] checkscript = args[1] # Test content in a temporary file tmpfile = Tempfile.new("validate_cmd") begin tmpfile.write(content) if Puppet::Util::Execution.respond_to?('execute') Puppet::Util::Execution.execute("#{checkscript} #{tmpfile.path}") else Puppet::Util.execute("#{checkscript} #{tmpfile.path}") end rescue Puppet::ExecutionFailure => detail msg += "\n#{detail}" raise Puppet::ParseError, msg ensure tmpfile.unlink end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_hash.rb000066400000000000000000000015501213204025400256550ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_hash, :doc => <<-'ENDHEREDOC') do |args| Validate that all passed values are hash data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_hash = { 'one' => 'two' } validate_hash($my_hash) The following values will fail, causing compilation to abort: validate_hash(true) validate_hash('some_string') $undefined = undef validate_hash($undefined) ENDHEREDOC unless args.length > 0 then raise Puppet::ParseError, ("validate_hash(): wrong number of arguments (#{args.length}; must be > 0)") end args.each do |arg| unless arg.is_a?(Hash) raise Puppet::ParseError, ("#{arg.inspect} is not a Hash. It looks to be a #{arg.class}") end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_re.rb000066400000000000000000000030531213204025400253400ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_re, :doc => <<-'ENDHEREDOC') do |args| Perform simple validation of a string against one or more regular expressions. The first argument of this function should be a string to test, and the second argument should be a stringified regular expression (without the // delimiters) or an array of regular expressions. If none of the regular expressions match the string passed in, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. The following strings will validate against the regular expressions: validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) The following strings will fail to validate, causing compilation to abort: validate_re('one', [ '^two', '^three' ]) A helpful error message can be returned like this: validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') ENDHEREDOC if (args.length < 2) or (args.length > 3) then raise Puppet::ParseError, ("validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)") end msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}" # We're using a flattened array here because we can't call String#any? in # Ruby 1.9 like we can in Ruby 1.8 raise Puppet::ParseError, (msg) unless [args[1]].flatten.any? do |re_str| args[0] =~ Regexp.compile(re_str) end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_slength.rb000066400000000000000000000044131213204025400263770ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_slength, :doc => <<-'ENDHEREDOC') do |args| Validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. It fails if the first argument is not a string or array of strings, and if arg 2 is not convertable to a number. The following values will pass: validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) The following valueis will not: validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) ENDHEREDOC raise Puppet::ParseError, ("validate_slength(): Wrong number of arguments (#{args.length}; must be = 2)") unless args.length == 2 unless (args[0].is_a?(String) or args[0].is_a?(Array)) raise Puppet::ParseError, ("validate_slength(): please pass a string, or an array of strings - what you passed didn't work for me at all - #{args[0].class}") end begin max_length = args[1].to_i rescue NoMethodError => e raise Puppet::ParseError, ("validate_slength(): Couldn't convert whatever you passed as the length parameter to an integer - sorry: " + e.message ) end raise Puppet::ParseError, ("validate_slength(): please pass a positive number as max_length") unless max_length > 0 case args[0] when String raise Puppet::ParseError, ("validate_slength(): #{args[0].inspect} is #{args[0].length} characters. It should have been less than or equal to #{max_length} characters") unless args[0].length <= max_length when Array args[0].each do |arg| if arg.is_a?(String) unless ( arg.is_a?(String) and arg.length <= max_length ) raise Puppet::ParseError, ("validate_slength(): #{arg.inspect} is #{arg.length} characters. It should have been less than or equal to #{max_length} characters") end else raise Puppet::ParseError, ("validate_slength(): #{arg.inspect} is not a string, it's a #{arg.class}") end end else raise Puppet::ParseError, ("validate_slength(): please pass a string, or an array of strings - what you passed didn't work for me at all - #{args[0].class}") end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/validate_string.rb000066400000000000000000000016041213204025400262400ustar00rootroot00000000000000module Puppet::Parser::Functions newfunction(:validate_string, :doc => <<-'ENDHEREDOC') do |args| Validate that all passed values are string data structures. Abort catalog compilation if any value fails this check. The following values will pass: $my_string = "one two" validate_string($my_string, 'three') The following values will fail, causing compilation to abort: validate_string(true) validate_string([ 'some', 'array' ]) $undefined = undef validate_string($undefined) ENDHEREDOC unless args.length > 0 then raise Puppet::ParseError, ("validate_string(): wrong number of arguments (#{args.length}; must be > 0)") end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, ("#{arg.inspect} is not a string. It looks to be a #{arg.class}") end end end end puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/values.rb000066400000000000000000000012661213204025400243640ustar00rootroot00000000000000# # values.rb # module Puppet::Parser::Functions newfunction(:values, :type => :rvalue, :doc => <<-EOS When given a hash this function will return the values of that hash. *Examples:* $hash = { 'a' => 1, 'b' => 2, 'c' => 3, } values($hash) This example would return: [1,2,3] EOS ) do |arguments| raise(Puppet::ParseError, "values(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size < 1 hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'values(): Requires hash to work with') end result = hash.values return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/values_at.rb000066400000000000000000000050661213204025400250520ustar00rootroot00000000000000# # values_at.rb # module Puppet::Parser::Functions newfunction(:values_at, :type => :rvalue, :doc => <<-EOS Finds value inside an array based on location. The first argument is the array you want to analyze, and the second element can be a combination of: * A single numeric index * A range in the form of 'start-stop' (eg. 4-9) * An array combining the above *Examples*: values_at(['a','b','c'], 2) Would return ['c']. values_at(['a','b','c'], ["0-1"]) Would return ['a','b']. values_at(['a','b','c','d','e'], [0, "2-3"]) Would return ['a','c','d']. EOS ) do |arguments| raise(Puppet::ParseError, "values_at(): Wrong number of " + "arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments.shift unless array.is_a?(Array) raise(Puppet::ParseError, 'values_at(): Requires array to work with') end indices = [arguments.shift].flatten() # Get them all ... Pokemon ... if not indices or indices.empty? raise(Puppet::ParseError, 'values_at(): You must provide ' + 'at least one positive index to collect') end result = [] indices_list = [] indices.each do |i| if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/) start = m[1].to_i stop = m[3].to_i type = m[2] if start > stop raise(Puppet::ParseError, 'values_at(): Stop index in ' + 'given indices range is smaller than the start index') elsif stop > array.size - 1 # First element is at index 0 is it not? raise(Puppet::ParseError, 'values_at(): Stop index in ' + 'given indices range exceeds array size') end range = case type when /^(\.\.|\-)$/ then (start .. stop) when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ... end range.each { |i| indices_list << i.to_i } else # Only positive numbers allowed in this case ... if not i.match(/^\d+$/) raise(Puppet::ParseError, 'values_at(): Unknown format ' + 'of given index') end # In Puppet numbers are often string-encoded ... i = i.to_i if i > array.size - 1 # Same story. First element is at index 0 ... raise(Puppet::ParseError, 'values_at(): Given index ' + 'exceeds array size') end indices_list << i end end # We remove nil values as they make no sense in Puppet DSL ... result = indices_list.collect { |i| array[i] }.compact return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/parser/functions/zip.rb000066400000000000000000000035311213204025400236640ustar00rootroot00000000000000# # zip.rb # module Puppet::Parser::Functions newfunction(:zip, :type => :rvalue, :doc => <<-EOS Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. *Example:* zip(['1','2','3'],['4','5','6']) Would result in: ["1", "4"], ["2", "5"], ["3", "6"] EOS ) do |arguments| # Technically we support three arguments but only first is mandatory ... raise(Puppet::ParseError, "zip(): Wrong number of arguments " + "given (#{arguments.size} for 2)") if arguments.size < 2 a = arguments[0] b = arguments[1] unless a.is_a?(Array) and b.is_a?(Array) raise(Puppet::ParseError, 'zip(): Requires array to work with') end flatten = arguments[2] if arguments[2] if flatten klass = flatten.class # We can have either true or false, or string which resembles boolean ... unless [FalseClass, TrueClass, String].include?(klass) raise(Puppet::ParseError, 'zip(): Requires either ' + 'boolean or string to work with') end if flatten.is_a?(String) # We consider all the yes, no, y, n and so on too ... flatten = case flatten # # This is how undef looks like in Puppet ... # We yield false in this case. # when /^$/, '' then false # Empty string will be false ... when /^(1|t|y|true|yes)$/ then true when /^(0|f|n|false|no)$/ then false when /^(undef|undefined)$/ then false # This is not likely to happen ... else raise(Puppet::ParseError, 'zip(): Unknown type of boolean given') end end end result = a.zip(b) result = flatten ? result.flatten : result return result end end # vim: set ts=2 sw=2 et : puppetlabs-stdlib-4.0.2/lib/puppet/provider/000077500000000000000000000000001213204025400210615ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/puppet/provider/file_line/000077500000000000000000000000001213204025400230075ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/puppet/provider/file_line/ruby.rb000066400000000000000000000026411213204025400243200ustar00rootroot00000000000000 Puppet::Type.type(:file_line).provide(:ruby) do def exists? lines.find do |line| line.chomp == resource[:line].chomp end end def create if resource[:match] handle_create_with_match() else handle_create_without_match() end end def destroy local_lines = lines File.open(resource[:path],'w') do |fh| fh.write(local_lines.reject{|l| l.chomp == resource[:line] }.join('')) end end private def lines # If this type is ever used with very large files, we should # write this in a different way, using a temp # file; for now assuming that this type is only used on # small-ish config files that can fit into memory without # too much trouble. @lines ||= File.readlines(resource[:path]) end def handle_create_with_match() regex = resource[:match] ? Regexp.new(resource[:match]) : nil match_count = lines.select { |l| regex.match(l) }.size if match_count > 1 raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end File.open(resource[:path], 'w') do |fh| lines.each do |l| fh.puts(regex.match(l) ? resource[:line] : l) end if (match_count == 0) fh.puts(resource[:line]) end end end def handle_create_without_match File.open(resource[:path], 'a') do |fh| fh.puts resource[:line] end end end puppetlabs-stdlib-4.0.2/lib/puppet/type/000077500000000000000000000000001213204025400202105ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/lib/puppet/type/anchor.rb000066400000000000000000000032461213204025400220140ustar00rootroot00000000000000Puppet::Type.newtype(:anchor) do desc <<-'ENDOFDESC' A simple resource type intended to be used as an anchor in a composite class. In Puppet 2.6, when a class declares another class, the resources in the interior class are not contained by the exterior class. This interacts badly with the pattern of composing complex modules from smaller classes, as it makes it impossible for end users to specify order relationships between the exterior class and other modules. The anchor type lets you work around this. By sandwiching any interior classes between two no-op resources that _are_ contained by the exterior class, you can ensure that all resources in the module are contained. class ntp { # These classes will have the correct order relationship with each # other. However, without anchors, they won't have any order # relationship to Class['ntp']. class { 'ntp::package': } -> class { 'ntp::config': } -> class { 'ntp::service': } # These two resources "anchor" the composed classes within the ntp # class. anchor { 'ntp::begin': } -> Class['ntp::package'] Class['ntp::service'] -> anchor { 'ntp::end': } } This allows the end user of the ntp module to establish require and before relationships with Class['ntp']: class { 'ntp': } -> class { 'mcollective': } class { 'mcollective': } -> class { 'ntp': } ENDOFDESC newparam :name do desc "The name of the anchor resource." end def refresh # We don't do anything with them, but we need this to # show that we are "refresh aware" and not break the # chain of propagation. end end puppetlabs-stdlib-4.0.2/lib/puppet/type/file_line.rb000066400000000000000000000041641213204025400224700ustar00rootroot00000000000000Puppet::Type.newtype(:file_line) do desc <<-EOT Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will add the line to ensure the desired state. Multiple resources may be declared to manage multiple lines in the same file. Example: file_line { 'sudo_rule': path => '/etc/sudoers', line => '%sudo ALL=(ALL) ALL', } file_line { 'sudo_rule_nopw': path => '/etc/sudoers', line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', } In this example, Puppet will ensure both of the specified lines are contained in the file /etc/sudoers. EOT ensurable do defaultvalues defaultto :present end newparam(:name, :namevar => true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(:match) do desc 'An optional regular expression to run against existing lines in the file;\n' + 'if a match is found, we replace that line rather than adding a new line.' end newparam(:line) do desc 'The line to be appended to the file located by the path parameter.' end newparam(:path) do desc 'The file Puppet will ensure contains the line specified by the line parameter.' validate do |value| unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/)) raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'") end end end # Autorequire the file resource if it's being managed autorequire(:file) do self[:path] end validate do unless self[:line] and self[:path] raise(Puppet::Error, "Both line and path are required attributes") end if (self[:match]) unless Regexp.new(self[:match]).match(self[:line]) raise(Puppet::Error, "When providing a 'match' parameter, the value must be a regex that matches against the value of your 'line' parameter") end end end end puppetlabs-stdlib-4.0.2/manifests/000077500000000000000000000000001213204025400171355ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/manifests/init.pp000066400000000000000000000006231213204025400204420ustar00rootroot00000000000000# Class: stdlib # # This module manages stdlib. Most of stdlib's features are automatically # loaded by Puppet, but this class should be declared in order to use the # standardized run stages. # # Parameters: none # # Actions: # # Declares all other classes in the stdlib module. Currently, this consists # of stdlib::stages. # # Requires: nothing # class stdlib { class { 'stdlib::stages': } } puppetlabs-stdlib-4.0.2/manifests/stages.pp000066400000000000000000000015331213204025400207660ustar00rootroot00000000000000# Class: stdlib::stages # # This class manages a standard set of run stages for Puppet. It is managed by # the stdlib class, and should not be declared independently. # # The high level stages are (in order): # # * setup # * main # * runtime # * setup_infra # * deploy_infra # * setup_app # * deploy_app # * deploy # # Parameters: none # # Actions: # # Declares various run-stages for deploying infrastructure, # language runtimes, and application layers. # # Requires: nothing # # Sample Usage: # # node default { # include stdlib # class { java: stage => 'runtime' } # } # class stdlib::stages { stage { 'setup': before => Stage['main'] } stage { 'runtime': require => Stage['main'] } -> stage { 'setup_infra': } -> stage { 'deploy_infra': } -> stage { 'setup_app': } -> stage { 'deploy_app': } -> stage { 'deploy': } } puppetlabs-stdlib-4.0.2/spec/000077500000000000000000000000001213204025400160765ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/classes/000077500000000000000000000000001213204025400175335ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/classes/anchor_spec.rb000066400000000000000000000012431213204025400223440ustar00rootroot00000000000000require 'puppet' require 'rspec-puppet' describe "anchorrefresh" do let(:node) { 'testhost.example.com' } let :pre_condition do <<-ANCHORCLASS class anchored { anchor { 'anchored::begin': } ~> anchor { 'anchored::end': } } class anchorrefresh { notify { 'first': } ~> class { 'anchored': } ~> anchor { 'final': } } ANCHORCLASS end def apply_catalog_and_return_exec_rsrc catalog = subject.to_ral transaction = catalog.apply transaction.resource_status("Anchor[final]") end it 'propagates events through the anchored class' do resource = apply_catalog_and_return_exec_rsrc expect(resource.restarted).to eq(true) end end puppetlabs-stdlib-4.0.2/spec/functions/000077500000000000000000000000001213204025400201065ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/functions/defined_with_params_spec.rb000066400000000000000000000025271213204025400254470ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'rspec-puppet' describe 'defined_with_params' do describe 'when a resource is not specified' do it { should run.with_params().and_raise_error(ArgumentError) } end describe 'when compared against a resource with no attributes' do let :pre_condition do 'user { "dan": }' end it do should run.with_params('User[dan]', {}).and_return(true) should run.with_params('User[bob]', {}).and_return(false) should run.with_params('User[dan]', {'foo' => 'bar'}).and_return(false) end end describe 'when compared against a resource with attributes' do let :pre_condition do 'user { "dan": ensure => present, shell => "/bin/csh", managehome => false}' end it do should run.with_params('User[dan]', {}).and_return(true) should run.with_params('User[dan]', '').and_return(true) should run.with_params('User[dan]', {'ensure' => 'present'} ).and_return(true) should run.with_params('User[dan]', {'ensure' => 'present', 'managehome' => false} ).and_return(true) should run.with_params('User[dan]', {'ensure' => 'absent', 'managehome' => false} ).and_return(false) end end end puppetlabs-stdlib-4.0.2/spec/functions/ensure_packages_spec.rb000066400000000000000000000024411213204025400246050ustar00rootroot00000000000000#! /usr/bin/env ruby require 'spec_helper' require 'rspec-puppet' describe 'ensure_packages' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'argument handling' do it 'fails with no arguments' do should run.with_params().and_raise_error(Puppet::ParseError) end it 'requires an array' do lambda { scope.function_ensure_packages([['foo']]) }.should_not raise_error end it 'fails when given a string' do should run.with_params('foo').and_raise_error(Puppet::ParseError) end end context 'given a catalog containing Package[puppet]{ensure => absent}' do let :pre_condition do 'package { puppet: ensure => absent }' end # NOTE: should run.with_params has the side effect of making the compiler # available to the test harness. it 'has no effect on Package[puppet]' do should run.with_params(['puppet']) rsrc = compiler.catalog.resource('Package[puppet]') rsrc.to_hash.should == {:ensure => "absent"} end end context 'given a clean catalog' do it 'declares package resources with ensure => present' do should run.with_params(['facter']) rsrc = compiler.catalog.resource('Package[facter]') rsrc.to_hash.should == {:name => "facter", :ensure => "present"} end end end puppetlabs-stdlib-4.0.2/spec/functions/ensure_resource_spec.rb000066400000000000000000000025241213204025400246600ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'rspec-puppet' describe 'ensure_resource' do describe 'when a type or title is not specified' do it do should run.with_params().and_raise_error(ArgumentError) should run.with_params(['type']).and_raise_error(ArgumentError) end end describe 'when compared against a resource with no attributes' do let :pre_condition do 'user { "dan": }' end it do should run.with_params('user', 'dan', {}) compiler.catalog.resource('User[dan]').to_s.should == 'User[dan]' end end describe 'when compared against a resource with attributes' do let :pre_condition do 'user { "dan": ensure => present, shell => "/bin/csh", managehome => false}' end it do # these first three should not fail should run.with_params('User', 'dan', {}) should run.with_params('User', 'dan', '') should run.with_params('User', 'dan', {'ensure' => 'present'}) should run.with_params('User', 'dan', {'ensure' => 'present', 'managehome' => false} ) # test that this fails should run.with_params('User', 'dan', {'ensure' => 'absent', 'managehome' => false} ).and_raise_error(Puppet::Error) end end end puppetlabs-stdlib-4.0.2/spec/functions/getparam_spec.rb000066400000000000000000000021711213204025400232460ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' require 'rspec-puppet' describe 'getparam' do describe 'when a resource is not specified' do it do should run.with_params().and_raise_error(ArgumentError) should run.with_params('User[dan]').and_raise_error(ArgumentError) should run.with_params('User[dan]', {}).and_raise_error(ArgumentError) should run.with_params('User[dan]', '').and_return('') end end describe 'when compared against a resource with no params' do let :pre_condition do 'user { "dan": }' end it do should run.with_params('User[dan]', 'shell').and_return('') end end describe 'when compared against a resource with params' do let :pre_condition do 'user { "dan": ensure => present, shell => "/bin/sh", managehome => false}' end it do should run.with_params('User[dan]', 'shell').and_return('/bin/sh') should run.with_params('User[dan]', '').and_return('') should run.with_params('User[dan]', 'ensure').and_return('present') should run.with_params('User[dan]', 'managehome').and_return(false) end end end puppetlabs-stdlib-4.0.2/spec/monkey_patches/000077500000000000000000000000001213204025400211075ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/monkey_patches/alias_should_to_must.rb000077500000000000000000000002271213204025400256610ustar00rootroot00000000000000require 'rspec' class Object # This is necessary because the RAL has a 'should' # method. alias :must :should alias :must_not :should_not end puppetlabs-stdlib-4.0.2/spec/monkey_patches/publicize_methods.rb000077500000000000000000000005621213204025400251530ustar00rootroot00000000000000# Some monkey-patching to allow us to test private methods. class Class def publicize_methods(*methods) saved_private_instance_methods = methods.empty? ? self.private_instance_methods : methods self.class_eval { public(*saved_private_instance_methods) } yield self.class_eval { private(*saved_private_instance_methods) } end end puppetlabs-stdlib-4.0.2/spec/spec.opts000066400000000000000000000000571213204025400177410ustar00rootroot00000000000000--format s --colour --loadby mtime --backtrace puppetlabs-stdlib-4.0.2/spec/spec_helper.rb000066400000000000000000000016661213204025400207250ustar00rootroot00000000000000dir = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH.unshift File.join(dir, 'lib') # Don't want puppet getting the command line arguments for rake or autotest ARGV.clear require 'puppet' require 'facter' require 'mocha' gem 'rspec', '>=2.0.0' require 'rspec/expectations' require 'puppetlabs_spec_helper/module_spec_helper' RSpec.configure do |config| # FIXME REVISIT - We may want to delegate to Facter like we do in # Puppet::PuppetSpecInitializer.initialize_via_testhelper(config) because # this behavior is a duplication of the spec_helper in Facter. config.before :each do # Ensure that we don't accidentally cache facts and environment between # test cases. This requires each example group to explicitly load the # facts being exercised with something like # Facter.collection.loader.load(:ipaddress) Facter::Util::Loader.any_instance.stubs(:load_all) Facter.clear Facter.clear_messages end end puppetlabs-stdlib-4.0.2/spec/unit/000077500000000000000000000000001213204025400170555ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/facter/000077500000000000000000000000001213204025400203215ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/facter/pe_version_spec.rb000066400000000000000000000041121213204025400240270ustar00rootroot00000000000000#!/usr/bin/env rspec require 'spec_helper' describe "PE Version specs" do before :each do # Explicitly load the pe_version.rb file which contains generated facts # that cannot be automatically loaded. Puppet 2.x implements # Facter.collection.load while Facter 1.x markes Facter.collection.load as # a private method. if Facter.collection.respond_to? :load Facter.collection.load(:pe_version) else Facter.collection.loader.load(:pe_version) end end context "If PE is installed" do %w{ 2.6.1 2.10.300 }.each do |version| puppetversion = "2.7.19 (Puppet Enterprise #{version})" context "puppetversion => #{puppetversion}" do before :each do Facter.fact(:puppetversion).stubs(:value).returns(puppetversion) end (major,minor,patch) = version.split(".") it "Should return true" do Facter.fact(:is_pe).value.should == true end it "Should have a version of #{version}" do Facter.fact(:pe_version).value.should == version end it "Should have a major version of #{major}" do Facter.fact(:pe_major_version).value.should == major end it "Should have a minor version of #{minor}" do Facter.fact(:pe_minor_version).value.should == minor end it "Should have a patch version of #{patch}" do Facter.fact(:pe_patch_version).value.should == patch end end end end context "When PE is not installed" do before :each do Facter.fact(:puppetversion).stubs(:value).returns("2.7.19") end it "is_pe is false" do Facter.fact(:is_pe).value.should == false end it "pe_version is nil" do Facter.fact(:pe_version).value.should be_nil end it "pe_major_version is nil" do Facter.fact(:pe_major_version).value.should be_nil end it "pe_minor_version is nil" do Facter.fact(:pe_minor_version).value.should be_nil end it "Should have a patch version" do Facter.fact(:pe_patch_version).value.should be_nil end end end puppetlabs-stdlib-4.0.2/spec/unit/facter/root_home_spec.rb000066400000000000000000000024771213204025400236650ustar00rootroot00000000000000require 'spec_helper' require 'facter/root_home' describe Facter::Util::RootHome do context "solaris" do let(:root_ent) { "root:x:0:0:Super-User:/:/sbin/sh" } let(:expected_root_home) { "/" } it "should return /" do Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) Facter::Util::RootHome.get_root_home.should == expected_root_home end end context "linux" do let(:root_ent) { "root:x:0:0:root:/root:/bin/bash" } let(:expected_root_home) { "/root" } it "should return /root" do Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) Facter::Util::RootHome.get_root_home.should == expected_root_home end end context "macosx" do let(:root_ent) { "root:*:0:0:System Administrator:/var/root:/bin/sh" } let(:expected_root_home) { "/var/root" } it "should return /var/root" do Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) Facter::Util::RootHome.get_root_home.should == expected_root_home end end context "windows" do before :each do Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(nil) end it "should be nil on windows" do Facter::Util::RootHome.get_root_home.should be_nil end end end puppetlabs-stdlib-4.0.2/spec/unit/facter/util/000077500000000000000000000000001213204025400212765ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/facter/util/puppet_settings_spec.rb000066400000000000000000000016771213204025400261050ustar00rootroot00000000000000require 'spec_helper' require 'facter/util/puppet_settings' describe Facter::Util::PuppetSettings do describe "#with_puppet" do context "Without Puppet loaded" do before(:each) do Module.expects(:const_get).with("Puppet").raises(NameError) end it 'should be nil' do subject.with_puppet { Puppet[:vardir] }.should be_nil end it 'should not yield to the block' do Puppet.expects(:[]).never subject.with_puppet { Puppet[:vardir] }.should be_nil end end context "With Puppet loaded" do module Puppet; end let(:vardir) { "/var/lib/puppet" } before :each do Puppet.expects(:[]).with(:vardir).returns vardir end it 'should yield to the block' do subject.with_puppet { Puppet[:vardir] } end it 'should return the nodes vardir' do subject.with_puppet { Puppet[:vardir] }.should eq vardir end end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/000077500000000000000000000000001213204025400203725ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/000077500000000000000000000000001213204025400216665ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/000077500000000000000000000000001213204025400236765ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/abs_spec.rb000077500000000000000000000012271213204025400260070ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the abs function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("abs").should == "function_abs" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_abs([]) }.should( raise_error(Puppet::ParseError)) end it "should convert a negative number into a positive" do result = scope.function_abs(["-34"]) result.should(eq(34)) end it "should do nothing with a positive number" do result = scope.function_abs(["5678"]) result.should(eq(5678)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/any2array_spec.rb000066400000000000000000000031021213204025400271410ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the any2array function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("any2array").should == "function_any2array" end it "should return an empty array if there is less than 1 argument" do result = scope.function_any2array([]) result.should(eq([])) end it "should convert boolean true to [ true ] " do result = scope.function_any2array([true]) result.should(eq([true])) end it "should convert one object to [object]" do result = scope.function_any2array(['one']) result.should(eq(['one'])) end it "should convert multiple objects to [objects]" do result = scope.function_any2array(['one', 'two']) result.should(eq(['one', 'two'])) end it "should return empty array it was called with" do result = scope.function_any2array([[]]) result.should(eq([])) end it "should return one-member array it was called with" do result = scope.function_any2array([['string']]) result.should(eq(['string'])) end it "should return multi-member array it was called with" do result = scope.function_any2array([['one', 'two']]) result.should(eq(['one', 'two'])) end it "should return members of a hash it was called with" do result = scope.function_any2array([{ 'key' => 'value' }]) result.should(eq(['key', 'value'])) end it "should return an empty array if it was called with an empty hash" do result = scope.function_any2array([{ }]) result.should(eq([])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/bool2num_spec.rb000077500000000000000000000012071213204025400267750ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the bool2num function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("bool2num").should == "function_bool2num" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_bool2num([]) }.should( raise_error(Puppet::ParseError)) end it "should convert true to 1" do result = scope.function_bool2num([true]) result.should(eq(1)) end it "should convert false to 0" do result = scope.function_bool2num([false]) result.should(eq(0)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/capitalize_spec.rb000077500000000000000000000010671213204025400273710ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the capitalize function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("capitalize").should == "function_capitalize" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_capitalize([]) }.should( raise_error(Puppet::ParseError)) end it "should capitalize the beginning of a string" do result = scope.function_capitalize(["abc"]) result.should(eq("Abc")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/chomp_spec.rb000077500000000000000000000010251213204025400263440ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the chomp function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("chomp").should == "function_chomp" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_chomp([]) }.should( raise_error(Puppet::ParseError)) end it "should chomp the end of a string" do result = scope.function_chomp(["abc\n"]) result.should(eq("abc")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/chop_spec.rb000077500000000000000000000010211213204025400261630ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the chop function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("chop").should == "function_chop" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_chop([]) }.should( raise_error(Puppet::ParseError)) end it "should chop the end of a string" do result = scope.function_chop(["asdf\n"]) result.should(eq("asdf")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/concat_spec.rb000066400000000000000000000007301213204025400265040ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the concat function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_concat([]) }.should( raise_error(Puppet::ParseError)) end it "should be able to concat an array" do result = scope.function_concat([['1','2','3'],['4','5','6']]) result.should(eq(['1','2','3','4','5','6'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/count_spec.rb000066400000000000000000000016751213204025400263760ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the count function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("count").should == "function_count" end it "should raise a ArgumentError if there is more than 2 arguments" do lambda { scope.function_count(['foo', 'bar', 'baz']) }.should( raise_error(ArgumentError)) end it "should be able to count arrays" do scope.function_count([["1","2","3"]]).should(eq(3)) end it "should be able to count matching elements in arrays" do scope.function_count([["1", "2", "2"], "2"]).should(eq(2)) end it "should not count nil or empty strings" do scope.function_count([["foo","bar",nil,""]]).should(eq(2)) end it 'does not count an undefined hash key or an out of bound array index (which are both :undef)' do expect(scope.function_count([["foo",:undef,:undef]])).to eq(1) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/delete_at_spec.rb000077500000000000000000000011161213204025400271650ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the delete_at function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("delete_at").should == "function_delete_at" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_delete_at([]) }.should( raise_error(Puppet::ParseError)) end it "should delete an item at specified location from an array" do result = scope.function_delete_at([['a','b','c'],1]) result.should(eq(['a','c'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/delete_spec.rb000077500000000000000000000023571213204025400265110ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the delete function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("delete").should == "function_delete" end it "should raise a ParseError if there are fewer than 2 arguments" do lambda { scope.function_delete([]) }.should( raise_error(Puppet::ParseError)) end it "should raise a ParseError if there are greater than 2 arguments" do lambda { scope.function_delete([[], 'foo', 'bar']) }.should( raise_error(Puppet::ParseError)) end it "should raise a TypeError if a number is passed as the first argument" do lambda { scope.function_delete([1, 'bar']) }.should( raise_error(TypeError)) end it "should delete all instances of an element from an array" do result = scope.function_delete([['a','b','c','b'],'b']) result.should(eq(['a','c'])) end it "should delete all instances of a substring from a string" do result = scope.function_delete(['foobarbabarz','bar']) result.should(eq('foobaz')) end it "should delete a key from a hash" do result = scope.function_delete([{ 'a' => 1, 'b' => 2, 'c' => 3 },'b']) result.should(eq({ 'a' => 1, 'c' => 3 })) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/downcase_spec.rb000077500000000000000000000012731213204025400270460ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the downcase function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("downcase").should == "function_downcase" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_downcase([]) }.should( raise_error(Puppet::ParseError)) end it "should downcase a string" do result = scope.function_downcase(["ASFD"]) result.should(eq("asfd")) end it "should do nothing to a string that is already downcase" do result = scope.function_downcase(["asdf asdf"]) result.should(eq("asdf asdf")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/empty_spec.rb000077500000000000000000000012351213204025400263770ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the empty function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("empty").should == "function_empty" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_empty([]) }.should( raise_error(Puppet::ParseError)) end it "should return a true for an empty string" do result = scope.function_empty(['']) result.should(eq(true)) end it "should return a false for a non-empty string" do result = scope.function_empty(['asdf']) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/flatten_spec.rb000077500000000000000000000016451213204025400267030ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the flatten function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("flatten").should == "function_flatten" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_flatten([]) }.should( raise_error(Puppet::ParseError)) end it "should raise a ParseError if there is more than 1 argument" do lambda { scope.function_flatten([[], []]) }.should( raise_error(Puppet::ParseError)) end it "should flatten a complex data structure" do result = scope.function_flatten([["a","b",["c",["d","e"],"f","g"]]]) result.should(eq(["a","b","c","d","e","f","g"])) end it "should do nothing to a structure that is already flat" do result = scope.function_flatten([["a","b","c","d"]]) result.should(eq(["a","b","c","d"])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/floor_spec.rb000066400000000000000000000023621213204025400263610ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the floor function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("floor").should == "function_floor" end it "should raise a ParseError if there is less than 1 argument" do lambda { scope.function_floor([]) }.should( raise_error(Puppet::ParseError, /Wrong number of arguments/)) end it "should should raise a ParseError if input isn't numeric (eg. String)" do lambda { scope.function_floor(["foo"]) }.should( raise_error(Puppet::ParseError, /Wrong argument type/)) end it "should should raise a ParseError if input isn't numeric (eg. Boolean)" do lambda { scope.function_floor([true]) }.should( raise_error(Puppet::ParseError, /Wrong argument type/)) end it "should return an integer when a numeric type is passed" do result = scope.function_floor([12.4]) result.is_a?(Integer).should(eq(true)) end it "should return the input when an integer is passed" do result = scope.function_floor([7]) result.should(eq(7)) end it "should return the largest integer less than or equal to the input" do result = scope.function_floor([3.8]) result.should(eq(3)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/fqdn_rotate_spec.rb000066400000000000000000000024671213204025400275540ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the fqdn_rotate function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("fqdn_rotate").should == "function_fqdn_rotate" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_fqdn_rotate([]) }.should( raise_error(Puppet::ParseError)) end it "should rotate a string and the result should be the same size" do scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.1") result = scope.function_fqdn_rotate(["asdf"]) result.size.should(eq(4)) end it "should rotate a string to give the same results for one host" do scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.1").twice scope.function_fqdn_rotate(["abcdefg"]).should eql(scope.function_fqdn_rotate(["abcdefg"])) end it "should rotate a string to give different values on different hosts" do scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.1") val1 = scope.function_fqdn_rotate(["abcdefghijklmnopqrstuvwxyz01234567890987654321"]) scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.2") val2 = scope.function_fqdn_rotate(["abcdefghijklmnopqrstuvwxyz01234567890987654321"]) val1.should_not eql(val2) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/get_module_path_spec.rb000066400000000000000000000040241213204025400303750ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:get_module_path) do Internals = PuppetlabsSpec::PuppetInternals class StubModule attr_reader :path def initialize(path) @path = path end end def scope(environment = "production") Internals.scope(:compiler => Internals.compiler(:node => Internals.node(:environment => environment))) end it 'should only allow one argument' do expect { scope.function_get_module_path([]) }.to raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) expect { scope.function_get_module_path(['1','2','3']) }.to raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) end it 'should raise an exception when the module cannot be found' do expect { scope.function_get_module_path(['foo']) }.to raise_error(Puppet::ParseError, /Could not find module/) end describe 'when locating a module' do let(:modulepath) { "/tmp/does_not_exist" } let(:path_of_module_foo) { StubModule.new("/tmp/does_not_exist/foo") } before(:each) { Puppet[:modulepath] = modulepath } it 'should be able to find module paths from the modulepath setting' do Puppet::Module.expects(:find).with('foo', 'production').returns(path_of_module_foo) scope.function_get_module_path(['foo']).should == path_of_module_foo.path end it 'should be able to find module paths when the modulepath is a list' do Puppet[:modulepath] = modulepath + ":/tmp" Puppet::Module.expects(:find).with('foo', 'production').returns(path_of_module_foo) scope.function_get_module_path(['foo']).should == path_of_module_foo.path end it 'should respect the environment' do pending("Disabled on Puppet 2.6.x") if Puppet.version =~ /^2\.6\b/ Puppet.settings[:environment] = 'danstestenv' Puppet::Module.expects(:find).with('foo', 'danstestenv').returns(path_of_module_foo) scope('danstestenv').function_get_module_path(['foo']).should == path_of_module_foo.path end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/getvar_spec.rb000066400000000000000000000024221213204025400265250ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:getvar) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling getvar from puppet' do it "should not compile when no arguments are passed" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = '$foo = getvar()' expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end it "should not compile when too many arguments are passed" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = '$foo = getvar("foo::bar", "baz")' expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end it "should lookup variables in other namespaces" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = <<-'ENDofPUPPETcode' class site::data { $foo = 'baz' } include site::data $foo = getvar("site::data::foo") if $foo != 'baz' { fail('getvar did not return what we expect') } ENDofPUPPETcode scope.compiler.compile end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/grep_spec.rb000077500000000000000000000010741213204025400261770ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the grep function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("grep").should == "function_grep" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_grep([]) }.should( raise_error(Puppet::ParseError)) end it "should grep contents from an array" do result = scope.function_grep([["aaabbb","bbbccc","dddeee"], "bbb"]) result.should(eq(["aaabbb","bbbccc"])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/has_interface_with_spec.rb000077500000000000000000000043431213204025400310720ustar00rootroot00000000000000#!/usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:has_interface_with) do let(:scope) do PuppetlabsSpec::PuppetInternals.scope end # The subject of these examples is the method itself. subject do function_name = Puppet::Parser::Functions.function(:has_interface_with) scope.method(function_name) end # We need to mock out the Facts so we can specify how we expect this function # to behave on different platforms. context "On Mac OS X Systems" do before :each do scope.stubs(:lookupvar).with("interfaces").returns('lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0') end it 'should have loopback (lo0)' do subject.call(['lo0']).should be_true end it 'should not have loopback (lo)' do subject.call(['lo']).should be_false end end context "On Linux Systems" do before :each do scope.stubs(:lookupvar).with("interfaces").returns('eth0,lo') scope.stubs(:lookupvar).with("ipaddress").returns('10.0.0.1') scope.stubs(:lookupvar).with("ipaddress_lo").returns('127.0.0.1') scope.stubs(:lookupvar).with("ipaddress_eth0").returns('10.0.0.1') scope.stubs(:lookupvar).with('muppet').returns('kermit') scope.stubs(:lookupvar).with('muppet_lo').returns('mspiggy') scope.stubs(:lookupvar).with('muppet_eth0').returns('kermit') end it 'should have loopback (lo)' do subject.call(['lo']).should be_true end it 'should not have loopback (lo0)' do subject.call(['lo0']).should be_false end it 'should have ipaddress with 127.0.0.1' do subject.call(['ipaddress', '127.0.0.1']).should be_true end it 'should have ipaddress with 10.0.0.1' do subject.call(['ipaddress', '10.0.0.1']).should be_true end it 'should not have ipaddress with 10.0.0.2' do subject.call(['ipaddress', '10.0.0.2']).should be_false end it 'should have muppet named kermit' do subject.call(['muppet', 'kermit']).should be_true end it 'should have muppet named mspiggy' do subject.call(['muppet', 'mspiggy']).should be_true end it 'should not have muppet named bigbird' do subject.call(['muppet', 'bigbird']).should be_false end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/has_ip_address_spec.rb000077500000000000000000000021121213204025400302040ustar00rootroot00000000000000#!/usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:has_ip_address) do let(:scope) do PuppetlabsSpec::PuppetInternals.scope end subject do function_name = Puppet::Parser::Functions.function(:has_ip_address) scope.method(function_name) end context "On Linux Systems" do before :each do scope.stubs(:lookupvar).with('interfaces').returns('eth0,lo') scope.stubs(:lookupvar).with('ipaddress').returns('10.0.2.15') scope.stubs(:lookupvar).with('ipaddress_eth0').returns('10.0.2.15') scope.stubs(:lookupvar).with('ipaddress_lo').returns('127.0.0.1') end it 'should have primary address (10.0.2.15)' do subject.call(['10.0.2.15']).should be_true end it 'should have lookupback address (127.0.0.1)' do subject.call(['127.0.0.1']).should be_true end it 'should not have other address' do subject.call(['192.1681.1.1']).should be_false end it 'should not have "mspiggy" on an interface' do subject.call(['mspiggy']).should be_false end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/has_ip_network_spec.rb000077500000000000000000000017171213204025400302620ustar00rootroot00000000000000#!/usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:has_ip_network) do let(:scope) do PuppetlabsSpec::PuppetInternals.scope end subject do function_name = Puppet::Parser::Functions.function(:has_ip_network) scope.method(function_name) end context "On Linux Systems" do before :each do scope.stubs(:lookupvar).with('interfaces').returns('eth0,lo') scope.stubs(:lookupvar).with('network').returns(:undefined) scope.stubs(:lookupvar).with('network_eth0').returns('10.0.2.0') scope.stubs(:lookupvar).with('network_lo').returns('127.0.0.1') end it 'should have primary network (10.0.2.0)' do subject.call(['10.0.2.0']).should be_true end it 'should have loopback network (127.0.0.0)' do subject.call(['127.0.0.1']).should be_true end it 'should not have other network' do subject.call(['192.168.1.0']).should be_false end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/has_key_spec.rb000066400000000000000000000027031213204025400266620ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:has_key) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling has_key from puppet' do it "should not compile when no arguments are passed" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = '$x = has_key()' expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end it "should not compile when 1 argument is passed" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = "$x = has_key('foo')" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end it "should require the first value to be a Hash" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = "$x = has_key('foo', 'bar')" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /expects the first argument to be a hash/) end end describe 'when calling the function has_key from a scope instance' do it 'should detect existing keys' do scope.function_has_key([{'one' => 1}, 'one']).should be_true end it 'should detect existing keys' do scope.function_has_key([{'one' => 1}, 'two']).should be_false end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/hash_spec.rb000066400000000000000000000010561213204025400261620ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the hash function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("hash").should == "function_hash" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_hash([]) }.should( raise_error(Puppet::ParseError)) end it "should convert an array to a hash" do result = scope.function_hash([['a',1,'b',2,'c',3]]) result.should(eq({'a'=>1,'b'=>2,'c'=>3})) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_array_spec.rb000066400000000000000000000014601213204025400270470ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_array function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_array").should == "function_is_array" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_array([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if passed an array" do result = scope.function_is_array([[1,2,3]]) result.should(eq(true)) end it "should return false if passed a hash" do result = scope.function_is_array([{'a'=>1}]) result.should(eq(false)) end it "should return false if passed a string" do result = scope.function_is_array(["asdf"]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_domain_name_spec.rb000066400000000000000000000036011213204025400301770ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_domain_name function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_domain_name").should == "function_is_domain_name" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_domain_name([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if a valid short domain name" do result = scope.function_is_domain_name(["x.com"]) result.should(be_true) end it "should return true if the domain is ." do result = scope.function_is_domain_name(["."]) result.should(be_true) end it "should return true if the domain is x.com." do result = scope.function_is_domain_name(["x.com."]) result.should(be_true) end it "should return true if a valid domain name" do result = scope.function_is_domain_name(["foo.bar.com"]) result.should(be_true) end it "should allow domain parts to start with numbers" do result = scope.function_is_domain_name(["3foo.2bar.com"]) result.should(be_true) end it "should allow domain to end with a dot" do result = scope.function_is_domain_name(["3foo.2bar.com."]) result.should(be_true) end it "should allow a single part domain" do result = scope.function_is_domain_name(["orange"]) result.should(be_true) end it "should return false if domain parts start with hyphens" do result = scope.function_is_domain_name(["-3foo.2bar.com"]) result.should(be_false) end it "should return true if domain contains hyphens" do result = scope.function_is_domain_name(["3foo-bar.2bar-fuzz.com"]) result.should(be_true) end it "should return false if domain name contains spaces" do result = scope.function_is_domain_name(["not valid"]) result.should(be_false) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_float_spec.rb000066400000000000000000000016721213204025400270430ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_float function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_float").should == "function_is_float" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_float([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if a float" do result = scope.function_is_float(["0.12"]) result.should(eq(true)) end it "should return false if a string" do result = scope.function_is_float(["asdf"]) result.should(eq(false)) end it "should return false if an integer" do result = scope.function_is_float(["3"]) result.should(eq(false)) end it "should return true if a float is created from an arithmetical operation" do result = scope.function_is_float([3.2*2]) result.should(eq(true)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_function_available.rb000066400000000000000000000015721213204025400305500ustar00rootroot00000000000000#!/usr/bin/env rspec require 'spec_helper' describe "the is_function_available function" do before :all do Puppet::Parser::Functions.autoloader.loadall end before :each do @scope = Puppet::Parser::Scope.new end it "should exist" do Puppet::Parser::Functions.function("is_function_available").should == "function_is_function_available" end it "should raise a ParseError if there is less than 1 arguments" do lambda { @scope.function_is_function_available([]) }.should( raise_error(Puppet::ParseError)) end it "should return false if a nonexistent function is passed" do result = @scope.function_is_function_available(['jeff_mccunes_left_sock']) result.should(eq(false)) end it "should return true if an available function is passed" do result = @scope.function_is_function_available(['require']) result.should(eq(true)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_hash_spec.rb000066400000000000000000000014621213204025400266560ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_hash function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_hash").should == "function_is_hash" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_hash([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if passed a hash" do result = scope.function_is_hash([{"a"=>1,"b"=>2}]) result.should(eq(true)) end it "should return false if passed an array" do result = scope.function_is_hash([["a","b"]]) result.should(eq(false)) end it "should return false if passed a string" do result = scope.function_is_hash(["asdf"]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_integer_spec.rb000066400000000000000000000017131213204025400273670ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_integer function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_integer").should == "function_is_integer" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_integer([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if an integer" do result = scope.function_is_integer(["3"]) result.should(eq(true)) end it "should return false if a float" do result = scope.function_is_integer(["3.2"]) result.should(eq(false)) end it "should return false if a string" do result = scope.function_is_integer(["asdf"]) result.should(eq(false)) end it "should return true if an integer is created from an arithmetical operation" do result = scope.function_is_integer([3*2]) result.should(eq(true)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_ip_address_spec.rb000066400000000000000000000022351213204025400300470ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_ip_address function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_ip_address").should == "function_is_ip_address" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_ip_address([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if an IPv4 address" do result = scope.function_is_ip_address(["1.2.3.4"]) result.should(eq(true)) end it "should return true if a full IPv6 address" do result = scope.function_is_ip_address(["fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74"]) result.should(eq(true)) end it "should return true if a compressed IPv6 address" do result = scope.function_is_ip_address(["fe00::1"]) result.should(eq(true)) end it "should return false if not valid" do result = scope.function_is_ip_address(["asdf"]) result.should(eq(false)) end it "should return false if IP octets out of range" do result = scope.function_is_ip_address(["1.1.1.300"]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_mac_address_spec.rb000066400000000000000000000015761213204025400302060ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_mac_address function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_mac_address").should == "function_is_mac_address" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_mac_address([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if a valid mac address" do result = scope.function_is_mac_address(["00:a0:1f:12:7f:a0"]) result.should(eq(true)) end it "should return false if octets are out of range" do result = scope.function_is_mac_address(["00:a0:1f:12:7f:g0"]) result.should(eq(false)) end it "should return false if not valid" do result = scope.function_is_mac_address(["not valid"]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_numeric_spec.rb000066400000000000000000000021551213204025400273750ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_numeric function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_numeric").should == "function_is_numeric" end it "should raise a ParseError if there is less than 1 argument" do lambda { scope.function_is_numeric([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if an integer" do result = scope.function_is_numeric(["3"]) result.should(eq(true)) end it "should return true if a float" do result = scope.function_is_numeric(["3.2"]) result.should(eq(true)) end it "should return true if an integer is created from an arithmetical operation" do result = scope.function_is_numeric([3*2]) result.should(eq(true)) end it "should return true if a float is created from an arithmetical operation" do result = scope.function_is_numeric([3.2*2]) result.should(eq(true)) end it "should return false if a string" do result = scope.function_is_numeric(["asdf"]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/is_string_spec.rb000066400000000000000000000016441213204025400272430ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the is_string function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("is_string").should == "function_is_string" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_is_string([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if a string" do result = scope.function_is_string(["asdf"]) result.should(eq(true)) end it "should return false if an integer" do result = scope.function_is_string(["3"]) result.should(eq(false)) end it "should return false if a float" do result = scope.function_is_string(["3.23"]) result.should(eq(false)) end it "should return false if an array" do result = scope.function_is_string([["a","b","c"]]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/join_keys_to_values_spec.rb000066400000000000000000000027221213204025400313130ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the join_keys_to_values function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("join_keys_to_values").should == "function_join_keys_to_values" end it "should raise a ParseError if there are fewer than two arguments" do lambda { scope.function_join_keys_to_values([{}]) }.should raise_error Puppet::ParseError end it "should raise a ParseError if there are greater than two arguments" do lambda { scope.function_join_keys_to_values([{}, 'foo', 'bar']) }.should raise_error Puppet::ParseError end it "should raise a TypeError if the first argument is an array" do lambda { scope.function_join_keys_to_values([[1,2], ',']) }.should raise_error TypeError end it "should raise a TypeError if the second argument is an array" do lambda { scope.function_join_keys_to_values([{}, [1,2]]) }.should raise_error TypeError end it "should raise a TypeError if the second argument is a number" do lambda { scope.function_join_keys_to_values([{}, 1]) }.should raise_error TypeError end it "should return an empty array given an empty hash" do result = scope.function_join_keys_to_values([{}, ":"]) result.should == [] end it "should join hash's keys to its values" do result = scope.function_join_keys_to_values([{'a'=>1,2=>'foo',:b=>nil}, ":"]) result.should =~ ['a:1','2:foo','b:'] end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/join_spec.rb000066400000000000000000000010371213204025400261750ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the join function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("join").should == "function_join" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_join([]) }.should( raise_error(Puppet::ParseError)) end it "should join an array into a string" do result = scope.function_join([["a","b","c"], ":"]) result.should(eq("a:b:c")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/keys_spec.rb000066400000000000000000000012331213204025400262070ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the keys function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("keys").should == "function_keys" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_keys([]) }.should( raise_error(Puppet::ParseError)) end it "should return an array of keys when given a hash" do result = scope.function_keys([{'a'=>1, 'b'=>2}]) # =~ performs 'array with same elements' (set) matching # For more info see RSpec::Matchers::MatchArray result.should =~ ['a','b'] end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/lstrip_spec.rb000066400000000000000000000010221213204025400265450ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the lstrip function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("lstrip").should == "function_lstrip" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_lstrip([]) }.should( raise_error(Puppet::ParseError)) end it "should lstrip a string" do result = scope.function_lstrip([" asdf"]) result.should(eq('asdf')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/max_spec.rb000077500000000000000000000013541213204025400260300ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the max function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("max").should == "function_max" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_max([]) }.should( raise_error(Puppet::ParseError)) end it "should be able to compare strings" do scope.function_max(["albatross","dog","horse"]).should(eq("horse")) end it "should be able to compare numbers" do scope.function_max([6,8,4]).should(eq(8)) end it "should be able to compare a number with a stringified number" do scope.function_max([1,"2"]).should(eq("2")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/member_spec.rb000066400000000000000000000013131213204025400265020ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the member function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("member").should == "function_member" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_member([]) }.should( raise_error(Puppet::ParseError)) end it "should return true if a member is in an array" do result = scope.function_member([["a","b","c"], "a"]) result.should(eq(true)) end it "should return false if a member is not in an array" do result = scope.function_member([["a","b","c"], "d"]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/merge_spec.rb000066400000000000000000000031561213204025400263410ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:merge) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling merge from puppet' do it "should not compile when no arguments are passed" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = '$x = merge()' expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end it "should not compile when 1 argument is passed" do pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ Puppet[:code] = "$my_hash={'one' => 1}\n$x = merge($my_hash)" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end end describe 'when calling merge on the scope instance' do it 'should require all parameters are hashes' do expect { new_hash = scope.function_merge([{}, '2'])}.to raise_error(Puppet::ParseError, /unexpected argument type String/) end it 'should be able to merge two hashes' do new_hash = scope.function_merge([{'one' => '1', 'two' => '1'}, {'two' => '2', 'three' => '2'}]) new_hash['one'].should == '1' new_hash['two'].should == '2' new_hash['three'].should == '2' end it 'should merge multiple hashes' do hash = scope.function_merge([{'one' => 1}, {'one' => '2'}, {'one' => '3'}]) hash['one'].should == '3' end it 'should accept empty hashes' do scope.function_merge([{},{},{}]).should == {} end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/min_spec.rb000077500000000000000000000013561213204025400260300ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the min function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("min").should == "function_min" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_min([]) }.should( raise_error(Puppet::ParseError)) end it "should be able to compare strings" do scope.function_min(["albatross","dog","horse"]).should(eq("albatross")) end it "should be able to compare numbers" do scope.function_min([6,8,4]).should(eq(4)) end it "should be able to compare a number with a stringified number" do scope.function_min([1,"2"]).should(eq(1)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/num2bool_spec.rb000066400000000000000000000035651213204025400270030ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the num2bool function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("num2bool").should == "function_num2bool" end it "should raise a ParseError if there are no arguments" do lambda { scope.function_num2bool([]) }.should( raise_error(Puppet::ParseError)) end it "should raise a ParseError if there are more than 1 arguments" do lambda { scope.function_num2bool(["foo","bar"]) }.should( raise_error(Puppet::ParseError)) end it "should raise a ParseError if passed something non-numeric" do lambda { scope.function_num2bool(["xyzzy"]) }.should( raise_error(Puppet::ParseError)) end it "should return true if passed string 1" do result = scope.function_num2bool(["1"]) result.should(be_true) end it "should return true if passed string 1.5" do result = scope.function_num2bool(["1.5"]) result.should(be_true) end it "should return true if passed number 1" do result = scope.function_num2bool([1]) result.should(be_true) end it "should return false if passed string 0" do result = scope.function_num2bool(["0"]) result.should(be_false) end it "should return false if passed number 0" do result = scope.function_num2bool([0]) result.should(be_false) end it "should return false if passed string -1" do result = scope.function_num2bool(["-1"]) result.should(be_false) end it "should return false if passed string -1.5" do result = scope.function_num2bool(["-1.5"]) result.should(be_false) end it "should return false if passed number -1" do result = scope.function_num2bool([-1]) result.should(be_false) end it "should return false if passed float -1.5" do result = scope.function_num2bool([-1.5]) result.should(be_false) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/parsejson_spec.rb000066400000000000000000000011451213204025400272420ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the parsejson function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("parsejson").should == "function_parsejson" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_parsejson([]) }.should( raise_error(Puppet::ParseError)) end it "should convert JSON to a data structure" do json = <<-EOS ["aaa","bbb","ccc"] EOS result = scope.function_parsejson([json]) result.should(eq(['aaa','bbb','ccc'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/parseyaml_spec.rb000066400000000000000000000011431213204025400272310ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the parseyaml function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("parseyaml").should == "function_parseyaml" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_parseyaml([]) }.should( raise_error(Puppet::ParseError)) end it "should convert YAML to a data structure" do yaml = <<-EOS - aaa - bbb - ccc EOS result = scope.function_parseyaml([yaml]) result.should(eq(['aaa','bbb','ccc'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/pick_spec.rb000066400000000000000000000017231213204025400261660ustar00rootroot00000000000000#!/usr/bin/env ruby -S rspec require 'spec_helper' describe "the pick function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("pick").should == "function_pick" end it 'should return the correct value' do scope.function_pick(['first', 'second']).should == 'first' end it 'should return the correct value if the first value is empty' do scope.function_pick(['', 'second']).should == 'second' end it 'should remove empty string values' do scope.function_pick(['', 'first']).should == 'first' end it 'should remove :undef values' do scope.function_pick([:undef, 'first']).should == 'first' end it 'should remove :undefined values' do scope.function_pick([:undefined, 'first']).should == 'first' end it 'should error if no values are passed' do expect { scope.function_pick([]) }.to raise_error(Puppet::Error, /Must provide non empty value./) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/prefix_spec.rb000066400000000000000000000010561213204025400265340ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the prefix function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("prefix").should == "function_prefix" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_prefix([]) }.should( raise_error(Puppet::ParseError)) end it "should return a prefixed array" do result = scope.function_prefix([['a','b','c'], 'p']) result.should(eq(['pa','pb','pc'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/range_spec.rb000066400000000000000000000017261213204025400263370ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the range function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("range").should == "function_range" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_range([]) }.should( raise_error(Puppet::ParseError)) end it "should return a letter range" do result = scope.function_range(["a","d"]) result.should(eq(['a','b','c','d'])) end it "should return a number range" do result = scope.function_range(["1","4"]) result.should(eq([1,2,3,4])) end it "should work with padded hostname like strings" do expected = ("host01".."host10").to_a scope.function_range(["host01","host10"]).should eq expected end it "should coerce zero padded digits to integers" do expected = (0..10).to_a scope.function_range(["00", "10"]).should eq expected end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/reject_spec.rb000077500000000000000000000011061213204025400265120ustar00rootroot00000000000000#!/usr/bin/env ruby require 'spec_helper' describe "the reject function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("reject").should == "function_reject" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_reject([]) }.should( raise_error(Puppet::ParseError)) end it "should reject contents from an array" do result = scope.function_reject([["1111", "aaabbb","bbbccc","dddeee"], "bbb"]) result.should(eq(["1111", "dddeee"])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/reverse_spec.rb000066400000000000000000000010421213204025400267050ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the reverse function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("reverse").should == "function_reverse" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_reverse([]) }.should( raise_error(Puppet::ParseError)) end it "should reverse a string" do result = scope.function_reverse(["asdfghijkl"]) result.should(eq('lkjihgfdsa')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/rstrip_spec.rb000066400000000000000000000012471213204025400265640ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the rstrip function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("rstrip").should == "function_rstrip" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_rstrip([]) }.should( raise_error(Puppet::ParseError)) end it "should rstrip a string" do result = scope.function_rstrip(["asdf "]) result.should(eq('asdf')) end it "should rstrip each element in an array" do result = scope.function_rstrip([["a ","b ", "c "]]) result.should(eq(['a','b','c'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/shuffle_spec.rb000066400000000000000000000013731213204025400266750ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the shuffle function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("shuffle").should == "function_shuffle" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_shuffle([]) }.should( raise_error(Puppet::ParseError)) end it "should shuffle a string and the result should be the same size" do result = scope.function_shuffle(["asdf"]) result.size.should(eq(4)) end it "should shuffle a string but the sorted contents should still be the same" do result = scope.function_shuffle(["adfs"]) result.split("").sort.join("").should(eq("adfs")) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/size_spec.rb000066400000000000000000000012141213204025400262050ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the size function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("size").should == "function_size" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_size([]) }.should( raise_error(Puppet::ParseError)) end it "should return the size of a string" do result = scope.function_size(["asdf"]) result.should(eq(4)) end it "should return the size of an array" do result = scope.function_size([["a","b","c"]]) result.should(eq(3)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/sort_spec.rb000066400000000000000000000011761213204025400262310ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the sort function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("sort").should == "function_sort" end it "should raise a ParseError if there is not 1 arguments" do lambda { scope.function_sort(['','']) }.should( raise_error(Puppet::ParseError)) end it "should sort an array" do result = scope.function_sort([["a","c","b"]]) result.should(eq(['a','b','c'])) end it "should sort a string" do result = scope.function_sort(["acb"]) result.should(eq('abc')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/squeeze_spec.rb000066400000000000000000000012711213204025400267170ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the squeeze function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("squeeze").should == "function_squeeze" end it "should raise a ParseError if there is less than 2 arguments" do lambda { scope.function_squeeze([]) }.should( raise_error(Puppet::ParseError)) end it "should squeeze a string" do result = scope.function_squeeze(["aaabbbbcccc"]) result.should(eq('abc')) end it "should squeeze all elements in an array" do result = scope.function_squeeze([["aaabbbbcccc","dddfff"]]) result.should(eq(['abc','df'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/str2bool_spec.rb000066400000000000000000000015771213204025400270150ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the str2bool function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("str2bool").should == "function_str2bool" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_str2bool([]) }.should( raise_error(Puppet::ParseError)) end it "should convert string 'true' to true" do result = scope.function_str2bool(["true"]) result.should(eq(true)) end it "should convert string 'undef' to false" do result = scope.function_str2bool(["undef"]) result.should(eq(false)) end it "should return the boolean it was called with" do result = scope.function_str2bool([true]) result.should(eq(true)) result = scope.function_str2bool([false]) result.should(eq(false)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/str2saltedsha512_spec.rb000066400000000000000000000032441213204025400302530ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the str2saltedsha512 function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("str2saltedsha512").should == "function_str2saltedsha512" end it "should raise a ParseError if there is less than 1 argument" do expect { scope.function_str2saltedsha512([]) }.to( raise_error(Puppet::ParseError) ) end it "should raise a ParseError if there is more than 1 argument" do expect { scope.function_str2saltedsha512(['foo', 'bar', 'baz']) }.to( raise_error(Puppet::ParseError) ) end it "should return a salted-sha512 password hash 136 characters in length" do result = scope.function_str2saltedsha512(["password"]) result.length.should(eq(136)) end it "should raise an error if you pass a non-string password" do expect { scope.function_str2saltedsha512([1234]) }.to( raise_error(Puppet::ParseError) ) end it "should generate a valid password" do # Allow the function to generate a password based on the string 'password' password_hash = scope.function_str2saltedsha512(["password"]) # Separate the Salt and Password from the Password Hash salt = password_hash[0..7] password = password_hash[8..-1] # Convert the Salt and Password from Hex to Binary Data str_salt = Array(salt.lines).pack('H*') str_password = Array(password.lines).pack('H*') # Combine the Binary Salt with 'password' and compare the end result saltedpass = Digest::SHA512.digest(str_salt + 'password') result = (str_salt + saltedpass).unpack('H*')[0] result.should == password_hash end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/strftime_spec.rb000066400000000000000000000015521213204025400270750ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the strftime function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("strftime").should == "function_strftime" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_strftime([]) }.should( raise_error(Puppet::ParseError)) end it "using %s should be higher then when I wrote this test" do result = scope.function_strftime(["%s"]) result.to_i.should(be > 1311953157) end it "using %s should be lower then 1.5 trillion" do result = scope.function_strftime(["%s"]) result.to_i.should(be < 1500000000) end it "should return a date when given %Y-%m-%d" do result = scope.function_strftime(["%Y-%m-%d"]) result.should =~ /^\d{4}-\d{2}-\d{2}$/ end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/strip_spec.rb000066400000000000000000000010151213204025400263730ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the strip function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("strip").should == "function_strip" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_strip([]) }.should( raise_error(Puppet::ParseError)) end it "should strip a string" do result = scope.function_strip([" ab cd "]) result.should(eq('ab cd')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/suffix_spec.rb000066400000000000000000000010561213204025400265430ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the suffix function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("suffix").should == "function_suffix" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_suffix([]) }.should( raise_error(Puppet::ParseError)) end it "should return a suffixed array" do result = scope.function_suffix([['a','b','c'], 'p']) result.should(eq(['ap','bp','cp'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/swapcase_spec.rb000066400000000000000000000010441213204025400270420ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the swapcase function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("swapcase").should == "function_swapcase" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_swapcase([]) }.should( raise_error(Puppet::ParseError)) end it "should swapcase a string" do result = scope.function_swapcase(["aaBBccDD"]) result.should(eq('AAbbCCdd')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/time_spec.rb000066400000000000000000000014111213204025400261700ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the time function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("time").should == "function_time" end it "should raise a ParseError if there is more than 2 arguments" do lambda { scope.function_time(['','']) }.should( raise_error(Puppet::ParseError)) end it "should return a number" do result = scope.function_time([]) result.should be_an(Integer) end it "should be higher then when I wrote this test" do result = scope.function_time([]) result.should(be > 1311953157) end it "should be lower then 1.5 trillion" do result = scope.function_time([]) result.should(be < 1500000000) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/to_bytes_spec.rb000077500000000000000000000031121213204025400270650ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the to_bytes function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("to_bytes").should == "function_to_bytes" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_to_bytes([]) }.should( raise_error(Puppet::ParseError)) end it "should convert kB to B" do result = scope.function_to_bytes(["4 kB"]) result.should(eq(4096)) end it "should work without B in unit" do result = scope.function_to_bytes(["4 k"]) result.should(eq(4096)) end it "should work without a space before unit" do result = scope.function_to_bytes(["4k"]) result.should(eq(4096)) end it "should work without a unit" do result = scope.function_to_bytes(["5678"]) result.should(eq(5678)) end it "should convert fractions" do result = scope.function_to_bytes(["1.5 kB"]) result.should(eq(1536)) end it "should convert scientific notation" do result = scope.function_to_bytes(["1.5e2 B"]) result.should(eq(150)) end it "should do nothing with a positive number" do result = scope.function_to_bytes([5678]) result.should(eq(5678)) end it "should should raise a ParseError if input isn't a number" do lambda { scope.function_to_bytes(["foo"]) }.should( raise_error(Puppet::ParseError)) end it "should should raise a ParseError if prefix is unknown" do lambda { scope.function_to_bytes(["5 uB"]) }.should( raise_error(Puppet::ParseError)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/type_spec.rb000066400000000000000000000023111213204025400262130ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the type function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("type").should == "function_type" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_type([]) }.should( raise_error(Puppet::ParseError)) end it "should return string when given a string" do result = scope.function_type(["aaabbbbcccc"]) result.should(eq('string')) end it "should return array when given an array" do result = scope.function_type([["aaabbbbcccc","asdf"]]) result.should(eq('array')) end it "should return hash when given a hash" do result = scope.function_type([{"a"=>1,"b"=>2}]) result.should(eq('hash')) end it "should return integer when given an integer" do result = scope.function_type(["1"]) result.should(eq('integer')) end it "should return float when given a float" do result = scope.function_type(["1.34"]) result.should(eq('float')) end it "should return boolean when given a boolean" do result = scope.function_type([true]) result.should(eq('boolean')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/unique_spec.rb000066400000000000000000000013051213204025400265420ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the unique function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("unique").should == "function_unique" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_unique([]) }.should( raise_error(Puppet::ParseError)) end it "should remove duplicate elements in a string" do result = scope.function_unique(["aabbc"]) result.should(eq('abc')) end it "should remove duplicate elements in an array" do result = scope.function_unique([["a","a","b","b","c"]]) result.should(eq(['a','b','c'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/upcase_spec.rb000066400000000000000000000012301213204025400265110ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the upcase function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("upcase").should == "function_upcase" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_upcase([]) }.should( raise_error(Puppet::ParseError)) end it "should upcase a string" do result = scope.function_upcase(["abc"]) result.should(eq('ABC')) end it "should do nothing if a string is already upcase" do result = scope.function_upcase(["ABC"]) result.should(eq('ABC')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/uriescape_spec.rb000066400000000000000000000013671213204025400272240ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the uriescape function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("uriescape").should == "function_uriescape" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_uriescape([]) }.should( raise_error(Puppet::ParseError)) end it "should uriescape a string" do result = scope.function_uriescape([":/?#[]@!$&'()*+,;= "]) result.should(eq('%3A%2F%3F%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D%20')) end it "should do nothing if a string is already safe" do result = scope.function_uriescape(["ABCdef"]) result.should(eq('ABCdef')) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_absolute_path_spec.rb000066400000000000000000000044501213204025400317430ustar00rootroot00000000000000require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_absolute_path) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } # The subject of these examples is the method itself. subject do # This makes sure the function is loaded within each test function_name = Puppet::Parser::Functions.function(:validate_absolute_path) scope.method(function_name) end describe "Valid Paths" do def self.valid_paths %w{ C:/ C:\\ C:\\WINDOWS\\System32 C:/windows/system32 X:/foo/bar X:\\foo\\bar /var/tmp /var/lib/puppet /var/opt/../lib/puppet } end context "Without Puppet::Util.absolute_path? (e.g. Puppet <= 2.6)" do before :each do # The intent here is to mock Puppet to behave like Puppet 2.6 does. # Puppet 2.6 does not have the absolute_path? method. This is only a # convenience test, stdlib should be run with the Puppet 2.6.x in the # $LOAD_PATH in addition to 2.7.x and master. Puppet::Util.expects(:respond_to?).with(:absolute_path?).returns(false) end valid_paths.each do |path| it "validate_absolute_path(#{path.inspect}) should not fail" do expect { subject.call [path] }.not_to raise_error Puppet::ParseError end end end context "Puppet without mocking" do valid_paths.each do |path| it "validate_absolute_path(#{path.inspect}) should not fail" do expect { subject.call [path] }.not_to raise_error Puppet::ParseError end end end end describe 'Invalid paths' do context 'Garbage inputs' do [ nil, [ nil ], { 'foo' => 'bar' }, { }, '', ].each do |path| it "validate_absolute_path(#{path.inspect}) should fail" do expect { subject.call [path] }.to raise_error Puppet::ParseError end end end context 'Relative paths' do %w{ relative1 . .. ./foo ../foo etc/puppetlabs/puppet opt/puppet/bin }.each do |path| it "validate_absolute_path(#{path.inspect}) should fail" do expect { subject.call [path] }.to raise_error Puppet::ParseError end end end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_array_spec.rb000066400000000000000000000024101213204025400302210ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_array) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling validate_array from puppet' do %w{ true false }.each do |the_string| it "should not compile when #{the_string} is a string" do Puppet[:code] = "validate_array('#{the_string}')" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not an Array/) end it "should not compile when #{the_string} is a bare word" do Puppet[:code] = "validate_array(#{the_string})" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not an Array/) end end it "should compile when multiple array arguments are passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = [ ] $bar = [ 'one', 'two' ] validate_array($foo, $bar) ENDofPUPPETcode scope.compiler.compile end it "should not compile when an undef variable is passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = undef validate_array($foo) ENDofPUPPETcode expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not an Array/) end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_augeas_spec.rb000066400000000000000000000063261213204025400303620ustar00rootroot00000000000000require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_augeas), :if => Puppet.features.augeas? do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } # The subject of these examplres is the method itself. subject do # This makes sure the function is loaded within each test function_name = Puppet::Parser::Functions.function(:validate_augeas) scope.method(function_name) end context 'Using Puppet::Parser::Scope.new' do describe 'Garbage inputs' do inputs = [ [ nil ], [ [ nil ] ], [ { 'foo' => 'bar' } ], [ { } ], [ '' ], [ "one", "one", "MSG to User", "4th arg" ], ] inputs.each do |input| it "validate_augeas(#{input.inspect}) should fail" do expect { subject.call [input] }.to raise_error Puppet::ParseError end end end describe 'Valid inputs' do inputs = [ [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns' ], [ "proc /proc proc nodev,noexec,nosuid 0 0\n", 'Fstab.lns'], ] inputs.each do |input| it "validate_augeas(#{input.inspect}) should not fail" do expect { subject.call input }.not_to raise_error end end end describe "Valid inputs which should raise an exception without a message" do # The intent here is to make sure valid inputs raise exceptions when they # don't specify an error message to display. This is the behvior in # 2.2.x and prior. inputs = [ [ "root:x:0:0:root\n", 'Passwd.lns' ], [ "127.0.1.1\n", 'Hosts.lns' ], ] inputs.each do |input| it "validate_augeas(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /validate_augeas.*?matched less than it should/ end end end describe "Nicer Error Messages" do # The intent here is to make sure the function returns the 3rd argument # in the exception thrown inputs = [ [ "root:x:0:0:root\n", 'Passwd.lns', [], 'Failed to validate passwd content' ], [ "127.0.1.1\n", 'Hosts.lns', [], 'Wrong hosts content' ], ] inputs.each do |input| it "validate_augeas(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /#{input[2]}/ end end end describe "Passing simple unit tests" do inputs = [ [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], ] inputs.each do |input| it "validate_augeas(#{input.inspect}) should fail" do expect { subject.call input }.not_to raise_error end end end describe "Failing simple unit tests" do inputs = [ [ "foobar:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], [ "root:x:0:0:root:/root:/bin/sh\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], ] inputs.each do |input| it "validate_augeas(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /testing path/ end end end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_bool_spec.rb000066400000000000000000000032741213204025400300470ustar00rootroot00000000000000#! /usr/bin/env/ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_bool) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling validate_bool from puppet' do %w{ true false }.each do |the_string| it "should not compile when #{the_string} is a string" do Puppet[:code] = "validate_bool('#{the_string}')" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a boolean/) end it "should compile when #{the_string} is a bare word" do Puppet[:code] = "validate_bool(#{the_string})" scope.compiler.compile end end it "should not compile when an arbitrary string is passed" do Puppet[:code] = 'validate_bool("jeff and dan are awesome")' expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a boolean/) end it "should not compile when no arguments are passed" do Puppet[:code] = 'validate_bool()' expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) end it "should compile when multiple boolean arguments are passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = true $bar = false validate_bool($foo, $bar, true, false) ENDofPUPPETcode scope.compiler.compile end it "should compile when multiple boolean arguments are passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = true $bar = false validate_bool($foo, $bar, true, false, 'jeff') ENDofPUPPETcode expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a boolean/) end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_cmd_spec.rb000066400000000000000000000046601213204025400276570ustar00rootroot00000000000000require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_cmd) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } # The subject of these examplres is the method itself. subject do # This makes sure the function is loaded within each test function_name = Puppet::Parser::Functions.function(:validate_cmd) scope.method(function_name) end context 'Using Puppet::Parser::Scope.new' do describe 'Garbage inputs' do inputs = [ [ nil ], [ [ nil ] ], [ { 'foo' => 'bar' } ], [ { } ], [ '' ], [ "one", "one", "MSG to User", "4th arg" ], ] inputs.each do |input| it "validate_cmd(#{input.inspect}) should fail" do expect { subject.call [input] }.to raise_error Puppet::ParseError end end end describe 'Valid inputs' do inputs = [ [ '/full/path/to/something', '/bin/echo' ], [ '/full/path/to/something', '/bin/cat' ], ] inputs.each do |input| it "validate_cmd(#{input.inspect}) should not fail" do expect { subject.call input }.not_to raise_error end end end describe "Valid inputs which should raise an exception without a message" do # The intent here is to make sure valid inputs raise exceptions when they # don't specify an error message to display. This is the behvior in # 2.2.x and prior. inputs = [ [ "hello", "/bin/false" ], ] inputs.each do |input| it "validate_cmd(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /validate_cmd.*?failed to validate content with command/ end end end describe "Nicer Error Messages" do # The intent here is to make sure the function returns the 3rd argument # in the exception thrown inputs = [ [ "hello", [ "bye", "later", "adios" ], "MSG to User" ], [ "greetings", "salutations", "Error, greetings does not match salutations" ], ] inputs.each do |input| it "validate_cmd(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /#{input[2]}/ end end end describe "Test output message" do it "validate_cmd('whatever', 'kthnksbye') should fail" do expect { subject.call ['whatever', 'kthnksbye'] }.to raise_error /kthnksbye.* returned 1/ end end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_hash_spec.rb000066400000000000000000000024011213204025400300260ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_hash) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling validate_hash from puppet' do %w{ true false }.each do |the_string| it "should not compile when #{the_string} is a string" do Puppet[:code] = "validate_hash('#{the_string}')" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a Hash/) end it "should not compile when #{the_string} is a bare word" do Puppet[:code] = "validate_hash(#{the_string})" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a Hash/) end end it "should compile when multiple hash arguments are passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = {} $bar = { 'one' => 'two' } validate_hash($foo, $bar) ENDofPUPPETcode scope.compiler.compile end it "should not compile when an undef variable is passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = undef validate_hash($foo) ENDofPUPPETcode expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a Hash/) end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_re_spec.rb000066400000000000000000000045561213204025400275260ustar00rootroot00000000000000require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_re) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } # The subject of these examplres is the method itself. subject do # This makes sure the function is loaded within each test function_name = Puppet::Parser::Functions.function(:validate_re) scope.method(function_name) end context 'Using Puppet::Parser::Scope.new' do describe 'Garbage inputs' do inputs = [ [ nil ], [ [ nil ] ], [ { 'foo' => 'bar' } ], [ { } ], [ '' ], [ "one", "one", "MSG to User", "4th arg" ], ] inputs.each do |input| it "validate_re(#{input.inspect}) should fail" do expect { subject.call [input] }.to raise_error Puppet::ParseError end end end describe 'Valid inputs' do inputs = [ [ '/full/path/to/something', '^/full' ], [ '/full/path/to/something', 'full' ], [ '/full/path/to/something', ['full', 'absent'] ], [ '/full/path/to/something', ['full', 'absent'], 'Message to the user' ], ] inputs.each do |input| it "validate_re(#{input.inspect}) should not fail" do expect { subject.call input }.not_to raise_error end end end describe "Valid inputs which should raise an exception without a message" do # The intent here is to make sure valid inputs raise exceptions when they # don't specify an error message to display. This is the behvior in # 2.2.x and prior. inputs = [ [ "hello", [ "bye", "later", "adios" ] ], [ "greetings", "salutations" ], ] inputs.each do |input| it "validate_re(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /validate_re.*?does not match/ end end end describe "Nicer Error Messages" do # The intent here is to make sure the function returns the 3rd argument # in the exception thrown inputs = [ [ "hello", [ "bye", "later", "adios" ], "MSG to User" ], [ "greetings", "salutations", "Error, greetings does not match salutations" ], ] inputs.each do |input| it "validate_re(#{input.inspect}) should fail" do expect { subject.call input }.to raise_error /#{input[2]}/ end end end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_slength_spec.rb000077500000000000000000000043351213204025400305620ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the validate_slength function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("validate_slength").should == "function_validate_slength" end it "should raise a ParseError if there is less than 2 arguments" do expect { scope.function_validate_slength([]) }.to(raise_error(Puppet::ParseError)) expect { scope.function_validate_slength(["asdf"]) }.to(raise_error(Puppet::ParseError)) end it "should raise a ParseError if argument 2 doesn't convert to a fixnum" do expect { scope.function_validate_slength(["moo",["2"]]) }.to(raise_error(Puppet::ParseError, /Couldn't convert whatever you passed/)) end it "should raise a ParseError if argument 2 converted, but to 0, e.g. a string" do expect { scope.function_validate_slength(["moo","monkey"]) }.to(raise_error(Puppet::ParseError, /please pass a positive number as max_length/)) end it "should raise a ParseError if argument 2 converted, but to 0" do expect { scope.function_validate_slength(["moo","0"]) }.to(raise_error(Puppet::ParseError, /please pass a positive number as max_length/)) end it "should fail if string greater then size" do expect { scope.function_validate_slength(["test", 2]) }.to(raise_error(Puppet::ParseError, /It should have been less than or equal to/)) end it "should fail if you pass an array of something other than strings" do expect { scope.function_validate_slength([["moo",["moo"],Hash.new["moo" => 7]], 7]) }.to(raise_error(Puppet::ParseError, /is not a string, it's a/)) end it "should fail if you pass something other than a string or array" do expect { scope.function_validate_slength([Hash.new["moo" => "7"],6]) }.to(raise_error(Puppet::ParseError), /please pass a string, or an array of strings/) end it "should not fail if string is smaller or equal to size" do expect { scope.function_validate_slength(["test", 5]) }.to_not(raise_error(Puppet::ParseError)) end it "should not fail if array of string is are all smaller or equal to size" do expect { scope.function_validate_slength([["moo","foo","bar"], 5]) }.to_not(raise_error(Puppet::ParseError)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/validate_string_spec.rb000066400000000000000000000034311213204025400304150ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe Puppet::Parser::Functions.function(:validate_string) do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } describe 'when calling validate_string from puppet' do %w{ foo bar baz }.each do |the_string| it "should compile when #{the_string} is a string" do Puppet[:code] = "validate_string('#{the_string}')" scope.compiler.compile end it "should compile when #{the_string} is a bare word" do Puppet[:code] = "validate_string(#{the_string})" scope.compiler.compile end end %w{ true false }.each do |the_string| it "should compile when #{the_string} is a string" do Puppet[:code] = "validate_string('#{the_string}')" scope.compiler.compile end it "should not compile when #{the_string} is a bare word" do Puppet[:code] = "validate_string(#{the_string})" expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a string/) end end it "should compile when multiple string arguments are passed" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = '' $bar = 'two' validate_string($foo, $bar) ENDofPUPPETcode scope.compiler.compile end it "should compile when an explicitly undef variable is passed (NOTE THIS MAY NOT BE DESIRABLE)" do Puppet[:code] = <<-'ENDofPUPPETcode' $foo = undef validate_string($foo) ENDofPUPPETcode scope.compiler.compile end it "should compile when an undefined variable is passed (NOTE THIS MAY NOT BE DESIRABLE)" do Puppet[:code] = <<-'ENDofPUPPETcode' validate_string($foobarbazishouldnotexist) ENDofPUPPETcode scope.compiler.compile end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/values_at_spec.rb000066400000000000000000000025151213204025400272230ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the values_at function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("values_at").should == "function_values_at" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_values_at([]) }.should( raise_error(Puppet::ParseError)) end it "should raise a ParseError if you try to use a range where stop is greater then start" do lambda { scope.function_values_at([['a','b'],["3-1"]]) }.should( raise_error(Puppet::ParseError)) end it "should return a value at from an array" do result = scope.function_values_at([['a','b','c'],"1"]) result.should(eq(['b'])) end it "should return a value at from an array when passed a range" do result = scope.function_values_at([['a','b','c'],"0-1"]) result.should(eq(['a','b'])) end it "should return chosen values from an array when passed number of indexes" do result = scope.function_values_at([['a','b','c'],["0","2"]]) result.should(eq(['a','c'])) end it "should return chosen values from an array when passed ranges and multiple indexes" do result = scope.function_values_at([['a','b','c','d','e','f','g'],["0","2","4-5"]]) result.should(eq(['a','c','e','f'])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/values_spec.rb000066400000000000000000000017751213204025400265460ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the values function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should exist" do Puppet::Parser::Functions.function("values").should == "function_values" end it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_values([]) }.should( raise_error(Puppet::ParseError)) end it "should return values from a hash" do result = scope.function_values([{'a'=>'1','b'=>'2','c'=>'3'}]) # =~ is the RSpec::Matchers::MatchArray matcher. # A.K.A. "array with same elements" (multiset) matching result.should =~ %w{ 1 2 3 } end it "should return a multiset" do result = scope.function_values([{'a'=>'1','b'=>'3','c'=>'3'}]) result.should =~ %w{ 1 3 3 } result.should_not =~ %w{ 1 3 } end it "should raise a ParseError unless a Hash is provided" do lambda { scope.function_values([['a','b','c']]) }.should( raise_error(Puppet::ParseError)) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/parser/functions/zip_spec.rb000066400000000000000000000007271213204025400260450ustar00rootroot00000000000000#! /usr/bin/env ruby -S rspec require 'spec_helper' describe "the zip function" do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it "should raise a ParseError if there is less than 1 arguments" do lambda { scope.function_zip([]) }.should( raise_error(Puppet::ParseError)) end it "should be able to zip an array" do result = scope.function_zip([['1','2','3'],['4','5','6']]) result.should(eq([["1", "4"], ["2", "5"], ["3", "6"]])) end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/provider/000077500000000000000000000000001213204025400222245ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/puppet/provider/file_line/000077500000000000000000000000001213204025400241525ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/puppet/provider/file_line/ruby_spec.rb000066400000000000000000000102161213204025400264720ustar00rootroot00000000000000require 'puppet' require 'tempfile' provider_class = Puppet::Type.type(:file_line).provider(:ruby) describe provider_class do context "when adding" do before :each do # TODO: these should be ported over to use the PuppetLabs spec_helper # file fixtures once the following pull request has been merged: # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files tmp = Tempfile.new('tmp') @tmpfile = tmp.path tmp.close! @resource = Puppet::Type::File_line.new( {:name => 'foo', :path => @tmpfile, :line => 'foo'} ) @provider = provider_class.new(@resource) end it 'should detect if the line exists in the file' do File.open(@tmpfile, 'w') do |fh| fh.write('foo') end @provider.exists?.should be_true end it 'should detect if the line does not exist in the file' do File.open(@tmpfile, 'w') do |fh| fh.write('foo1') end @provider.exists?.should be_nil end it 'should append to an existing file when creating' do @provider.create File.read(@tmpfile).chomp.should == 'foo' end end context "when matching" do before :each do # TODO: these should be ported over to use the PuppetLabs spec_helper # file fixtures once the following pull request has been merged: # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files tmp = Tempfile.new('tmp') @tmpfile = tmp.path tmp.close! @resource = Puppet::Type::File_line.new( { :name => 'foo', :path => @tmpfile, :line => 'foo = bar', :match => '^foo\s*=.*$', } ) @provider = provider_class.new(@resource) end it 'should raise an error if more than one line matches, and should not have modified the file' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") end @provider.exists?.should be_nil expect { @provider.create }.to raise_error(Puppet::Error, /More than one line.*matches/) File.read(@tmpfile).should eql("foo1\nfoo=blah\nfoo2\nfoo=baz") end it 'should replace a line that matches' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo=blah\nfoo2") end @provider.exists?.should be_nil @provider.create File.read(@tmpfile).chomp.should eql("foo1\nfoo = bar\nfoo2") end it 'should add a new line if no lines match' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo2") end @provider.exists?.should be_nil @provider.create File.read(@tmpfile).should eql("foo1\nfoo2\nfoo = bar\n") end it 'should do nothing if the exact line already exists' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo = bar\nfoo2") end @provider.exists?.should be_true @provider.create File.read(@tmpfile).chomp.should eql("foo1\nfoo = bar\nfoo2") end end context "when removing" do before :each do # TODO: these should be ported over to use the PuppetLabs spec_helper # file fixtures once the following pull request has been merged: # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files tmp = Tempfile.new('tmp') @tmpfile = tmp.path tmp.close! @resource = Puppet::Type::File_line.new( {:name => 'foo', :path => @tmpfile, :line => 'foo', :ensure => 'absent' } ) @provider = provider_class.new(@resource) end it 'should remove the line if it exists' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo\nfoo2") end @provider.destroy File.read(@tmpfile).should eql("foo1\nfoo2") end it 'should remove the line without touching the last new line' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo\nfoo2\n") end @provider.destroy File.read(@tmpfile).should eql("foo1\nfoo2\n") end it 'should remove any occurence of the line' do File.open(@tmpfile, 'w') do |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") end @provider.destroy File.read(@tmpfile).should eql("foo1\nfoo2\n") end end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/type/000077500000000000000000000000001213204025400213535ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/spec/unit/puppet/type/anchor_spec.rb000066400000000000000000000003271213204025400241660ustar00rootroot00000000000000#!/usr/bin/env ruby require 'puppet' anchor = Puppet::Type.type(:anchor).new(:name => "ntp::begin") describe anchor do it "should stringify normally" do anchor.to_s.should == "Anchor[ntp::begin]" end end puppetlabs-stdlib-4.0.2/spec/unit/puppet/type/file_line_spec.rb000066400000000000000000000050401213204025400246370ustar00rootroot00000000000000require 'puppet' require 'tempfile' describe Puppet::Type.type(:file_line) do let :file_line do Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'line', :path => '/tmp/path') end it 'should accept a line and path' do file_line[:line] = 'my_line' file_line[:line].should == 'my_line' file_line[:path] = '/my/path' file_line[:path].should == '/my/path' end it 'should accept a match regex' do file_line[:match] = '^foo.*$' file_line[:match].should == '^foo.*$' end it 'should not accept a match regex that does not match the specified line' do expect { Puppet::Type.type(:file_line).new( :name => 'foo', :path => '/my/path', :line => 'foo=bar', :match => '^bar=blah$' )}.to raise_error(Puppet::Error, /the value must be a regex that matches/) end it 'should accept a match regex that does match the specified line' do expect { Puppet::Type.type(:file_line).new( :name => 'foo', :path => '/my/path', :line => 'foo=bar', :match => '^\s*foo=.*$' )}.not_to raise_error end it 'should accept posix filenames' do file_line[:path] = '/tmp/path' file_line[:path].should == '/tmp/path' end it 'should not accept unqualified path' do expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, /File paths must be fully qualified/) end it 'should require that a line is specified' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => '/tmp/file') }.to raise_error(Puppet::Error, /Both line and path are required attributes/) end it 'should require that a file is specified' do expect { Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'path') }.to raise_error(Puppet::Error, /Both line and path are required attributes/) end it 'should default to ensure => present' do file_line[:ensure].should eq :present end it "should autorequire the file it manages" do catalog = Puppet::Resource::Catalog.new file = Puppet::Type.type(:file).new(:name => "/tmp/path") catalog.add_resource file catalog.add_resource file_line relationship = file_line.autorequire.find do |rel| (rel.source.to_s == "File[/tmp/path]") and (rel.target.to_s == file_line.to_s) end relationship.should be_a Puppet::Relationship end it "should not autorequire the file it manages if it is not managed" do catalog = Puppet::Resource::Catalog.new catalog.add_resource file_line file_line.autorequire.should be_empty end end puppetlabs-stdlib-4.0.2/spec/watchr.rb000066400000000000000000000035321213204025400177160ustar00rootroot00000000000000ENV['FOG_MOCK'] ||= 'true' ENV['AUTOTEST'] = 'true' ENV['WATCHR'] = '1' system 'clear' def growl(message) growlnotify = `which growlnotify`.chomp title = "Watchr Test Results" image = case message when /(\d+)\s+?(failure|error)/i ($1.to_i == 0) ? "~/.watchr_images/passed.png" : "~/.watchr_images/failed.png" else '~/.watchr_images/unknown.png' end options = "-w -n Watchr --image '#{File.expand_path(image)}' -m '#{message}' '#{title}'" system %(#{growlnotify} #{options} &) end def run(cmd) puts(cmd) `#{cmd}` end def run_spec_test(file) if File.exist? file result = run "rspec --format p --color #{file}" growl result.split("\n").last puts result else puts "FIXME: No test #{file} [#{Time.now}]" end end def filter_rspec(data) data.split("\n").find_all do |l| l =~ /^(\d+)\s+exampl\w+.*?(\d+).*?failur\w+.*?(\d+).*?pending/ end.join("\n") end def run_all_tests system('clear') files = Dir.glob("spec/**/*_spec.rb").join(" ") result = run "rspec #{files}" growl_results = filter_rspec result growl growl_results puts result puts "GROWL: #{growl_results}" end # Ctrl-\ Signal.trap 'QUIT' do puts " --- Running all tests ---\n\n" run_all_tests end @interrupted = false # Ctrl-C Signal.trap 'INT' do if @interrupted then @wants_to_quit = true abort("\n") else puts "Interrupt a second time to quit" @interrupted = true Kernel.sleep 1.5 # raise Interrupt, nil # let the run loop catch it run_suite end end def file2spec(file) result = file.sub('lib/puppet/', 'spec/unit/puppet/').gsub(/\.rb$/, '_spec.rb') result = file.sub('lib/facter/', 'spec/unit/facter/').gsub(/\.rb$/, '_spec.rb') end watch( 'spec/.*_spec\.rb' ) do |md| #run_spec_test(md[0]) run_all_tests end watch( 'lib/.*\.rb' ) do |md| # run_spec_test(file2spec(md[0])) run_all_tests end puppetlabs-stdlib-4.0.2/tests/000077500000000000000000000000001213204025400163065ustar00rootroot00000000000000puppetlabs-stdlib-4.0.2/tests/file_line.pp000066400000000000000000000003021213204025400205700ustar00rootroot00000000000000# This is a simple smoke test # of the file_line resource type. file { '/tmp/dansfile': ensure => present }-> file_line { 'dans_line': line => 'dan is awesome', path => '/tmp/dansfile', } puppetlabs-stdlib-4.0.2/tests/has_interface_with.pp000066400000000000000000000013621213204025400224770ustar00rootroot00000000000000include stdlib info('has_interface_with(\'lo\'):', has_interface_with('lo')) info('has_interface_with(\'loX\'):', has_interface_with('loX')) info('has_interface_with(\'ipaddress\', \'127.0.0.1\'):', has_interface_with('ipaddress', '127.0.0.1')) info('has_interface_with(\'ipaddress\', \'127.0.0.100\'):', has_interface_with('ipaddress', '127.0.0.100')) info('has_interface_with(\'network\', \'127.0.0.0\'):', has_interface_with('network', '127.0.0.0')) info('has_interface_with(\'network\', \'128.0.0.0\'):', has_interface_with('network', '128.0.0.0')) info('has_interface_with(\'netmask\', \'255.0.0.0\'):', has_interface_with('netmask', '255.0.0.0')) info('has_interface_with(\'netmask\', \'256.0.0.0\'):', has_interface_with('netmask', '256.0.0.0')) puppetlabs-stdlib-4.0.2/tests/has_ip_address.pp000066400000000000000000000002371213204025400216210ustar00rootroot00000000000000include stdlib info('has_ip_address(\'192.168.1.256\'):', has_ip_address('192.168.1.256')) info('has_ip_address(\'127.0.0.1\'):', has_ip_address('127.0.0.1')) puppetlabs-stdlib-4.0.2/tests/has_ip_network.pp000066400000000000000000000002301213204025400216560ustar00rootroot00000000000000include stdlib info('has_ip_network(\'127.0.0.0\'):', has_ip_network('127.0.0.0')) info('has_ip_network(\'128.0.0.0\'):', has_ip_network('128.0.0.0')) puppetlabs-stdlib-4.0.2/tests/init.pp000066400000000000000000000000171213204025400176100ustar00rootroot00000000000000include stdlib