Пример #1
0
def set_up_hypothesis() -> None:
    default_settings = settings(
        # Turn off the health checks because setUp/tearDown are too slow
        suppress_health_check=[HealthCheck.too_slow],
        # Turn off the example database; we don't have a way to persist this
        # or share this across runs, so we don't derive any benefit from it at
        # this time.
        database=None,
    )

    # Configure Hypothesis to run faster when iterating locally
    settings.register_profile(
        "dev", settings(default_settings, max_examples=5, timeout=0)
    )
    # ... and use the defaults (which have more combinations) when running
    # on CI, which we want to be more deterministic.
    settings.register_profile(
        "ci", settings(default_settings, derandomize=True, timeout=120)
    )

    # Use the dev profile by default, but use the ci profile on sandcastle.
    settings.load_profile(
        "ci" if is_sandcastle() else os.getenv("HYPOTHESIS_PROFILE", "dev")
    )

    # We need to set a global (but non-conflicting) path to store some state
    # during hypothesis example runs.  We want to avoid putting this state in
    # the repo.
    set_hypothesis_home_dir(tempfile.mkdtemp(prefix="eden_hypothesis."))
    atexit.register(cleanup_tmp_dir, pathlib.Path(hypothesis_home_dir()))
Пример #2
0
def run():
    filterwarnings('error')
    filterwarnings('ignore', category=ImportWarning)
    filterwarnings('ignore', category=FutureWarning, module='pandas._version')

    # Fixed in recent versions but allowed by pytest=3.0.0; see #1630
    filterwarnings('ignore', category=DeprecationWarning, module='pluggy')

    # See https://github.com/numpy/numpy/pull/432
    filterwarnings('ignore', message='numpy.dtype size changed')
    filterwarnings('ignore', message='numpy.ufunc size changed')

    # Imported by Pandas in version 1.9, but fixed in later versions.
    filterwarnings(
        'ignore',
        message='Importing from numpy.testing.decorators is deprecated'
    )
    filterwarnings(
        'ignore',
        message='Importing from numpy.testing.nosetester is deprecated'
    )

    new_home = mkdtemp()
    set_hypothesis_home_dir(new_home)
    assert settings.default.database.path.startswith(new_home)

    charmap()
    assert os.path.exists(charmap_file()), charmap_file()
    assert isinstance(settings, type)

    # We do a smoke test here before we mess around with settings.
    x = settings()

    import hypothesis._settings as settings_module

    for s in settings_module.all_settings.values():
        v = getattr(x, s.name)
        # Check if it has a dynamically defined default and if so skip
        # comparison.
        if getattr(settings, s.name).show_default:
            assert v == s.default, '%r == x.%s != s.%s == %r' % (
                v, s.name, s.name, s.default,
            )

    settings.register_profile('default', settings(
        max_examples=10 if IN_COVERAGE_TESTS else not_set,
        timeout=unlimited,
    ))

    settings.register_profile(
        'speedy', settings(
            max_examples=5,
        ))

    settings.register_profile('debug', settings(verbosity=Verbosity.debug))

    settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'default'))
Пример #3
0
def pytest_configure(config):
    core.running_under_pytest = True
    profile = config.getoption(LOAD_PROFILE_OPTION)
    if profile:
        settings.load_profile(profile)
    seed = config.getoption(SEED_OPTION)
    if seed is not None:
        try:
            seed = int(seed)
        except ValueError:
            pass
        core.global_force_seed = seed
    config.addinivalue_line(
        'markers',
        'hypothesis: Tests which use hypothesis.')
Пример #4
0
def run():
    warnings.filterwarnings(u'error', category=UnicodeWarning)

    set_hypothesis_home_dir(mkdtemp())

    charmap()
    assert os.path.exists(charmap_file())
    assert isinstance(settings, type)

    settings.register_profile(
        'default', settings(timeout=-1, strict=True)
    )

    settings.register_profile(
        'speedy', settings(
            timeout=1, max_examples=5,
        ))

    settings.register_profile(
        'nonstrict', settings(strict=False)
    )

    settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'default'))
Пример #5
0
def run():
    warnings.filterwarnings('error', category=UnicodeWarning)
    warnings.filterwarnings('error', category=HypothesisDeprecationWarning)

    set_hypothesis_home_dir(mkdtemp())

    charmap()
    assert os.path.exists(charmap_file()), charmap_file()
    assert isinstance(settings, type)

    # We do a smoke test here before we mess around with settings.
    x = settings()

    import hypothesis._settings as settings_module

    for s in settings_module.all_settings.values():
        v = getattr(x, s.name)
        # Check if it has a dynamically defined default and if so skip
        # comparison.
        if getattr(settings, s.name).show_default:
            assert v == s.default, '%r == x.%s != s.%s == %r' % (
                v, s.name, s.name, s.default,
            )

    settings.register_profile('default', settings(
        timeout=unlimited, use_coverage=not (IN_COVERAGE_TESTS or PYPY)))

    settings.register_profile('with_coverage', settings(
        timeout=unlimited, use_coverage=True,
    ))

    settings.register_profile(
        'speedy', settings(
            max_examples=5,
        ))

    settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'default'))
def pytest_configure(config):
    core.running_under_pytest = True
    profile = config.getoption(LOAD_PROFILE_OPTION)
    if profile:
        settings.load_profile(profile)
    verbosity_name = config.getoption(VERBOSITY_OPTION)
    if verbosity_name:
        verbosity_value = Verbosity[verbosity_name]
        profile_name = "%s-with-%s-verbosity" % (
            settings._current_profile,
            verbosity_name,
        )
        # register_profile creates a new profile, exactly like the current one,
        # with the extra values given (in this case 'verbosity')
        settings.register_profile(profile_name, verbosity=verbosity_value)
        settings.load_profile(profile_name)
    seed = config.getoption(SEED_OPTION)
    if seed is not None:
        try:
            seed = int(seed)
        except ValueError:
            pass
        core.global_force_seed = seed
    config.addinivalue_line("markers", "hypothesis: Tests which use hypothesis.")
