Exemplo n.º 1
0
def needs_ssh(func):
    """ Decorator for tests that should only be run if a SSH client is
    available (ie RUN_SSH_TESTS=1).
    """
    if os.environ.get('RUN_SSH_TESTS', False):
        return func
    else:
        return nottest(func)
Exemplo n.º 2
0
def only_run_with_partitioned_database(cls):
    """
    Only runs the test with the partitioned database settings.
    """
    if not settings.USE_PARTITIONED_DATABASE:
        return nottest(cls)

    return partitioned(cls)
Exemplo n.º 3
0
def needs_ssh(func):
    """ Decorator for tests that should only be run if a SSH client is
    available (ie RUN_SSH_TESTS=1).
    """
    if os.environ.get('RUN_SSH_TESTS', False):
        return func
    else:
        return nottest(func)
Exemplo n.º 4
0
Arquivo: common.py Projeto: Kozea/Dyko
def common(function):
    """Decorator to explicit a test which must run for all access points.

    All the tests are saved in :const:`COMMON_TESTS`.

    """
    function = nottest(function)
    COMMON_TESTS.append(function)
    return function
Exemplo n.º 5
0
Arquivo: base.py Projeto: 10to8/rauth
    def decorated(func):
        frame = stack()[1]
        frame_locals = frame[0].f_locals

        base_name = func.__name__
        for f in iterable:
            if not isfunction(f):
                raise TypeError('Arguments should be wrapped in a function.')
            name_suffix = ' --> ' + '(' + str(f()[-1]) + ')'
            name = base_name + name_suffix
            new_func = _new_func(name, func, f)
            frame_locals[name] = new_func
        return nottest(func)
Exemplo n.º 6
0
    def decorated(func):
        frame = stack()[1]
        frame_locals = frame[0].f_locals

        base_name = func.__name__
        for f in iterable:
            if not isfunction(f):
                raise TypeError('Arguments should be wrapped in a function.')
            name_suffix = ' --> ' + '(' + str(f()[-1]) + ')'
            name = base_name + name_suffix
            new_func = _new_func(name, func, f)
            frame_locals[name] = new_func
        return nottest(func)
Exemplo n.º 7
0
    def parameterized_expand_wrapper(f):
        stack = inspect.stack()
        frame = stack[1]
        frame_locals = frame[0].f_locals

        base_name = f.__name__
        for num, args in enumerate(input):
            name_suffix = "_%s" %(num, )
            if len(args) > 0 and isinstance(args[0], basestring):
                name_suffix += "_" + to_safe_name(args[0])
            name = base_name + name_suffix
            new_func = parameterized_expand_helper(name, f, args)
            frame_locals[name] = new_func
        return nottest(f)
Exemplo n.º 8
0
        def parameterized_expand_wrapper(f):
            stack = inspect.stack()
            frame = stack[1]
            frame_locals = frame[0].f_locals

            base_name = f.__name__
            get_input = cls.input_as_callable(input)
            for num, args in enumerate(get_input()):
                p = param.from_decorator(args)
                name_suffix = "_%s" % (num, )
                if len(p.args) > 0 and isinstance(p.args[0], basestring):
                    name_suffix += "_" + cls.to_safe_name(p.args[0])
                name = base_name + name_suffix
                frame_locals[name] = cls.param_as_standalone_func(p, f, name)
            return nottest(f)
Exemplo n.º 9
0
        def parameterized_expand_wrapper(f):
            stack = inspect.stack()
            frame = stack[1]
            frame_locals = frame[0].f_locals

            base_name = f.__name__
            get_input = cls.input_as_callable(input)
            for num, args in enumerate(get_input()):
                p = param.from_decorator(args)
                name_suffix = "_%s" %(num, )
                if len(p.args) > 0 and isinstance(p.args[0], six.string_types):
                    name_suffix += "_" + cls.to_safe_name(p.args[0])
                name = base_name + name_suffix
                frame_locals[name] = cls.param_as_standalone_func(p, f, name)
            return nottest(f)
