util.py: new fmt_dict() function, add test

This commit is contained in:
The MMGen Project 2023-09-25 13:25:02 +00:00
commit e1c9756250
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
4 changed files with 65 additions and 3 deletions

View file

@ -1 +1 @@
July 2023
September 2023

View file

@ -1 +1 @@
14.0.dev1
14.0.dev2

View file

@ -190,6 +190,20 @@ def fmt_list(iterable,fmt='dfl',indent='',conv=None):
conv = conv or _conv
return indent + (sep+indent).join(lq+conv(e)+rq for e in iterable)
def fmt_dict(mapping,fmt='dfl',kconv=None,vconv=None):
"pretty-format a dict"
kc,vc,sep,fs = {
'dfl': ( str, str, ", ", "'{}' ({})" ),
'square': ( str, str, ", ", "'{}' [{}]" ),
'equal': ( str, str, ", ", "'{}'={}" ),
'equal_spaced': ( str, str, ", ", "'{}' = {}" ),
'kwargs': ( str, repr, ", ", "{}={}" ),
'colon': ( str, repr, ", ", "{}:{}" ),
}[fmt]
kconv = kconv or kc
vconv = vconv or vc
return sep.join(fs.format(kconv(k),vconv(v)) for k,v in mapping.items())
def list_gen(*data):
"""
Generate a list from an arg tuple of sublists

View file

@ -5,7 +5,8 @@ test.unit_tests_d.ut_misc: utility unit tests for the MMGen suite
"""
from ..include.common import vmsg
from mmgen.util import fmt_list,list_gen
from mmgen.util import fmt_list,fmt_dict,list_gen
from mmgen.color import cyan
class unit_tests:
@ -46,6 +47,53 @@ class unit_tests:
vmsg('')
return True
def fmt_dict(self,name,ut):
samples = {
'url': {
'name':'Example',
'desc':'Sample URL',
'rank': 1,
'error': None,
'url':'https://example.com/foobar.html',
},
'choice': {
'c': 'curl',
'a': 'aiohttp',
'r': 'requests',
},
'cmdline': {
'cmd': ["ls","-l"],
'text': 'foo bar',
'stdin': None,
'offset': 123,
'env': {},
}
}
chks = {
'cmdline': {
None: "'cmd' (['ls', '-l']), 'text' (foo bar), 'stdin' (None), 'offset' (123), 'env' ({})",
'dfl': "'cmd' (['ls', '-l']), 'text' (foo bar), 'stdin' (None), 'offset' (123), 'env' ({})",
'square': "'cmd' [['ls', '-l']], 'text' [foo bar], 'stdin' [None], 'offset' [123], 'env' [{}]",
'equal': "'cmd'=['ls', '-l'], 'text'=foo bar, 'stdin'=None, 'offset'=123, 'env'={}",
'equal_spaced': "'cmd' = ['ls', '-l'], 'text' = foo bar, 'stdin' = None, 'offset' = 123, 'env' = {}",
'kwargs': "cmd=['ls', '-l'], text='foo bar', stdin=None, offset=123, env={}",
'colon': "cmd:['ls', '-l'], text:'foo bar', stdin:None, offset:123, env:{}",
}
}
col1_w = max(len(str(e)) for e in list(chks.values())[0]) + 1
for name,sample in samples.items():
vmsg(cyan(f'Input: {sample}'))
for fmt,chk in list(chks.values())[0].items():
res = fmt_dict(sample,fmt=fmt) if fmt else fmt_dict(sample)
vmsg(f' {str(fmt)+":":{col1_w}} {res}')
if name in chks:
assert res == chks[name][fmt], f'{res} != {chks[name][fmt]}'
vmsg('')
return True
def list_gen(self,name,ut):
res = list_gen(
['a'],