Пример #7
0
    def run_and_statis(
        self,
        quant=False,
        max_examples=100,
        reproduce=None,
        min_success_num=25,
        passes=None,
        model=None,
        params=None,
    ):
        self.init_statistical_parameters()
        settings.register_profile(
            "dev",
            max_examples=max_examples,
            suppress_health_check=hypothesis.HealthCheck.all(),
            deadline=None,
            print_blob=True,
            derandomize=True,
            report_multiple_bugs=False,
            verbosity=Verbosity.verbose)

        if os.getenv('HYPOTHESIS_TEST_PROFILE') == "ci":
            settings.load_profile("ci")
        elif os.getenv('HYPOTHESIS_TEST_PROFILE') == "ce":
            settings.load_profile("ce")
        else:
            settings.load_profile("dev")

        self.passes = passes
        self.add_ignore_pass_case()

        def program_generator(draw):
            return self.sample_program_configs(draw)

        def inputs_generator(draw):
            return self.prepare_input_data(draw)

        def run_test(prog_config):
            return self.run_test(quant=quant, prog_configs=[prog_config])

        def run_model_test(inputs_configs):
            return self.run_model_test(inputs_configs=[inputs_configs],
                                       model=model,
                                       params=params)

        # if current unittest is not active on the input targ    paddlelite_not_support_flag = Trueet, we will exit directly.
        gl.set_all_test_ops(self.get_target(),
                            self.get_nnadapter_device_name(), sys.argv[0])
        if not self.is_actived():
            logging.info("Error: This test is not actived on " +
                         self.get_target())
            return

        if not self.is_nnadapter_device_actived():
            logging.info("Error: This test is not actived on " +
                         self.get_nnadapter_device_name())
            return

        if self.get_target().upper() == "NNADAPTER":
            self.assertTrue(
                self.args.nnadapter_device_names != "",
                "Args Error: Please set nnadapter_device_names when target=nnadapter!"
            )

        if self.is_model_test():
            generator = st.composite(inputs_generator)
            loop_func = given(generator())(run_model_test)
        else:
            generator = st.composite(program_generator)
            loop_func = given(generator())(run_test)

        if reproduce is not None:
            loop_func = reproduce(loop_func)
        logging.info("Start to running test of {}".format(type(self)))
        loop_func()
        if self.is_model_test():
            logging.info(
                "===================Statistical Information==================="
            )
            logging.info("Number of Input Configs: {}".format(max_examples))
            logging.info("Number of Predictor Kinds: {}".format(
                int(self.num_predictor_kinds)))
        else:
            logging.info(
                "===================Statistical Information==================="
            )
            logging.info(
                "Number of Generated Programs: {}".format(max_examples))
            logging.info("Number of Predictor Kinds: {}".format(
                int(self.num_predictor_kinds)))
            self.assertTrue(
                self.num_predictor_kinds > 0,
                "Number of Predictor Kinds must be greater than 0")
            logging.info("Number of Ran Programs: {}".format(
                self.num_ran_programs_list))
            logging.info("Number of Invalid Programs: {}".format(
                self.num_invalid_programs_list))
            logging.info("Number of Ignored Tests: {}".format(
                self.num_ignore_tests_list))
            successful_ran_programs = int(
                (sum(self.num_ran_programs_list) +
                 sum(self.num_ignore_tests_list)) / self.num_predictor_kinds)

            logging.info(
                "Number of successfully ran programs approximately equal to {}"
                .format(successful_ran_programs))
            if successful_ran_programs < min_success_num:
                logging.fatal(
                    "At least {} programs need to ran successfully, but now only about {} programs satisfied."
                    .format(min_success_num, successful_ran_programs))
                assert False
Пример #8
0
def teardown_function(fn):
    settings.load_profile('default')
    warnings.simplefilter('once', HypothesisDeprecationWarning)
Пример #9
0
    Tuple,
)
from cattr._compat import bytes, unicode

import attr

from attr import make_class, NOTHING
from hypothesis import strategies as st, settings, HealthCheck

settings.register_profile(
    "CI",
    settings(suppress_health_check=[HealthCheck.too_slow]),
    deadline=None)

if "CI" in os.environ:
    settings.load_profile("CI")

primitive_strategies = st.sampled_from([
    (st.integers(), int),
    (st.floats(allow_nan=False), float),
    (st.text(), unicode),
    (st.binary(), bytes),
])


@st.composite
def enums_of_primitives(draw):
    """Generate enum classes with primitive values."""
    names = draw(st.sets(st.text(min_size=1), min_size=1))
    n = len(names)
    vals = draw(
import pytest

from   hypothesis import given, settings
import hypothesis.strategies as st

from radical.entk import Pipeline, Stage, Task
from radical.entk import states
from radical.entk.exceptions import *


# ------------------------------------------------------------------------------
#

# Hypothesis settings
settings.register_profile("travis", max_examples=100, deadline=None)
settings.load_profile("travis")

def test_stage_initialization():
    """
    ***Purpose***: Test if all attributes have, thus expect, the
    correct data types
    """

    s = Stage()

    assert s.uid == None
    assert s.name == None
    assert s.tasks == set()
    assert s.state == states.INITIAL
    assert s.state_history == [states.INITIAL]
    assert s._task_count == 0
Пример #11
0
import os

import pytest
from flask import Flask
from hypothesis import settings

settings.register_profile('slow', settings(max_examples=200))
settings.register_profile('fast', settings(max_examples=20))
settings.load_profile(os.getenv(u'HYPOTHESIS_PROFILE', 'fast'))


@pytest.fixture(autouse=True)
def flask(request):
    app = Flask(__name__)
    ctx = app.test_request_context('/')
    ctx.push()

    request.addfinalizer(ctx.pop)
Пример #12
0
    })


