1# Copyright (C) 2010 Apple Inc. All rights reserved.
2#
3# Redistribution and use in source and binary forms, with or without
4# modification, are permitted provided that the following conditions
5# are met:
6# 1.  Redistributions of source code must retain the above copyright
7#     notice, this list of conditions and the following disclaimer.
8# 2.  Redistributions in binary form must reproduce the above copyright
9#     notice, this list of conditions and the following disclaimer in the
10#     documentation and/or other materials provided with the distribution.
11#
12# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
13# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
14# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
15# DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
16# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
17# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
18# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
19# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
20# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
21# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22
23import logging
24
25_log = logging.getLogger(__name__)
26
27
28def skip_if(klass, condition, message=None, logger=None):
29    """Makes all test_* methods in a given class no-ops if the given condition
30    is False. Backported from Python 3.1+'s unittest.skipIf decorator."""
31    if not logger:
32        logger = _log
33    if not condition:
34        return klass
35    for name in dir(klass):
36        attr = getattr(klass, name)
37        if not callable(attr):
38            continue
39        if not name.startswith('test_'):
40            continue
41        setattr(klass, name, _skipped_method(attr, message, logger))
42    klass._printed_skipped_message = False
43    return klass
44
45
46def _skipped_method(method, message, logger):
47    def _skip(*args):
48        if method.im_class._printed_skipped_message:
49            return
50        method.im_class._printed_skipped_message = True
51        logger.info('Skipping %s.%s: %s' % (method.__module__, method.im_class.__name__, message))
52    return _skip
53