add 'pathprefix2dict' utility for use by DataSourceNoCloud
This commit is contained in:
parent
cd864a69eb
commit
20c9edf01f
@ -1889,3 +1889,28 @@ def expand_dotted_devname(dotted):
|
||||
return toks
|
||||
else:
|
||||
return (dotted, None)
|
||||
|
||||
|
||||
def pathprefix2dict(base, required=None, optional=None, delim=os.path.sep):
|
||||
# return a dictionary populated with keys in 'required' and 'optional'
|
||||
# by reading files in prefix + delim + entry
|
||||
if required is None:
|
||||
required = []
|
||||
if optional is None:
|
||||
optional = []
|
||||
|
||||
missing = []
|
||||
ret = {}
|
||||
for f in required + optional:
|
||||
try:
|
||||
ret[f] = load_file(base + delim + f, quiet=False)
|
||||
except IOError as e:
|
||||
if e.errno != errno.ENOENT:
|
||||
raise
|
||||
if f in required:
|
||||
missing.append(f)
|
||||
|
||||
if len(missing):
|
||||
raise ValueError("Missing required files: %s", ','.join(missing))
|
||||
|
||||
return ret
|
||||
|
40
tests/unittests/test_pathprefix2dict.py
Normal file
40
tests/unittests/test_pathprefix2dict.py
Normal file
@ -0,0 +1,40 @@
|
||||
from cloudinit import util
|
||||
|
||||
from mocker import MockerTestCase
|
||||
from tests.unittests.helpers import populate_dir
|
||||
|
||||
|
||||
class TestPathPrefix2Dict(MockerTestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = self.makeDir()
|
||||
|
||||
def test_required_only(self):
|
||||
dirdata = {'f1': 'f1content', 'f2': 'f2content'}
|
||||
populate_dir(self.tmp, dirdata)
|
||||
|
||||
ret = util.pathprefix2dict(self.tmp, required=['f1', 'f2'])
|
||||
self.assertEqual(dirdata, ret)
|
||||
|
||||
def test_required_missing(self):
|
||||
dirdata = {'f1': 'f1content'}
|
||||
populate_dir(self.tmp, dirdata)
|
||||
kwargs = {'required': ['f1', 'f2']}
|
||||
self.assertRaises(ValueError, util.pathprefix2dict, self.tmp, **kwargs)
|
||||
|
||||
def test_no_required_and_optional(self):
|
||||
dirdata = {'f1': 'f1c', 'f2': 'f2c'}
|
||||
populate_dir(self.tmp, dirdata)
|
||||
|
||||
ret = util.pathprefix2dict(self.tmp, required=None,
|
||||
optional=['f1', 'f2'])
|
||||
self.assertEqual(dirdata, ret)
|
||||
|
||||
def test_required_and_optional(self):
|
||||
dirdata = {'f1': 'f1c', 'f2': 'f2c'}
|
||||
populate_dir(self.tmp, dirdata)
|
||||
|
||||
ret = util.pathprefix2dict(self.tmp, required=['f1'], optional=['f2'])
|
||||
self.assertEqual(dirdata, ret)
|
||||
|
||||
# vi: ts=4 expandtab
|
Loading…
x
Reference in New Issue
Block a user