@pytest.fixture
def create(tmpdir):
    def inner(name, content, list_name='default'):
        tmpdir.ensure_dir(list_name).join(name).write(
            'BEGIN:VCALENDAR\n'
            'BEGIN:VTODO\n' +
            content +
            'END:VTODO\n'
            'END:VCALENDAR'
        )

    return inner


settings.register_profile("ci", settings(
    max_examples=1000,
    verbosity=Verbosity.verbose,
    suppress_health_check=[HealthCheck.too_slow]
))
settings.register_profile("deterministic", settings(
    derandomize=True,
))

if os.getenv('DETERMINISTIC_TESTS', 'false').lower() == 'true':
    settings.load_profile("deterministic")
elif os.getenv('CI', 'false').lower() == 'true':
    settings.load_profile("ci")
Пример #13
0
is_python2 = sys.version_info < (3, 0)

try:  # Python2 compatibility
    range = xrange
except NameError:
    pass

settings.register_profile("ci", settings(
    max_examples=500, deadline=None, timeout=unlimited))
settings.register_profile("dev", settings(max_examples=10, deadline=2000))
settings.register_profile("debug", settings(
    max_examples=10, verbosity=Verbosity.verbose, deadline=2000))
try:
    env = os.getenv('HYPOTHESIS_PROFILE', 'dev')
    settings.load_profile(env)
except errors.InvalidArgument:
    sys.exit('Unknown hypothesis profile: %s.' % env)

uint18 = st.integers(min_value=0, max_value=2**18)
uint32 = st.integers(min_value=0, max_value=2**32-1)
integer = st.integers(min_value=0, max_value=2**31-1)

range_max_size = 2**18

range_big_step = uint18.flatmap(lambda n:
                                st.builds(range, st.just(n),
                                          st.integers(
                                              min_value=n+1, max_value=n+range_max_size),
                                          st.integers(min_value=2**8, max_value=range_max_size//8)))
Пример #14
0
LS5_NBAR_STORAGE_TYPE = LS5_SAMPLES / 'ls5_geographic.yaml'
LS5_NBAR_ALBERS_STORAGE_TYPE = LS5_SAMPLES / 'ls5_albers.yaml'

CONFIG_FILE_PATHS = [
    str(INTEGRATION_TESTS_DIR / 'agdcintegration.conf'),
    os.path.expanduser('~/.datacube_integration.conf')
]

# Configure Hypothesis to allow slower tests, because we're testing datasets
# and disk IO rather than scalar values in memory.  Ask @Zac-HD for details.
settings.register_profile('opendatacube',
                          timeout=-1,
                          deadline=5000,
                          max_examples=10,
                          suppress_health_check=[HealthCheck.too_slow])
settings.load_profile('opendatacube')


@pytest.fixture
def global_integration_cli_args():
    """
    The first arguments to pass to a cli command for integration test configuration.
    """
    # List of a config files in order.
    return list(itertools.chain(*(('--config', f) for f in CONFIG_FILE_PATHS)))


@pytest.fixture
def datacube_env_name(request):
    if hasattr(request, 'param'):
        return request.param
Пример #15
0
def setup_logging():
    click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG)


try:
    import pytest_benchmark
except ImportError:

    @pytest.fixture
    def benchmark():
        return lambda x: x()
else:
    del pytest_benchmark

settings.register_profile(
    "dev", settings(suppress_health_check=[HealthCheck.too_slow]))
settings.load_profile("dev")

settings.register_profile(
    "ci", settings(
        max_examples=1000,
        verbosity=Verbosity.verbose,
    ))
settings.register_profile(
    "deterministic", settings(derandomize=True, perform_health_check=False))

if os.environ.get('DETERMINISTIC_TESTS', 'false').lower() == 'true':
    settings.load_profile("deterministic")
elif os.environ.get('CI', 'false').lower() == 'true':
    settings.load_profile("ci")
Пример #16
0
from swh.model.hashutil import hash_to_hex, hash_to_bytes
from swh.model.identifiers import directory_identifier
from swh.storage.algos.revisions_walker import get_revisions_walker
from swh.storage.tests.algos.test_snapshot import (  # noqa
    origins as new_origin_strategy, snapshots as new_snapshot)
from swh.web.tests.data import get_tests_data

# Module dedicated to the generation of input data for tests through
# the use of hypothesis.
# Some of these data are sampled from a test archive created and populated
# in the swh.web.tests.data module.

# Set the swh-web hypothesis profile if none has been explicitly set
hypothesis_default_settings = settings.get_profile('default')
if repr(settings()) == repr(hypothesis_default_settings):
    settings.load_profile('swh-web')

# Import tests data
tests_data = get_tests_data()
storage = tests_data['storage']

# The following strategies exploit the hypothesis capabilities

_generated_checksums = set()


def _filter_checksum(cs):
    if not int.from_bytes(cs, byteorder='little') or \
            cs in _generated_checksums:
        return False
    _generated_checksums.add(cs)
Пример #17
0
def load_profile(name=getenv('HYPOTHESIS_PROFILE') or 'default'):
    """Load the Hypothesis profile with the given name."""
    settings.load_profile(name)
Пример #18
0
    49534,
    50083,
    50630,
    51179,
    53736,
    54832,
    56109,
    57204,
    57754,
])
leap_sec_days = set([d - 1 for d in leap_sec_mjds])
near_leap_sec_days = list(
    sorted([d - 1 for d in leap_sec_days] + [d + 1 for d in leap_sec_days]))

settings.register_profile("relaxed", deadline=2000)
settings.load_profile("relaxed")


