From 7cf3075729c2f48e8d1d441f8a80b009c166b595 Mon Sep 17 00:00:00 2001 From: Steve Abatangle Date: Tue, 22 Nov 2022 13:03:55 -0800 Subject: Squashed commit of the following: (#13069) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Res validation should be aware of action prop reqs. The get and set methods in the Property class (for resource validation) check that a property is required if its value is nil. However, they don't check to see whether the property was required for the specific action the resource is using, so any use of get and set will throw an exception if used with a resource that doesn't use a required property, even when the property is not required for that action. What I'm describing is easier to understand with an example: the current version of the chef-client cookbook has a recipe (cron.rb) with a resource that uses the :delete action. When you try to get that resource, it throws an exception, explaining that :command is a required property—but it's only required for the :create action, not for :delete. Co-authored-by: Steve Abatangle --- spec/unit/property/validation_spec.rb | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'spec') 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 -- cgit v1.2.1