Exemplo n.º 10
0
        def parameterized_expand_wrapper(f, instance=None):
            stack = inspect.stack()
            frame = stack[1]
            frame_locals = frame[0].f_locals

            base_name = f.__name__
            get_input = cls.input_as_callable(input)
            for num, args in enumerate(get_input()):
                p = param.from_decorator(args)
                if testcase_func_name:
                    # Caller wants to over-ride default test case func/method naming scheme.
                    name = testcase_func_name(f, num, p)
                else:
                    name_suffix = "_%s" %(num, )
                    if len(p.args) > 0 and isinstance(p.args[0], string_types):
                        name_suffix += "_" + cls.to_safe_name(p.args[0])
                    name = base_name + name_suffix

                testcase_func_doc_func = (testcase_func_doc or default_testcase_func_doc)
                doc = testcase_func_doc_func(f, num, p)

                frame_locals[name] = cls.param_as_standalone_func(p, f, name)
                frame_locals[name].__doc__ = doc
            return nottest(f)
Exemplo n.º 11
0
from io import StringIO
import os

import mock
from mock import patch, MagicMock, Mock
from nose.tools import assert_equal, assert_raises, nottest
from pyfakefs import fake_filesystem_unittest

from streamalert.shared.config import load_config
from streamalert.shared.exceptions import ConfigError
from streamalert_cli.config import CLIConfig
from streamalert_cli.test.handler import TestRunner
from tests.unit.streamalert_cli.test.helpers import basic_test_file_json

# Keep nose from trying to treat this as a test
TestRunner = nottest(TestRunner)


class TestTestRunner(fake_filesystem_unittest.TestCase):
    """Test the TestEventFile class"""
    # pylint: disable=protected-access

    TEST_CONFIG_PATH = 'tests/unit/conf'
    _DEFAULT_EVENT_PATH = 'rules/community/unit_test/file.json'

    def setUp(self):
        cli_config = CLIConfig(config_path='tests/unit/conf')
        with patch('streamalert.rules_engine.rules_engine.load_config',
                   Mock(return_value=load_config(self.TEST_CONFIG_PATH))):
            self.runner = TestRunner(MagicMock(), cli_config)
Exemplo n.º 12
0
limitations under the License.
"""
from mock import Mock

from nose.tools import assert_equal, nottest
from pyfakefs import fake_filesystem_unittest

from streamalert_cli.test.event_file import TestEventFile
from streamalert_cli.test.results import TestResult
from tests.unit.streamalert_cli.test.helpers import (
    basic_test_event_data,
    basic_test_file_json,
)

# Keep nose from trying to treat these as tests
TestEventFile = nottest(TestEventFile)
TestResult = nottest(TestResult)


class TestTestEventFile(fake_filesystem_unittest.TestCase):
    """Test the TestEventFile class"""

    _DEFAULT_EVENT_PATH = 'rules/community/unit_test/file.json'

    def setUp(self):
        self.setUpPyfakefs()

        # Create a single test event file
        self.fs.create_file(self._DEFAULT_EVENT_PATH,
                            contents=basic_test_file_json())
Exemplo n.º 13
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
from nose.tools import nottest

from openfisca_core.tools.test_runner import generate_tests

from openfisca_tunisia.tests import base

nottest(generate_tests)

options_by_dir = {
    'reforms/plf_2017': {
        'reforms': ['plf_2017'],
    },
    'fiches_de_paie': {},
    'formulas': {},
    'scipy': {
        'reforms': ['de_net_a_brut'],
        'requires': 'scipy'
    },
}


def test():
    for directory, options in options_by_dir.iteritems():
        path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), directory))

        if options.get('requires'):
Exemplo n.º 14
0
def skip_if_py2(function):
    if sys.version_info[0] < 3:
        print("MHCflurry requires python 3. Skipping test.")
        return nottest(function)
    return function
Exemplo n.º 15
0
        process = subprocess.Popen(
            ['jshint', '-c', JSHINT_RC] + files,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        messages, _ = process.communicate(timeout=5)
        self.assertEqual(process.returncode, 0,
                         '\n' + messages.decode('utf-8'))


class JSTestsBase(ViceroyFlaskTestCase):
    viceroy_flask_app = app

    @classmethod
    def setUpClass(cls):
        app.locale_dir = tempfile.mkdtemp()
        gettextjs.compile_locale_path(LOCALE_PATH, app.locale_dir,
                                      gettextjs.JS_MODE)
        gettextjs.compile_locale_path(LOCALE_PATH, app.locale_dir,
                                      gettextjs.JSON_MODE)
        super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(app.locale_dir)
        super().tearDownClass()


JSTests = nottest(build_test_case)('ViceroySuccessTests', TESTS_JS_FILE,
                                   FixedQUnitScanner, JSTestsBase)
Exemplo n.º 16
0
from __future__ import absolute_import
import os
import unittest
import yaml
from contextlib import contextmanager
from copy import copy

from django.apps import apps
from django.test.simple import build_test
from django.conf import settings
from nose.tools import nottest

build_test = nottest(build_test)


class DependenciesNotFound(Exception):
    pass


class OptimizedTestRunnerMixin(object):
    """
    You can have any TestRunner mixin this class to add db optimizations to it.
    What this does is allow you to explicitly declare test app dependencies and then
    using this test runner will only bootstrap those apps. If an app needs the database
    but has very few dependencies this can drastically improve speedup times.

    There are two ways to optimize tests, by app and by test class.

    By app:

    To optimize tests by app, you should add the app as an entry to `app_test_db_dependencies.yml`.
