Source

nose / unit_tests / test_plugins.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import logging
import os
import sys
import unittest
import nose.plugins
from optparse import OptionParser
import tempfile
from warnings import warn, filterwarnings, resetwarnings

from nose import SkipTest
from nose.config import Config
from nose.plugins.attrib import AttributeSelector
from nose.plugins.base import Plugin
from nose.plugins.cover import Coverage
from nose.plugins.doctests import Doctest
from nose.plugins.prof import Profile

from mock import *

class P(Plugin):
    """Plugin of destiny!"""    
    pass

class ErrPlugin(object):
    def load(self):
        raise Exception("Failed to load the plugin")
    
class ErrPkgResources(object):
    def iter_entry_points(self, ep):
        yield ErrPlugin()

        
# some plugins have 2.4-only features
compat_24 = sys.version_info >= (2, 4)


class TestBuiltinPlugins(unittest.TestCase):

    def setUp(self):
        self.p = sys.path[:]

    def tearDown(self):
        sys.path = self.p[:]
                
    def test_add_options(self):
        conf = Config()
        opt = Bucket()
        parser = MockOptParser()
        plug = P()

        plug.add_options(parser)
        o, d = parser.opts[0]
        # print d
        assert o[0] == '--with-p'
        assert d['action'] == 'store_true'
        assert not d['default']
        assert d['dest'] == 'enable_plugin_p'
        assert d['help'] == 'Enable plugin P: Plugin of destiny! [NOSE_WITH_P]'

        opt.enable_plugin_p = True
        plug.configure(opt, conf)
        assert plug.enabled

        
class TestDoctestPlugin(unittest.TestCase):

    def setUp(self):
        self.p = sys.path[:]

    def tearDown(self):
        sys.path = self.p[:]
    
    def test_add_options(self):
        # doctest plugin adds some options...
        conf = Config()
        opt = Bucket()
        parser = MockOptParser()
        plug = Doctest()
        
        plug.add_options(parser, {})
        o, d = parser.opts[0]
        assert o[0] == '--with-doctest'

        o2, d2 = parser.opts[1]
        assert o2[0] == '--doctest-tests'
        
        o3, d3 = parser.opts[2]
        assert o3[0] == '--doctest-extension'

    def test_config(self):
        # test that configuration works properly when both environment
        # and command line specify a doctest extension
        parser = OptionParser()
        env = {'NOSE_DOCTEST_EXTENSION':'ext'}
        argv = ['--doctest-extension', 'txt']
        dtp = Doctest()
        dtp.add_options(parser, env)
        options, args = parser.parse_args(argv)
        
        print options
        print args
        self.assertEqual(options.doctestExtension, ['ext', 'txt'])

        env = {}
        parser = OptionParser()
        dtp.add_options(parser, env)
        options, args = parser.parse_args(argv)
        print options
        print args
        self.assertEqual(options.doctestExtension, ['txt'])
            
    def test_want_file(self):
        # doctest plugin can select module and/or non-module files
        conf = Config()
        opt = Bucket()
        plug = Doctest()
        plug.can_configure = True
        plug.configure(opt, conf)
        
        assert plug.wantFile('foo.py')
        assert not plug.wantFile('bar.txt')
        assert not plug.wantFile('buz.rst')
        assert not plug.wantFile('bing.mov')
        
        plug.extension = ['.txt', '.rst']
        assert plug.wantFile('/path/to/foo.py')
        assert plug.wantFile('/path/to/bar.txt')
        assert plug.wantFile('/path/to/buz.rst')
        assert not plug.wantFile('/path/to/bing.mov')
        
    def test_matches(self):
        # doctest plugin wants tests from all NON-test modules
        conf = Config()
        opt = Bucket()
        plug = Doctest()
        plug.can_configure = True
        plug.configure(opt, conf)
        assert not plug.matches('test')
        assert plug.matches('foo')

    def test_collect_pymodule(self):
        here = os.path.dirname(__file__)
        support = os.path.join(here, 'support')
        if not support in sys.path:
            sys.path.insert(0, support)
        import foo.bar.buz
        
        conf = Config()
        opt = Bucket()
        plug = Doctest()
        plug.can_configure = True
        plug.configure(opt, conf)
        suite = plug.loadTestsFromModule(foo.bar.buz)        
        expect = ['[afunc (foo.bar.buz)]']
        for test in suite:
            self.assertEqual(str(test), expect.pop(0))

    def test_addresses(self):
        here = os.path.dirname(__file__)
        support = os.path.join(here, 'support')
        if not support in sys.path:
            sys.path.insert(0, support)
        import foo.bar.buz
        
        conf = Config()
        opt = Bucket()
        plug = Doctest()
        plug.can_configure = True
        plug.configure(opt, conf)
        suite = plug.loadTestsFromModule(foo.bar.buz)
        for test in suite:
            print test.address()
            file, mod, call = test.address()
            self.assertEqual(mod, 'foo.bar.buz')
            self.assertEqual(call, None)
            for case in test:
                print case.address()
                file, mod, call = case.address()
                self.assertEqual(mod, 'foo.bar.buz')
                self.assertEqual(call, 'afunc')
            
    def test_collect_txtfile(self):
        here = os.path.abspath(os.path.dirname(__file__))
        support = os.path.join(here, 'support')
        fn = os.path.join(support, 'foo', 'doctests.txt')
        
        conf = Config()        
        opt = Bucket()
        plug = Doctest()
        plug.can_configure = True
        plug.configure(opt, conf)
        plug.extension = ['.txt']
        suite = plug.loadTestsFromFile(fn)
        for test in suite:
            assert str(test).endswith('doctests.txt')
            assert test.address(), "Test %s has no address"
        
    def test_collect_no_collect(self):
        # bug http://nose.python-hosting.com/ticket/55 
        # we got "iteration over non-sequence" when no files match
        here = os.path.abspath(os.path.dirname(__file__))
        support = os.path.join(here, 'support')
        plug = Doctest()
        for test in plug.loadTestsFromFile(os.path.join(support, 'foo')):
            self.fail("Expected no tests, got %s" % test)


