예제 #1
0
def only_run_with_partitioned_database(cls):
    """
    Only runs the test with the partitioned database settings.
    """
    skip_unless = skipUnless(settings.USE_PARTITIONED_DATABASE,
                             'Only applicable if sharding is setup')
    return skip_unless(partitioned(cls))
예제 #2
0
파일: utils.py 프로젝트: dimagi/commcare-hq
def only_run_with_partitioned_database(cls):
    """
    Only runs the test with the partitioned database settings.
    """
    skip_unless = skipUnless(
        settings.USE_PARTITIONED_DATABASE, 'Only applicable if sharding is setup'
    )
    return skip_unless(partitioned(cls))
예제 #3
0
def _importorskip(modname, minversion=None):
    try:
        mod = importlib.import_module(modname)
        has = True
        if minversion is not None:
            if LooseVersion(mod.__version__) < LooseVersion(minversion):
                raise ImportError('Minimum version not satisfied')
    except ImportError:
        has = False
    # TODO: use pytest.skipif instead of unittest.skipUnless
    # Using `unittest.skipUnless` is a temporary workaround for pytest#568,
    # wherein class decorators stain inherited classes.
    # xref: xarray#1531, implemented in xarray #1557.
    func = unittest.skipUnless(has, reason='requires {}'.format(modname))
    return has, func
예제 #4
0
파일: __init__.py 프로젝트: jcmgray/xarray
def _importorskip(modname, minversion=None):
    try:
        mod = importlib.import_module(modname)
        has = True
        if minversion is not None:
            if LooseVersion(mod.__version__) < LooseVersion(minversion):
                raise ImportError('Minimum version not satisfied')
    except ImportError:
        has = False
    # TODO: use pytest.skipif instead of unittest.skipUnless
    # Using `unittest.skipUnless` is a temporary workaround for pytest#568,
    # wherein class decorators stain inherited classes.
    # xref: xarray#1531, implemented in xarray #1557.
    func = unittest.skipUnless(has, reason='requires {}'.format(modname))
    return has, func
예제 #5
0
        pass
elif "asyncore" in EVENT_LOOP_MANAGER:
    from cassandra.io.asyncorereactor import AsyncoreConnection
    connection_class = AsyncoreConnection
elif "twisted" in EVENT_LOOP_MANAGER:
    from cassandra.io.twistedreactor import TwistedConnection
    connection_class = TwistedConnection
elif "asyncio" in EVENT_LOOP_MANAGER:
    from cassandra.io.asyncioreactor import AsyncioConnection
    connection_class = AsyncioConnection

else:
    try:
        from cassandra.io.libevreactor import LibevConnection
        connection_class = LibevConnection
    except ImportError as e:
        log.debug('Could not import LibevConnection, '
                  'using connection_class=None; '
                  'failed with error:\n {}'.format(
                      repr(e)
                  ))
        connection_class = None


def is_windows():
    return "Windows" in platform.system()


notwindows = unittest.skipUnless(not is_windows(), "This test is not adequate for windows")
notpypy = unittest.skipUnless(not platform.python_implementation() == 'PyPy', "This tests is not suitable for pypy")
예제 #6
0
if "gevent" in EVENT_LOOP_MANAGER:
    import gevent.monkey
    gevent.monkey.patch_all()
    from cassandra.io.geventreactor import GeventConnection
    connection_class = GeventConnection
elif "eventlet" in EVENT_LOOP_MANAGER:
    from eventlet import monkey_patch
    monkey_patch()

    from cassandra.io.eventletreactor import EventletConnection
    connection_class = EventletConnection
elif "async" in EVENT_LOOP_MANAGER:
    from cassandra.io.asyncorereactor import AsyncoreConnection
    connection_class = AsyncoreConnection
elif "twisted" in EVENT_LOOP_MANAGER:
    from cassandra.io.twistedreactor import TwistedConnection
    connection_class = TwistedConnection

else:
    try:
        from cassandra.io.libevreactor import LibevConnection
        connection_class = LibevConnection
    except ImportError:
        connection_class = None


MONKEY_PATCH_LOOP = bool(os.getenv('MONKEY_PATCH_LOOP', False))

notwindows = unittest.skipUnless(not "Windows" in platform.system(), "This test is not adequate for windows")
notpypy = unittest.skipUnless(not platform.python_implementation() == 'PyPy', "This tests is not suitable for pypy")
notmonkeypatch = unittest.skipUnless(MONKEY_PATCH_LOOP, "Skipping this test because monkey patching is required")
예제 #7
0
PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))


def local_decorator_creator():
    if not CASSANDRA_IP.startswith("127.0.0."):
        return unittest.skip('Tests only runs against local C*')

    def _id_and_mark(f):
        f.local = True

    return _id_and_mark


