'Test caching of searches'

def test_search_caching(self):

    from calibre.db.search import LRUCache
    class TestCache(LRUCache, ):
        hit_counter = 0
        miss_counter = 0
        def get(self, key, default=None):
            ans = LRUCache.get(self, key, default=default)
            if (ans is not None):
                self.hit_counter += 1
            else:
                self.miss_counter += 1
        @property
        def cc(self):
            self.hit_counter = self.miss_counter = 0
        @property
        def counts(self):
            return (self.hit_counter, self.miss_counter)
    cache = self.init_cache()
    cache._search_api.cache = c = TestCache()
    ae = self.assertEqual
    def test(hit, result, *args, **kw):
        c.cc
        num = kw.get(u'num', 2)
        ae(cache.search(*args), result)
        ae(c.counts, ((num, 0) if hit else (0, num)))
        c.cc
    test(False, {3}, u'Unknown')
    test(True, {3}, u'Unknown')
    test(True, {3}, u'Unknown')
    cache._search_api.MAX_CACHE_UPDATE = 0
    cache.set_field(u'title', {3: u'xxx'})
    test(False, {3}, u'Unknown')
    test(True, {3}, u'Unknown')
    c.limit = 5
    for i in range(6):
        test(False, set(), (u'nomatch_%s' % i))
    test(False, {3}, u'Unknown')
    test(False, {3}, u'', u'unknown', num=1)
    test(True, {3}, u'', u'unknown', num=1)
    test(True, {3}, u'Unknown', u'unknown', num=1)
    cache._search_api.MAX_CACHE_UPDATE = 100
    test(False, {2, 3}, u'title:=xxx    or    title:"=Title    One"')
    cache.set_field(u'publisher', {3: u'ppppp', 2: u'other'})
    test(True, {2, 3}, u'title:=xxx    or    title:"=Title    One"')