class TestAttribPlugin(unittest.TestCase):

    def test_add_options(self):
        plug = AttributeSelector()
        parser = MockOptParser()
        plug.add_options(parser)

        expect = [(('-a', '--attr'),
                   {'dest': 'attr', 'action': 'append', 'default': None,
                    'metavar': 'ATTR',
                    'help': 'Run only tests that have attributes '
                    'specified by ATTR [NOSE_ATTR]'})]

        if compat_24:
            expect.append(
                (('-A', '--eval-attr'),
                 {'dest': 'eval_attr', 'action': 'append',
                  'default': None, 'metavar': 'EXPR',
                  'help': 'Run only tests for whose attributes the '
                  'Python expression EXPR evaluates to True '
                  '[NOSE_EVAL_ATTR]'}))
        self.assertEqual(parser.opts, expect)

        opt = Bucket()
        opt.attr = ['!slow']
        plug.configure(opt, Config())
        assert plug.enabled
        self.assertEqual(plug.attribs, [[('slow', False)]])

        opt.attr = ['fast,quick', 'weird=66']
        plug.configure(opt, Config())
        self.assertEqual(plug.attribs, [[('fast', True),
                                         ('quick', True)],
                                        [('weird', '66')]])

        # don't die on trailing ,
        opt.attr = [ 'something,' ]
        plug.configure(opt, Config())
        self.assertEqual(plug.attribs, [[('something', True)]] )
        
        if compat_24:
            opt.attr = None
            opt.eval_attr = [ 'weird >= 66' ]
            plug.configure(opt, Config())
            self.assertEqual(plug.attribs[0][0][0], 'weird >= 66')
            assert callable(plug.attribs[0][0][1])
                       
    def test_basic_attr(self):
        def f():
            pass
        f.a = 1

        def g():
            pass
    
        plug = AttributeSelector()
        plug.attribs = [[('a', True)]]
        assert plug.wantFunction(f) is not False
        assert not plug.wantFunction(g)

    def test_class_attr(self):
        class TestP:
            foo = True
            def h():
                pass

        def i():
            pass
        
        plug = AttributeSelector()
        plug.attribs = [[('foo', True)]]
        assert plug.wantMethod(TestP.h) is not False
        assert plug.wantFunction(i) is False
        
    def test_eval_attr(self):
        if not compat_24:
            warn("No support for eval attributes in python versions older"
                 " than 2.4")
            return
        def f():
            pass
        f.monkey = 2
        
        def g():
            pass
        g.monkey = 6

        def h():
            pass
        h.monkey = 5
        
        cnf = Config()
        opt = Bucket()
        opt.eval_attr = "monkey > 5"
        plug = AttributeSelector()
        plug.configure(opt, cnf)

        assert not plug.wantFunction(f)
        assert plug.wantFunction(g) is not False
        assert not plug.wantFunction(h)

    def test_attr_a_b(self):
        def f1():
            pass
        f1.tags = ['a', 'b']

        def f2():
            pass
        f2.tags = ['a', 'c']

        def f3():
            pass
        f3.tags = ['b', 'c']

        def f4():
            pass
        f4.tags = ['c', 'd']
        
        cnf = Config()
        parser = OptionParser()
        plug = AttributeSelector()

        plug.add_options(parser)

        # OR
        opt, args = parser.parse_args(['test', '-a', 'tags=a',
                                       '-a', 'tags=b'])
        print opt
        plug.configure(opt, cnf)

        assert plug.wantFunction(f1) is None
        assert plug.wantFunction(f2) is None
        assert plug.wantFunction(f3) is None
        assert not plug.wantFunction(f4)

        # AND
        opt, args = parser.parse_args(['test', '-a', 'tags=a,tags=b'])
        print opt
        plug.configure(opt, cnf)

        assert plug.wantFunction(f1) is None
        assert not plug.wantFunction(f2)
        assert not plug.wantFunction(f3)
        assert not plug.wantFunction(f4)
        

class TestProfPlugin(unittest.TestCase):

    def setUp(self):        
        if not Profile.available():
            raise SkipTest('profile plugin not available; skipping')

    def test_options(self):
        parser = OptionParser()
        conf = Config()
        plug = Profile()

        plug.add_options(parser, {})
        opts = [ o._long_opts[0] for o in parser.option_list ]
        assert '--profile-sort' in opts
        assert '--profile-stats-file' in opts
        assert '--with-profile' in opts
        assert '--profile-restrict' in opts

    def test_begin(self):
        plug = Profile()
        plug.pfile = tempfile.mkstemp()[1]
        try:
            plug.begin()
            assert plug.prof
        finally:
            plug.finalize(None)

    def test_prepare_test(self):
        r = {}
        class dummy:
            def runcall(self, f, r):
                r[1] = f(), "wrapped"
        def func():
            return "func"
        
        plug = Profile()
        plug.prof = dummy()
        result = plug.prepareTest(func)
        try:
            result(r)
            assert r[1] == ("func", "wrapped")
        finally:
            plug.finalize(None)

    def test_finalize(self):
        def func():
            pass

        plug = Profile()
        plug.begin()
        plug.prepareTest(func)
        pfile = plug.pfile
        try:
            assert os.path.exists(pfile)
        finally:
            plug.finalize(None)
        assert not os.path.exists(pfile), \
               "finalize did not remove temp file %s" % pfile

if __name__ == '__main__':
    unittest.main()