util.py: list_gen(): support inclusion of multiple members, add test

This commit is contained in:
The MMGen Project 2023-09-25 13:25:01 +00:00
commit e1a9f0870f
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
2 changed files with 40 additions and 6 deletions

View file

@ -190,15 +190,20 @@ def fmt_list(iterable,fmt='dfl',indent=''):
def list_gen(*data):
"""
add element to list if condition is true or absent
Generate a list from an arg tuple of sublists
- The last element of each sublist is a condition. If it evaluates to true, the preceding
elements of the sublist are included in the result. Otherwise the sublist is skipped.
- If a sublist contains only one element, the condition defaults to true.
"""
assert type(data) in (list,tuple), f'{type(data).__name__} not in (list,tuple)'
def gen():
for i in data:
assert type(i) == list, f'{type(i).__name__} != list'
assert len(i) in (1,2), f'{len(i)} not in (1,2)'
if len(i) == 1 or i[1]:
yield i[0]
for d in data:
assert type(d) == list, f'{type(d).__name__} != list'
if len(d) == 1:
yield d[0]
elif d[-1]:
for idx in range(len(d)-1):
yield d[idx]
return list(gen())
def remove_dups(iterable,edesc='element',desc='list',quiet=False,hide=False):

29
test/unit_tests_d/ut_util.py Executable file
View file

@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""
test.unit_tests_d.ut_misc: utility unit tests for the MMGen suite
"""
from ..include.common import vmsg
from mmgen.util import list_gen
class unit_tests:
def list_gen(self,name,ut):
res = list_gen(
['a'],
['b', 1==2],
['c', 'x'],
['d', int],
['e', None, 1, 'f', isinstance(7,int)],
['g', 'h', 0],
[None],
[0],
[False],
)
chk = ['a', 'c', 'd', 'e', None, 1, 'f', None, 0, False]
vmsg('=> ' + str(res))
assert res == chk, f'{res} != {chk}'
vmsg('')
return True