From 23b711954b1c1ba8deb4035503797c2f38a8ce12 Mon Sep 17 00:00:00 2001 From: Paul Berry Date: Wed, 23 Feb 2011 14:59:13 -0800 Subject: Maint: Add an assertion mechanism to Puppet This patch allows us to make C-style "assertions" in Puppet code, e.g.: assert_that { condition } assert_that(message) { condition } These methods will raise an exception if the environment variable PUPPET_ENABLE_ASSERTIONS is set to a non-empty value, and the the condition evaluates to false. If the environment variable PUPPET_ENABLE_ASSERTIONS is not set, then the condition is not even checked. Switching the assertions on with PUPPET_ENABLE_ASSERTIONS carries three advantages: 1. It makes it possible to put potentially expensive checks in assertions without degrading the performance of the code in production environments. 2. It allows strict assertions to catch Puppet bugs early in development, without increasing the risk of a crash in production environments. 3. It allows a simple command-line mechanism to run any Puppet command with assertions enabled. --- lib/puppet/util/monkey_patches.rb | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lib/puppet/util/monkey_patches.rb b/lib/puppet/util/monkey_patches.rb index 6b5af8350..85854a04c 100644 --- a/lib/puppet/util/monkey_patches.rb +++ b/lib/puppet/util/monkey_patches.rb @@ -48,3 +48,21 @@ if RUBY_VERSION == '1.8.7' end end +class Object + # The following code allows callers to make assertions that are only + # checked when the environment variable PUPPET_ENABLE_ASSERTIONS is + # set to a non-empty string. For example: + # + # assert_that { condition } + # assert_that(message) { condition } + if ENV["PUPPET_ENABLE_ASSERTIONS"].to_s != '' + def assert_that(message = nil) + unless yield + raise Exception.new("Assertion failure: #{message}") + end + end + else + def assert_that(message = nil) + end + end +end -- cgit