@composite
def possible_leap_sec_days(draw):
    y = draw(integers(2017, 2050))
    s = draw(booleans())
    if s:
        m = Time(datetime(y, 6, 30, 0, 0, 0), scale="tai").mjd
    else:
        m = Time(datetime(y, 12, 31, 0, 0, 0), scale="tai").mjd
    return int(np.round(m))


@composite
def leap_sec_day_mjd(draw):
Пример #19
0
import os

from pytest import fixture
from hypothesis import settings

from chalice.app import Chalice

# From:
# http://hypothesis.readthedocs.io/en/latest/settings.html#settings-profiles
# On travis we'll have it run through more iterations.
settings.register_profile('ci', settings(max_examples=2000))
# When you're developing locally, we'll only run a few examples
# to keep unit tests fast.  If you want to run more iterations
# locally just set HYPOTHESIS_PROFILE=ci.
settings.register_profile('dev', settings(max_examples=10))
settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'dev'))


@fixture(autouse=True)
def ensure_no_local_config(no_local_config):
    pass


@fixture
def sample_app():
    app = Chalice('sample')

    @app.route('/')
    def foo():
        return {}
Пример #20
0
from profiles.repositories import SQLAlchemyOrcidTokens, SQLAlchemyProfiles
from profiles.utilities import expires_at

BUILD_PATH = os.path.dirname(os.path.dirname(
    os.path.realpath(__file__))) + '/build/'

TEST_DATABASE_NAME = 'test.db'
TEST_DATABASE_PATH = BUILD_PATH + TEST_DATABASE_NAME
TEST_DATABASE_URI = 'sqlite:///' + TEST_DATABASE_PATH

logging.disable(logging.CRITICAL)

set_hypothesis_home_dir(BUILD_PATH + 'hypothesis/home')
hyp_settings.register_profile(
    'default', hyp_settings(database_file=BUILD_PATH + 'hypothesis/db'))
hyp_settings.load_profile('default')


