Allow to parse io streams from open .ini files
Change-Id: I01d25369f277ec01b02deeb47f9ac6bd8d4d81f3
This commit is contained in:
parent
60cde436a3
commit
5477cc5fde
|
@ -15,11 +15,16 @@ from __future__ import absolute_import
|
|||
|
||||
import typing
|
||||
|
||||
IniFileTextType = typing.Union[str, typing.Iterable[str]]
|
||||
|
||||
def parse_ini_file(text: str, section='DEFAULT') \
|
||||
|
||||
def parse_ini_file(text: IniFileTextType,
|
||||
section='DEFAULT') \
|
||||
-> typing.Dict[typing.Tuple[str, str], typing.Any]:
|
||||
if isinstance(text, str):
|
||||
text = text.splitlines()
|
||||
content: typing.Dict[typing.Tuple[str, str], typing.Any] = {}
|
||||
for line in text.splitlines():
|
||||
for line in text:
|
||||
line = line.rsplit('#', 1)[0] # Remove comments
|
||||
line = line.strip() # strip whitespaces
|
||||
if not line:
|
||||
|
|
|
@ -13,6 +13,10 @@
|
|||
# under the License.
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import tobiko
|
||||
from tobiko.tests import unit
|
||||
|
||||
|
@ -23,8 +27,30 @@ class ParseIniFileTest(unit.TobikoUnitTest):
|
|||
text = """
|
||||
my_option = my value
|
||||
"""
|
||||
result = tobiko.parse_ini_file(text=text, section='default-section')
|
||||
self.assertEqual({('default-section', 'my_option'): 'my value'},
|
||||
result = tobiko.parse_ini_file(text=text)
|
||||
self.assertEqual({('DEFAULT', 'my_option'): 'my value'},
|
||||
result)
|
||||
|
||||
def test_parse_ini_with_lines(self):
|
||||
lines = ['a = 3',
|
||||
'b=4']
|
||||
result = tobiko.parse_ini_file(text=lines)
|
||||
self.assertEqual({('DEFAULT', 'a'): '3',
|
||||
('DEFAULT', 'b'): '4'},
|
||||
result)
|
||||
|
||||
def test_parse_ini_with_io(self):
|
||||
text = """
|
||||
my_option = my value
|
||||
"""
|
||||
fd, temp_file = tempfile.mkstemp(text=True)
|
||||
self.addCleanup(os.remove, temp_file)
|
||||
with os.fdopen(fd, 'wt') as stream:
|
||||
stream.write(text)
|
||||
|
||||
with io.open(temp_file, 'rt') as stream:
|
||||
result = tobiko.parse_ini_file(text=stream)
|
||||
self.assertEqual({('DEFAULT', 'my_option'): 'my value'},
|
||||
result)
|
||||
|
||||
def test_parse_ini_file_with_default_section(self):
|
||||
|
|
Loading…
Reference in New Issue