Skip to content
Snippets Groups Projects
Commit c2060bdb authored by Honza Mach's avatar Honza Mach
Browse files

Minor changes in code and documentation, preparations for unit tests

parent f4ae43f8
No related branches found
No related tags found
No related merge requests found
#https://github.com/piuccio/cowsay # TODO: Implement library similar to the https://github.com/piuccio/cowsay
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Copyright (C) since 2016 Jan Mach <honza.mach.ml@gmail.com>
# Use of this source is governed by the MIT license, see LICENSE file.
#-------------------------------------------------------------------------------
import unittest
from unittest.mock import Mock, MagicMock, call
from pprint import pformat, pprint
import os
import sys
import shutil
# Generate the path to custom 'lib' directory
#lib = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
#sys.path.insert(0, lib)
import pydgets.widgets
class TestWidgets(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_01_basic(self):
"""
Perform the basic operativity tests.
"""
self.assertTrue(True)
self.assertEqual(0, 0)
if __name__ == "__main__":
unittest.main()
#!/usr/bin/python3 #!/usr/bin/python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
# Copyright (C) 2015-2016 Jan Mach <honza.mach.ml@gmail.com> # Copyright (C) since 2016 Jan Mach <honza.mach.ml@gmail.com>
# Use of this source is governed by the MIT license, see LICENSE file. # Use of this source is governed by the MIT license, see LICENSE file.
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
""" """
Console widget library. Console widget library for Python3.
This library is intended to help in data presentation from various console scripts.
It provides tools for easy formating and rendering of many usefull 'widgets' like
lists, tree strutures, tables, etc.
.. note::
Although production code is based on this library, it should still be considered
work in progress.
""" """
import os import os
...@@ -18,6 +28,8 @@ import time ...@@ -18,6 +28,8 @@ import time
import pprint import pprint
DFLT_TABLE_STYLE = 'utf8.b' DFLT_TABLE_STYLE = 'utf8.b'
# Detected terminal width and height
TERMINAL_WIDTH = 0 TERMINAL_WIDTH = 0
TERMINAL_HEIGHT = 0 TERMINAL_HEIGHT = 0
...@@ -71,6 +83,7 @@ TEXT_FORMATING = { ...@@ -71,6 +83,7 @@ TEXT_FORMATING = {
'rst': '\033[0m', 'rst': '\033[0m',
} }
# Text alignment index
TEXT_ALIGNMENT = { TEXT_ALIGNMENT = {
'<': '<', 'l': '<', 'left': '<', 'L': '<', 'LEFT': '<', '<': '<', 'l': '<', 'left': '<', 'L': '<', 'LEFT': '<',
'>': '>', 'r': '>', 'right': '>', 'R': '>', 'RIGHT': '>', '>': '>', 'r': '>', 'right': '>', 'R': '>', 'RIGHT': '>',
...@@ -115,7 +128,7 @@ BORDER_STYLES = { ...@@ -115,7 +128,7 @@ BORDER_STYLES = {
'bh': '#', 'bv': '#', 'bl': '#', 'bm': '#', 'br': '#' 'bh': '#', 'bv': '#', 'bl': '#', 'bm': '#', 'br': '#'
}, },
'utf8.a': { 'utf8.a': {
# Alternativelly define the characters with unicode codes # Alternativelly it is possible to define the characters with unicode codes
#'th': '\u2500', 'tv': '\u2502', 'tl': '\u250c', 'tm': '\u252c', 'tr': '\u2510', #'th': '\u2500', 'tv': '\u2502', 'tl': '\u250c', 'tm': '\u252c', 'tr': '\u2510',
#'mh': '\u2500', 'mv': '\u2502', 'ml': '\u251c', 'mm': '\u253c', 'mr': '\u2524', #'mh': '\u2500', 'mv': '\u2502', 'ml': '\u251c', 'mm': '\u253c', 'mr': '\u2524',
#'bh': '\u2500', 'bv': '\u2502', 'bl': '\u2514', 'bm': '\u2534', 'br': '\u2518' #'bh': '\u2500', 'bv': '\u2502', 'bl': '\u2514', 'bm': '\u2534', 'br': '\u2518'
...@@ -277,7 +290,7 @@ TREE_STYLES = { ...@@ -277,7 +290,7 @@ TREE_STYLES = {
def terminal_size(): def terminal_size():
""" """
Detect the size of terminal window in rows and columns. Detect the current size of terminal window as a numer of rows and columns.
""" """
try: try:
(rows, columns) = os.popen('stty size', 'r').read().split() (rows, columns) = os.popen('stty size', 'r').read().split()
...@@ -286,17 +299,20 @@ def terminal_size(): ...@@ -286,17 +299,20 @@ def terminal_size():
return (columns, rows) return (columns, rows)
# Currently ignore any errors and return some reasonable default values. # Currently ignore any errors and return some reasonable default values.
# Errors may occur, when the library is used in non-terminal application
# like daemon.
except: except:
pass pass
return (80, 24) return (80, 24)
# Detect the terminal size automatically after library initialization
(TERMINAL_WIDTH, TERMINAL_HEIGHT) = terminal_size() (TERMINAL_WIDTH, TERMINAL_HEIGHT) = terminal_size()
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
class ConsoleWidget: class ConsoleWidget:
""" """
Base class for all console widgets. Base class for all console widgets implemented by this library.
This class provides basic common methods for widget setup and rendering. This class provides basic common methods for widget setup and rendering.
""" """
...@@ -354,7 +370,7 @@ class ConsoleWidget: ...@@ -354,7 +370,7 @@ class ConsoleWidget:
""" """
Get list of all appropriate settings and their default values. Get list of all appropriate settings and their default values.
The returned list is then used setup() and get_setup() methods to setup The returned list is then used in setup() and get_setup() methods to setup
the widget internal settings. the widget internal settings.
""" """
return [ return [
...@@ -387,7 +403,7 @@ class ConsoleWidget: ...@@ -387,7 +403,7 @@ class ConsoleWidget:
def get_setup(self, content = None, **kwargs): def get_setup(self, content = None, **kwargs):
""" """
Get current setup by combining internal settings with the one given. Get current setup by combining internal settings with the ones given.
""" """
if content is None: if content is None:
content = self.content content = self.content
...@@ -1373,21 +1389,51 @@ class BarChartWidget(MultiLineWidget): ...@@ -1373,21 +1389,51 @@ class BarChartWidget(MultiLineWidget):
if __name__ == "__main__": if __name__ == "__main__":
""" """
Perform the demonstration. Perform the library demonstration.
""" """
widget_groups = ['all', 'data', 'text', 'line', 'box', 'list', 'tree', 'table', 'progress', 'barchart']
section_separator = "\n --------------------------------------------\n"
argparser = argparse.ArgumentParser(description = "pydgets - Console widget library for Python 3") argparser = argparse.ArgumentParser(description = "pydgets - Console widget library for Python 3")
argparser.add_argument('--group', help = 'pick a group of widgets', choices = ['all', 'data', 'text', 'line', 'box', 'list', 'tree', 'table', 'progress', 'barchart'], default='all') argparser.add_argument('--group', help = 'pick a group of widgets', choices = widget_groups, default='all')
args = argparser.parse_args() args = argparser.parse_args()
print("""
==============================================
_____ _ _
| __ \ | | | |
| |__) |_ _ __| | __ _ ___ | |_ ___
| ___/| | | | / _` | / _` | / _ \| __|/ __|
| | | |_| || (_| || (_| || __/| |_ \__ \\
|_| \__, | \__,_| \__, | \___| \__||___/
__/ | __/ |
|___/ |___/
==============================================
ıllıllı PYTHON3 CONSOLE WIDGET LIBRARY ıllıllı
==============================================
""")
argparser.print_help()
print(section_separator)
#---------------------------------------------------------------------------
(columns, rows) = terminal_size() (columns, rows) = terminal_size()
print("Detected terminal size {} x {} (WxH)".format(columns, rows)) print("Detected terminal size {} x {} (WxH)".format(columns, rows))
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'data'): if args.group in ('all', 'data'):
print("") print("")
labelptrn = " {:<60s} "
textw = TextWidget()
print("Demonstrations of TextWidget data formating capabilities...") print("Demonstrations of TextWidget data formating capabilities...")
print("") print("")
labelptrn = " {:<60s} "
textw = TextWidget()
for conv in ( for conv in (
[523689, 'int'], [523689, 'int'],
[123523.689111, 'float'], [123523.689111, 'float'],
...@@ -1401,6 +1447,7 @@ if __name__ == "__main__": ...@@ -1401,6 +1447,7 @@ if __name__ == "__main__":
label = labelptrn.format(label) label = labelptrn.format(label)
print(label, textw.render(conv[0], data_type = conv[1])) print(label, textw.render(conv[0], data_type = conv[1]))
print("")
print("Demonstrations of TextWidget data highlighting capabilities...") print("Demonstrations of TextWidget data highlighting capabilities...")
print("") print("")
...@@ -1412,8 +1459,13 @@ if __name__ == "__main__": ...@@ -1412,8 +1459,13 @@ if __name__ == "__main__":
for val in ('50', '150'): for val in ('50', '150'):
label = " Data decoration '{}'".format(val) label = " Data decoration '{}'".format(val)
label = labelptrn.format(label)
print(label, textw.render(val, text_highlight = deco)) print(label, textw.render(val, text_highlight = deco))
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'text'): if args.group in ('all', 'text'):
print("") print("")
labelptrn = " {:<60s} " labelptrn = " {:<60s} "
...@@ -1456,6 +1508,10 @@ if __name__ == "__main__": ...@@ -1456,6 +1508,10 @@ if __name__ == "__main__":
label = labelptrn.format(label) label = labelptrn.format(label)
print(labelptrn.format(label), textw.render(label, text_formating = {"fg": fg, "bg": bg, "attr": attr})) print(labelptrn.format(label), textw.render(label, text_formating = {"fg": fg, "bg": bg, "attr": attr}))
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'line'): if args.group in ('all', 'line'):
print("") print("")
print("Demonstrations of StatusLineWidget...") print("Demonstrations of StatusLineWidget...")
...@@ -1466,6 +1522,10 @@ if __name__ == "__main__": ...@@ -1466,6 +1522,10 @@ if __name__ == "__main__":
print(linew.render('Test status line text, right align, right padding with custom character', padding_right = 5, padding_char = '#', align = '>', text_formating = {"bg": "on_blue"})) print(linew.render('Test status line text, right align, right padding with custom character', padding_right = 5, padding_char = '#', align = '>', text_formating = {"bg": "on_blue"}))
print(linew.render('Test status line text, margin', margin = 5, text_formating = {"bg": "on_yellow"})) print(linew.render('Test status line text, margin', margin = 5, text_formating = {"bg": "on_yellow"}))
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'list'): if args.group in ('all', 'list'):
print("") print("")
print("Demonstrations of ListWidget...") print("Demonstrations of ListWidget...")
...@@ -1498,6 +1558,10 @@ if __name__ == "__main__": ...@@ -1498,6 +1558,10 @@ if __name__ == "__main__":
listw = ListWidget() listw = ListWidget()
listw.display(data) listw.display(data)
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'tree'): if args.group in ('all', 'tree'):
print("") print("")
print("Demonstrations of TreeWidget...") print("Demonstrations of TreeWidget...")
...@@ -1532,6 +1596,10 @@ if __name__ == "__main__": ...@@ -1532,6 +1596,10 @@ if __name__ == "__main__":
treew = TreeWidget() treew = TreeWidget()
treew.display(data, tree_style = s) treew.display(data, tree_style = s)
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'box'): if args.group in ('all', 'box'):
print("") print("")
print("Demonstrations of BoxWidget...") print("Demonstrations of BoxWidget...")
...@@ -1542,6 +1610,10 @@ if __name__ == "__main__": ...@@ -1542,6 +1610,10 @@ if __name__ == "__main__":
print("") print("")
boxw.display(text, header_content = h, width = 150, padding = 1, border_style = s, header_formating = {"bg": "on_red"}) boxw.display(text, header_content = h, width = 150, padding = 1, border_style = s, header_formating = {"bg": "on_red"})
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'table'): if args.group in ('all', 'table'):
print("") print("")
print("Demonstrations of TableWidget...") print("Demonstrations of TableWidget...")
...@@ -1560,6 +1632,10 @@ if __name__ == "__main__": ...@@ -1560,6 +1632,10 @@ if __name__ == "__main__":
] ]
tablew.display(tbody, columns = tcols) tablew.display(tbody, columns = tcols)
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'progress'): if args.group in ('all', 'progress'):
print("") print("")
print("Demonstrations of ProgressBarWidget...") print("Demonstrations of ProgressBarWidget...")
...@@ -1569,6 +1645,10 @@ if __name__ == "__main__": ...@@ -1569,6 +1645,10 @@ if __name__ == "__main__":
progw.display(i/100) progw.display(i/100)
time.sleep(1) time.sleep(1)
print(section_separator)
#---------------------------------------------------------------------------
if args.group in ('all', 'barchart'): if args.group in ('all', 'barchart'):
print("") print("")
print("Demonstrations of BarChartWidget...") print("Demonstrations of BarChartWidget...")
...@@ -1592,4 +1672,10 @@ if __name__ == "__main__": ...@@ -1592,4 +1672,10 @@ if __name__ == "__main__":
324, 324,
12, 12,
] ]
barch.display(chbody, bars = chbars) barch.display(chbody, bars = chbars, bar_formating = {"fg": "blue", "bg": "on_blue"})
print(section_separator)
#---------------------------------------------------------------------------
argparser.print_help()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment