Skip to content

Commit

Permalink
change: add an utility function to find multiple processors
Browse files Browse the repository at this point in the history
add an utility function .processors.finds_with_pred to find multiple
processors matches with predicate, and its test cases.
  • Loading branch information
ssato committed Jan 11, 2019
1 parent bb65fed commit 0e74d9e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
13 changes: 11 additions & 2 deletions anyconfig/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
24 changes: 22 additions & 2 deletions tests/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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):
Expand Down

0 comments on commit 0e74d9e

Please sign in to comment.