avocado.utils.astring: Add tabular_output() utility function

Add the tabular_output() API to avocado.utils.astring.
That function allows us to align a matrix (list of strings) properly
for output exhibition. This operation is heavily used in informational
plugins, such as the list and plugin list plugins.

As we generally want tests to come with new APIs, this
includes one simple unittest for it.

Changes from v1:

 * Rename from matrix_to_str() to tabular_data(), suggested by rmoura
 * Added a unittest.
Signed-off-by: NLucas Meneghel Rodrigues <lmr@redhat.com>
上级 58e5a85c
......@@ -114,3 +114,48 @@ def strip_console_codes(output, custom_codes=None):
old_word = tmp_word
return_str += tmp_word[len(special_code):]
return return_str
def tabular_output(matrix, header=None):
"""
Return a pretty, aligned string representation of a nxm matrix.
This representation can be used to print any tabular data, such as
database results. It works by scanning the lengths of each element
in each column, and determining the format string dynamically.
:param matrix: Matrix representation (list with n rows of m elements).
:param header: Optional tuple or list with header elements to be displayed.
:return: String with the tabular output, lines separated by unix line feeds.
:rtype: str
"""
if type(header) is list:
header = tuple(header)
lengths = []
if header:
for column in header:
lengths.append(len(column))
for row in matrix:
for i, column in enumerate(row):
column = unicode(column).encode("utf-8")
col_len = len(column)
try:
max_len = lengths[i]
if col_len > max_len:
lengths[i] = col_len
except IndexError:
lengths.append(col_len)
lengths = tuple(lengths)
format_string = ""
for length in lengths:
format_string += "%-" + str(length) + "s "
format_string += "\n"
matrix_str = ""
if header:
matrix_str += format_string % header
for row in matrix:
matrix_str += format_string % tuple(row)
return matrix_str
import unittest
import os
import sys
# simple magic for using scripts within a source tree
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
basedir = os.path.dirname(basedir)
if os.path.isdir(os.path.join(basedir, 'avocado')):
sys.path.append(basedir)
from avocado.utils import astring
class AstringTest(unittest.TestCase):
def testTabularOutput(self):
matrix = [('foo', 'bar'), ('/bin/bar/sbrubles',
'/home/myuser/sbrubles')]
self.assertTrue(astring.tabular_output(matrix),
('foo bar \n'
'/bin/bar/sbrubles /home/myuser/sbrubles \n'))
header = ['id', 'path']
self.assertTrue(astring.tabular_output(matrix, header),
('id path \n'
'foo bar \n'
'/bin/bar/sbrubles /home/myuser/sbrubles \n'))
if __name__ == '__main__':
unittest.main()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册