From e1a9f0870f941214679f5f8cc08b1b1f3bdd27f8 Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Mon, 25 Sep 2023 13:25:01 +0000 Subject: [PATCH] util.py: list_gen(): support inclusion of multiple members, add test --- mmgen/util.py | 17 +++++++++++------ test/unit_tests_d/ut_util.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) create mode 100755 test/unit_tests_d/ut_util.py diff --git a/mmgen/util.py b/mmgen/util.py index 506be9db..9cfe49ba 100755 --- a/mmgen/util.py +++ b/mmgen/util.py @@ -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): diff --git a/test/unit_tests_d/ut_util.py b/test/unit_tests_d/ut_util.py new file mode 100755 index 00000000..057de93e --- /dev/null +++ b/test/unit_tests_d/ut_util.py @@ -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