Skip to content
Snippets Groups Projects
Commit 06890f06 authored by Moul's avatar Moul
Browse files

Table: Fixes from the review (#203)

Fix types
Improve method
Set value types in blocks cells in order to get the proper format
parent 83b4344d
No related branches found
No related tags found
1 merge request!199#203: Harmonize tables style using Texttable
Pipeline #16380 passed
......@@ -180,7 +180,11 @@ def print_blocks_views(issuers, current_nbr, number, detailed):
sorted_list = sorted(issuers, key=itemgetter("block"), reverse=True)
table = tui.Table(style="columns")
table.set_cols_align(["r", "r", "r", "r", "r", "l"])
table.set_cols_dtype(["i", "t", "t", "t", "i", "t"])
table.fill_from_dict_list(sorted_list)
table.set_cols_align(["r", "r", "r", "r", "r", "l"])
table.set_cols_dtype(["i", "t", "t", "t", "i", "t"])
print(f"\n{table.draw()}")
else:
......@@ -198,10 +202,12 @@ def print_blocks_views(issuers, current_nbr, number, detailed):
issued["blocks"] = 1
list_issued.append(issued)
for issued in list_issued:
issued["percent"] = issued["blocks"] / number * 100
issued["percent"] = round(issued["blocks"] / number * 100)
sorted_list = sorted(list_issued, key=itemgetter("blocks"), reverse=True)
table = tui.Table(style="columns")
table.fill_from_dict_list(sorted_list)
table.set_cols_align(["l", "r", "r"])
table.set_cols_dtype(["t", "i", "i"])
print(f"from {len(list_issued)} issuers\n{table.draw()}")
......
......@@ -113,8 +113,6 @@ def show_amount_from_pubkey(label: str, inputs_balance: List[int]) -> None:
]
)
# table = tui.create_table()
# echo(tui.vert_table(table, display))
table = tui.Table()
table.fill_rows(display)
echo(table.draw())
......
......@@ -16,7 +16,7 @@
import shutil
import sys
from collections import OrderedDict
from typing import List, Optional
from typing import Dict, List, Optional, Union
import click
from texttable import Texttable
......@@ -25,7 +25,6 @@ from silkaj import constants
from silkaj import crypto_tools as ct
from silkaj import wot_tools
HORIZ_TABLE_CHARS = ["", "", "", ""]
VERT_TABLE_CHARS = ["", "", "", ""]
......@@ -79,67 +78,66 @@ class Table(Texttable):
self,
style="default",
):
Texttable.__init__(self, max_width=shutil.get_terminal_size()[0])
super().__init__(max_width=shutil.get_terminal_size().columns)
if style == "columns":
self.set_deco(self.HEADER | self.VLINES | self.BORDER)
self.set_chars(VERT_TABLE_CHARS)
def fill_rows(self, rows: list, headers=None):
def fill_rows(self, rows: List[List], header: List = None) -> None:
"""
Fills a table from headers and rows list.
Fills a table from header and rows list.
`rows` is a list of lists representing each row content.
each element of `rows` and headers must be of same length.
each element of `rows` and header must be of same length.
"""
if headers:
if header:
if len(rows) == 0:
rows.append([""] * len(headers))
assert len(headers) == len(rows[0])
self.header(headers)
rows.append([""] * len(header))
assert len(header) == len(rows[0])
self.header(header)
for line in rows:
assert len(line) == len(rows[0])
self.add_row(line)
return self
def fill_from_dict(self, _dict: OrderedDict):
def fill_from_dict(self, _dict: Union[Dict, OrderedDict]) -> None:
"""
Given an OrderedDict where each value represents a column,
fill a table where labels are dict keys and columns are dict values.
This function stops on the first line with only empty cells.
Given a dict where each value represents a column,
fill a table where labels are dict keys and columns are dict values
This function stops on the first line with only empty cells
"""
labels = list(_dict.keys())
content = []
keys = list(_dict.keys())
rows = []
n = 0
while True:
line = []
row = []
empty_cells_number = 0
for label in labels:
for key in keys:
try:
line.append(_dict[label][n])
row.append(_dict[key][n])
except IndexError:
line.append("")
row.append("")
empty_cells_number += 1
# break on first empty line
if empty_cells_number == len(labels):
# break on first empty row
if empty_cells_number == len(keys):
break
content.append(line)
rows.append(row)
n += 1
return self.fill_rows(content, labels)
return self.fill_rows(rows, keys)
def fill_from_dict_list(self, dict_list: list):
def fill_from_dict_list(self, dict_list: List[Dict]) -> None:
"""
Given a list of dict with same keys,
fills the table with keys as headers.
fills the table with keys as header
"""
headers = list(dict_list[0].keys())
header = list(dict_list[0].keys())
content = []
for _dict in dict_list:
assert list(_dict.keys()) == headers
assert list(_dict.keys()) == header
line = []
for head in headers:
for head in header:
line.append(_dict[head])
content.append(line)
return self.fill_rows(content, headers)
return self.fill_rows(content, header)
......@@ -79,8 +79,7 @@ def test_gen_pubkey_checksum(pubkey, checksum):
def test_create_table():
expected = Texttable(max_width=shutil.get_terminal_size()[0])
expected = Texttable(max_width=shutil.get_terminal_size().columns)
expected.add_rows([["one", "two"], ["three", "four"]])
expected.set_chars(tui.VERT_TABLE_CHARS)
......@@ -93,7 +92,7 @@ def test_create_table():
@pytest.mark.parametrize(
"rows, headers, expected",
"rows, header, expected",
[
(
[
......@@ -138,14 +137,13 @@ def test_create_table():
),
],
)
def test_fill_rows(rows, headers, expected):
def test_fill_rows(rows, header, expected):
table = tui.Table()
if not expected:
with pytest.raises(AssertionError) as pytest_error:
table.fill_rows(rows, headers)
assert pytest_error.type == AssertionError # is it useful ?
with pytest.raises(AssertionError):
table.fill_rows(rows, header)
else:
table.fill_rows(rows, headers)
table.fill_rows(rows, header)
assert table.draw() == expected
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment