PageRenderTime 26ms CodeModel.GetById 13ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/test_index.py

http://github.com/SurveyMonkey/CheesePrism
Python | 226 lines | 200 code | 19 blank | 7 comment | 5 complexity | 93c82889347c11f59f4510049d268767 MD5 | raw file
  1from cheeseprism.utils import resource_spec
  2from itertools import count
  3from mock import Mock
  4from mock import patch
  5from nose.tools import raises
  6from path import path
  7from pprint import pformat as pprint
  8import logging
  9import textwrap
 10import unittest
 11
 12
 13logger = logging.getLogger(__name__)
 14here = path(__file__).parent
 15
 16
 17def test_data_from_path():
 18    from cheeseprism import index
 19    datafile = here / 'index.json'
 20    assert index.IndexManager.data_from_path(datafile) == {}
 21    datafile.write_text("{}")
 22    assert index.IndexManager.data_from_path(datafile) == {}
 23
 24
 25class IndexTestCase(unittest.TestCase):
 26    counter = count()
 27    index_parent = "egg:CheesePrism#tests/test-indexes"
 28
 29    tdir = path(resource_spec('egg:CheesePrism#tests'))
 30    dummy = here / "dummypackage/dist/dummypackage-0.0dev.tar.gz"
 31    
 32    @classmethod
 33    def get_base(cls):
 34        return path(resource_spec(cls.index_parent))
 35
 36    @property
 37    def base(self): return self.get_base()
 38    
 39    def make_one(self, index_name='test-index'):
 40        from cheeseprism import index
 41        self.count = next(self.counter)
 42        index_path = self.base / ("%s-%s" %(self.count, index_name))
 43        return index.IndexManager(index_path)
 44
 45    def setUp(self):
 46        #@@ factor out im creation
 47        self.im = self.make_one()
 48        self.dummy.copy(self.im.path)
 49        self.dummypath = self.im.path / self.dummy.name
 50
 51    def test_register_archive(self):
 52        pkgdata, md5 = self.im.register_archive(self.dummypath)
 53        assert md5 == '3ac58d89cb7f7b718bc6d0beae85c282'
 54        assert pkgdata
 55        
 56        idxjson = self.im.data_from_path(self.im.datafile_path)
 57        assert md5 in idxjson 
 58        assert idxjson[md5] == pkgdata
 59
 60    def test_write_datafile(self):
 61        """
 62        create and write archive data to index.json 
 63        """
 64        data = self.im.write_datafile(hello='computer')
 65        assert 'hello' in data
 66        assert self.im.datafile_path.exists()
 67        assert 'hello' in self.im.data_from_path(self.im.datafile_path)
 68
 69    def test_write_datafile_w_existing_datafile(self):
 70        """
 71        write data to an existing datafile
 72        """
 73        data = self.im.write_datafile(hello='computer')
 74        assert self.im.datafile_path.exists()
 75
 76        data = self.im.write_datafile(hello='operator')
 77        assert data['hello'] == 'operator'
 78        assert self.im.data_from_path(self.im.datafile_path)['hello'] == 'operator'
 79
 80
 81    def test_regenerate_index(self):
 82        home, leaves = self.im.regenerate_all()
 83        pth = self.im.path
 84        file_structure = [(x.parent.name, x.name) for x in pth.walk()]
 85        index_name = u'%s-test-index' %self.count
 86        expected = [(index_name, u'dummypackage'),
 87                    (u'dummypackage', u'index.html'),
 88                    (path(u'dummypackage'), path(u'index.json')),                    
 89                    (index_name, u'dummypackage-0.0dev.tar.gz'),
 90                    (index_name, u'index.html')]
 91
 92        assert len(leaves) == 1
 93        assert leaves[0].exists()
 94        assert leaves[0].name == 'index.html'
 95        assert leaves[0].parent.name == 'dummypackage'
 96        assert file_structure == expected, \
 97               textwrap.dedent("""
 98               File structure does not match::
 99
100               expected:
101
102                %s
103
104               actual:
105
106                %s""") %(pprint(expected), pprint(file_structure))
107
108    @patch('cheeseprism.index.IndexManager.regenerate_leaf')
109    def test_regenerate_leaf_event(self, rl):
110        """
111        Cover event subscriber
112        """
113        from cheeseprism.event import PackageAdded
114        from cheeseprism.index import rebuild_leaf
115
116        event = PackageAdded(self.im, self.tdir / path('dummypackage2/dist/dummypackage-0.1.tar.gz'))
117        out = rebuild_leaf(event)
118        assert out is not None
119        assert rl.call_args == (('dummypackage',), {})
120
121    def test_regenerate_leaf(self):
122        [x for x in self.im.regenerate_all()]
123        leafindex = self.im.path / 'dummypackage/index.html'
124        new_arch = self.tdir / path('dummypackage2/dist/dummypackage-0.1.tar.gz')
125        new_arch.copy(self.im.path)
126        added = self.im.path / new_arch.name
127
128        before_txt = leafindex.text()
129        info = self.im.pkginfo_from_file(added)
130        out = self.im.regenerate_leaf(info.name)
131        assert before_txt != out.text()
132
133    @patch('pyramid.threadlocal.get_current_registry')
134    def test_notify_packages_added(self, getreg):
135        from cheeseprism.index import notify_packages_added
136        pkg = dict(name='pkg', version='0.1'); pkgs = pkg,
137        index = Mock(name='index')
138        reg = getreg.return_value = Mock(name='registry')                
139        out = list(notify_packages_added(index, pkgs))
140
141        assert len(out) == 1
142        assert getreg.called
143        assert reg.notify.called
144        (event,), _ = reg.notify.call_args
145        assert event.im is index
146        assert event.version == '0.1'
147        assert event.name == 'pkg'
148
149    @raises(StopIteration)
150    def test_notify_packages_added_raises(self):
151        from cheeseprism.index import notify_packages_added
152        next(notify_packages_added(Mock(name='index'), []))
153
154    def tearDown(self):
155        logger.debug("teardown: %s", self.count)
156        dirs = self.base.dirs()
157        logger.info(pprint(dirs))
158        logger.info(pprint([x.rmtree() for x in dirs]))
159
160
161class ClassOrStaticMethods(unittest.TestCase):
162
163    def test_move_on_error(self):
164        from cheeseprism.index import IndexManager
165        exc, path = Mock(), Mock()
166        IndexManager.move_on_error('errors', exc, path)
167        assert path.rename.called
168        assert path.rename.call_args[0][0] == 'errors'
169
170    @patch('pkginfo.bdist.BDist', new=Mock(return_value=True))
171    def test_pkginfo_from_file_egg(self):
172        """
173        .pkginfo_from_file: bdist
174        """                
175        from cheeseprism.index import IndexManager
176        assert IndexManager.pkginfo_from_file('blah.egg') is True
177
178    @patch('pkginfo.sdist.SDist', new=Mock(return_value=True))
179    def test_pkginfo_from_file_sdist(self):
180        """
181        .pkginfo_from_file: sdist
182        """        
183        from cheeseprism.index import IndexManager
184        for ext in ('.gz','.tgz', '.bz2', '.zip'):
185            assert IndexManager.pkginfo_from_file('blah.%s' %ext) is True
186
187    @raises(RuntimeError)
188    def test_pkginfo_from_bad_ext(self):
189        """
190        .pkginfo_from_file with unrecognized extension
191        """
192        from cheeseprism.index import IndexManager
193        IndexManager.pkginfo_from_file('adfasdkfha.adkfhalsdk')
194
195    @raises(RuntimeError)
196    def test_pkginfo_from_no_ext(self):
197        """
198        .pkginfo_from_file with no extension
199        """
200        from cheeseprism.index import IndexManager
201        IndexManager.pkginfo_from_file('adfasdkfha')        
202    
203    def test_pkginfo_from_file_exc_and_handler(self):
204        """
205        .pkginfo_from_file with exception and handler
206        """
207        from cheeseprism.index import IndexManager
208        exc = Exception("BOOM")
209        with patch('pkginfo.bdist.BDist', side_effect=exc):
210            eh = Mock(name='error_handler')
211            IndexManager.pkginfo_from_file('bad.egg', handle_error=eh)
212        assert eh.called
213        assert eh.call_args[0] == (exc, 'bad.egg'), eh.call_args[0]
214
215    @raises(ValueError)
216    def test_pkginfo_from_file_exc(self):
217        """
218        .pkginfo_from_file with exception and no handler
219        """
220        from cheeseprism.index import IndexManager
221        exc = ValueError("BOOM")
222        with patch('pkginfo.bdist.BDist', side_effect=exc):
223            IndexManager.pkginfo_from_file('bad.egg')
224
225def test_cleanup():
226    assert not IndexTestCase.get_base().dirs()