@fixture(scope='session')
def app(request: FixtureRequest) -> Flask:
    app = create_app(
        DevConfig(
            orcid={
                'api_uri': 'http://www.example.com/api',
                'authorize_uri': 'http://www.example.com/oauth/authorize',
                'token_uri': 'http://www.example.com/oauth/token',
                'client_id': 'server_client_id',
                'client_secret': 'server_client_secret',
                'read_public_access_token': 'server_read_public_access_token',
                'webhook_access_token': 'server_webhook_access_token',
                'webhook_key': 'webhook_key',
Пример #21
0
"""
Tests for the eliot package.
"""

# Increase hypothesis deadline so we don't time out on PyPy:
from hypothesis import settings

settings.register_profile("eliot", deadline=1000)
settings.load_profile("eliot")
Пример #22
0
from hypothesis import HealthCheck, settings

settings.register_profile(
    "slow",
    deadline=None,
    suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much],
)
settings.load_profile("slow")
Пример #23
0
# -*- coding: utf-8 -*-
# Copyright 2009-2021 Joshua Bronson. All Rights Reserved.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""Set up hypothesis."""

from datetime import timedelta
from os import getenv

from hypothesis import settings

MAX_EXAMPLES_DEFAULT = 200
DEADLINE_DEFAULT = 200

SETTINGS = {
    'max_examples':
    int(getenv('HYPOTHESIS_MAX_EXAMPLES') or MAX_EXAMPLES_DEFAULT),
    'deadline':
    timedelta(
        milliseconds=int(getenv('HYPOTHESIS_DEADLINE') or DEADLINE_DEFAULT)),
}
settings.register_profile('custom', **SETTINGS)
settings.load_profile('custom')
Пример #24
0
from hypothesis import database
from datetime import timedelta

settings.register_profile(
    "quick",
    max_examples=100,
    database=database.ExampleDatabase(".hypothesis-db"),
    print_blob=True,
)
settings.register_profile(
    "extended",
    max_examples=1000,
    database=database.ExampleDatabase(".hypothesis-db"),
    print_blob=True,
)
settings.load_profile("quick")


@st.composite
def message_typedef_gen(draw, max_depth=3, anon=False, types=None, named_fields=True):
    output = {}
    field_numbers = draw(
        st.lists(st.integers(min_value=1, max_value=2000).map(str), min_size=1)
    )
    # pre-generate names so we can be sure they're unique
    field_names = draw(st.lists(st.from_regex(blackboxprotobuf.NAME_REGEX), min_size=len(field_numbers), max_size=len(field_numbers), unique_by=lambda x: x.lower()))
    if types is None:
        message_types = [
            field_type
            for field_type in type_maps.WIRETYPES.keys()
            if field_type in input_map and input_map[field_type] is not None
Пример #25
0
"""
Configuration for tests.
"""

from hypothesis import settings

settings.register_profile("dit", deadline=None)
settings.load_profile("dit")
Пример #26
0
# -*- test-case-name: klein.test -*-
# Copyright (c) 2011-2021. See LICENSE for details.
"""
Tests for L{klein}.
"""

from hypothesis import HealthCheck, settings

settings.register_profile(
    "patience",
    settings(
        deadline=None,
        suppress_health_check=[HealthCheck.too_slow],
    ),
)
settings.load_profile("patience")
Пример #27
0
def teardown_module():
    settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'default'))
Пример #28
0
#from functools import reduce
from future.builtins import (ascii, filter, hex, map, oct, zip, object, str,
    range)

from {{parent}}.{{project}} import classic

try:
    from hypothesis import (given, note, settings, Verbosity, 
        strategies as st)
except ImportError as exc:
    raise unittest.SkipTest(__name__ + ': ' + repr(exc))


settings.register_profile('debug', settings(verbosity = Verbosity.
    normal, max_examples = 5, max_iterations = 10))
settings.load_profile('debug')

def in_epsilon(val_a, val_b, tolerance=0.001):
    #return ((abs(val_a) - tolerance) <= abs(val_b) and
    #    (abs(val_a) + tolerance) >= abs(val_b))
    delta = abs(tolerance)
    #return (val_a - delta) <= val_b and (val_a + delta) >= val_b
    return (not (val_a + delta) < val_b) and (not (val_b + delta) < val_a)

def setUpModule():
    #print('Setup module: {0}'.format(__name__))
    pass

def tearDownModule():
    #print('Teardown module: {0}'.format(__name__))
    pass
Пример #29
0
def setup_function(fn):
    settings.load_profile("nonstrict")
    warnings.simplefilter("always", HypothesisDeprecationWarning)
Пример #30
0
from django.test import override_settings
from django.urls import reverse
from django_webtest import WebTestMixin
from hypothesis import given, settings
from hypothesis.extra.django import TestCase
from hypothesis.strategies import text, binary, sampled_from

from rest_framework_simplejwt.tokens import AccessToken

from ...auth.tests.fakes import fake_user
from ..models import DataFile
from .fakes import fake_data_file

# Override default deadline for all tests to 8s
settings.register_profile("ci", deadline=800.0)
settings.load_profile("ci")


class ComplexModelFilesApi(WebTestMixin, TestCase):
    @given(
        file_description=text(alphabet=string.ascii_letters,
                              min_size=1,
                              max_size=10), )
    def test_data_is_valid___object_is_created(self, file_description):
        user = fake_user()

        response = self.app.post(
            reverse('data-file-list', kwargs={'version': 'v1'}),
            headers={
                'Authorization': 'Bearer {}'.format(AccessToken.for_user(user))
            },
Пример #31
0
from radical.entk.execman.base import Base_ResourceManager as BaseRmgr
from radical.entk.execman.rp import TaskManager as RPTmgr
from radical.entk.execman.rp import ResourceManager as RPRmgr
from radical.entk.execman.mock import TaskManager as MockTmgr
from radical.entk.execman.mock import ResourceManager as MockRmgr
from radical.entk import exceptions as ree
from radical.entk import Task, states

hostname = os.environ.get('RMQ_HOSTNAME', 'localhost')
port = int(os.environ.get('RMQ_PORT', 5672))
username = os.environ.get('RMQ_USERNAME')
password = os.environ.get('RMQ_PASSWORD')

# Hypothesis settings
settings.register_profile("travis", max_examples=100, deadline=None)
settings.load_profile("travis")

os.environ['ENTK_HB_INTERVAL'] = '5'


# ------------------------------------------------------------------------------
#
def test_tmgr_base_initialization():

    try:
        home = os.environ.get('HOME', '/home')
        folder = glob.glob('%s/.radical/utils/test.*' % home)

        for f in folder:
            shutil.rmtree(f)
    except:
Пример #32
0
# -*- coding: utf-8 -*-
from hypothesis import settings
from hypothesis.strategies import (fixed_dictionaries, lists, booleans,
                                   integers, text, none, composite,
                                   sampled_from, one_of, just)

from functools import partial
import re

settings.register_profile("unit", settings(
    database=None,
    max_examples=1,
))
settings.load_profile("unit")

_descriptive_alphabet = (
    # start with some normal alphanumerics
    u"abcdefghijklmnopABCDEFGHIJKLMNOP123"
    # some characters likely to fudge up poor escaping
    + u"\"\'<&%"
    # some printable unicode oddities
    + u"£Ⰶⶼ"
    # various weird types of spaces
    + u" \u200d\u2029\u202f")
_nonspace_cluster_re = re.compile(r"\S+", flags=re.UNICODE)


# we use this filter against hypothesis-generated strings so we don't unnecessarily trigger
# min/max word limits
# hint: use partial for tinkering with the kwargs
def _word_count_filter(s, min_words=1, max_words=None):
Пример #33
0
# -*- test-case-name: klein.test -*-
# Copyright (c) 2017-2018. See LICENSE for details.

"""
Tests for L{klein}.
"""

from hypothesis import HealthCheck, settings

settings.register_profile(
    "patience", settings(suppress_health_check=[HealthCheck.too_slow])
)
settings.load_profile("patience")
Пример #34
0
    import numpy as np
    import scipy.special as sp
except ImportError:
    has_scipy = False

# Package / Application
from .. import pyerf


# ---------------------------------------------------------------------------
### Constants and Setup
# ---------------------------------------------------------------------------
# Create a profile for testing on CI (Travis, GitLab, etc.)
settings.register_profile('ci', settings(max_examples=1000))
if os.getenv('CI', None) is not None:
    settings.load_profile('ci')


# ---------------------------------------------------------------------------
### Helper Functions
# ---------------------------------------------------------------------------
def frange(x, y, jump):
    while x < y:
        yield float(x)
        x += decimal.Decimal(jump)


@pytest.fixture(scope="module", params=[True, False])
def use_math_stdlib(request):
    # this 1st import is just to bring things into the namespace.
    from .. import pyerf
Пример #35
0
# contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
#
# END HEADER

from __future__ import absolute_import, division, print_function

import os
import sys

from hypothesis import HealthCheck, settings
from tests.common.setup import run

if __name__ == u"__main__":
    run()

    settings.register_profile(
        "default", settings(suppress_health_check=[HealthCheck.too_slow])
    )

    settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", "default"))

    os.environ.setdefault(u"DJANGO_SETTINGS_MODULE", u"tests.django.toys.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
Пример #36
0
from hypothesis import settings, HealthCheck

from chalice.app import Chalice

# From:
# http://hypothesis.readthedocs.io/en/latest/settings.html#settings-profiles
# On travis we'll have it run through more iterations.
settings.register_profile(
    'ci', settings(max_examples=2000,
                   suppress_health_check=[HealthCheck.too_slow]),
)
# When you're developing locally, we'll only run a few examples
# to keep unit tests fast.  If you want to run more iterations
# locally just set HYPOTHESIS_PROFILE=ci.
settings.register_profile('dev', settings(max_examples=10))
settings.load_profile(os.getenv('HYPOTHESIS_PROFILE', 'dev'))

print("HYPOTHESIS PROFILE: %s" % os.environ.get("HYPOTHESIS_PROFILE"))


@fixture(autouse=True)
def ensure_no_local_config(no_local_config):
    pass


@fixture
def sample_app():
    app = Chalice('sample')

    @app.route('/')
    def foo():
Пример #37
0
 def pytest_configure(config):
     from hypothesis import settings
     profile = config.getoption(LOAD_PROFILE_OPTION)
     if profile:
         settings.load_profile(profile)
Пример #38
0
from bidict import (
    OrderedBidirectionalMapping, IGNORE, OVERWRITE, RAISE,
    bidict, loosebidict, looseorderedbidict, orderedbidict,
    frozenbidict, frozenorderedbidict)
from bidict.compat import iteritems, viewitems
from collections import OrderedDict
from hypothesis import given, settings
from hypothesis.strategies import integers, lists, tuples
from os import getenv
import pytest


# https://groups.google.com/d/msg/hypothesis-users/8FVs--1yUl4/JEkJ02euEwAJ
settings.register_profile('default', settings(strict=True))
settings.load_profile(getenv('HYPOTHESIS_PROFILE', 'default'))


def to_inv_odict(items):
    return OrderedDict((v, k) for (k, v) in items)


def prune_dup_vals(items):
    return list(iteritems(to_inv_odict(iteritems(to_inv_odict(items)))))


ondupbehaviors = (IGNORE, OVERWRITE, RAISE)
mutable_bidict_types = (bidict, loosebidict, looseorderedbidict, orderedbidict)
bidict_types = mutable_bidict_types + (frozenbidict, frozenorderedbidict)
mutating_methods_by_arity = {
    0: ('clear', 'popitem',),
Пример #39
0
import os
from hypothesis import settings, Verbosity

settings.register_profile("ci", settings(max_examples=100))
settings.register_profile("dev", settings(max_examples=5))
settings.register_profile("debug", settings(max_examples=10, verbosity=Verbosity.verbose))

settings.load_profile(os.environ.get(u'HYPOTHESIS_PROFILE', 'dev'))
Пример #40
0
 def pytest_configure(config):
     from hypothesis import settings
     profile = config.getoption(LOAD_PROFILE_OPTION)
     if profile:
         settings.load_profile(profile)
Пример #41
0
from backports.tempfile import TemporaryDirectory
from celery.exceptions import Retry
from hypothesis import given
from hypothesis import settings as hypothesis_settings
from hypothesis.strategies import text
from mock import patch, Mock, ANY
from oasislmf.utils.status import OASIS_TASK_STATUS
from pathlib2 import Path

from src.conf.iniconf import SettingsPatcher, settings
from src.model_execution_worker.tasks import start_analysis, InvalidInputsException, MissingInputsException, \
    start_analysis_task, get_oasislmf_config_path

# Override default deadline for all tests to 8s
hypothesis_settings.register_profile("ci", deadline=800.0)
hypothesis_settings.load_profile("ci")


class StartAnalysis(TestCase):
    def create_tar(self, target):
        with TemporaryDirectory() as media_root, tarfile.open(target,
                                                              'w') as tar:
            paths = [
                Path(media_root, 'events.bin'),
                Path(media_root, 'returnperiods.bin'),
                Path(media_root, 'occurrence.bin'),
                Path(media_root, 'periods.bin'),
            ]

            for path in paths:
                path.touch()
Пример #42
0
from static_frame import IndexHierarchy
from static_frame import IndexHierarchyGO

from static_frame import IndexGO
from static_frame import Series
from static_frame import Frame
from static_frame import FrameGO

MAX_ROWS = 8
MAX_COLUMNS = 10


hypo_settings.register_profile("sf",
        suppress_health_check=[HealthCheck.too_slow])
hypo_settings.load_profile("sf")

#-------------------------------------------------------------------------------
# spacings

# @lru_cache(maxsize=32)
def subset_contiguous_sum(target):
    '''
    Return an iterabel of integers that sum to the target. This does not find all combinations or permutations, just all combintation of the range from 1 to the number (inclusive).
    '''
    # based on https://stackoverflow.com/questions/4632322/finding-all-possible-combinations-of-numbers-to-reach-a-given-sum

    if target == 0:
        return ()

    if not (0 < target <= 32):
Пример #43
0
def load_profile(name=getenv('HYPOTHESIS_PROFILE') or 'default'):
    """Load the Hypothesis profile with the given name."""
    settings.load_profile(name)
Пример #44
0
def reload_profile():
    # Setting Hypothesis profile in a pytester-style test leads to overriding it globally
    yield
    settings.load_profile("default")
# -*- coding: utf-8 -*-
from hypothesis import settings
from hypothesis.strategies import (
    fixed_dictionaries, lists,
    text, integers, text, none,
    composite, one_of,
    just)

from functools import partial
import re

settings.register_profile("unit", settings(
    database=None,
    max_examples=1,
))
settings.load_profile("unit")


_descriptive_alphabet = (
    # start with some normal alphanumerics
    u"abcdefghijklmnopABCDEFGHIJKLMNOP123"
    # some characters likely to fudge up poor escaping
    u"\"\'<&%"
    # some printable unicode oddities
    u"£Ⰶⶼ"
    # various weird types of spaces
    u" \u200d\u2029\u202f"
)
_nonspace_cluster_re = re.compile(r"\S+", flags=re.UNICODE)

Пример #46
0
import os
import sys
import warnings

from hypothesis import HealthCheck, settings

from tests.common.setup import run

if __name__ == "__main__":
    run()

    settings.register_profile(
        "default", settings(suppress_health_check=[HealthCheck.too_slow]))

    settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", "default"))

    os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                          "tests.django.toys.settings")

    # This triggers a deprecation warning on some older versions of Django
    # because of its use of the imp module.
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=DeprecationWarning)
        from django.core.management import execute_from_command_line

    try:
        from django.utils.deprecation import RemovedInDjango50Warning
    except ImportError:
        RemovedInDjango50Warning = ()
Пример #47
0
import platform
import os
import sys

from hypothesis import settings, HealthCheck

impl = platform.python_implementation()

settings.register_profile("ci", settings(max_examples=1000,
                                         suppress_health_check=[HealthCheck.too_slow]))
settings.register_profile("pypy", settings(suppress_health_check=[HealthCheck.too_slow]))

settings.load_profile(os.getenv("HYPOTHESIS_PROFILE",
                                "default" if impl != "PyPy" else "pypy"))

# serve can't even be imported on Py3, so totally ignore it even from collection
collect_ignore = []
if sys.version_info[0] >= 3:
    serve = os.path.join(os.path.dirname(__file__), "serve")
    collect_ignore.extend([os.path.join(root, f)
                           for root, _, files in os.walk(serve)
                           for f in files])
Property testing for functions in huffman.py.
"""

import unittest
from random import shuffle
from huffman import byte_to_bits, bits_to_byte, get_bit, make_freq_dict
from huffman import huffman_tree, get_codes, number_nodes
from huffman import generate_compressed, generate_uncompressed
from huffman import avg_length, tree_to_bytes, num_nodes_to_bytes
from nodes import HuffmanNode
from hypothesis import given, assume, settings
from hypothesis.strategies import binary, integers, dictionaries, text

settings.register_profile("norand", settings(derandomize=True,
                                             max_examples=200))
settings.load_profile("norand")


class TestByteUtilities(unittest.TestCase):
    """Property tests for byte functions"""
    @given(integers(0, 255))
    def test_byte_to_bits(self, b):
        """byte_to_bits produces binary strings of length 8"""

        self.assertTrue(set(byte_to_bits(b)).issubset({"0", "1"}))
        self.assertEqual(len(byte_to_bits(b)), 8)

    @given(text(["0", "1"], 0, 4, 8))
    def test_bits_to_byte(self, s):
        """bits_to_byte produces byte"""
Пример #49
0
import unicodenazi

warnings.filterwarnings('error', category=UnicodeWarning)
unicodenazi.enable()

from hypothesis import settings
from hypothesis.configuration import set_hypothesis_home_dir

set_hypothesis_home_dir(mkdtemp())

assert isinstance(settings, type)

settings.register_profile(
    'default', settings(timeout=-1, strict=True)
)
settings.load_profile('default')

import inspect
import os


TESTS = [
    'test_testdecorators',
]

import sys
sys.path.append(os.path.join(
    os.path.dirname(__file__), "..", "tests", "cover",
))

if __name__ == '__main__':
Пример #50
0
# isort: STDLIB
import unittest
from fractions import Fraction
from os import sys

# isort: THIRDPARTY
from hypothesis import given, settings, strategies

# isort: LOCAL
from justbases import Rationals, RoundingMethods

# isort considers this third party, but it is not
from tests.test_hypothesis._utils import build_base, build_radix  # isort:skip

if sys.gettrace() is not None:
    settings.load_profile("tracing")


class RadixTestCase(unittest.TestCase):
    """Tests for radix."""
    @given(build_radix(16, 3), build_base(16))
    @settings(max_examples=50, deadline=None)
    def test_in_base(self, radix, base):
        """
        Test that roundtrip is identity modulo number of 0s in
        non repeating part.
        """
        result = radix.in_base(base).in_base(radix.base)
        self.assertEqual(result.sign, radix.sign)
        self.assertEqual(result.integer_part, radix.integer_part)
        self.assertEqual(result.repeating_part, radix.repeating_part)
Пример #51
0
Property-based tests for encoding/decoding methods.

These ones pass, just as you'd hope!

"""
from __future__ import absolute_import, division, print_function

import hypothesis.extra.numpy as npst
import hypothesis.strategies as st
from hypothesis import given, settings

import xarray as xr

# Run for a while - arrays are a bigger search space than usual
settings.register_profile("ci", deadline=None)
settings.load_profile("ci")


an_array = npst.arrays(
    dtype=st.one_of(
        npst.unsigned_integer_dtypes(),
        npst.integer_dtypes(),
        npst.floating_dtypes(),
    ),
    shape=npst.array_shapes(max_side=3),  # max_side specified for performance
)


@given(st.data(), an_array)
def test_CFMask_coder_roundtrip(data, arr):
    names = data.draw(st.lists(st.text(), min_size=arr.ndim,
Пример #52
0
from os import getenv
from weakref import ref

import pytest
from hypothesis import assume, given, settings, strategies as strat

from bidict import (BidictException, IGNORE, OVERWRITE, RAISE,
                    BidirectionalMapping, bidict, OrderedBidict,
                    OrderedBidictBase, frozenbidict, FrozenOrderedBidict,
                    namedbidict, pairs, inverted)

from bidict.compat import (PY2, PYPY, iterkeys, itervalues, iteritems, izip,
                           Hashable, Mapping, MutableMapping)

settings.register_profile('default', settings(max_examples=250, deadline=None))
settings.load_profile(getenv('HYPOTHESIS_PROFILE', 'default'))


def inverse_odict(items):
    """An OrderedDict containing the inverse of each item in *items*."""
    return OrderedDict((v, k) for (k, v) in items)


def ensure_no_dup(items):
    """Given some hypothesis-generated items, prune any with duplicated keys or values."""
    pruned = list(iteritems(inverse_odict(iteritems(inverse_odict(items)))))
    assume(len(pruned) >= len(items) // 2)
    return pruned


def ensure_dup(key=False, val=False):
Пример #53
0
def setup_module():
    settings.load_profile('benchmarking')
Пример #54
0
import astroid

from hypothesis import settings
from pytest import skip
from python_ta.typecheck.base import TypeFail
from .. import custom_hypothesis_support as cs
settings.load_profile("pyta")


def test_classdef_attribute_assign():
    """Test whether type of attributes are properly being set."""
    program = f'class Network:\n' \
              f'    def __init__(self, name, id):\n' \
              f'        self.name = name\n' \
              f'        self.id = id' \
              f'\n' \
              f'rogers = Network("Rogers", 5)\n' \
              f'rogers.name = "BoB"\n' \
              f'self = Network("asdf", 5)\n' \
              f'self.name = "asdfaBoB"\n' \
              f'\n'
    module, inferer = cs._parse_text(program)
    classdef_node = next(module.nodes_of_class(astroid.ClassDef))
    for attribute_lst in classdef_node.instance_attrs.values():
        for instance in attribute_lst:
            attribute_type = inferer.type_constraints\
                .resolve(classdef_node.type_environment.lookup_in_env(instance.attrname))
            value_type = inferer.type_constraints.resolve(
                instance.parent.value.inf_type.getValue())
            assert attribute_type == value_type
Пример #55
0
from os import environ

from hypothesis import settings

settings.register_profile('dev', settings(max_examples=10))
settings.register_profile('ci', settings())


if environ.get('CI', False):
    settings.load_profile('ci')
else:
    settings.load_profile('dev')
Пример #56
0
from hypothesis.strategies import (characters, text, lists, composite,
                                   integers, booleans, sampled_from)

_DEFAULT_HEADERS = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

log = init_logger()

# https://hypothesis.readthedocs.io/en/latest/healthchecks.html
# https://hypothesis.readthedocs.io/en/latest/settings.html#default-settings
settings.register_profile(
    "health_suppress_slow",
    suppress_health_check=(hypothesis.HealthCheck.too_slow, ))
settings.load_profile("health_suppress_slow")

ROOT_URL = SAPI_MOUNTPOINT


def nice_strings(bad_chars):
    """
    A Hypothesis strategy to generate reasonable name strings
    """
    def sane_first_character(s):
        c = s[0]
        return c not in ['/']

    return text(alphabet=characters(blacklist_characters=bad_chars,
                                    whitelist_categories=['Ll'],
                                    min_codepoint=ord('0'),
Пример #57
0
import astroid
import nose
from hypothesis import given, settings
from typing import List
import tests.custom_hypothesis_support as cs
settings.load_profile("pyta")


@given(cs.subscript_node(cs.simple_homogeneous_list_node(min_size=1), cs.index_node()))
def test_inference_list_subscript(node):
    """Test whether visitor properly set the type constraint of Subscript node representing list-index access."""
    module, _ = cs._parse_text(node)
    for subscript_node in module.nodes_of_class(astroid.Subscript):
        list_node = subscript_node.value
        assert subscript_node.type_constraints.type == list_node.elts[0].type_constraints.type


@given(cs.subscript_node(cs.simple_homogeneous_list_node(min_size=1), cs.slice_node()))
def test_subscript_homogeneous_list_slice(node):
    """Test visitor of Subscript node representing slicing of homogeneous list."""
    module, _ = cs._parse_text(node)
    for subscript_node in module.nodes_of_class(astroid.Subscript):
        list_node = subscript_node.value
        assert subscript_node.type_constraints.type == List[list_node.elts[0].type_constraints.type]


# TODO: this test currently fails
# @given(cs.simple_homogeneous_dict_node(min_size=1))
# def test_inference_dict_subscript(node):
#     """Note that this test only takes in a dictionary because the subscript index
#     must be the same type as the dictionary's keys in order to type check.
Пример #58
0
import sys

from hypothesis import HealthCheck, settings

settings.register_profile(
    "default",
    suppress_health_check=[HealthCheck.too_slow],
    max_examples=10,
)
settings.register_profile(
    "ci",
    suppress_health_check=[HealthCheck.too_slow],
    max_examples=30,
    deadline=None,
)
settings.register_profile(
    "windows",
    suppress_health_check=[HealthCheck.too_slow],
    max_examples=10,
    deadline=None,
)

settings.load_profile("default")

if sys.platform in ("win32", ):
    settings.load_profile("windows")

# NOTE: this is currently tailored for Github actions
if os.environ.get("CI", None) == "true":
    settings.load_profile("ci")
Пример #59
0
def teardown_function(fn):
    settings.load_profile("default")
    warnings.simplefilter("once", HypothesisDeprecationWarning)
Пример #60
0
import etcd3.exceptions
import etcd3.utils as utils
from etcd3.client import EtcdTokenCallCredentials

etcd_version = os.environ.get('TEST_ETCD_VERSION', 'v3.2.8')

os.environ['ETCDCTL_API'] = '3'

if six.PY2:
    int_types = (int, long)
else:
    int_types = (int, )

# Don't set any deadline in Hypothesis
settings.register_profile("default", deadline=None)
settings.load_profile("default")


def etcdctl(*args):
    endpoint = os.environ.get('PYTHON_ETCD_HTTP_URL')
    if endpoint:
        args = ['--endpoints', endpoint] + list(args)
    args = ['etcdctl', '-w', 'json'] + list(args)
    print(" ".join(args))
    output = subprocess.check_output(args)
    return json.loads(output.decode('utf-8'))


# def etcdctl2(*args):
#     # endpoint = os.environ.get('PYTHON_ETCD_HTTP_URL')
#     # if endpoint: