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): ...@@ -180,7 +180,11 @@ def print_blocks_views(issuers, current_nbr, number, detailed):
sorted_list = sorted(issuers, key=itemgetter("block"), reverse=True) sorted_list = sorted(issuers, key=itemgetter("block"), reverse=True)
table = tui.Table(style="columns") 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.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()}") print(f"\n{table.draw()}")
else: else:
...@@ -198,10 +202,12 @@ def print_blocks_views(issuers, current_nbr, number, detailed): ...@@ -198,10 +202,12 @@ def print_blocks_views(issuers, current_nbr, number, detailed):
issued["blocks"] = 1 issued["blocks"] = 1
list_issued.append(issued) list_issued.append(issued)
for issued in list_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) sorted_list = sorted(list_issued, key=itemgetter("blocks"), reverse=True)
table = tui.Table(style="columns") table = tui.Table(style="columns")
table.fill_from_dict_list(sorted_list) 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()}") 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: ...@@ -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 = tui.Table()
table.fill_rows(display) table.fill_rows(display)
echo(table.draw()) echo(table.draw())
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
import shutil import shutil
import sys import sys
from collections import OrderedDict from collections import OrderedDict
from typing import List, Optional from typing import Dict, List, Optional, Union
import click import click
from texttable import Texttable from texttable import Texttable
...@@ -25,7 +25,6 @@ from silkaj import constants ...@@ -25,7 +25,6 @@ from silkaj import constants
from silkaj import crypto_tools as ct from silkaj import crypto_tools as ct
from silkaj import wot_tools from silkaj import wot_tools
HORIZ_TABLE_CHARS = ["", "", "", ""]
VERT_TABLE_CHARS = ["", "", "", ""] VERT_TABLE_CHARS = ["", "", "", ""]
...@@ -79,67 +78,66 @@ class Table(Texttable): ...@@ -79,67 +78,66 @@ class Table(Texttable):
self, self,
style="default", style="default",
): ):
Texttable.__init__(self, max_width=shutil.get_terminal_size()[0]) super().__init__(max_width=shutil.get_terminal_size().columns)
if style == "columns": if style == "columns":
self.set_deco(self.HEADER | self.VLINES | self.BORDER) self.set_deco(self.HEADER | self.VLINES | self.BORDER)
self.set_chars(VERT_TABLE_CHARS) 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. `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: if len(rows) == 0:
rows.append([""] * len(headers)) rows.append([""] * len(header))
assert len(headers) == len(rows[0]) assert len(header) == len(rows[0])
self.header(headers) self.header(header)
for line in rows: for line in rows:
assert len(line) == len(rows[0]) assert len(line) == len(rows[0])
self.add_row(line) 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, Given a dict where each value represents a column,
fill a table where labels are dict keys and columns are dict values. fill a table where labels are dict keys and columns are dict values
This function stops on the first line with only empty cells. This function stops on the first line with only empty cells
""" """
labels = list(_dict.keys()) keys = list(_dict.keys())
content = [] rows = []
n = 0 n = 0
while True: while True:
line = [] row = []
empty_cells_number = 0 empty_cells_number = 0
for label in labels: for key in keys:
try: try:
line.append(_dict[label][n]) row.append(_dict[key][n])
except IndexError: except IndexError:
line.append("") row.append("")
empty_cells_number += 1 empty_cells_number += 1
# break on first empty line # break on first empty row
if empty_cells_number == len(labels): if empty_cells_number == len(keys):
break break
content.append(line) rows.append(row)
n += 1 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, 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 = [] content = []
for _dict in dict_list: for _dict in dict_list:
assert list(_dict.keys()) == headers assert list(_dict.keys()) == header
line = [] line = []
for head in headers: for head in header:
line.append(_dict[head]) line.append(_dict[head])
content.append(line) 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): ...@@ -79,8 +79,7 @@ def test_gen_pubkey_checksum(pubkey, checksum):
def test_create_table(): def test_create_table():
expected = Texttable(max_width=shutil.get_terminal_size().columns)
expected = Texttable(max_width=shutil.get_terminal_size()[0])
expected.add_rows([["one", "two"], ["three", "four"]]) expected.add_rows([["one", "two"], ["three", "four"]])
expected.set_chars(tui.VERT_TABLE_CHARS) expected.set_chars(tui.VERT_TABLE_CHARS)
...@@ -93,7 +92,7 @@ def test_create_table(): ...@@ -93,7 +92,7 @@ def test_create_table():
@pytest.mark.parametrize( @pytest.mark.parametrize(
"rows, headers, expected", "rows, header, expected",
[ [
( (
[ [
...@@ -138,14 +137,13 @@ def test_create_table(): ...@@ -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() table = tui.Table()
if not expected: if not expected:
with pytest.raises(AssertionError) as pytest_error: with pytest.raises(AssertionError):
table.fill_rows(rows, headers) table.fill_rows(rows, header)
assert pytest_error.type == AssertionError # is it useful ?
else: else:
table.fill_rows(rows, headers) table.fill_rows(rows, header)
assert table.draw() == expected assert table.draw() == expected
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment