From ea7c0c493e35d9f0224ff55e0bc7a2936a244280 Mon Sep 17 00:00:00 2001 From: Adam Leff Date: Mon, 6 Mar 2017 15:46:35 -0700 Subject: [PATCH] Provide a method-based accessor for SimpleConfig hashes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When SimpleConfig parses a config file that has sections, such as a mysqld config file, the values within that section are returned via a Hash. However, we do not provide an easy way to write tests for those deep hash values: ``` describe mysql_conf('/tmp/my.cnf') do its('mysqld.expire_logs_days') { should cmp 10 } end MySQL Configuration ∅ undefined method `expire_logs_days' for # ``` This change provides a method-based accessor for Hashes that are built via SimpleConfig. ``` describe mysql_conf('/tmp/my.cnf') do its('mysqld.expire_logs_days') { should cmp 10 } end MySQL Configuration ✔ mysqld.expire_logs_days should cmp == 10 ``` Fixes #1541 by changing the way the attributes are fetched. Signed-off-by: Adam Leff --- lib/utils/simpleconfig.rb | 8 +++++++- test/unit/utils/simpleconfig_test.rb | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/utils/simpleconfig.rb b/lib/utils/simpleconfig.rb index 63c285dbc..2a60314e7 100644 --- a/lib/utils/simpleconfig.rb +++ b/lib/utils/simpleconfig.rb @@ -73,7 +73,13 @@ class SimpleConfig m = opts[:group_re].match(line) return nil if m.nil? @groups.push(m[1]) - @vals = @params[m[1]] = {} + + # We use a Hashie::Mash to provide method syntax for retrieving + # values. For configs that have keys whose values may be hashes + # (such as a mysql config that has [sections]), providing + # a hash whose values are accessible via methods provide + # a better user experience with `its` blocks. + @vals = @params[m[1]] = Hashie::Mash.new end def parse_implicit_assignment_line(line, opts) diff --git a/test/unit/utils/simpleconfig_test.rb b/test/unit/utils/simpleconfig_test.rb index 6f2f65a32..130fd3365 100644 --- a/test/unit/utils/simpleconfig_test.rb +++ b/test/unit/utils/simpleconfig_test.rb @@ -77,4 +77,11 @@ describe 'SimpleConfig Default Parser' do cur.params.must_equal(res) cur.groups.must_equal(['g', 'k']) end + + it 'provides methods to access returned hashes' do + cur = SimpleConfig.new("[section1]\nkey1 = value1\n\n[section2]\nkey2 = value2\n") + cur.params['section1'].key1.must_equal('value1') + cur.params['section2'].key2.must_equal('value2') + cur.params['section2'].missing_key.must_be_nil + end end