diff --git a/anyconfig/processors.py b/anyconfig/processors.py index 8022b672..28e462e4 100644 --- a/anyconfig/processors.py +++ b/anyconfig/processors.py @@ -45,6 +45,16 @@ def load_plugins(pgroup, safe=True): return list(_load_plugins_itr(pgroup, safe=safe)) +def finds_with_pred(predicate, prs): + """ + :param predicate: any callable to filter results + :param prs: A list of :class:`anyconfig.models.processor.Processor` classes + :return: A list of appropriate processor classes or [] + """ + return sorted((p for p in prs if predicate(p)), + key=operator.methodcaller("priority"), reverse=True) + + def find_with_pred(predicate, prs): """ :param predicate: any callable to filter results @@ -75,8 +85,7 @@ def find_with_pred(predicate, prs): >>> x = find_with_pred(lambda p: p.type() == "x", prs) >>> assert x is None """ - _prs = sorted((p for p in prs if predicate(p)), - key=operator.methodcaller("priority"), reverse=True) + _prs = finds_with_pred(predicate, prs) if _prs: return _prs[0] # Found. diff --git a/tests/processors.py b/tests/processors.py index 8b6a3bf2..3f7b952f 100644 --- a/tests/processors.py +++ b/tests/processors.py @@ -20,16 +20,17 @@ class A(anyconfig.models.processor.Processor): class A2(A): - pass + _priority = 20 # Higher priority than A. class A3(A): - _priority = 99 # Higher priority than A. + _priority = 99 # Higher priority than A and A2. class B(anyconfig.models.processor.Processor): _type = "yaml" _extensions = ['yaml', 'yml'] + _priority = 99 # Higher priority than C. class C(anyconfig.models.processor.Processor): @@ -50,6 +51,25 @@ def test_10_eq(self): self.assertNotEqual(a1, a22) +class Test_20_finds_functions(unittest.TestCase): + + def test_10_finds_with_pred__type(self): + def _finds_by_type(typ): + return TT.finds_with_pred(lambda p: p.type() == typ, PRS) + + self.assertEqual(_finds_by_type("json"), [A3, A2, A]) + self.assertEqual(_finds_by_type("yaml"), [B, C]) + self.assertEqual(_finds_by_type("undefined"), []) + + def test_20_finds_with_pred__ext(self): + def _finds_with_pred__ext(ext): + return TT.finds_with_pred(lambda p: ext in p.extensions(), PRS) + + self.assertEqual(_finds_with_pred__ext("js"), [A3, A2, A]) + self.assertEqual(_finds_with_pred__ext("yml"), [B, C]) + self.assertEqual(_finds_with_pred__ext("xyz"), []) + + class Test_30_find_functions(unittest.TestCase): def assertInstance(self, obj, cls):