root/galaxy-central/eggs/nose-0.11.1-py2.6.egg/nose/case.py @ 3

リビジョン 3, 12.2 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

行番号 
1"""nose unittest.TestCase subclasses. It is not necessary to subclass these
2classes when writing tests; they are used internally by nose.loader.TestLoader
3to create test cases from test functions and methods in test classes.
4"""
5import logging
6import sys
7import unittest
8from nose.config import Config
9from nose.failure import Failure # for backwards compatibility
10from nose.util import resolve_name, test_address, try_run
11
12log = logging.getLogger(__name__)
13
14
15__all__ = ['Test']
16
17
18class Test(unittest.TestCase):
19    """The universal test case wrapper.
20
21    When a plugin sees a test, it will always see an instance of this
22    class. To access the actual test case that will be run, access the
23    test property of the nose.case.Test instance.   
24    """
25    __test__ = False # do not collect
26    def __init__(self, test, config=None, resultProxy=None):
27        # sanity check
28        if not callable(test):
29            raise TypeError("nose.case.Test called with argument %r that "
30                            "is not callable. A callable is required."
31                            % test)
32        self.test = test
33        if config is None:
34            config = Config()
35        self.config = config
36        self.tbinfo = None
37        self.capturedOutput = None
38        self.resultProxy = resultProxy
39        self.plugins = config.plugins
40        self.passed = None
41        unittest.TestCase.__init__(self)
42       
43    def __call__(self, *arg, **kwarg):
44        return self.run(*arg, **kwarg)
45
46    def __str__(self):
47        name = self.plugins.testName(self)
48        if name is not None:
49            return name
50        return str(self.test)
51
52    def __repr__(self):
53        return "Test(%r)" % self.test
54
55    def afterTest(self, result):
56        """Called after test is complete (after result.stopTest)
57        """
58        try:
59            afterTest = result.afterTest
60        except AttributeError:
61            pass
62        else:
63            afterTest(self.test)
64
65    def beforeTest(self, result):
66        """Called before test is run (before result.startTest)
67        """
68        try:
69            beforeTest = result.beforeTest
70        except AttributeError:
71            pass
72        else:
73            beforeTest(self.test)
74
75    def exc_info(self):
76        """Extract exception info.
77        """       
78        exc, exv, tb = sys.exc_info()
79        return (exc, exv, tb)
80       
81    def id(self):
82        """Get a short(er) description of the test
83        """
84        return self.test.id()
85
86    def address(self):
87        """Return a round-trip name for this test, a name that can be
88        fed back as input to loadTestByName and (assuming the same
89        plugin configuration) result in the loading of this test.
90        """
91        if hasattr(self.test, 'address'):
92            return self.test.address()
93        else:
94            # not a nose case
95            return test_address(self.test)
96
97    def _context(self):
98        try:
99            return self.test.context
100        except AttributeError:
101            pass
102        try:
103            return self.test.__class__
104        except AttributeError:
105            pass
106        try:
107            return resolve_name(self.test.__module__)
108        except AttributeError:
109            pass
110        return None               
111    context = property(_context, None, None,
112                      """Get the context object of this test (if any).""")
113   
114    def run(self, result):
115        """Modified run for the test wrapper.
116
117        From here we don't call result.startTest or stopTest or
118        addSuccess.  The wrapper calls addError/addFailure only if its
119        own setup or teardown fails, or running the wrapped test fails
120        (eg, if the wrapped "test" is not callable).
121
122        Two additional methods are called, beforeTest and
123        afterTest. These give plugins a chance to modify the wrapped
124        test before it is called and do cleanup after it is
125        called. They are called unconditionally.
126        """
127        if self.resultProxy:
128            result = self.resultProxy(result, self)
129        try:
130            try:
131                self.beforeTest(result)
132                self.runTest(result)
133            except KeyboardInterrupt:
134                raise
135            except:
136                err = sys.exc_info()
137                result.addError(self, err)
138        finally:
139            self.afterTest(result)
140       
141    def runTest(self, result):
142        """Run the test. Plugins may alter the test by returning a
143        value from prepareTestCase. The value must be callable and
144        must accept one argument, the result instance.
145        """       
146        test = self.test
147        plug_test = self.config.plugins.prepareTestCase(self)
148        if plug_test is not None:
149            test = plug_test
150        test(result)
151       
152    def shortDescription(self):
153        desc = self.plugins.describeTest(self)
154        if desc is not None:
155            return desc
156        doc = self.test.shortDescription()
157        if doc is not None:
158            return doc
159        # work around bug in unittest.TestCase.shortDescription
160        # with multiline docstrings.
161        test = self.test
162        try:
163            doc = test._testMethodDoc # 2.5
164        except AttributeError:
165            try:
166                doc = test._TestCase__testMethodDoc # 2.4 and earlier
167            except AttributeError:
168                pass
169        if doc is not None:
170            doc = doc.strip().split("\n")[0].strip()
171        return doc
172
173
174class TestBase(unittest.TestCase):
175    """Common functionality for FunctionTestCase and MethodTestCase.
176    """
177    __test__ = False # do not collect
178   
179    def id(self):
180        return str(self)
181       
182    def runTest(self):
183        self.test(*self.arg)
184   
185    def shortDescription(self):
186        if hasattr(self.test, 'description'):
187            return self.test.description
188        func, arg = self._descriptors()
189        doc = getattr(func, '__doc__', None)
190        if not doc:
191            doc = str(self)
192        return doc.strip().split("\n")[0].strip()
193
194   
195class FunctionTestCase(TestBase):
196    """TestCase wrapper for test functions.
197
198    Don't use this class directly; it is used internally in nose to
199    create test cases for test functions.
200    """
201    __test__ = False # do not collect
202   
203    def __init__(self, test, setUp=None, tearDown=None, arg=tuple(),
204                 descriptor=None):
205        """Initialize the MethodTestCase.
206
207        Required argument:
208
209        * test -- the test function to call.
210
211        Optional arguments:
212
213        * setUp -- function to run at setup.
214
215        * tearDown -- function to run at teardown.
216
217        * arg -- arguments to pass to the test function. This is to support
218          generator functions that yield arguments.
219
220        * descriptor -- the function, other than the test, that should be used
221          to construct the test name. This is to support generator functions.
222        """
223       
224        self.test = test
225        self.setUpFunc = setUp
226        self.tearDownFunc = tearDown
227        self.arg = arg
228        self.descriptor = descriptor
229        TestBase.__init__(self)       
230
231    def address(self):
232        """Return a round-trip name for this test, a name that can be
233        fed back as input to loadTestByName and (assuming the same
234        plugin configuration) result in the loading of this test.
235        """
236        if self.descriptor is not None:
237            return test_address(self.descriptor)
238        else:
239            return test_address(self.test)   
240
241    def _context(self):
242        return resolve_name(self.test.__module__)
243    context = property(_context, None, None,
244                      """Get context (module) of this test""")
245       
246    def setUp(self):
247        """Run any setup function attached to the test function
248        """
249        if self.setUpFunc:
250            self.setUpFunc()
251        else:
252            names = ('setup', 'setUp', 'setUpFunc')
253            try_run(self.test, names)
254
255    def tearDown(self):
256        """Run any teardown function attached to the test function
257        """
258        if self.tearDownFunc:
259            self.tearDownFunc()
260        else:
261            names = ('teardown', 'tearDown', 'tearDownFunc')
262            try_run(self.test, names)
263       
264    def __str__(self):
265        func, arg = self._descriptors()
266        if hasattr(func, 'compat_func_name'):
267            name = func.compat_func_name
268        else:
269            name = func.__name__
270        name = "%s.%s" % (func.__module__, name)
271        if arg:
272            name = "%s%s" % (name, arg)
273        # FIXME need to include the full dir path to disambiguate
274        # in cases where test module of the same name was seen in
275        # another directory (old fromDirectory)
276        return name
277    __repr__ = __str__
278   
279    def _descriptors(self):
280        """Get the descriptors of the test function: the function and
281        arguments that will be used to construct the test name. In
282        most cases, this is the function itself and no arguments. For
283        tests generated by generator functions, the original
284        (generator) function and args passed to the generated function
285        are returned.
286        """
287        if self.descriptor:
288            return self.descriptor, self.arg
289        else:           
290            return self.test, self.arg
291
292
293class MethodTestCase(TestBase):
294    """Test case wrapper for test methods.
295
296    Don't use this class directly; it is used internally in nose to
297    create test cases for test methods.
298    """
299    __test__ = False # do not collect
300   
301    def __init__(self, method, test=None, arg=tuple(), descriptor=None):
302        """Initialize the MethodTestCase.
303
304        Required argument:
305
306        * method -- the method to call, may be bound or unbound. In either
307          case, a new instance of the method's class will be instantiated to
308          make the call.
309
310        Optional arguments:
311
312        * test -- the test function to call. If this is passed, it will be
313          called instead of getting a new bound method of the same name as the
314          desired method from the test instance. This is to support generator
315          methods that yield inline functions.
316
317        * arg -- arguments to pass to the test function. This is to support
318          generator methods that yield arguments.
319
320        * descriptor -- the function, other than the test, that should be used
321          to construct the test name. This is to support generator methods.
322        """
323        self.method = method
324        self.test = test
325        self.arg = arg
326        self.descriptor = descriptor
327        self.cls = method.im_class
328        self.inst = self.cls()
329        if self.test is None:
330            method_name = self.method.__name__
331            self.test = getattr(self.inst, method_name)           
332        TestBase.__init__(self)
333
334    def __str__(self):
335        func, arg = self._descriptors()
336        if hasattr(func, 'compat_func_name'):
337            name = func.compat_func_name
338        else:
339            name = func.__name__
340        name = "%s.%s.%s" % (self.cls.__module__,
341                             self.cls.__name__,
342                             name)
343        if arg:
344            name = "%s%s" % (name, arg)
345        return name
346    __repr__ = __str__
347
348    def address(self):
349        """Return a round-trip name for this test, a name that can be
350        fed back as input to loadTestByName and (assuming the same
351        plugin configuration) result in the loading of this test.
352        """
353        if self.descriptor is not None:
354            return test_address(self.descriptor)
355        else:
356            return test_address(self.method)
357
358    def _context(self):
359        return self.cls
360    context = property(_context, None, None,
361                      """Get context (class) of this test""")
362
363    def setUp(self):
364        try_run(self.inst, ('setup', 'setUp'))
365
366    def tearDown(self):
367        try_run(self.inst, ('teardown', 'tearDown'))
368       
369    def _descriptors(self):
370        """Get the descriptors of the test method: the method and
371        arguments that will be used to construct the test name. In
372        most cases, this is the method itself and no arguments. For
373        tests generated by generator methods, the original
374        (generator) method and args passed to the generated method
375        or function are returned.
376        """
377        if self.descriptor:
378            return self.descriptor, self.arg
379        else:
380            return self.method, self.arg
Note: リポジトリブラウザについてのヘルプは TracBrowser を参照してください。