gracefully handle missing parent key

This commit is contained in:
Jason Ertel
2024-06-08 07:44:46 -04:00
parent 5600fed9c4
commit f96b82b112
2 changed files with 12 additions and 1 deletions

View File

@@ -170,7 +170,7 @@ def replace(args):
def getKeyValue(content, key): def getKeyValue(content, key):
pieces = key.split(".", 1) pieces = key.split(".", 1)
if len(pieces) > 1: if len(pieces) > 1 and pieces[0] in content:
return getKeyValue(content[pieces[0]], pieces[1]) return getKeyValue(content[pieces[0]], pieces[1])
return content.get(key, None) return content.get(key, None)

View File

@@ -416,6 +416,17 @@ class TestRemove(unittest.TestCase):
self.assertEqual(result, 2) self.assertEqual(result, 2)
self.assertEqual("", mock_stdout.getvalue()) self.assertEqual("", mock_stdout.getvalue())
def test_get_missing_parent(self):
with patch('sys.stdout', new=StringIO()) as mock_stdout:
filename = "/tmp/so-yaml_test-get.yaml"
file = open(filename, "w")
file.write("{key1: { child1: 123, child2: { deep1: 45 } }, key2: false, key3: [e,f,g]}")
file.close()
result = soyaml.get([filename, "key1.child3.deep3"])
self.assertEqual(result, 2)
self.assertEqual("", mock_stdout.getvalue())
def test_get_usage(self): def test_get_usage(self):
with patch('sys.exit', new=MagicMock()) as sysmock: with patch('sys.exit', new=MagicMock()) as sysmock:
with patch('sys.stderr', new=StringIO()) as mock_stderr: with patch('sys.stderr', new=StringIO()) as mock_stderr: