class Filter: """Stores a single filter for comparing a field to a value""" #: OPERATORS contains a list of comparisons and operations for running #: queries OPERATORS = { 'eq': lambda x, y: x == y, 'ne': lambda x, y: x != y, 'gt': lambda x, y: x > y, 'lt': lambda x, y: x < y, 'ge': lambda x, y: x >= y, 'le': lambda x, y: x <= y, 'in': lambda x, y: x in y, 'contains': lambda x, y: y in x, } def __init__(self, filter_obj): """creates a filter object from a dict""" self.field = Field(filter_obj['field']) self.operator = filter_obj['op'] self.value = filter_obj['value'] def run(self, document): """runs the test against the document, comparing the metadata field specified by the filter's field against the provided value using the provided operation """ return self.OPERATORS[self.operator]( self.field.run(document), self.value) @classmethod def is_filter(cls, obj): """duck-types a dict to see if it looks like a filter object""" try: if sorted(obj.keys()) != ['field', 'op', 'value']: return False if obj['op'] not in cls.OPERATORS: return False return True except: return False
def test_metadata(self): field = Field('metadata:foo.bar') self.assertEqual(field.run(self.d), 42) field = Field('metadata:foo.baz') self.assertEqual(field.run(self.d), None)
def test_name(self): field = Field('name:') self.assertEqual(field.run(self.d), 'Test document')
def test_document(self): field = Field('document:') self.assertEqual(field.run(self.d), 'asdf')