source: main/waeup.kofa/trunk/src/waeup/kofa/utils/tests/test_helpers.py @ 7941

Last change on this file since 7941 was 7940, checked in by uli, 13 years ago

Move import.

  • Property svn:keywords set to Id
File size: 9.2 KB
Line 
1# -*- coding: utf-8 -*-
2
3## $Id: test_helpers.py 7940 2012-03-22 01:48:46Z uli $
4##
5## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
6## This program is free software; you can redistribute it and/or modify
7## it under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 2 of the License, or
9## (at your option) any later version.
10##
11## This program is distributed in the hope that it will be useful,
12## but WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14## GNU General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with this program; if not, write to the Free Software
18## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19##
20
21import os
22import shutil
23import tempfile
24import unittest
25import doctest
26from cStringIO import StringIO
27from zope import schema
28from zope.interface import Interface, Attribute
29from zope.security.testing import Principal, Participation
30from zope.security.management import newInteraction, endInteraction
31from waeup.kofa.utils import helpers
32
33from zope.interface import Interface, implements
34class IFakeObject(Interface):
35    """Some marker interface."""
36
37class FakeObject(object):
38    implements(IFakeObject)
39
40class RemoveFileOrDirectoryTestCase(unittest.TestCase):
41
42    def setUp(self):
43        self.dirpath = tempfile.mkdtemp()
44        self.filepath = os.path.join(self.dirpath, 'somefile')
45        self.non_file = os.path.join(self.dirpath, 'nonfile')
46        open(self.filepath, 'wb').write('Hi!')
47        return
48
49    def tearDown(self):
50        if os.path.exists(self.dirpath):
51            shutil.rmtree(self.dirpath)
52        return
53
54    def test_handle_not_existing_path(self):
55        result = helpers.remove_file_or_directory(self.non_file)
56        self.assertTrue(result is None)
57        return
58
59    def test_handle_dir(self):
60        helpers.remove_file_or_directory(self.dirpath)
61        self.assertFalse(
62            os.path.exists(self.dirpath)
63            )
64        return
65
66    def test_handle_file(self):
67        helpers.remove_file_or_directory(self.filepath)
68        self.assertFalse(
69            os.path.exists(self.filepath)
70            )
71        return
72
73class CopyFileSystemTreeTestCase(unittest.TestCase):
74    # Test edge cases of copy_filesystem_tree().
75    #
76    # This is a typical case of tests not written as doctest as it is
77    # normally not interesting for developers and we only want to make
78    # sure everything works as expected.
79    def setUp(self):
80        self.existing_src = tempfile.mkdtemp()
81        self.filepath = os.path.join(self.existing_src, 'somefile')
82        open(self.filepath, 'wb').write('Hi!')
83        self.existing_dst = tempfile.mkdtemp()
84        self.not_existing_dir = tempfile.mkdtemp()
85        shutil.rmtree(self.not_existing_dir)
86
87        pass
88
89    def tearDown(self):
90        shutil.rmtree(self.existing_src)
91        shutil.rmtree(self.existing_dst)
92        pass
93
94    def test_source_and_dst_existing(self):
95        helpers.copy_filesystem_tree(self.existing_src, self.existing_dst)
96        self.assertTrue(
97            os.path.exists(
98                os.path.join(self.existing_dst, 'somefile')
99                )
100            )
101        return
102
103    def test_source_not_existing(self):
104        self.assertRaises(
105            ValueError,
106            helpers.copy_filesystem_tree,
107            self.not_existing_dir,
108            self.existing_dst
109            )
110        return
111
112    def test_dest_not_existing(self):
113        self.assertRaises(
114            ValueError,
115            helpers.copy_filesystem_tree,
116            self.existing_src,
117            self.not_existing_dir
118            )
119        return
120
121    def test_src_not_a_dir(self):
122        self.assertRaises(
123            ValueError,
124            helpers.copy_filesystem_tree,
125            self.filepath,
126            self.existing_dst
127            )
128        return
129
130    def test_dst_not_a_dir(self):
131        self.assertRaises(
132            ValueError,
133            helpers.copy_filesystem_tree,
134            self.existing_src,
135            self.filepath
136            )
137        return
138
139class ReST2HTMLTestCase(unittest.TestCase):
140
141    def setUp(self):
142        self.expected = u'<div class="document">\n\n\n<p>Some '
143        self.expected += u'test with \xfcmlaut</p>\n</div>'
144        return
145
146    def test_ascii_umlauts(self):
147        # Make sure we convert umlauts correctly to unicode.
148        source = 'Some test with ümlaut'
149        result = helpers.ReST2HTML(source)
150        self.assertEqual(result, self.expected)
151
152    def test_unicode_umlauts(self):
153        # Make sure we convert umlauts correctly to unicode.
154        source = u'Some test with ümlaut'
155        result = helpers.ReST2HTML(source)
156        self.assertEqual(result, self.expected)
157
158    def test_unicode_output_from_ascii(self):
159        source = 'Some test with ümlaut'
160        self.assertTrue(isinstance(helpers.ReST2HTML(source), unicode))
161
162    def test_unicode_output_from_unicode(self):
163        source = u'Some test with ümlaut'
164        self.assertTrue(isinstance(helpers.ReST2HTML(source), unicode))
165
166
167class FactoryBaseTestCase(unittest.TestCase):
168
169    def test_ifaces(self):
170        # We test all relevant parts in the docstring. But the interfaces
171        # method has to be tested to please the coverage report as well.
172        factory = helpers.FactoryBase()
173        factory.factory = FakeObject
174        self.assertTrue(factory.getInterfaces()(IFakeObject))
175        return
176
177class CurrentPrincipalTestCase(unittest.TestCase):
178
179    def tearDown(test):
180        endInteraction() # Just in case, one is still lingering around
181
182    def test_existing_principal(self):
183        # We can get the current principal if one is involved
184        principal = Principal('myprincipal')
185        newInteraction(Participation(principal))
186        result = helpers.get_current_principal()
187        self.assertTrue(result is principal)
188
189    def test_no_participation(self):
190        # Interactions without participation are handled correctly
191        newInteraction()
192        result = helpers.get_current_principal()
193        self.assertTrue(result is None)
194
195    def test_not_existing_principal(self):
196        # Missing interactions do not raise errors.
197        result = helpers.get_current_principal()
198        self.assertTrue(result is None)
199
200class CmpFilesTestCase(unittest.TestCase):
201
202    def setUp(self):
203        self.workdir = tempfile.mkdtemp()
204
205    def tearDown(self):
206        shutil.rmtree(self.workdir)
207
208    def test_equal(self):
209        p1 = os.path.join(self.workdir, 'sample1')
210        p2 = os.path.join(self.workdir, 'sample2')
211        f1 = open(p1, 'wb').write('Hi!')
212        f2 = open(p2, 'wb').write('Hi!')
213        assert helpers.cmp_files(open(p1, 'r'), open(p2, 'r')) is True
214
215    def test_unequal(self):
216        p1 = os.path.join(self.workdir, 'sample1')
217        p2 = os.path.join(self.workdir, 'sample2')
218        f1 = open(p1, 'wb').write('Hi!')
219        f2 = open(p2, 'wb').write('Ho!')
220        assert helpers.cmp_files(open(p1, 'r'), open(p2, 'r')) is False
221
222class FileSizeTestCase(unittest.TestCase):
223
224    def setUp(self):
225        self.workdir = tempfile.mkdtemp()
226
227    def tearDown(self):
228        shutil.rmtree(self.workdir)
229
230    def test_real_file(self):
231        # we can get the size of real files
232        path = os.path.join(self.workdir, 'sample.txt')
233        open(path, 'wb').write('My content')
234        self.assertEqual(
235            int(helpers.file_size(open(path, 'rb'))), 10)
236        return
237
238    def test_stringio_file(self):
239        # we can get the size of file-like objects
240        self.assertEqual(
241            helpers.file_size(StringIO('my sample content')), 17)
242
243class IfaceNamesTestCase(unittest.TestCase):
244
245    def test_iface_names(self):
246        class I1(Interface):
247            foo = Attribute("""Some Foo""")
248            def bar(blah):
249                pass
250            i1_name = schema.TextLine(title=u'i1 name')
251        class I2(I1):
252            baz = schema.TextLine(title=u'some baz')
253
254        result1 = helpers.iface_names(I2)
255        result2 = helpers.iface_names(I1)
256        result3 = helpers.iface_names(I2, exclude_attribs=False)
257        result4 = helpers.iface_names(I2, exclude_methods=False)
258        result5 = helpers.iface_names(I2, omit='i1_name')
259        self.assertEqual(sorted(result1), ['baz', 'i1_name'])
260        self.assertEqual(sorted(result2), ['i1_name'])
261        self.assertEqual(sorted(result3), ['baz', 'foo', 'i1_name'])
262        self.assertEqual(sorted(result4), ['bar', 'baz', 'i1_name'])
263        self.assertEqual(sorted(result5), ['baz'])
264        return
265
266def test_suite():
267    suite = unittest.TestSuite()
268    # Register local test cases...
269    for testcase in [
270        ReST2HTMLTestCase,
271        FactoryBaseTestCase,
272        CopyFileSystemTreeTestCase,
273        RemoveFileOrDirectoryTestCase,
274        CurrentPrincipalTestCase,
275        CmpFilesTestCase,
276        FileSizeTestCase,
277        IfaceNamesTestCase,
278        ]:
279        suite.addTests(
280            unittest.TestLoader().loadTestsFromTestCase(testcase)
281            )
282    # Add tests from docstrings in helpers.py...
283    suite.addTests(
284        doctest.DocTestSuite(
285            helpers,
286            optionflags = doctest.ELLIPSIS + doctest.REPORT_NDIFF,
287            )
288        )
289    return suite
290
291if __name__ == '__main__':
292    unittest.main(defaultTest='test_suite')
Note: See TracBrowser for help on using the repository browser.