Exemplo n.º 17
0
    ]


##################################################
# Testing the VisualisableNetworkStructure class #
##################################################


### template
@with_setup(setup_units)
@with_setup(setup_vns)
def test_VNS_():
    assert False


nottest(test_VNS_)
### template


@with_setup(setup_units)
@with_setup(setup_vns)
def test_VNS___eq__():
    "Equality of two VisualisableNetworkStructures."
    u1, u2 = Unit(1, 1, 2), Unit(2, 3, 2)
    V.add_population(iter(Tns.vns_units))
    V.connect_units(Tns.vns_units[0], Tns.vns_units[1], -1)
    V.connect_units(Tns.vns_units[1], Tns.vns_units[0], 0.3)
    V.add_unit(u1, "bar")
    V.add_unit(u2, "foo")
    V.connect_maps("bar", "foo")
    w = VNS()
Exemplo n.º 18
0
from nose.tools import nottest, with_setup, assert_raises

from rules.predicates import predicate
from rules.rulesets import (RuleSet, default_rules, add_rule, remove_rule,
                            rule_exists, test_rule)

test_rule = nottest(test_rule)


def reset_ruleset(ruleset):
    def fn():
        for k in list(ruleset.keys()):
            ruleset.pop(k)

    return fn


@predicate
def always_true():
    return True


@with_setup(reset_ruleset(default_rules), reset_ruleset(default_rules))
def test_shared_ruleset():
    add_rule('somerule', always_true)
    assert 'somerule' in default_rules
    assert rule_exists('somerule')
    assert test_rule('somerule')
    remove_rule('somerule')
    assert not rule_exists('somerule')
Exemplo n.º 19
0
try:
    import unittest2 as unittest
except ImportError:
    import unittest

from wsgiref.simple_server import make_server

from nose.tools import nottest
from wsgiref.util import setup_testing_defaults
setup_testing_defaults = nottest(setup_testing_defaults)

from iscool_e.pynba.middleware import PynbaMiddleware
from iscool_e.pynba.globals import pynba
from iscool_e.pynba import monitor


class MiddlewareTestCase(unittest.TestCase):
    def test_context(self):
        def app(environ, start_response):
            with pynba.timer(foo="bar") as timer:
                status = '200 OK'
                headers = [('Content-type', 'text/plain')]
                start_response(status, headers)

            return ['foo', 'bar']

        middleware = PynbaMiddleware(app, ('127.0.0.1', 5000))
        self.call_as_wsgi(middleware)

    def call_as_wsgi(self, callable, environ=None, close=True):
        """Invoke callable via WSGI, returning status, headers, response."""
Exemplo n.º 20
0
 def wrap(fn):
     if None in args:
         return nottest(fn)
     return fn
Exemplo n.º 21
0
class JSTestsBase(ViceroyFlaskTestCase):
    viceroy_flask_app = app

    @classmethod
    def setUpClass(cls):
        app.locale_dir = tempfile.mkdtemp()
        gettextjs.compile_locale_path(
            LOCALE_PATH,
            app.locale_dir,
            gettextjs.JS_MODE
        )
        gettextjs.compile_locale_path(
            LOCALE_PATH,
            app.locale_dir,
            gettextjs.JSON_MODE
        )
        super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(app.locale_dir)
        super().tearDownClass()


JSTests = nottest(build_test_case)(
    'ViceroySuccessTests',
    TESTS_JS_FILE,
    FixedQUnitScanner,
    JSTestsBase
)
Exemplo n.º 22
0
from nose.tools import nottest

from ....fixtures import premade_app
from ....testcases import DustyTestCase
from dusty.systems.docker.testing_image import (
    _ensure_testing_spec_base_image,
    _make_installed_requirements_image,
    _make_installed_testing_image,
    _get_split_volumes,
    _get_create_container_volumes,
    _get_create_container_binds,
)
from dusty.systems.docker.testing_image import ensure_test_image

nottest(ensure_test_image)  # silly Nose, this isn't a test function


class TestTestingImages(DustyTestCase):
    def setUp(self):
        super(TestTestingImages, self).setUp()
        app = premade_app()
        app["test"] = {"once": ["npm install"]}
        self.specs = {"apps": {"fake-app": app}}

    def test_ensure_testing_spec_base_image_image(self):
        mock_docker_client = Mock()
        testing_spec = {"image": "dusty/image"}
        self.assertEquals(_ensure_testing_spec_base_image(mock_docker_client, testing_spec), "dusty/image")

    def test_ensure_testing_spec_base_image_build(self):
Exemplo n.º 23
0
    try:
        # noinspection PyUnresolvedReferences
        from comptests import comptest  # as unit_test

        # noinspection PyUnresolvedReferences
        from comptests import run_module_tests  # as run_tests_for_this_module

        # noinspection PyUnresolvedReferences
        from comptests.comptests import (
            get_comptests_output_dir, )  # as get_output_dir_for_test

        if show_info:
            logger.warning("Using the Comptests testing framework.")

        using_fake_tests = False
        unit_test = nottest(comptest)
        run_tests_for_this_module = nottest(run_module_tests)
        get_output_dir_for_test = nottest(get_comptests_output_dir)
    except ImportError:
        if show_info:
            logger.warning(
                "Unit tests are disabled because Comptests not found.")
        using_fake_tests = True

if using_fake_tests:

    @nottest
    def unit_test(f):
        return f

    @nottest
Exemplo n.º 24
0
    extract_tests_from_files,
    get_recipe_test_paths,
    get_test_infos,
    is_valid_test_directory,
    is_valid_test_file,
    write_test_infos_csv,
)

from .test_datakitchen_client import (
    DUMMY_USERNAME,
    DUMMY_PASSWORD,
    DUMMY_KITCHEN,
    DUMMY_URL,
)

extract_tests_from_files = nottest(extract_tests_from_files)
get_recipe_test_paths = nottest(get_recipe_test_paths)
get_test_infos = nottest(get_test_infos)
is_valid_test_directory = nottest(is_valid_test_directory)
is_valid_test_file = nottest(is_valid_test_file)
write_test_infos_csv = nottest(write_test_infos_csv)

DATESTAMP = '2021-04-07 12:36:01.047096'
PARENT_DIR = Path(__file__).parent
VALID_TEST_PATH_1 = Path('Recipe/Node/notebook.json')
VALID_TEST_PATH_2 = Path('Recipe/Node/actions/foo.json')
RESOURCES_TEST_PATH = Path('Recipe/resources/foo.json')
INVALID_TEST_PATH_DIRNAME = Path('Recipe/Node/foo/notebook.json')
INVALID_TEST_PATH_DEPTH = Path('Recipe/Node/actions/foo/foo.json')
INVALID_TEST_PATH_FILENAME = Path('Recipe/Node/actions/foo.txt')
Exemplo n.º 25
0
from nose.tools import nottest
from saucelabsfixture import (
    SauceConnectFixture,
    SSTOnDemandFixture,
    )
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from sst.actions import (
    assert_text,
    get_element,
    go_to,
    wait_for,
    )
from testtools import clone_test_with_new_id

# Nose is over-zealous.
nottest(clone_test_with_new_id)


def get_browser_names_from_env():
    """Parse the environment variable ``MAAS_TEST_BROWSERS`` to get a list of
    the browsers to use for the JavaScript tests.

    Returns ['Firefox'] if the environment variable is not present.
    """
    names = os.environ.get('MAAS_TEST_BROWSERS', 'Firefox')
    return extract_word_list(names)


# See <https://saucelabs.com/docs/ondemand/browsers/env/python/se2/linux> for
# more information on browser/platform choices.
remote_browsers = {
Exemplo n.º 26
0
   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from mock import patch

from nose.tools import assert_equal, nottest

from streamalert_cli.test.event import TestEvent
from tests.unit.streamalert_cli.test.helpers import basic_test_event_data

TestEvent = nottest(TestEvent)


class TestTestEvent:
    """Test the TestEvent class"""

    # pylint: disable=no-self-use,protected-access
    def setup(self):
        # pylint: disable=attribute-defined-outside-init
        self._default_event = TestEvent(basic_test_event_data())

    @staticmethod
    def basic_config():
        return {
            'logs': {
                'misc_log_type': {
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
from nose.tools import nottest

from openfisca_core.tools.test_runner import generate_tests

from openfisca_tunisia_pension.tests import base

nottest(generate_tests)

options_by_dir = {
    'formulas': {},
    }


def test():
    for directory, options in options_by_dir.iteritems():
        path = os.path.abspath(os.path.join(os.path.dirname(__file__), directory))

        if options.get('requires'):
            # Check if the required package was successfully imported in tests/base.py
            if getattr(base, options.get('requires')) is None:
                continue

        if not options.get('default_relative_error_margin') and not options.get('default_absolute_error_margin'):
            options['default_absolute_error_margin'] = 0.005

        reform_keys = options.get('reforms')
        tax_benefit_system = base.get_cached_composed_reform(
Exemplo n.º 28
0
from nose.tools import nottest
from saucelabsfixture import (
    SauceConnectFixture,
    SSTOnDemandFixture,
)
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from sst.actions import (
    assert_text,
    get_element,
    go_to,
    wait_for,
)
from testtools import clone_test_with_new_id

# Nose is over-zealous.
nottest(clone_test_with_new_id)


def get_browser_names_from_env():
    """Parse the environment variable ``MAAS_TEST_BROWSERS`` to get a list of
    the browsers to use for the JavaScript tests.

    Returns ['Firefox'] if the environment variable is not present.
    """
    names = os.environ.get('MAAS_TEST_BROWSERS', 'Firefox')
    return extract_word_list(names)


# See <https://saucelabs.com/docs/ondemand/browsers/env/python/se2/linux> for
# more information on browser/platform choices.
remote_browsers = {
Exemplo n.º 29
0
from nose.tools import nottest, with_setup, assert_raises

from rules.predicates import predicate
from rules.rulesets import (RuleSet, default_rules, add_rule, remove_rule,
                            rule_exists, test_rule)


test_rule = nottest(test_rule)


def reset_ruleset(ruleset):
    def fn():
        for k in list(ruleset.keys()):
            ruleset.pop(k)
    return fn


@predicate
def always_true():
    return True


@with_setup(reset_ruleset(default_rules), reset_ruleset(default_rules))
def test_shared_ruleset():
    add_rule('somerule', always_true)
    assert 'somerule' in default_rules
    assert rule_exists('somerule')
    assert test_rule('somerule')
    remove_rule('somerule')
    assert not rule_exists('somerule')
Exemplo n.º 30
0
def require_two_i2c_buses(f):
    if config['SINGLE_BUS']:
        return nottest(f)
    else:
        return f
Exemplo n.º 31
0
                                               itertools.repeat(-1, 14)))
    Tns.vns_units = [Unit(u_id, x, y, z)
                     for (u_id, x, y, z) in itertools.izip(Tns.l_id, Tns.l_x,
                                                           Tns.l_y, Tns.l_z)]


##################################################
# Testing the VisualisableNetworkStructure class #
##################################################

### template
@with_setup(setup_units)
@with_setup(setup_vns)
def test_VNS_():
    assert False
nottest(test_VNS_)
### template

@with_setup(setup_units)
@with_setup(setup_vns)
def test_VNS___eq__():
    "Equality of two VisualisableNetworkStructures."
    u1, u2 = Unit(1, 1, 2), Unit(2, 3, 2)
    V.add_population(iter(Tns.vns_units))
    V.connect_units(Tns.vns_units[0], Tns.vns_units[1], -1)
    V.connect_units(Tns.vns_units[1], Tns.vns_units[0], 0.3)
    V.add_unit(u1, "bar")
    V.add_unit(u2, "foo")
    V.connect_maps("bar", "foo")
    w = VNS()
    w.add_unit(u2, "foo")
Exemplo n.º 32
0
def phone_only(x):
  if os.path.isfile("/init.qcom.rc"):
    return x
  else:
    return nottest(x)
Exemplo n.º 33
0
# Copyright 2012-2015 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for `maasserver.testing.yui3`."""

__all__ = []

from maastesting.testcase import MAASTestCase
from maastesting.yui3 import (
    extract_tests,
    gen_failed_test_messages,
    get_failed_tests_message,
)
from nose.tools import nottest

# Nose is over-zealous.
nottest(extract_tests)
nottest(gen_failed_test_messages)
nottest(get_failed_tests_message)

# From http://yuilibrary.com/yui/docs/test/#testsuite-level-events
example_results = {
    'failed': 3,
    'ignored': 0,
    'name': 'Test Suite 0',
    'passed': 3,
    'testCase0': {
        'failed': 1,
        'ignored': 0,
        'name': 'testCase0',
        'passed': 1,
        'test0': {
Exemplo n.º 34
0
import uuid
import nose.tools
from nose.tools import assert_equals, raises, nottest
import matplotlib
matplotlib.use('agg')
from ..plotting import *
plot_train_test_curve = nottest(plot_train_test_curve)


def _create_plot_auc_cm_cr_for_multi_class():
    """Helper function to create mock datasets"""
    TRAIN_SET_SIZE = 500
    HOLD_OUT_SET_SIZE = 1000
    NUM_OF_METRICS = 100
    FEATURE_COLUMNS = ['METRIC_{}'.format(i) for i in range(NUM_OF_METRICS)]
    Xtrain = pd.DataFrame(np.random.random((TRAIN_SET_SIZE, NUM_OF_METRICS)),
                          columns=FEATURE_COLUMNS)
    Xtest = pd.DataFrame(np.random.random((HOLD_OUT_SET_SIZE, NUM_OF_METRICS)),
                         columns=FEATURE_COLUMNS)
    ytrain = [
        np.random.randint(0, len(EWS360ClassLabels))
        for num in range(TRAIN_SET_SIZE)
    ]
    ytest = [
        np.random.randint(0, len(EWS360ClassLabels))
        for num in range(HOLD_OUT_SET_SIZE)
    ]
    eval_set = [(Xtrain, ytrain), (Xtest, ytest)]
    xgb_classifier_mdl = xgboost.XGBClassifier(n_estimators=50)
    xgb_classifier_mdl.fit(Xtrain,
                           ytrain,
Exemplo n.º 35
0
def phone_only(x):
  if PC:
    return nottest(x)
  else:
    return x
Exemplo n.º 36
0
from nose.tools import nottest
from django.conf import settings
from django.db import models
from oioioi.filetracker.fields import FileField

if getattr(settings, 'TESTS', False):

    class TestFileModel(models.Model):
        file_field = FileField(upload_to='tests')

    TestFileModel = nottest(TestFileModel)
Exemplo n.º 37
0
from tqdm import tqdm
import numpy as np
from os import remove, path

from tpot import TPOTClassifier, TPOTRegressor
from tpot.export_utils import export_pipeline, generate_import_code, _indent, \
    generate_pipeline_code, get_by_name, set_param_recursive
from tpot.operator_utils import TPOTOperatorClassFactory
from tpot.config.classifier import classifier_config_dict

from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from deap import creator

from nose.tools import assert_raises, assert_equal, nottest
train_test_split = nottest(train_test_split)
test_operator_key_1 = 'sklearn.feature_selection.SelectPercentile'
test_operator_key_2 = 'sklearn.feature_selection.SelectFromModel'
TPOTSelectPercentile, TPOTSelectPercentile_args = TPOTOperatorClassFactory(
    test_operator_key_1,
    classifier_config_dict[test_operator_key_1]
)

TPOTSelectFromModel, TPOTSelectFromModel_args = TPOTOperatorClassFactory(
    test_operator_key_2,
    classifier_config_dict[test_operator_key_2]
)

digits_data = load_digits()
training_features, testing_features, training_target, testing_target = \
    train_test_split(digits_data.data.astype(np.float64), digits_data.target.astype(np.float64), random_state=42)
Exemplo n.º 38
0
 def __call__(self, function):
     function = nottest(function)
     function.teardown = self.teardown
     if getattr(function, "__available__", True):
         self.aps.append(function)
     return function
Exemplo n.º 39
0
str = None

__metaclass__ = type
__all__ = []

from maastesting.testcase import MAASTestCase
from maastesting.yui3 import (
    extract_tests,
    gen_failed_test_messages,
    get_failed_tests_message,
    )
from nose.tools import nottest

# Nose is over-zealous.
nottest(extract_tests)
nottest(gen_failed_test_messages)
nottest(get_failed_tests_message)


# From http://yuilibrary.com/yui/docs/test/#testsuite-level-events
example_results = {
    'failed': 3,
    'ignored': 0,
    'name': 'Test Suite 0',
    'passed': 3,
    'testCase0': {
        'failed': 1,
        'ignored': 0,
        'name': 'testCase0',
        'passed': 1,
Exemplo n.º 40
0
# Copyright (c) 2008-2015 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause

import logging
from datetime import datetime

from nose.tools import assert_almost_equal, eq_, nottest
from metpy.io.gini import GiniFile, GiniProjection
from metpy.cbook import get_test_data

log = logging.getLogger('metpy.io.gini')
log.setLevel(logging.ERROR)

get_test_data = nottest(get_test_data)


class TestGini(object):
    'Tests for GINI file reader'
    @staticmethod
    def basic_test():
        'Basic test of GINI reading'
        f = GiniFile(get_test_data('WEST-CONUS_4km_WV_20151208_2200.gini'))
        pdb = f.prod_desc
        eq_(pdb.source, 1)
        eq_(pdb.creating_entity, 'GOES-15')
        eq_(pdb.sector_id, 'West CONUS')
        eq_(pdb.channel, 'WV (6.5/6.7 micron)')
        eq_(pdb.num_records, 1280)
        eq_(pdb.record_len, 1100)
        eq_(pdb.datetime, datetime(2015, 12, 8, 22, 0, 19, 0))
Exemplo n.º 41
0
def phone_only(x):
    if ANDROID:
        return x
    else:
        return nottest(x)
Exemplo n.º 42
0
 def _nottest_unless(f):
     if criteria:
         return f
     return nottest(f)
Exemplo n.º 43
0
from nose.tools import nottest
from selenium import webdriver

def test_baidu_should_return_training_as_first_result_if_you_search_selenium():

    driver = webdriver.Firefox()

    driver.get("http://www.baidu.com")

    element = driver.find_element_by_id("kw")

    element.send_keys("selenium")

    button = driver.find_element_by_css_selector("input#su")

    button.click()

    driver.implicitly_wait(30)

    driver.save_screenshot("result.png")

    driver.quit()

nottest(test_baidu_should_return_training_as_first_result_if_you_search_selenium)
Exemplo n.º 44
0
 def _nottest_if(f):
     if not criteria:
         return f
     return nottest(f)
Exemplo n.º 45
0
try:
    import unittest2 as unittest
except ImportError:
    import unittest

from wsgiref.simple_server import make_server

from nose.tools import nottest
from wsgiref.util import setup_testing_defaults
setup_testing_defaults = nottest(setup_testing_defaults)

from iscool_e.pynba.middleware import PynbaMiddleware
from iscool_e.pynba.globals import pynba
from iscool_e.pynba import monitor

class MiddlewareTestCase(unittest.TestCase):
    def test_context(self):
        def app(environ, start_response):
            with pynba.timer(foo="bar") as timer:
                status = '200 OK'
                headers = [('Content-type', 'text/plain')]
                start_response(status, headers)

            return ['foo', 'bar']

        middleware = PynbaMiddleware(app, ('127.0.0.1', 5000))
        self.call_as_wsgi(middleware)

    def call_as_wsgi(self, callable, environ=None, close=True):
        """Invoke callable via WSGI, returning status, headers, response."""
        if environ is None:
Exemplo n.º 46
0
from nose.tools import nottest
from django.conf import settings
from django.db import models
from oioioi.filetracker.fields import FileField

if getattr(settings, 'TESTS', False):
    class TestFileModel(models.Model):
        file_field = FileField(upload_to='tests')
    TestFileModel = nottest(TestFileModel)