Пример #1
0
def skip_if_pyside_missing(func):
    """
    Decorated that allows to skips a test if PySide is missing.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    return unittest.skipIf(_is_pyside_missing(), "PySide is missing")(func)
Пример #2
0
class OpenMPTests(unittest2.TestCase):
    def setUp(self):
        self._num_threads = chemfp.get_num_threads()

    def tearDown(self):
        chemfp.set_num_threads(self._num_threads)

    def test_num_threads_is_max_threads(self):
        self.assertEquals(chemfp.get_num_threads(), chemfp.get_max_threads())

    def test_set_to_zero(self):
        chemfp.set_num_threads(0)
        self.assertEquals(chemfp.get_num_threads(), 1)

    def test_set_to_one(self):
        chemfp.set_num_threads(1)
        self.assertEquals(chemfp.get_num_threads(), 1)

    def test_set_to_two(self):
        chemfp.set_num_threads(2)
        self.assertEquals(chemfp.get_num_threads(), 2)

    test_set_to_two = unittest2.skipIf(
        skip_omp, "Multiple OMP threads not available")(test_set_to_two)

    def test_set_to_max(self):
        chemfp.set_num_threads(chemfp.get_max_threads())
        self.assertEquals(chemfp.get_num_threads(), chemfp.get_max_threads())

    def test_set_beyond_max(self):
        chemfp.set_num_threads(chemfp.get_max_threads() + 1)
        self.assertEquals(chemfp.get_num_threads(), chemfp.get_max_threads())
Пример #3
0
def only_run_with_non_partitioned_database(cls):
    """
    Only runs the test with the non-partitioned database settings.
    """
    skip_if = skipIf(settings.USE_PARTITIONED_DATABASE,
                     'Only applicable when sharding is not setup')
    return skip_if(cls)
Пример #4
0
def skipIfXmlSupportMissing(func):
    config = lldb.SBDebugger.GetBuildConfiguration()
    xml = config.GetValueForKey("xml")

    fail_value = True  # More likely to notice if something goes wrong
    have_xml = xml.GetValueForKey("value").GetBooleanValue(fail_value)
    return unittest2.skipIf(not have_xml, "requires xml support")(func)
Пример #5
0
def skip_if_pyside_missing(func):
    """
    Decorated that allows to skips a test if PySide is missing.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    return unittest.skipIf(_is_pyside_missing(), "PySide is missing")(func)
Пример #6
0
def only_run_with_non_partitioned_database(cls):
    """
    Only runs the test with the non-partitioned database settings.
    """
    skip_if = skipIf(
        settings.USE_PARTITIONED_DATABASE, 'Only applicable when sharding is not setup'
    )
    return skip_if(cls)
Пример #7
0
def skipRemote(func):  # noqa
    """Decorator to skip tests based on whether server is remote,
    Remote in the sense whether it is Sauce Labs"""

    remote = int(conf.properties['main.remote'])
    return unittest2.skipIf(
        remote == 1,
        "Skipping as setup related to sauce labs is missing")(func)
Пример #8
0
def only_run_on_nix(func):
    """
    Decorator that allows to skip a test if not running on linux/macosx.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    running_windows = is_windows()
    return unittest.skipIf(running_windows, "Linux/Macosx only test.")(func)
Пример #9
0
def only_run_on_windows(func):
    """
    Decorator that allows to skip a test if not running on windows.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    running_nix = not is_windows()
    return unittest.skipIf(running_nix, "Windows only test.")(func)
Пример #10
0
def skipIfLLVMTargetMissing(target):
    config = lldb.SBDebugger.GetBuildConfiguration()
    targets = config.GetValueForKey("targets").GetValueForKey("value")
    found = False
    for i in range(targets.GetSize()):
        if targets.GetItemAtIndex(i).GetStringValue(99) == target:
            found = True
            break

    return unittest2.skipIf(not found, "requires " + target)
Пример #11
0
        def decorator(fn, path=arg):
            if path:
                cond = not os.path.exists(path)
            else:
                try:
                    self.search_server()
                    cond = False  # found
                except:
                    cond = True  # not found

            return skipIf(cond, "%s not found" % self.name)(fn)
Пример #12
0
    def decorator(fn, path=arg):
        if path:
            cond = not os.path.exists(path)
        else:
            try:
                find_program('postgres', ['bin'])  # raise exception if not found
                cond = False
            except:
                cond = True  # not found

        return skipIf(cond, "PostgreSQL not found")(fn)
Пример #13
0
def interactive(func):
    """
    Decorator that allows to skip a test if the interactive flag is not set
    on the command line.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    interactive_in_argv = "--interactive" not in sys.argv
    return unittest.skipIf(
        interactive_in_argv,
        "add --interactive on the command line to run this test.")(func)
Пример #14
0
def skipIf(condition, reason):
    """
    A docorator for test skipping.
    """
    version = getPythonVersion()
    if version >= 2.7:
        import unittest
        return unittest.skipIf(condition, reason)
    else:
        import unittest2
        return unittest2.skipIf(condition, reason)
Пример #15
0
def only_run_on_nix(func):
    """
    Decorator that allows to skip a test if not running on linux/macosx.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    running_windows = sys.platform == "win32"
    return unittest.skipIf(
        running_windows,
        "Linux/Macosx only test."
    )(func)
Пример #16
0
def only_run_on_windows(func):
    """
    Decorator that allows to skip a test if not running on windows.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    running_nix = sys.platform != "win32"
    return unittest.skipIf(
        running_nix,
        "Windows only test."
    )(func)
Пример #17
0
        def decorator(fn, path=arg):
            if path:
                cond = not os.path.exists(path)
            else:
                try:
                    self.search_server()
                    cond = False  # found
                except:
                    cond = True  # not found

            return skipIf(cond, "%s not found" % self.name)(fn)
Пример #18
0
def skipIf(condition, reason):
    """
    A docorator for test skipping.
    """
    version = getPythonVersion()
    if version >= 2.7:
        import unittest
        return unittest.skipIf(condition, reason)
    else:
        import unittest2
        return unittest2.skipIf(condition, reason)
Пример #19
0
def interactive(func):
    """
    Decorator that allows to skip a test if the interactive flag is not set
    on the command line.
    :param func: Function to be decorated.
    :returns: The decorated function.
    """
    interactive_in_argv = "--interactive" not in sys.argv
    return unittest.skipIf(
        interactive_in_argv,
        "add --interactive on the command line to run this test."
    )(func)
Пример #20
0
    def decorator(fn, path=arg):
        if path:
            cond = not os.path.exists(path)
        else:
            try:
                find_program('postgres',
                             ['bin'])  # raise exception if not found
                cond = False
            except:
                cond = True  # not found

        return skipIf(cond, "PostgreSQL not found")(fn)
Пример #21
0

class ParserTestCase(object):

    def setUp(self):
        self.old_parser = settings.COMPRESS_PARSER
        settings.COMPRESS_PARSER = self.parser_cls
        super(ParserTestCase, self).setUp()

    def tearDown(self):
        settings.COMPRESS_PARSER = self.old_parser


class LxmlParserTests(ParserTestCase, CompressorTestCase):
    parser_cls = 'compressor.parser.LxmlParser'
LxmlParserTests = skipIf(lxml is None, 'lxml not found')(LxmlParserTests)


class Html5LibParserTests(ParserTestCase, CompressorTestCase):
    parser_cls = 'compressor.parser.Html5LibParser'

    def test_css_split(self):
        out = [
            (SOURCE_FILE, os.path.join(settings.COMPRESS_ROOT, u'css/one.css'), u'css/one.css', u'<link charset="utf-8" href="/media/css/one.css" rel="stylesheet" type="text/css">'),
            (SOURCE_HUNK, u'p { border:5px solid green;}', None, u'<style type="text/css">p { border:5px solid green;}</style>'),
            (SOURCE_FILE, os.path.join(settings.COMPRESS_ROOT, u'css/two.css'), u'css/two.css', u'<link charset="utf-8" href="/media/css/two.css" rel="stylesheet" type="text/css">'),
        ]
        split = self.css_node.split_contents()
        split = [(x[0], x[1], x[2], self.css_node.parser.elem_str(x[3])) for x in split]
        self.assertEqual(out, split)
Пример #22
0
def SkipIfCppImplementation(func):
  return unittest.skipIf(
      api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
      'C++ implementation does not expose unknown fields to Python')(func)
Пример #23
0
def skipIfRemote(func):
    """Decorate the item to skip tests if testing remotely."""
    return unittest2.skipIf(lldb.remote_platform,
                            "skip on remote platform")(func)
Пример #24
0
            my_cpu = self._get_cpus()

            proc = mitogen.parent.popen(
                args=['cp', '/proc/self/status', tf.name])
            proc.wait()

            his_cpu = self._get_cpus(tf.name)
            self.assertNotEquals(my_cpu, his_cpu)
            self.policy._clear()
        finally:
            tf.close()


class MockLinuxPolicyTest(testlib.TestCase):
    klass = ansible_mitogen.affinity.LinuxPolicy

    # Test struct.pack() in _set_cpu_mask().

    def test_high_cpus(self):
        policy = self.klass(cpu_count=4096)
        for x in range(1, 4096, 32):
            policy.assign_subprocess()


MockLinuxPolicyTest = unittest2.skipIf(
    condition=(not sys.platform.startswith('linuxPolicy')),
    reason='select.select() not supported')(MockLinuxPolicyTest)

if __name__ == '__main__':
    unittest2.main()
Пример #25
0
import sys
import textwrap

from tornado.testing import bind_unused_port

# Encapsulate the choice of unittest or unittest2 here.
# To be used as 'from tornado.test.util import unittest'.
if sys.version_info < (2, 7):
    # In py26, we must always use unittest2.
    import unittest2 as unittest
else:
    # Otherwise, use whichever version of unittest was imported in
    # tornado.testing.
    from tornado.testing import unittest

skipIfNonUnix = unittest.skipIf(os.name != 'posix' or sys.platform == 'cygwin',
                                "non-unix platform")

# travis-ci.org runs our tests in an overworked virtual machine, which makes
# timing-related tests unreliable.
skipOnTravis = unittest.skipIf('TRAVIS' in os.environ,
                               'timing tests unreliable on travis')

# Set the environment variable NO_NETWORK=1 to disable any tests that
# depend on an external network.
skipIfNoNetwork = unittest.skipIf('NO_NETWORK' in os.environ,
                                  'network access disabled')

skipIfNoIPv6 = unittest.skipIf(not socket.has_ipv6, 'ipv6 support not present')

skipBefore33 = unittest.skipIf(sys.version_info < (3, 3),
                               'PEP 380 (yield from) not available')
Пример #26
0
def skipNotPOSIX():
    return unittest.skipIf(os.name != 'posix',
                           'This test works only on POSIX')
Пример #27
0
def SkipCheckUnknownFieldIfCppImplementation(func):
    return unittest.skipIf(
        api_implementation.Type() == 'cpp'
        and api_implementation.Version() == 2,
        'Addtional test for pure python involved protect members')(func)
Пример #28
0
import sys
import textwrap

from tornado.testing import bind_unused_port

# Encapsulate the choice of unittest or unittest2 here.
# To be used as 'from tornado.test.util import unittest'.
if sys.version_info < (2, 7):
    # In py26, we must always use unittest2.
    import unittest2 as unittest  # type: ignore
else:
    # Otherwise, use whichever version of unittest was imported in
    # tornado.testing.
    from tornado.testing import unittest

skipIfNonUnix = unittest.skipIf(os.name != 'posix' or sys.platform == 'cygwin',
                                "non-unix platform")

# travis-ci.org runs our tests in an overworked virtual machine, which makes
# timing-related tests unreliable.
skipOnTravis = unittest.skipIf('TRAVIS' in os.environ,
                               'timing tests unreliable on travis')

skipOnAppEngine = unittest.skipIf('APPENGINE_RUNTIME' in os.environ,
                                  'not available on Google App Engine')

# Set the environment variable NO_NETWORK=1 to disable any tests that
# depend on an external network.
skipIfNoNetwork = unittest.skipIf('NO_NETWORK' in os.environ,
                                  'network access disabled')

skipIfNoIPv6 = unittest.skipIf(not socket.has_ipv6, 'ipv6 support not present')
Пример #29
0
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import unittest
from unittest2 import skipIf
import os

from eulxml.xmlmap import load_xmlobject_from_file, load_xmlobject_from_string
from eulxml.xmlmap import eadmap

proxy_required = skipIf('HTTP_PROXY' not in os.environ,
                        'Schema validation test requires an HTTP_PROXY')


class TestEad(unittest.TestCase):
    FIXTURE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                'fixtures', 'heaney653.xml')

    def setUp(self):
        self.ead = load_xmlobject_from_file(self.FIXTURE_FILE, eadmap.EncodedArchivalDescription)

    def test_init(self):
        self.assert_(isinstance(self.ead, eadmap.EncodedArchivalDescription))

    def test_basic_fields(self):
        self.assertEqual(unicode(self.ead.title), "Seamus Heaney collection, 1972-1997")
        self.assertEqual(unicode(self.ead.eadid), u'heaney653')
Пример #30
0
class ParserTestCase(object):
    def setUp(self):
        self.old_parser = settings.COMPRESS_PARSER
        settings.COMPRESS_PARSER = self.parser_cls
        super(ParserTestCase, self).setUp()

    def tearDown(self):
        settings.COMPRESS_PARSER = self.old_parser


class LxmlParserTests(ParserTestCase, CompressorTestCase):
    parser_cls = "compressor.parser.LxmlParser"


LxmlParserTests = skipIf(lxml is None, "lxml not found")(LxmlParserTests)


class Html5LibParserTests(ParserTestCase, CompressorTestCase):
    parser_cls = "compressor.parser.Html5LibParser"

    def setUp(self):
        super(Html5LibParserTests, self).setUp()
        # special version of the css since the parser sucks
        self.css = """\
