root/pyndexter/trunk/pyndexter/indexers/_mock.py

Revision 452, 1.8 kB (checked in by athomas, 1 year ago)

pyndexter: All modules are now prefixed with _ to avoid import collisions. Updated unit tests.

  • Property svn:eol-style set to native
Line 
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2006 Alec Thomas <alec@swapoff.org>
4 #
5 # This software is licensed as described in the file COPYING, which
6 # you should have received as part of this distribution.
7 #
8
9 """
10 Memory-only indexer used primarily for unit testing. Takes no options.
11 """
12
13 from StringIO import StringIO
14 from pyndexter import *
15
16
17 class MockIndexer(Indexer):
18     """Memory-only indexer."""
19
20     def __init__(self, framework, path=None):
21         Indexer.__init__(self, framework)
22         self.close()
23
24     def close(self):
25         self.attributes = {}
26         self.cache = {}
27
28     def __iter__(self):
29         uris = self.attributes.keys()
30         uris.sort()
31         for uri in uris:
32             yield uri
33
34     def fetch(self, uri):
35         try:
36             return Document(content=self.cache[uri], quality=0.99,
37                             **self.attributes[uri])
38         except KeyError:
39             raise DocumentNotFound(uri)
40
41     def discard(self, uri):
42         del self.attributes[uri]
43         del self.cache[uri]
44
45     def index(self, document):
46         from copy import copy
47         self.attributes[document.uri] = copy(document.attributes)
48         self.cache[document.uri] = document.content
49
50     def search(self, query):
51         docs = self.cache.keys()
52         docs.sort()
53         return MockResult(self, query, docs)
54
55
56 indexer_factory = PluginFactory(MockIndexer)
57
58
59 class MockResult(Result):
60     def __iter__(self):
61         for uri in self.context:
62             if self.query(self.indexer.framework.reduce(self.indexer.cache[uri].lower())):
63                 yield self._translate(uri)
64
65     def __getitem__(self, index):
66         return self._translate(self.context[index])
67
68     def _translate(self, uri):
69         attributes = self.indexer.attributes[uri]
70         return Hit(current=self.indexer.framework.fetch,
71                    indexed=self.indexer.fetch, **attributes)
Note: See TracBrowser for help on using the browser.