From e670b272752b5632142fb2d410f53fae369def7a Mon Sep 17 00:00:00 2001 From: david22swan Date: Wed, 11 Dec 2024 10:56:58 +0000 Subject: [PATCH] (CAT-2164) Correct `yaml_syntax_validator` to error on empty file Previously empty yaml files would pass and be accepted as valid when PDK validate was run. However this was contrasted by Puppet and the puppetserver requiring files to always contain a valid yaml and so we are updating the pdk to be in line with this. --- .../validate/yaml/yaml_syntax_validator.rb | 28 +++++++++++++------ .../yaml/yaml_syntax_validator_spec.rb | 15 ++++++++++ 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/lib/pdk/validate/yaml/yaml_syntax_validator.rb b/lib/pdk/validate/yaml/yaml_syntax_validator.rb index 4b0123404..148c617c8 100644 --- a/lib/pdk/validate/yaml/yaml_syntax_validator.rb +++ b/lib/pdk/validate/yaml/yaml_syntax_validator.rb @@ -49,15 +49,25 @@ def validate_target(report, target) end begin - ::YAML.safe_load(PDK::Util::Filesystem.read_file(target), permitted_classes: YAML_ALLOWLISTED_CLASSES, permitted_symbols: [], aliases: true) - - report.add_event( - file: target, - source: name, - state: :passed, - severity: 'ok' - ) - 0 + data = ::YAML.safe_load(PDK::Util::Filesystem.read_file(target), permitted_classes: YAML_ALLOWLISTED_CLASSES, permitted_symbols: [], aliases: true) + if data.is_a?(Hash) + report.add_event( + file: target, + source: name, + state: :passed, + severity: 'ok' + ) + 0 + else + report.add_event( + file: target, + source: name, + state: :failure, + severity: 'error', + message: format('File does not contain a valid YAML hash.') + ) + 1 + end rescue Psych::SyntaxError => e report.add_event( file: target, diff --git a/spec/unit/pdk/validate/yaml/yaml_syntax_validator_spec.rb b/spec/unit/pdk/validate/yaml/yaml_syntax_validator_spec.rb index 0997194f0..4e110d7e0 100644 --- a/spec/unit/pdk/validate/yaml/yaml_syntax_validator_spec.rb +++ b/spec/unit/pdk/validate/yaml/yaml_syntax_validator_spec.rb @@ -109,5 +109,20 @@ expect(return_value).to eq(1) end end + + context 'when a target is provided that contains no YAML' do + let(:target) { { name: '.sync.yaml', content: '' } } + + it 'adds a failure event to the report' do + expect(report).to receive(:add_event).with({ + file: target[:name], + source: 'yaml-syntax', + state: :failure, + severity: 'error', + message: a_string_matching(/\AFile does not contain a valid YAML hash/) + }) + expect(return_value).to eq(1) + end + end end end