local = local_decorator_creator()
notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1,
                                    'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(
    PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(
    PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')
protocolv5 = unittest.skipUnless(
    5 in get_supported_protocol_versions(),
    'Protocol versions less than 5 are not supported')

greaterthancass20 = unittest.skipUnless(
    CASSANDRA_VERSION >= Version('2.1'),
    'Cassandra version 2.1 or greater required')
greaterthancass21 = unittest.skipUnless(
    CASSANDRA_VERSION >= Version('2.2'),
    'Cassandra version 2.2 or greater required')
greaterthanorequalcass30 = unittest.skipUnless(
예제 #8
0

has_matplotlib, requires_matplotlib = _importorskip('matplotlib')
has_scipy, requires_scipy = _importorskip('scipy')
has_pydap, requires_pydap = _importorskip('pydap.client')
has_netCDF4, requires_netCDF4 = _importorskip('netCDF4')
has_h5netcdf, requires_h5netcdf = _importorskip('h5netcdf')
has_pynio, requires_pynio = _importorskip('Nio')
has_dask, requires_dask = _importorskip('dask')
has_bottleneck, requires_bottleneck = _importorskip('bottleneck')
has_rasterio, requires_rasterio = _importorskip('rasterio')
has_pathlib, requires_pathlib = _importorskip('pathlib')

# some special cases
has_scipy_or_netCDF4 = has_scipy or has_netCDF4
requires_scipy_or_netCDF4 = unittest.skipUnless(
    has_scipy_or_netCDF4, reason='requires scipy or netCDF4')
if not has_pathlib:
    has_pathlib, requires_pathlib = _importorskip('pathlib2')

if has_dask:
    import dask
    dask.set_options(get=dask.get)

try:
    _SKIP_FLAKY = not pytest.config.getoption("--run-flaky")
    _SKIP_NETWORK_TESTS = not pytest.config.getoption("--run-network-tests")
except (ValueError, AttributeError):
    # Can't get config from pytest, e.g., because xarray is installed instead
    # of being run from a development version (and hence conftests.py is not
    # available). Don't run flaky tests.
    _SKIP_FLAKY = True
예제 #9
0
    if Version(CASSANDRA_VERSION) >= Version('2.2'):
        return None
    if Version(CASSANDRA_VERSION) >= Version('2.1'):
        return 4
    elif Version(CASSANDRA_VERSION) >= Version('2.0'):
        return 3
    else:
        return None


default_protocol_version = get_default_protocol()

PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

local = unittest.skipUnless(CASSANDRA_IP.startswith("127.0.0."),
                            'Tests only runs against local C*')
notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1,
                                    'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(
    PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(
    PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')
protocolv5 = unittest.skipUnless(
    5 in get_supported_protocol_versions(),
    'Protocol versions less than 5 are not supported')

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(
예제 #10
0
            log.info("Using DSE credentials file located at {0}".format(DSE_CRED))
            CCM_KWARGS['dse_credentials_file'] = DSE_CRED


if CASSANDRA_VERSION >= '2.2':
    default_protocol_version = 4
elif CASSANDRA_VERSION >= '2.1':
    default_protocol_version = 3
elif CASSANDRA_VERSION >= '2.0':
    default_protocol_version = 2
else:
    default_protocol_version = 1

PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')

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')
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")


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:
예제 #11
0
# 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.
"""Various utilities used in tests."""

import contextlib
import os
import tempfile
import shutil
import sys

import six
import unittest2

RunOnlyOnPython27 = unittest2.skipUnless(sys.version_info[:2] == (2, 7),
                                         'Only runs in Python 2.7')


@contextlib.contextmanager
def TempDir(change_to=False):
    if change_to:
        original_dir = os.getcwd()
    path = tempfile.mkdtemp()
    try:
        if change_to:
            os.chdir(path)
        yield path
    finally:
        if change_to:
            os.chdir(original_dir)
        shutil.rmtree(path)
예제 #12
0
import cassandra


_connections = {}

DEFAULT_KEYSPACE = 'cqlengine_test'
CQL_SKIP_EXECUTE = bool(os.getenv('CQL_SKIP_EXECUTE', False))
CASSANDRA_VERSION = "2.2.7"
PROTOCOL_VERSION = 4

cass_version = None
cql_version = None
log = logging.getLogger(__name__)

pypy = unittest.skipUnless(
    platform.python_implementation() == "PyPy",
    "Test is skipped unless it's on PyPy",
)


def get_server_versions():
    """
    Probe system.local table to determine Cassandra and CQL version.
    Returns a tuple of (cassandra_version, cql_version).
    """
    global cass_version, cql_version

    if cass_version is not None:
        return (cass_version, cql_version)

    c = Cluster()
    s = c.connect()
예제 #13
0
import os
import sys
try:
    import unittest2 as unittest
except ImportError:
    import unittest

from rpaths import unicode, Path, PosixPath, WindowsPath


windows_only = unittest.skipUnless(issubclass(Path, WindowsPath),
                                   "Only runs on Windows")
posix_only = unittest.skipUnless(issubclass(Path, PosixPath),
                                 "Only runs on POSIX")


class TestConcrete(unittest.TestCase):
    """Tests for Path.

    Because this tests the concrete Path, it needs to be run on both Windows
    and POSIX to ensure everything is correct.
    """
    def test_cwd(self):
        """Tests cwd, in_dir."""
        cwd = os.getcwd()

        if os.name == 'nt' and isinstance(cwd, bytes):
            cwd = cwd.decode('mbcs')
        elif os.name != 'nt' and isinstance(cwd, unicode):
            cwd = cwd.encode(sys.getfilesystemencoding())
        self.assertEqual(Path.cwd().path, cwd)
예제 #14
0
class TestGitWorkingCopy(unittest.TestCase, BaseTestWorkingCopy):
    
    def setUp(self):
        self.repository_path = os.path.abspath("../example_repositories/git")
        os.symlink("%s/git" % self.repository_path, "%s/.git" % self.repository_path)
        self.repos = GitRepository(self.repository_path)
        self.tmpdir = tempfile.mkdtemp()
        self.repos.checkout(self.tmpdir)
        self.wc = GitWorkingCopy(self.tmpdir)
        self.latest_version = "38598c93c7036a1c44bbb6075517243edfa88860"
        self.previous_version = "3491ce1d9a66abc9d49d5844ee05167c6a854ad9"
        
    def tearDown(self):
        os.unlink("%s/.git" % self.repository_path)
        shutil.rmtree(self.tmpdir)
TestGitWorkingCopy = unittest.skipUnless(have_git, "Could not import git")(TestGitWorkingCopy) # not using as class decorator for the sake of Python 2.5


#@unittest.skipUnless(have_pysvn, "Could not import pysvn")
class TestSubversionWorkingCopy(unittest.TestCase, BaseTestWorkingCopy):
    
    def setUp(self):
        self.repository_path = os.path.abspath("../example_repositories/subversion")
        self.repos = SubversionRepository("file://%s" % self.repository_path)
        self.tmpdir = tempfile.mkdtemp()
        self.repos.checkout(self.tmpdir)
        self.wc = SubversionWorkingCopy(self.tmpdir)
        self.latest_version = "3"
        self.previous_version = "1"
        
    def tearDown(self):
예제 #15
0
class TestGitWorkingCopy(unittest.TestCase, BaseTestWorkingCopy):

    def setUp(self):
        self.repository_path = os.path.abspath("../example_repositories/git")
        os.symlink("%s/git" % self.repository_path, "%s/.git" % self.repository_path)
        self.repos = GitRepository(self.repository_path)
        self.tmpdir = tempfile.mkdtemp()
        self.repos.checkout(self.tmpdir)
        self.wc = GitWorkingCopy(self.tmpdir)
        self.latest_version = "38598c93c7036a1c44bbb6075517243edfa88860"
        self.previous_version = "3491ce1d9a66abc9d49d5844ee05167c6a854ad9"

    def tearDown(self):
        os.unlink("%s/.git" % self.repository_path)
        shutil.rmtree(self.tmpdir)
TestGitWorkingCopy = unittest.skipUnless(have_git, "Could not import git")(TestGitWorkingCopy) # not using as class decorator for the sake of Python 2.5


#@unittest.skipUnless(have_pysvn, "Could not import pysvn")
class TestSubversionWorkingCopy(unittest.TestCase, BaseTestWorkingCopy):

    def setUp(self):
        self.repository_path = os.path.abspath("../example_repositories/subversion")
        self.repos = SubversionRepository("file://%s" % self.repository_path)
        self.tmpdir = tempfile.mkdtemp()
        self.repos.checkout(self.tmpdir)
        self.wc = SubversionWorkingCopy(self.tmpdir)
        self.latest_version = "3"
        self.previous_version = "1"

    def tearDown(self):
예제 #16
0
PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))


def local_decorator_creator():
    if not CASSANDRA_IP.startswith("127.0.0."):
        return unittest.skip('Tests only runs against local C*')

    def _id_and_mark(f):
        f.local = True
        return f

    return _id_and_mark

local = local_decorator_creator()
notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')
protocolv5 = unittest.skipUnless(5 in get_supported_protocol_versions(), 'Protocol versions less than 5 are not supported')

greaterthancass20 = unittest.skipUnless(CASSANDRA_VERSION >= Version('2.1'), 'Cassandra version 2.1 or greater required')
greaterthancass21 = unittest.skipUnless(CASSANDRA_VERSION >= Version('2.2'), 'Cassandra version 2.2 or greater required')
greaterthanorequalcass30 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.0'), 'Cassandra version 3.0 or greater required')
greaterthanorequalcass36 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.6'), 'Cassandra version 3.6 or greater required')
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.10 or greater required')
greaterthanorequalcass40 = unittest.skipUnless(CASSANDRA_VERSION >= Version('4.0'), 'Cassandra version 4.0 or greater required')
lessthanorequalcass40 = unittest.skipIf(CASSANDRA_VERSION >= Version('4.0'), 'Cassandra version 4.0 or greater required')
lessthancass30 = unittest.skipUnless(CASSANDRA_VERSION < Version('3.0'), 'Cassandra version less then 3.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")
예제 #17
0
            self._load_product_from_data(self.global_env, self.default_product)
            self._env = env = ProductEnvironment(
                    self.global_env, self.default_product)
        return env

    @env.setter
    def env(self, value):
        pass

    def setUp(self):
        test_pygments.PygmentsRendererTestCase.setUp(self)
        self.pygments = Mimeview(self.env).renderers[0]

    def tearDown(self):
        self.global_env.reset_db()
        self.global_env = self._env = None

ProductPygmentsRendererTestCase = unittest.skipUnless(
        test_pygments.have_pygments, 
        'mimeview/tests/pygments (no pygments installed)'
    )(ProductPygmentsRendererTestCase)

def test_suite():
    return unittest.TestSuite([
            unittest.makeSuite(ProductPygmentsRendererTestCase,'test'),
        ])

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

예제 #18
0
has_scipy, requires_scipy = _importorskip('scipy')
has_pydap, requires_pydap = _importorskip('pydap.client')
has_netCDF4, requires_netCDF4 = _importorskip('netCDF4')
has_h5netcdf, requires_h5netcdf = _importorskip('h5netcdf')
has_pynio, requires_pynio = _importorskip('Nio')
has_cftime, requires_cftime = _importorskip('cftime')
has_dask, requires_dask = _importorskip('dask')
has_bottleneck, requires_bottleneck = _importorskip('bottleneck')
has_rasterio, requires_rasterio = _importorskip('rasterio')
has_pathlib, requires_pathlib = _importorskip('pathlib')
has_zarr, requires_zarr = _importorskip('zarr', minversion='2.2')
has_np112, requires_np112 = _importorskip('numpy', minversion='1.12.0')

# some special cases
has_scipy_or_netCDF4 = has_scipy or has_netCDF4
requires_scipy_or_netCDF4 = unittest.skipUnless(
    has_scipy_or_netCDF4, reason='requires scipy or netCDF4')
has_cftime_or_netCDF4 = has_cftime or has_netCDF4
requires_cftime_or_netCDF4 = unittest.skipUnless(
    has_cftime_or_netCDF4, reason='requires cftime or netCDF4')
if not has_pathlib:
    has_pathlib, requires_pathlib = _importorskip('pathlib2')
if has_dask:
    import dask
    if LooseVersion(dask.__version__) < '0.18':
        dask.set_options(get=dask.get)
    else:
        dask.config.set(scheduler='sync')
try:
    import_seaborn()
    has_seaborn = True
except ImportError:
예제 #19
0
        errors = data['validation_errors']
        self.assertIn('email', errors)
        self.assertIn('enter a value', errors['email'].lower())

        # everything required is now provided
        person = dict(name='Jeffrey', email='*****@*****.**', age=24)
        response = self.app.post('/api/test', data=dumps(person))
        self.assertEqual(response.status_code, 201)
        personid = loads(response.data)['id']

        # check that the provided field values are in there
        response = self.app.get('/api/test/' + str(personid))
        self.assertEqual(response.status_code, 200)
        data = loads(response.data)
        self.assertEqual(data['name'], 'Jeffrey')
        self.assertEqual(data['email'], '*****@*****.**')


# skipUnless should be used as a decorator, but Python 2.5 doesn't have
# decorators.
SAVTest = skipUnless(has_savalidation and sav_version >= (0, 2),
                     'savalidation not found.')(SAVTest)


def load_tests(loader, standard_tests, pattern):
    """Returns the test suite for this module."""
    suite = TestSuite()
    suite.addTest(loader.loadTestsFromTestCase(SimpleValidationTest))
    suite.addTest(loader.loadTestsFromTestCase(SAVTest))
    return suite
예제 #20
0
파일: utils.py 프로젝트: dzderic/logbook
else:
    import unittest
import logbook
import six

_missing = object()


def get_total_delta_seconds(delta):
    """
    Replacement for datetime.timedelta.total_seconds() for Python 2.5, 2.6 and 3.1
    """
    return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6


require_py3 = unittest.skipUnless(six.PY3, "Requires Python 3")
def require_module(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return unittest.skip("Requires the %r module" % (module_name,))
    return lambda func: func

class LogbookTestSuite(unittest.TestSuite):
    pass

class LogbookTestCase(unittest.TestCase):
    def setUp(self):
        self.log = logbook.Logger('testlogger')

# silence deprecation warning displayed on Py 3.2
예제 #21
0
else:
    log.info("Using Cassandra version: %s", CASSANDRA_VERSION)
    CCM_KWARGS["version"] = CASSANDRA_VERSION

if CASSANDRA_VERSION >= "2.2":
    default_protocol_version = 4
elif CASSANDRA_VERSION >= "2.1":
    default_protocol_version = 3
elif CASSANDRA_VERSION >= "2.0":
    default_protocol_version = 2
else:
    default_protocol_version = 1

PROTOCOL_VERSION = int(os.getenv("PROTOCOL_VERSION", default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, "Protocol v1 not supported")
lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, "Protocol versions 4 or greater not supported")
greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, "Protocol versions less than 4 are not supported")

greaterthancass20 = unittest.skipUnless(CASSANDRA_VERSION >= "2.1", "Cassandra version 2.1 or greater required")
greaterthanorequalcass30 = unittest.skipUnless(CASSANDRA_VERSION >= "3.0", "Cassandra version 3.0 or greater required")
lessthancass30 = unittest.skipUnless(CASSANDRA_VERSION < "3.0", "Cassandra version less then 3.0 required")


def get_cluster():
    return CCM_CLUSTER


def get_node(node_id):
    return CCM_CLUSTER.nodes["node%s" % node_id]
예제 #22
0
def skipSlowTest():
    return skipUnless(os.environ.get('PYCHEF_SLOW_TESTS'), 'slow tests skipped, set $PYCHEF_SLOW_TESTS=1 to enable')
예제 #23
0
        default_handler = signal.getsignal(signal.SIGINT)
        unittest2.installHandler()
        unittest2.removeHandler()
        self.assertEqual(signal.getsignal(signal.SIGINT), default_handler)

        # check that calling removeHandler multiple times has no ill-effect
        unittest2.removeHandler()
        self.assertEqual(signal.getsignal(signal.SIGINT), default_handler)

    def testRemoveHandlerAsDecorator(self):
        default_handler = signal.getsignal(signal.SIGINT)
        unittest2.installHandler()

        def test():
            self.assertEqual(signal.getsignal(signal.SIGINT), default_handler)

        test = unittest2.removeHandler(test)

        test()
        self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)


# 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")
TestBreak = skipper(TestBreak)

if __name__ == '__main__':
    unittest2.main()
예제 #24
0
def skipSlowTest():
    return skipUnless(
        os.environ.get('PYCHEF_SLOW_TESTS'),
        'slow tests skipped, set $PYCHEF_SLOW_TESTS=1 to enable')
예제 #25
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()
예제 #26
0
파일: __init__.py 프로젝트: jcmgray/xarray
has_scipy, requires_scipy = _importorskip('scipy')
has_pydap, requires_pydap = _importorskip('pydap.client')
has_netCDF4, requires_netCDF4 = _importorskip('netCDF4')
has_h5netcdf, requires_h5netcdf = _importorskip('h5netcdf')
has_pynio, requires_pynio = _importorskip('Nio')
has_cftime, requires_cftime = _importorskip('cftime')
has_dask, requires_dask = _importorskip('dask')
has_bottleneck, requires_bottleneck = _importorskip('bottleneck')
has_rasterio, requires_rasterio = _importorskip('rasterio')
has_pathlib, requires_pathlib = _importorskip('pathlib')
has_zarr, requires_zarr = _importorskip('zarr', minversion='2.2')
has_np112, requires_np112 = _importorskip('numpy', minversion='1.12.0')

# some special cases
has_scipy_or_netCDF4 = has_scipy or has_netCDF4
requires_scipy_or_netCDF4 = unittest.skipUnless(
    has_scipy_or_netCDF4, reason='requires scipy or netCDF4')
has_cftime_or_netCDF4 = has_cftime or has_netCDF4
requires_cftime_or_netCDF4 = unittest.skipUnless(
    has_cftime_or_netCDF4, reason='requires cftime or netCDF4')
if not has_pathlib:
    has_pathlib, requires_pathlib = _importorskip('pathlib2')
if has_dask:
    import dask
    dask.set_options(get=dask.get)
try:
    import_seaborn()
    has_seaborn = True
except ImportError:
    has_seaborn = False
requires_seaborn = unittest.skipUnless(has_seaborn, reason='requires seaborn')
예제 #27
0
파일: test.py 프로젝트: alex2/vorlauf
def skip_unless_words(func):
    return unittest2.skipUnless(
        os.path.isfile(words_file),
        'Cannot find system words file {}'.format(words_file)
    )(func)
예제 #28
0
                           PUBCHEM_SDF,
                           errors="this-is-not.a.valid! setting")


# Test classes for the different toolkits


class TestOpenBabelReadStructureFingerprints(unittest2.TestCase,
                                             ReadStructureFingerprints):
    type = "OpenBabel-FP2/1"
    num_bits = 1021
    fp_size = 128


TestOpenBabelReadStructureFingerprints = (unittest2.skipUnless(
    has_openbabel,
    "Open Babel not available")(TestOpenBabelReadStructureFingerprints))


class TestOpenEyeReadStructureFingerprints(unittest2.TestCase,
                                           ReadStructureFingerprints):
    type = "OpenEye-Path/1"
    num_bits = 1024
    fp_size = 128


TestOpenEyeReadStructureFingerprints = (unittest2.skipUnless(
    has_openeye,
    "OpenEye not available")(TestOpenEyeReadStructureFingerprints))

예제 #29
0
            log.info("Using DSE credentials file located at {0}".format(DSE_CRED))
            CCM_KWARGS['dse_credentials_file'] = DSE_CRED


if CASSANDRA_VERSION >= '2.2':
    default_protocol_version = 4
elif CASSANDRA_VERSION >= '2.1':
    default_protocol_version = 3
elif CASSANDRA_VERSION >= '2.0':
    default_protocol_version = 2
else:
    default_protocol_version = 1

PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')

greaterthancass20 = unittest.skipUnless(CASSANDRA_VERSION >= '2.1', 'Cassandra version 2.1 or greater required')
greaterthanorequalcass30 = unittest.skipUnless(CASSANDRA_VERSION >= '3.0', 'Cassandra version 3.0 or greater required')
lessthancass30 = unittest.skipUnless(CASSANDRA_VERSION < '3.0', 'Cassandra version less then 3.0 required')


def get_cluster():
    return CCM_CLUSTER


def get_node(node_id):
    return CCM_CLUSTER.nodes['node%s' % node_id]
예제 #30
0
else:
    log.info('Using Cassandra version: %s', CASSANDRA_VERSION)
    CCM_KWARGS['version'] = CASSANDRA_VERSION

if CASSANDRA_VERSION >= '2.2':
    default_protocol_version = 4
elif CASSANDRA_VERSION >= '2.1':
    default_protocol_version = 3
elif CASSANDRA_VERSION >= '2.0':
    default_protocol_version = 2
else:
    default_protocol_version = 1

PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported')


def get_cluster():
    return CCM_CLUSTER


def get_node(node_id):
    return CCM_CLUSTER.nodes['node%s' % node_id]


def use_multidc(dc_list):
    use_cluster(MULTIDC_CLUSTER_NAME, dc_list, start=True)


def use_singledc(start=True):
예제 #31
0
파일: utils.py 프로젝트: yinlinz/logbook
    import unittest
import logbook
from logbook.helpers import StringIO

_missing = object()


def get_total_delta_seconds(delta):
    """
    Replacement for datetime.timedelta.total_seconds() for Python 2.5, 2.6 and 3.1
    """
    return (delta.microseconds +
            (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6


require_py3 = unittest.skipUnless(sys.version_info[0] == 3,
                                  "Requires Python 3")


def require_module(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return unittest.skip("Requires the %r module" % (module_name, ))
    return lambda func: func


class LogbookTestSuite(unittest.TestSuite):
    pass


class LogbookTestCase(unittest.TestCase):
예제 #32
0
def check_rd201012():
    import rdkit.rdBase
    from rdkit.rdBase import rdkitVersion
    assert rdkitVersion[:7] == "2010.12", rdkitVersion

def check_rd201112_svn():
    import rdkit.rdBase
    from rdkit.rdBase import rdkitVersion
    assert rdkitVersion[:7] == "2011.12", rdkitVersion

def _check(required):
    req = required.split()
    for name in versions:
        if name in req:
            return
    raise AssertionError("Missing one of %r: %r" % (required, versions))

class TestToxVersion(unittest2.TestCase):
    def test_enough_specifications(self):
        _check("x32 x64")
        _check("py25 py26 py27 py32")
        _check("oe174 oe2011Oct ob223 ob230 ob23svn1 rd201106 rd201103 rd201012 rd201112_svn")
        
    def test_version(self):
        for name in versions:
            func = globals()["check_" + name]
            func()

TestToxVersion = unittest2.skipUnless(envstr, "Not building under the tox environment")(
    TestToxVersion)
예제 #33
0
# See the License for the specific language governing permissions and
# limitations under the License.

"""Various utilities used in tests."""

import contextlib
import os
import tempfile
import shutil
import sys

import six
import unittest2


RunOnlyOnPython27 = unittest2.skipUnless(sys.version_info[:2] == (2, 7), "Only runs in Python 2.7")


@contextlib.contextmanager
def TempDir(change_to=False):
    if change_to:
        original_dir = os.getcwd()
    path = tempfile.mkdtemp()
    try:
        if change_to:
            os.chdir(path)
        yield path
    finally:
        if change_to:
            os.chdir(original_dir)
        shutil.rmtree(path)
예제 #34
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')
예제 #35
0
    if Version(CASSANDRA_VERSION) >= Version('2.2'):
        return None
    if Version(CASSANDRA_VERSION) >= Version('2.1'):
        return 4
    elif Version(CASSANDRA_VERSION) >= Version('2.0'):
        return 3
    else:
        return None

default_protocol_version = get_default_protocol()


PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')
protocolv5 = unittest.skipUnless(5 in get_supported_protocol_versions(), 'Protocol versions less than 5 are not supported')

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")


def wait_for_node_socket(node, timeout):
    binary_itf = node.network_interfaces['binary']
예제 #36
0
import os
from functools import partial

try:
    import unittest2 as unittest
except ImportError:
    import unittest

if not hasattr(unittest, "skipUnless"):
    raise Exception("Please install unittest2 package (unittest.skipUnless attribute is missing)")

SKLIK_LOGIN = os.environ.get("SKLIK_LOGIN")
SKLIK_PASSWORD = os.environ.get("SKLIK_PASSWORD")

SKLIK_BAJAJA_URL = "https://api.sklik.cz/sandbox/bajaja/RPC2"
SKLIK_CIPISEK_URL = "https://api.sklik.cz/sandbox/cipisek/RPC2"


only_with_login = partial(
    unittest.skipUnless(SKLIK_LOGIN and SKLIK_PASSWORD, "SKLIK_LOGIN or SKLIK_PASSWORD environment var not set")
)


def get_client(cls, url=SKLIK_CIPISEK_URL):
    return cls(url, SKLIK_LOGIN, SKLIK_PASSWORD, debug=False)
예제 #37
0
파일: decorators.py 프로젝트: Aj0Ay/lldb
def skipUnlessPlatform(oslist):
    """Decorate the item to skip tests unless 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.skipUnless(lldbplatformutil.getPlatform() in oslist,
                                "requires one of %s" % (", ".join(oslist)))
예제 #38
0
from __future__ import unicode_literals

import os
import sys
try:
    import unittest2 as unittest
except ImportError:
    import unittest

from rpaths import unicode, dict_union, Path, PosixPath, WindowsPath, \
    Pattern, pattern2re

windows_only = unittest.skipUnless(issubclass(Path, WindowsPath),
                                   "Only runs on Windows")
posix_only = unittest.skipUnless(issubclass(Path, PosixPath),
                                 "Only runs on POSIX")


class TestConcrete(unittest.TestCase):
    """Tests for Path.

    Because this tests the concrete Path, it needs to be run on both Windows
    and POSIX to ensure everything is correct.
    """
    def test_cwd(self):
        """Tests cwd, in_dir."""
        cwd = os.getcwd()

        if os.name == 'nt' and isinstance(cwd, bytes):
            cwd = cwd.decode('mbcs')
        elif os.name != 'nt' and isinstance(cwd, unicode):
예제 #39
0

def is_gevent_monkey_patched():
    if 'gevent.monkey' not in sys.modules:
        return False
    import gevent.socket
    return socket.socket is gevent.socket.socket


def is_gevent_time_monkey_patched():
    import gevent.monkey
    return "time" in gevent.monkey.saved


def is_eventlet_time_monkey_patched():
    import eventlet
    return eventlet.patcher.is_monkey_patched('time')


def is_monkey_patched():
    return is_gevent_monkey_patched() or is_eventlet_monkey_patched()


MONKEY_PATCH_LOOP = bool(os.getenv('MONKEY_PATCH_LOOP', False))

notwindows = unittest.skipUnless(not "Windows" in platform.system(),
                                 "This test is not adequate for windows")
notpypy = unittest.skipUnless(not platform.python_implementation() == 'PyPy',
                              "This tests is not suitable for pypy")
notmonkeypatch = unittest.skipUnless(
    MONKEY_PATCH_LOOP, "Skpping this test because monkey patching is required")
예제 #40
0
log.setLevel('DEBUG')
# if nose didn't already attach a log handler, add one here
if not log.handlers:
    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter(
            '%(asctime)s %(levelname)s [%(module)s:%(lineno)s]: %(message)s'))
    log.addHandler(handler)


def is_eventlet_monkey_patched():
    if 'eventlet.patcher' not in sys.modules:
        return False
    import eventlet.patcher
    return eventlet.patcher.is_monkey_patched('socket')


def is_gevent_monkey_patched():
    if 'gevent.monkey' not in sys.modules:
        return False
    import gevent.socket
    return socket.socket is gevent.socket.socket


def is_monkey_patched():
    return is_gevent_monkey_patched() or is_eventlet_monkey_patched()


notwindows = unittest.skipUnless(not "Windows" in platform.system(),
                                 "This test is not adequate for windows")
예제 #41
0
            log.info(
                "Using DSE credentials file located at {0}".format(DSE_CRED))
            CCM_KWARGS['dse_credentials_file'] = DSE_CRED

if CASSANDRA_VERSION >= '2.2':
    default_protocol_version = 4
elif CASSANDRA_VERSION >= '2.1':
    default_protocol_version = 3
elif CASSANDRA_VERSION >= '2.0':
    default_protocol_version = 2
else:
    default_protocol_version = 1

PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1,
                                    'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(
    PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(
    PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')

greaterthancass20 = unittest.skipUnless(
    CASSANDRA_VERSION >= '2.1', 'Cassandra version 2.1 or greater required')
greaterthanorequalcass30 = unittest.skipUnless(
    CASSANDRA_VERSION >= '3.0', 'Cassandra version 3.0 or greater required')
lessthancass30 = unittest.skipUnless(
    CASSANDRA_VERSION < '3.0', 'Cassandra version less then 3.0 required')


def wait_for_node_socket(node, timeout):
    binary_itf = node.network_interfaces['binary']
예제 #42
0
import os
from functools import partial

try:
    import unittest2 as unittest
except ImportError:
    import unittest

if not hasattr(unittest, 'skipUnless'):
    raise Exception(
        'Please install unittest2 package (unittest.skipUnless attribute is missing)'
    )

SKLIK_LOGIN = os.environ.get('SKLIK_LOGIN')
SKLIK_PASSWORD = os.environ.get('SKLIK_PASSWORD')

SKLIK_BAJAJA_URL = 'https://api.sklik.cz/sandbox/bajaja/RPC2'
SKLIK_CIPISEK_URL = 'https://api.sklik.cz/sandbox/cipisek/RPC2'

only_with_login = partial(
    unittest.skipUnless(
        SKLIK_LOGIN and SKLIK_PASSWORD,
        "SKLIK_LOGIN or SKLIK_PASSWORD environment var not set"))


def get_client(cls, url=SKLIK_CIPISEK_URL):
    return cls(url, SKLIK_LOGIN, SKLIK_PASSWORD, debug=False)
예제 #43
0
# limitations under the License.

from cassandra.cython_deps import HAVE_CYTHON, HAVE_NUMPY

if HAVE_CYTHON:
    import pyximport
    pyximport.install()

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).
    """
    try:
        return __import__(import_path, fromlist=[True])
    except ImportError:
        if HAVE_CYTHON:
            raise
        return None


# @cythontest
# def test_something(self): ...
cythontest = unittest.skipUnless(HAVE_CYTHON, 'Cython is not available')
numpytest  = unittest.skipUnless(HAVE_CYTHON and HAVE_NUMPY, 'NumPy is not available')
예제 #44
0
    from cassandra.io.twistedreactor import TwistedConnection
    connection_class = TwistedConnection
elif "asyncio" in EVENT_LOOP_MANAGER:
    from cassandra.io.asyncioreactor import AsyncioConnection
    connection_class = AsyncioConnection

else:
    try:
        from cassandra.io.libevreactor import LibevConnection
        connection_class = LibevConnection
    except ImportError:
        connection_class = None


# If set to to true this will force the Cython tests to run regardless of whether they are installed
cython_env = os.getenv('VERIFY_CYTHON', "False")


VERIFY_CYTHON = False

if(cython_env == 'True'):
    VERIFY_CYTHON = True


def is_windows():
    return "Windows" in platform.system()


notwindows = unittest.skipUnless(not is_windows(), "This test is not adequate for windows")
notpypy = unittest.skipUnless(not platform.python_implementation() == 'PyPy', "This tests is not suitable for pypy")
예제 #45
0
def skipUnlessTargetAndroid(func):
    return unittest2.skipUnless(lldbplatformutil.target_is_android(),
                                "requires target to be Android")(func)
예제 #46
0
        self.assertEqual(200, response.status_code)
        data = loads(response.data)
        self.assertEqual(2, len(data["pets"]))
        for pet in data["pets"]:
            self.assertEqual(owner.id, pet["ownerid"])

        response = self.app.get("/api/lazy_pet/1")
        self.assertEqual(200, response.status_code)
        data = loads(response.data)
        self.assertFalse(isinstance(data["owner"], list))
        self.assertEqual(owner.id, data["ownerid"])


# skipUnless should be used as a decorator, but Python 2.5 doesn't have
# decorators.
FSATest = skipUnless(has_flask_sqlalchemy, "Flask-SQLAlchemy not found.")(FSAModelTest)


class ModelTestCase(TestSupport):
    """Provides tests for helper functions which operate on pure SQLAlchemy
    models.

    """

    def test_get_columns(self):
        """Test for getting the names of columns as strings."""
        columns = _get_columns(self.Person)
        self.assertEqual(sorted(columns.keys()), sorted(["age", "birth_date", "computers", "id", "name", "other"]))

    def test_get_relations(self):
        """Tests getting the names of the relations of a model as strings."""
예제 #47
0
def skipUnlessPlatform(oslist):
    """Decorate the item to skip tests unless 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.skipUnless(lldbplatformutil.getPlatform() in oslist,
                                "requires one of %s" % (", ".join(oslist)))
예제 #48
0
        errors = data['validation_errors']
        assert 'email' in errors
        assert 'enter a value' in errors['email'].lower()

        # everything required is now provided
        person = dict(name='Jeffrey', email='*****@*****.**', age=24)
        response = self.app.post('/api/test', data=dumps(person))
        assert response.status_code == 201
        personid = loads(response.data)['id']

        # check that the provided field values are in there
        response = self.app.get('/api/test/' + str(personid))
        assert response.status_code == 200
        data = loads(response.data)
        assert data['name'] == 'Jeffrey'
        assert data['email'] == '*****@*****.**'


# skipUnless should be used as a decorator, but Python 2.5 doesn't have
# decorators.
SAVTest = skipUnless(has_savalidation and sav_version >= (0, 2),
                     'savalidation not found.')(SAVTest)


def load_tests(loader, standard_tests, pattern):
    """Returns the test suite for this module."""
    suite = TestSuite()
    suite.addTest(loader.loadTestsFromTestCase(SimpleValidationTest))
    suite.addTest(loader.loadTestsFromTestCase(SAVTest))
    return suite
예제 #49
0
PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))


def local_decorator_creator():
    if USE_CASS_EXTERNAL or not CASSANDRA_IP.startswith("127.0.0."):
        return unittest.skip('Tests only runs against local C*')

    def _id_and_mark(f):
        f.local = True
        return f

    return _id_and_mark

local = local_decorator_creator()
notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1, 'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')
protocolv5 = unittest.skipUnless(5 in get_supported_protocol_versions(), 'Protocol versions less than 5 are not supported')
greaterthancass20 = unittest.skipUnless(CASSANDRA_VERSION >= Version('2.1'), 'Cassandra version 2.1 or greater required')
greaterthancass21 = unittest.skipUnless(CASSANDRA_VERSION >= Version('2.2'), 'Cassandra version 2.2 or greater required')
greaterthanorequalcass30 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.0'), 'Cassandra version 3.0 or greater required')
greaterthanorequalcass31 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.1'), 'Cassandra version 3.1 or greater required')
greaterthanorequalcass36 = unittest.skipUnless(CASSANDRA_VERSION >= Version('3.6'), 'Cassandra version 3.6 or greater required')
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")
예제 #50
0
            log.info(
                "Using DSE credentials file located at {0}".format(DSE_CRED))
            CCM_KWARGS['dse_credentials_file'] = DSE_CRED

if CASSANDRA_VERSION >= '2.2':
    default_protocol_version = 4
elif CASSANDRA_VERSION >= '2.1':
    default_protocol_version = 3
elif CASSANDRA_VERSION >= '2.0':
    default_protocol_version = 2
else:
    default_protocol_version = 1

PROTOCOL_VERSION = int(os.getenv('PROTOCOL_VERSION', default_protocol_version))

notprotocolv1 = unittest.skipUnless(PROTOCOL_VERSION > 1,
                                    'Protocol v1 not supported')
lessthenprotocolv4 = unittest.skipUnless(
    PROTOCOL_VERSION < 4, 'Protocol versions 4 or greater not supported')
greaterthanprotocolv3 = unittest.skipUnless(
    PROTOCOL_VERSION >= 4, 'Protocol versions less than 4 are not supported')

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')
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")
예제 #51
0
        response = self.app.get('/api/person')
        assert response.status_code == 200
        assert len(loads(response.data)['objects']) == 1
        assert loads(response.data)['objects'][0]['id'] == 1
        response = self.app.patch('/api2/person/1',
                                  data=dumps(dict(name='bar')))
        assert response.status_code == 200
        assert loads(response.data)['id'] == 1
        assert loads(response.data)['name'] == 'bar'

        # test that the model is the same as before
        response = self.app.get('/readonly/person')
        assert response.status_code == 200
        assert len(loads(response.data)['objects']) == 1
        assert loads(response.data)['objects'][0]['id'] == 1
        assert loads(response.data)['objects'][0]['name'] == 'bar'


# skipUnless should be used as a decorator, but Python 2.5 doesn't have
# decorators.
FSATest = skipUnless(has_flask_sqlalchemy,
                     'Flask-SQLAlchemy not found.')(FSATest)


def load_tests(loader, standard_tests, pattern):
    """Returns the test suite for this module."""
    suite = TestSuite()
    suite.addTest(loader.loadTestsFromTestCase(APIManagerTest))
    suite.addTest(loader.loadTestsFromTestCase(FSATest))
    return suite
예제 #52
0
else:
    import unittest
import logbook
from logbook.helpers import StringIO

_missing = object()


def get_total_delta_seconds(delta):
    """
    Replacement for datetime.timedelta.total_seconds() for Python 2.5, 2.6 and 3.1
    """
    return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6) / 10**6


require_py3 = unittest.skipUnless(sys.version_info[0] == 3, "Requires Python 3")
def require_module(module_name):
    try:
        __import__(module_name)
    except ImportError:
        return unittest.skip("Requires the %r module" % (module_name,))
    return lambda func: func

class LogbookTestSuite(unittest.TestSuite):
    pass

class LogbookTestCase(unittest.TestCase):
    def setUp(self):
        self.log = logbook.Logger('testlogger')

# silence deprecation warning displayed on Py 3.2