<link href="/media/css/one.css" rel="stylesheet" type="text/css">
<style type="text/css">p { border:5px solid green;}</style>
<link href="/media/css/two.css" rel="stylesheet" type="text/css">"""
        self.css_node = CssCompressor(self.css)

    def test_css_split(self):
Пример #31
0
        if permission == PRIVATE:
            return Authenticated in principals
        # Cliquet default authz policy uses prefixed_userid.
        prefixed = [getattr(context, 'prefixed_userid', None)]
        return USER_PRINCIPAL in (principals + prefixed)

    def principals_allowed_by_permission(self, context, permission):
        raise NotImplementedError()  # PRAGMA NOCOVER


def authorize(permits=True, authz_class=None):
    """Patch the default authorization policy to return what is specified
    in :param:permits.
    """
    if authz_class is None:
        authz_class = 'cliquet.tests.support.AllowAuthorizationPolicy'

    def wrapper(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            with mock.patch(
                    '%s.permits' % authz_class,
                    return_value=permits):
                return f(*args, **kwargs)
        return wrapped
    return wrapper

skip_if_travis = unittest.skipIf('TRAVIS' in os.environ, "travis")
skip_if_no_postgresql = unittest.skipIf(psycopg2 is None,
                                        "postgresql is not installed.")
Пример #32
0
    def tearDown(self):
        self.COMPRESS_OFFLINE_CONTEXT = self.old_offline_context
        super(OfflineGenerationConditionTestCase, self).tearDown()


class OfflineGenerationTemplateTagTestCase(OfflineTestCaseMixin, TestCase):
    templates_dir = "test_templatetag"
    expected_hash = "a27e1d3a619a"


class OfflineGenerationStaticTemplateTagTestCase(OfflineTestCaseMixin, TestCase):
    templates_dir = "test_static_templatetag"
    expected_hash = "dfa2bb387fa8"
# This test uses {% static %} which was introduced in django 1.4
OfflineGenerationStaticTemplateTagTestCase = skipIf(
    django.VERSION[1] < 4, 'Django 1.4 not found') (OfflineGenerationStaticTemplateTagTestCase)


class OfflineGenerationTestCaseWithContext(OfflineTestCaseMixin, TestCase):
    templates_dir = "test_with_context"
    expected_hash = "5838e2fd66af"

    def setUp(self):
        self.old_offline_context = settings.COMPRESS_OFFLINE_CONTEXT
        settings.COMPRESS_OFFLINE_CONTEXT = {
            'content': 'OK!',
        }
        super(OfflineGenerationTestCaseWithContext, self).setUp()

    def tearDown(self):
        settings.COMPRESS_OFFLINE_CONTEXT = self.old_offline_context
Пример #33
0
def only_for(version):
    """Should be used as a decorator for a unittest.TestCase test method"""
    return unittest.skipIf(
        sys.version < version,
        'This test requires at least {0} version of Python.'.format(version))
Пример #34
0
def skipIfPlatform(oslist):
    """Decorate the item to skip tests if running on one of the listed platforms."""
    # This decorator cannot be ported to `skipIf` yet because it is used on entire
    # classes, which `skipIf` explicitly forbids.
    return unittest2.skipIf(lldbplatformutil.getPlatform() in oslist,
                            "skip on %s" % (", ".join(oslist)))
Пример #35
0
        settings['fxa-oauth.webapp.authorized_domains'] = ['*.firefox.com', ]

        if additional_settings is not None:
            settings.update(additional_settings)
        return settings

    def tearDown(self):
        super(BaseWebTest, self).tearDown()
        self.db.flush()


class ThreadMixin(object):

    def setUp(self):
        super(ThreadMixin, self).setUp()
        self._threads = []

    def tearDown(self):
        super(ThreadMixin, self).tearDown()

        for thread in self._threads:
            thread.join()

    def _create_thread(self, *args, **kwargs):
        thread = threading.Thread(*args, **kwargs)
        self._threads.append(thread)
        return thread


skip_if_travis = unittest.skipIf('TRAVIS' in os.environ, "travis")
Пример #36
0
 def wrapper(func):
     return unittest.skipIf("TRAVIS" in os.environ, reason)(func)
Пример #37
0
 def decorator(func):
     return unittest.skipIf(
         platform.system() not in ['Darwin', 'Linux'], reason)(func)
Пример #38
0
def skip_if_linux():
    return unittest.skipIf(LINUX and SKIP_PYTHON_IMPL,
                           "not worth being tested on LINUX (pure python)")
def skipIfTargetAndroid(func):
    return unittest2.skipIf(lldbplatformutil.target_is_android(),
                            "skip on target Android")(func)
Пример #40
0
import socket
import sys

from tornado.testing import bind_unused_port

# Encapsulate the choice of unittest or unittest2 here.
# To be used as 'from tornado.test.util import unittest'.
if sys.version_info < (2, 7):
    # In py26, we must always use unittest2.
    import unittest2 as unittest
else:
    # Otherwise, use whichever version of unittest was imported in
    # tornado.testing.
    from tornado.testing import unittest

skipIfNonUnix = unittest.skipIf(os.name != 'posix' or sys.platform == 'cygwin',
                                "non-unix platform")

# travis-ci.org runs our tests in an overworked virtual machine, which makes
# timing-related tests unreliable.
skipOnTravis = unittest.skipIf(True,
                               'timing tests unreliable on travis')

# Set the environment variable NO_NETWORK=1 to disable any tests that
# depend on an external network.
skipIfNoNetwork = unittest.skipIf('NO_NETWORK' in os.environ,
                                  'network access disabled')

skipIfNoIPv6 = unittest.skipIf(not socket.has_ipv6, 'ipv6 support not present')


def refusing_port():
Пример #41
0
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 "
    "if threads have been used")
class TestBreakDefaultIntHandler(TestBreak):
    int_handler = signal.default_int_handler

@unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill")
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 "
    "if threads have been used")
class TestBreakSignalIgnored(TestBreak):
    int_handler = signal.SIG_IGN

@unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill")
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 "
    "if threads have been used")
class TestBreakSignalDefault(TestBreak):
    int_handler = signal.SIG_DFL


# Should also skip some tests on Jython
skipper = unittest2.skipUnless(hasattr(os, 'kill') and signal is not None,
                               "test uses os.kill(...) and the signal module")
skipper2 = unittest2.skipIf(sys.platform == 'win32', "can't run on windows")

TestBreak = skipper(skipper2(TestBreak))

if __name__ == '__main__':
    unittest2.main()
Пример #42
0
def only_for(version):
    """Should be used as a decorator for a unittest.TestCase test method"""
    return unittest.skipIf(
        sys.version < version,
        'This test requires at least {0} version of Python.'.format(version))
Пример #43
0
 def decorator(func):
     return unittest.skipIf(
         platform.system() not in ['Darwin', 'Linux'], reason)(func)
Пример #44
0
def only_for_versions_higher(version):
    """Should be used as a decorator for a unittest.TestCase test method"""
    return unittest.skipIf(
        sys.version < version,
        'This test requires version of Python higher than {0}'.format(version))
Пример #45
0
def _get_bool_config_skip_if_decorator(key):
    config = lldb.SBDebugger.GetBuildConfiguration()
    value_node = config.GetValueForKey(key)
    fail_value = True  # More likely to notice if something goes wrong
    have = value_node.GetValueForKey("value").GetBooleanValue(fail_value)
    return unittest2.skipIf(not have, "requires " + key)
Пример #46
0
def skipNotPOSIX():
    return unittest.skipIf(os.name != 'posix',
                           'This test works only on POSIX')
Пример #47
0
def skipIfReproducer(func):
    """Skip this test if the environment is set up to run LLDB with reproducers."""
    return unittest2.skipIf(
        configuration.capture_path or configuration.replay_path,
        "reproducers unsupported")(func)
Пример #48
0
import os

from unittest2 import skipIf

# setting environment variable PULP_RUN_BROKEN_TESTS to any non-empty value
# will cause the tests to not skip broken tests. This is useful for when
# someone is ready to work on fixing the broken tests.
skip_broken = skipIf(not bool(os.environ.get('PULP_RUN_BROKEN_TESTS')),
                     'skipping known-broken test')
Пример #49
0
def skipIfPlatform(oslist):
    """Decorate the item to skip tests if running on one of the listed platforms."""
    # This decorator cannot be ported to `skipIf` yet because it is used on entire
    # classes, which `skipIf` explicitly forbids.
    return unittest2.skipIf(lldbplatformutil.getPlatform() in oslist,
                            "skip on %s" % (", ".join(oslist)))
Пример #50
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from cassandra.cython_deps import HAVE_CYTHON, HAVE_NUMPY
from tests.integration import VERIFY_CYTHON

try:
    import unittest2 as unittest
except ImportError:
    import unittest  # noqa

def cyimport(import_path):
    """
    Import a Cython module if available, otherwise return None
    (and skip any relevant tests).
    """
    if HAVE_CYTHON:
        import pyximport
        py_importer, pyx_importer = pyximport.install()
        mod = __import__(import_path, fromlist=[True])
        pyximport.uninstall(py_importer, pyx_importer)
        return mod


# @cythontest
# def test_something(self): ...
cythontest = unittest.skipUnless((HAVE_CYTHON or VERIFY_CYTHON) or VERIFY_CYTHON, 'Cython is not available')
notcython = unittest.skipIf(HAVE_CYTHON, 'Cython not supported')
numpytest = unittest.skipUnless((HAVE_CYTHON and HAVE_NUMPY) or VERIFY_CYTHON, 'NumPy is not available')
Пример #51
0
greaterthancass20 = unittest.skipUnless(
    CASSANDRA_VERSION >= '2.1', 'Cassandra version 2.1 or greater required')
greaterthancass21 = unittest.skipUnless(
    CASSANDRA_VERSION >= '2.2', 'Cassandra version 2.2 or greater required')
greaterthanorequalcass30 = unittest.skipUnless(
    CASSANDRA_VERSION >= '3.0', 'Cassandra version 3.0 or greater required')
greaterthanorequalcass36 = unittest.skipUnless(
    CASSANDRA_VERSION >= '3.6', 'Cassandra version 3.6 or greater required')
lessthancass30 = unittest.skipUnless(
    CASSANDRA_VERSION < '3.0', 'Cassandra version less then 3.0 required')
dseonly = unittest.skipUnless(DSE_VERSION,
                              "Test is only applicalbe to DSE clusters")
pypy = unittest.skipUnless(platform.python_implementation() == "PyPy",
                           "Test is skipped unless it's on PyPy")
notpy3 = unittest.skipIf(sys.version_info >= (3, 0),
                         "Test not applicable for Python 3.x runtime")


def wait_for_node_socket(node, timeout):
    binary_itf = node.network_interfaces['binary']
    if not common.check_socket_listening(binary_itf, timeout=timeout):
        log.warn("Unable to connect to binary socket for node " + node.name)
    else:
        log.debug("Node %s is up and listening " % (node.name, ))


def check_socket_listening(itf, timeout=60):
    end = time.time() + timeout
    while time.time() <= end:
        try:
            sock = socket.socket()
try:
    # python 2.x
    import unittest2 as unittest

    PENALTY_MEM = 10
    PENALTY_CPU = 100
except ImportError:
    # python 3.x
    import unittest

    PENALTY_MEM = 10
    PENALTY_CPU = 150


enableIf = unittest.skipIf(
    os.getenv("PREFIXTREE_PERF") is None or sys.version_info[:2] < (2, 7),
    "Set PREFIXTREE_PERF environment variable to run performance tests",
)


def run_benchmark(script):
    cmd = ["PYTHONPATH=. {0} {1}".format(sys.executable, script)]
    output = subprocess.check_output(cmd, shell=True)
    mem, time = output.split()
    return float(mem), float(time)


class TestPerformance(unittest.TestCase):
    def _benchmark(self):
        mem_dict, cpu_dict = run_benchmark("tests/benchmark_dict.py")
        TestPerformance._cpu_dict = cpu_dict
        TestPerformance._mem_dict = mem_dict
Пример #53
0
    def method(self, x):
        pass


class OldStyleFoo:
    a = 10

    def __init__(self):
        self.b = 20

    def method(self, x):
        pass


skip_old_style = unittest.skipIf(py3,
                                 'In Python 3 there are no old style classes')


class TestAttrCompletion(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.com = autocomplete.AttrCompletion()

    def test_att_matches_found_on_instance(self):
        self.assertSetEqual(self.com.matches(2, 'a.', locals_={'a': Foo()}),
                            set(['a.method', 'a.a', 'a.b']))

    @skip_old_style
    def test_att_matches_found_on_old_style_instance(self):
        self.assertSetEqual(self.com.matches(2, 'a.',
                                             locals_={'a': OldStyleFoo()}),
Пример #54
0
def _get_bool_config_skip_if_decorator(key):
    have = _get_bool_config(key)
    return unittest2.skipIf(not have, "requires " + key)
Пример #55
0
greaterthanorequalcass3_10 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.10'), 'Cassandra version 3.10 or greater required')
greaterthanorequalcass3_11 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.11'), 'Cassandra version 3.11 or greater required')
greaterthanorequalcass40 = unittest.skipUnless(CASSANDRA_VERSION >= Version('4.0-a'), 'Cassandra version 4.0 or greater required')
lessthanorequalcass40 = unittest.skipUnless(CASSANDRA_VERSION <= Version('4.0-a'), 'Cassandra version less or equal to 4.0 required')
lessthancass40 = unittest.skipUnless(CASSANDRA_VERSION < Version('4.0-a'), 'Cassandra version less than 4.0 required')
lessthancass30 = unittest.skipUnless(CASSANDRA_VERSION < Version('3.0'), 'Cassandra version less then 3.0 required')
greaterthanorequaldse68 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('6.8'), "DSE 6.8 or greater required for this test")
greaterthanorequaldse67 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('6.7'), "DSE 6.7 or greater required for this test")
greaterthanorequaldse60 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('6.0'), "DSE 6.0 or greater required for this test")
greaterthanorequaldse51 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('5.1'), "DSE 5.1 or greater required for this test")
greaterthanorequaldse50 = unittest.skipUnless(DSE_VERSION and DSE_VERSION >= Version('5.0'), "DSE 5.0 or greater required for this test")
lessthandse51 = unittest.skipUnless(DSE_VERSION and DSE_VERSION < Version('5.1'), "DSE version less than 5.1 required")
lessthandse60 = unittest.skipUnless(DSE_VERSION and DSE_VERSION < Version('6.0'), "DSE version less than 6.0 required")

pypy = unittest.skipUnless(platform.python_implementation() == "PyPy", "Test is skipped unless it's on PyPy")
notpy3 = unittest.skipIf(sys.version_info >= (3, 0), "Test not applicable for Python 3.x runtime")
requiresmallclockgranularity = unittest.skipIf("Windows" in platform.system() or "asyncore" in EVENT_LOOP_MANAGER,
                                               "This test is not suitible for environments with large clock granularity")
requiressimulacron = unittest.skipIf(SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"), "Simulacron jar hasn't been specified or C* version is 2.0")
requirecassandra = unittest.skipIf(DSE_VERSION, "Cassandra required")
notdse = unittest.skipIf(DSE_VERSION, "DSE not supported")
requiredse = unittest.skipUnless(DSE_VERSION, "DSE required")
requirescloudproxy = unittest.skipIf(CLOUD_PROXY_PATH is None, "Cloud Proxy path hasn't been specified")

libevtest = unittest.skipUnless(EVENT_LOOP_MANAGER=="libev", "Test timing designed for libev loop")

def wait_for_node_socket(node, timeout):
    binary_itf = node.network_interfaces['binary']
    if not common.check_socket_listening(binary_itf, timeout=timeout):
        log.warning("Unable to connect to binary socket for node " + node.name)
    else:
Пример #56
0

class CssTidyTestCase(TestCase):
    def test_tidy(self):
        content = """
