Skip to content

Commit

Permalink
enhancement: introduce an utility function find_by_type_or_id
Browse files Browse the repository at this point in the history
add an utility function .processors.find_by_type_or_id to find
appropriate processor object by data type *or* Processor's ID, and
some test code.
  • Loading branch information
ssato committed Dec 22, 2018
1 parent eb8108b commit 4f4de8f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
31 changes: 31 additions & 0 deletions anyconfig/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,37 @@ def pred(pcls):
return processor()


def find_by_type_or_id(type_or_id, prs,
cls=anyconfig.models.processor.Processor):
"""
:param type_or_id:
Type of the data to process or ID of the processor class or
:class:`anyconfig.models.processor.Processor` class object or its
instance
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param cls: A class object to compare with `type_or_id`
:return:
Most appropriate processor instance to process files of given data type
or processor `type_or_id` found by its ID or None
:raises: UnknownProcessorTypeError
"""
if isinstance(type_or_id, cls):
return type_or_id

if type(type_or_id) == type(cls) and issubclass(type_or_id, cls):
return type_or_id()

def pred(pcls):
"""Predicate"""
return pcls.cid() == type_or_id or pcls.type() == type_or_id

processor = find_with_pred(pred, prs)
if processor is None:
raise UnknownProcessorTypeError(type_or_id)

return processor()


def find_by_fileext(fileext, prs):
"""
:param fileext: File extension
Expand Down
13 changes: 12 additions & 1 deletion tests/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,13 @@ class B(anyconfig.models.processor.Processor):
_extensions = ['yaml', 'yml']


PRS = [A, A2, A3, B]
class C(anyconfig.models.processor.Processor):
_cid = "dummy"
_type = "yaml"
_extensions = ['yaml', 'yml']


PRS = [A, A2, A3, B, C]


class Test_10_Processor(unittest.TestCase):
Expand Down Expand Up @@ -75,6 +81,11 @@ def test_20_find_by_type(self):
self.assertRaises(UnknownProcessorTypeError, TT.find_by_type,
"X", PRS)

def test_24_find_by_type_or_id(self):
self.assertTrue(isinstance(TT.find_by_type_or_id("json", PRS), A3))
self.assertTrue(isinstance(TT.find_by_type_or_id("yaml", PRS), B))
self.assertTrue(isinstance(TT.find_by_type_or_id("dummy", PRS), C))

def test_30_find_by_fileext(self):
self.assertEqual(TT.find_by_fileext("jsn", PRS), A3)
self.assertEqual(TT.find_by_fileext("yml", PRS), B)
Expand Down

0 comments on commit 4f4de8f

Please sign in to comment.