summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/chef/property.rb11
-rw-r--r--spec/unit/property/validation_spec.rb30
2 files changed, 38 insertions, 3 deletions
diff --git a/lib/chef/property.rb b/lib/chef/property.rb
index 1d91495397..b111a56f5c 100644
--- a/lib/chef/property.rb
+++ b/lib/chef/property.rb
@@ -307,7 +307,7 @@ class Chef
#
def required?(action = nil)
if !action.nil? && options[:required].is_a?(Array)
- options[:required].include?(action)
+ (options[:required] & Array(action)).any?
else
!!options[:required]
end
@@ -426,7 +426,7 @@ class Chef
end
end
- if value.nil? && required?
+ if value.nil? && required?(resource_action(resource))
raise Chef::Exceptions::ValidationFailed, "#{name} is a required property"
else
value
@@ -455,7 +455,7 @@ class Chef
Chef.deprecated(:property, options[:deprecated])
end
- if value.nil? && required?
+ if value.nil? && required?(resource_action(resource))
raise Chef::Exceptions::ValidationFailed, "#{name} is a required property"
else
value
@@ -768,5 +768,10 @@ class Chef
end
visitor.call(value)
end
+
+ # action from resource, if available
+ def resource_action(resource)
+ resource.action if resource.respond_to?(:action)
+ end
end
end
diff --git a/spec/unit/property/validation_spec.rb b/spec/unit/property/validation_spec.rb
index c8daee1580..215dd0cc7f 100644
--- a/spec/unit/property/validation_spec.rb
+++ b/spec/unit/property/validation_spec.rb
@@ -600,6 +600,36 @@ describe "Chef::Resource.property validation" do
it "does not fail if it is not specified, on running the doit2 action" do
expect { resource.run_action(:doit2) }.not_to raise_error
end
+
+ context "when an action does not require it" do
+ before do
+ resource.action(:doit2)
+ end
+
+ it "retrieval succeeds if x is not set when resource uses the doit2 action" do
+ expect { resource.x }.not_to raise_error
+ end
+
+ it "succeeds with set to nil when resource uses the doit2 action" do
+ expect { resource.x nil }.not_to raise_error
+ end
+ end
+
+ context "when an action requires it" do
+ before do
+ # NOTE: this is already the default action, but it doesn't
+ # hurt to be clear about the situation.
+ resource.action(:doit)
+ end
+
+ it "if x is not specified, retrieval fails for the doit action" do
+ expect { resource.x }.to raise_error Chef::Exceptions::ValidationFailed
+ end
+
+ it "value nil is not valid for the doit action (required means 'not nil')" do
+ expect { resource.x nil }.to raise_error Chef::Exceptions::ValidationFailed
+ end
+ end
end
with_property ":x, String, required: true" do