/* Some comment */
font,th,td,p{
color: black;
}
"""
        from compressor.filters.csstidy import CSSTidyFilter
        self.assertEqual(
            "font,th,td,p{color:#000;}", CSSTidyFilter(content).input())

CssTidyTestCase = skipIf(
    find_command(settings.COMPRESS_CSSTIDY_BINARY) is None,
    'CSStidy binary %r not found' % settings.COMPRESS_CSSTIDY_BINARY,
)(CssTidyTestCase)


class PrecompilerTestCase(TestCase):

    def setUp(self):
        self.filename = os.path.join(test_dir, 'media/css/one.css')
        with open(self.filename) as f:
            self.content = f.read()
        self.test_precompiler = os.path.join(test_dir, 'precompiler.py')

    def test_precompiler_infile_outfile(self):
        command = '%s %s -f {infile} -o {outfile}' % (sys.executable, self.test_precompiler)
        compiler = CompilerFilter(content=self.content, filename=self.filename, command=command)
        self.assertEqual(u"body { color:#990; }", compiler.input())
Пример #57
0
def SkipCheckUnknownFieldIfCppImplementation(func):
  return unittest.skipIf(
      api_implementation.Type() == 'cpp' and api_implementation.Version() == 2,
      'Addtional test for pure python involved protect members')(func)
Пример #58
0
def only_for_versions_lower(version):
    """Should be used as a decorator for a unittest.TestCase test method"""
    return unittest.skipIf(
        sys.version > version,
        'This test requires version of Python lower than {0}'.format(version))
Пример #59
0
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 "
    "if threads have been used")
class TestBreakDefaultIntHandler(TestBreak):
    int_handler = signal.default_int_handler

@unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill")
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 "
    "if threads have been used")
class TestBreakSignalIgnored(TestBreak):
    int_handler = signal.SIG_IGN

@unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill")
@unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows")
@unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 "
    "if threads have been used")
class TestBreakSignalDefault(TestBreak):
    int_handler = signal.SIG_DFL


# Should also skip some tests on Jython
skipper = unittest2.skipUnless(hasattr(os, 'kill') and signal is not None,
                               "test uses os.kill(...) and the signal module")
skipper2 = unittest2.skipIf(sys.platform == 'win32', "can't run on windows")

TestBreak = skipper(skipper2(TestBreak))

if __name__ == '__main__':
    unittest2.main()
Пример #60
0
    from tests.integration import VERIFY_CYTHON
except ImportError:
    VERIFY_CYTHON = False

try:
    import unittest2 as unittest
except ImportError:
    import unittest  # noqa


def cyimport(import_path):
    """
    Import a Cython module if available, otherwise return None
    (and skip any relevant tests).
    """
    if HAVE_CYTHON:
        import pyximport
        py_importer, pyx_importer = pyximport.install()
        mod = __import__(import_path, fromlist=[True])
        pyximport.uninstall(py_importer, pyx_importer)
        return mod


# @cythontest
# def test_something(self): ...
cythontest = unittest.skipUnless((HAVE_CYTHON or VERIFY_CYTHON)
                                 or VERIFY_CYTHON, 'Cython is not available')
notcython = unittest.skipIf(HAVE_CYTHON, 'Cython not supported')
numpytest = unittest.skipUnless((HAVE_CYTHON and HAVE_NUMPY) or VERIFY_CYTHON,
                                'NumPy is not available')