Example #1
0
 def test_slope_inter(self):
     hdr = self.header_class()
     assert_equal(hdr.get_slope_inter(), (1.0, None))
     for in_tup, exp_err, out_tup, raw_slope in (
         ((2.0,), None, (2.0, None), 2.),
         ((None,), None, (None, None), np.nan),
         ((1.0, None), None, (1.0, None), 1.),
         # non zero intercept causes error
         ((None, 1.1), HeaderTypeError, (None, None), np.nan),
         ((2.0, 1.1), HeaderTypeError, (None, None), 2.),
         # null scalings
         ((0.0, None), HeaderDataError, (None, None), 0.),
         ((np.nan, np.nan), None, (None, None), np.nan),
         ((np.nan, None), None, (None, None), np.nan),
         ((None, np.nan), None, (None, None), np.nan),
         ((np.inf, None), HeaderDataError, (None, None), np.inf),
         ((-np.inf, None), HeaderDataError, (None, None), -np.inf),
         ((None, 0.0), None, (None, None), np.nan)):
         hdr = self.header_class()
         if not exp_err is None:
             assert_raises(exp_err, hdr.set_slope_inter, *in_tup)
             # raw set
             if not in_tup[0] is None:
                 hdr['scl_slope'] = in_tup[0]
         else:
             hdr.set_slope_inter(*in_tup)
             assert_equal(hdr.get_slope_inter(), out_tup)
             # Check set survives through checking
             hdr = Spm99AnalyzeHeader.from_header(hdr, check=True)
             assert_equal(hdr.get_slope_inter(), out_tup)
         assert_array_equal(hdr['scl_slope'], raw_slope)
Example #2
0
def test_invalid_format():
    blosc_args = BloscArgs()
    with create_tmp_files() as (tdir, in_file, out_file, dcmp_file):
        create_array(1, in_file)
        pack_file(in_file, out_file, blosc_args=blosc_args)
        nt.assert_raises(FormatVersionMismatch,
                         unpack_file, out_file, dcmp_file)
Example #3
0
def test_append_diag():
    # Routine for appending diagonal elements
    assert_array_equal(append_diag(np.diag([2,3,1]), [1]),
                       np.diag([2,3,1,1]))
    assert_array_equal(append_diag(np.diag([2,3,1]), [1,1]),
                       np.diag([2,3,1,1,1]))
    aff = np.array([[2,0,0],
                    [0,3,0],
                    [0,0,1],
                    [0,0,1]])
    assert_array_equal(append_diag(aff, [5], [9]),
                       [[2,0,0,0],
                        [0,3,0,0],
                        [0,0,0,1],
                        [0,0,5,9],
                        [0,0,0,1]])
    assert_array_equal(append_diag(aff, [5,6], [9,10]),
                       [[2,0,0,0,0],
                        [0,3,0,0,0],
                        [0,0,0,0,1],
                        [0,0,5,0,9],
                        [0,0,0,6,10],
                        [0,0,0,0,1]])
    aff = np.array([[2,0,0,0],
                    [0,3,0,0],
                    [0,0,0,1]])
    assert_array_equal(append_diag(aff, [5], [9]),
                       [[2,0,0,0,0],
                        [0,3,0,0,0],
                        [0,0,0,5,9],
                        [0,0,0,0,1]])
    # Length of starts has to match length of steps
    assert_raises(ValueError, append_diag, aff, [5,6], [9])
Example #4
0
    def test_fatal_failure(self, espy_mock):
        """Test an index attempt that fails catastrophically.
        """

        # It's mocks all the way down.
        sub_mock = mock.MagicMock()
        espy_mock.Elasticsearch.return_value = sub_mock

        es_storage = ESCrashStorage(config=self.config)

        crash_id = a_processed_crash['uuid']

        # Oh the humanity!
        failure_exception = Exception('horrors')
        sub_mock.index.side_effect = failure_exception

        # Submit a crash and ensure that it failed.
        assert_raises(
            Exception,
            es_storage.save_raw_and_processed,
            a_raw_crash,
            None,
            a_processed_crash,
            crash_id
        )
Example #5
0
def test_check_enum():
    from vispy.gloo import gl
    
    # Test enums
    assert util.check_enum(gl.GL_RGB) == 'rgb' 
    assert util.check_enum(gl.GL_TRIANGLE_STRIP) == 'triangle_strip' 
    
    # Test strings
    assert util.check_enum('RGB') == 'rgb' 
    assert util.check_enum('Triangle_STRIp') == 'triangle_strip' 
    
    # Test wrong input
    assert_raises(ValueError, util.check_enum, int(gl.GL_RGB))
    assert_raises(ValueError, util.check_enum, int(gl.GL_TRIANGLE_STRIP))
    assert_raises(ValueError, util.check_enum, [])
    
    # Test with test
    util.check_enum('RGB', 'test', ('rgb', 'alpha')) == 'rgb' 
    util.check_enum(gl.GL_ALPHA, 'test', ('rgb', 'alpha')) == 'alpha' 
    #
    assert_raises(ValueError, util.check_enum, 'RGB', 'test', ('a', 'b'))
    assert_raises(ValueError, util.check_enum, gl.GL_ALPHA, 'test', ('a', 'b'))
    
    # Test PyOpenGL enums
    try:
        from OpenGL import GL
    except ImportError:
        return  # we cannot test PyOpenGL
    #
    assert util.check_enum(GL.GL_RGB) == 'rgb' 
    assert util.check_enum(GL.GL_TRIANGLE_STRIP) == 'triangle_strip' 
Example #6
0
    def test_anonymous_user_cannot_read_webhook(self):
        """Test anonymous users cannot read a webhook"""

        project = ProjectFactory.create()
        webhook = WebhookFactory.create(project_id=project.id)

        assert_raises(Unauthorized, ensure_authorized_to, 'read', webhook)
Example #7
0
 def test_mail_user_without_email(self):
     # send email
     test_email = {'recipient': model.User.by_name(u'mary'),
                   'subject': 'Meeting',
                   'body': 'The meeting is cancelled.',
                   'headers': {'header1': 'value1'}}
     assert_raises(mailer.MailerException, mailer.mail_user, **test_email)
Example #8
0
def test_UniformTime_preserves_uniformity():
    "Uniformity: allow ops which keep it, and deny those which break it"
    utime = ts.UniformTime(t0=0, length=10, sampling_rate=1)

    def assign_to_one_element_of(t):
        t[0] = 42

    nt.assert_raises(ValueError, assign_to_one_element_of, utime)

    # same as utime, but starting 10s later
    utime10 = ts.UniformTime(t0=10, length=10, sampling_rate=1)
    utime += 10  # constants treated as having same units as utime
    npt.assert_equal(utime, utime10)

    # same as utime, but with a lower sampling rate
    utime_2 = ts.UniformTime(t0=10, length=10, sampling_interval=2)
    utime += np.arange(10)  # make utime match utime_2
    npt.assert_equal(utime, utime_2)
    npt.assert_equal(utime.sampling_interval, utime_2.sampling_interval)

    utime = ts.UniformTime(t0=5, length=10, sampling_rate=1)
    utime *= 2  # alternative way to make utime match utime_2
    npt.assert_equal(utime.sampling_interval, utime_2.sampling_interval)
    npt.assert_equal(utime.sampling_rate, utime_2.sampling_rate)

    nonuniform = np.concatenate((list(range(2)), list(range(3)), list(range(5))))

    def iadd_nonuniform(t):
        t += nonuniform

    nt.assert_raises(ValueError, iadd_nonuniform, utime)
Example #9
0
def test_check_symmetric():
    arr_sym = np.array([[0, 1], [1, 2]])
    arr_bad = np.ones(2)
    arr_asym = np.array([[0, 2], [0, 2]])

    test_arrays = {'dense': arr_asym,
                   'dok': sp.dok_matrix(arr_asym),
                   'csr': sp.csr_matrix(arr_asym),
                   'csc': sp.csc_matrix(arr_asym),
                   'coo': sp.coo_matrix(arr_asym),
                   'lil': sp.lil_matrix(arr_asym),
                   'bsr': sp.bsr_matrix(arr_asym)}

    # check error for bad inputs
    assert_raises(ValueError, check_symmetric, arr_bad)

    # check that asymmetric arrays are properly symmetrized
    for arr_format, arr in test_arrays.items():
        # Check for warnings and errors
        assert_warns(UserWarning, check_symmetric, arr)
        assert_raises(ValueError, check_symmetric, arr, raise_exception=True)

        output = check_symmetric(arr, raise_warning=False)
        if sp.issparse(output):
            assert_equal(output.format, arr_format)
            assert_array_equal(output.toarray(), arr_sym)
        else:
            assert_array_equal(output, arr_sym)
Example #10
0
 def test_assert_greater():
     # Check that the nose implementation of assert_less gives the
     # same thing as the scikit's
     assert_greater(1, 0)
     _assert_greater(1, 0)
     assert_raises(AssertionError, assert_greater, 0, 1)
     assert_raises(AssertionError, _assert_greater, 0, 1)
Example #11
0
def test_readonly_path():
    path = Path.unit_circle()

    def modify_vertices():
        path.vertices = path.vertices * 2.0

    assert_raises(AttributeError, modify_vertices)
Example #12
0
def test_import_class():
    assert_raises(ImproperlyConfigured, import_class,
                  'rapidsms.tests.router.test_base.BadClassName')
    assert_raises(ImproperlyConfigured, import_class,
                  'rapidsms.tests.router.bad_module.MockRouter')
    assert_equals(import_class('rapidsms.tests.router.test_base.MockRouter'),
                  MockRouter)
Example #13
0
def test_get_test_router():
    with setting(TEST_RAPIDSMS_ROUTER='rapidsms.tests.router.test_base.BadClassName'):
        assert_raises(ImproperlyConfigured, get_test_router)
    with setting(TEST_RAPIDSMS_ROUTER='rapidsms.tests.router.bad_module.MockRouter'):
        assert_raises(ImproperlyConfigured, get_test_router)
    with setting(TEST_RAPIDSMS_ROUTER='rapidsms.tests.router.test_base.MockRouter'):
        assert_equals(get_test_router(), MockRouter)
Example #14
0
 def test_quality_as_ep(self):
     """SeriesParser: test that qualities are not picked as ep"""
     from flexget.utils import qualities
     for quality in qualities.all_components():
         s = SeriesParser(name='FooBar')
         s.data = 'FooBar %s XviD-FlexGet' % quality.name
         assert_raises(ParseWarning, s.parse)
Example #15
0
 def test_sound_as_ep(self):
     """SeriesParser: test that sound infos are not picked as ep"""
     for sound in SeriesParser.sounds:
         s = SeriesParser()
         s.name = 'FooBar'
         s.data = 'FooBar %s XViD-FlexGet' % sound
         assert_raises(ParseWarning, s.parse)
def test_exc_symbolic():
    def symbolic(exec_backward=True):
        x = mx.sym.Variable('x')
        y = mx.sym.Variable('y')
        z = mx.sym.Variable('z')
        x_shape = (2, 2)
        z_shape = (3, 2)
        inputs = [x, y]
        out = mx.symbol.ElementWiseSum(*inputs, name="esum")
        out = mx.sym.dot(z, out)
        out2 = mx.sym.random.normal(0, -1, x_shape, ctx=default_context())
        out = mx.sym.dot(out, out2)
        out = mx.sym.make_loss(out)
        arr = {'x': mx.nd.random.normal(0, 1, x_shape, ctx=default_context()),
               'y': mx.nd.random.normal(0, 1, x_shape, ctx=default_context()),
               'z': mx.nd.random.normal(0, 1, z_shape, ctx=default_context())}
        arr_grad = {'x': mx.nd.empty(x_shape), 'y': mx.nd.empty(x_shape), 'z': mx.nd.empty(z_shape)}
        exec1 = out.bind(ctx=default_context(), args=arr, args_grad=arr_grad)
        outputs = exec1.forward()
        if exec_backward:
            exec1.backward()
            exec1.grad_arrays[0].asnumpy()
        else:
            outputs[0].asnumpy()

    assert_raises(MXNetError, symbolic, False)
    assert_raises(MXNetError, symbolic, True)
Example #17
0
def test_fail_fetch_haxby_simple():
    # Test a dataset fetching failure to validate sandboxing
    local_url = "file://" + os.path.join(datadir, "pymvpa-exampledata.tar.bz2")
    datasetdir = os.path.join(tmpdir, 'haxby2001_simple', 'pymvpa-exampledata')
    os.makedirs(datasetdir)
    # Create a dummy file. If sandboxing is successful, it won't be overwritten
    dummy = open(os.path.join(datasetdir, 'attributes.txt'), 'w')
    dummy.write('stuff')
    dummy.close()

    path = 'pymvpa-exampledata'

    opts = {'uncompress': True}
    files = [
        (os.path.join(path, 'attributes.txt'), local_url, opts),
        # The following file does not exists. It will cause an abortion of
        # the fetching procedure
        (os.path.join(path, 'bald.nii.gz'), local_url, opts)
    ]

    assert_raises(IOError, utils._fetch_files,
                  os.path.join(tmpdir, 'haxby2001_simple'), files,
                  verbose=0)
    dummy = open(os.path.join(datasetdir, 'attributes.txt'), 'r')
    stuff = dummy.read(5)
    dummy.close()
    assert_equal(stuff, 'stuff')
Example #18
0
def test_remove_invalid():
    """
    Remove_invalid() removes invalid lines, track lines, and comments
    """
    a = pybedtools.BedTool("""
    chr1 100 200
    chr1 100 90
    track name='try to break parser'
    chr1 100 200
    chr1 100 200
    chr1 100 200
    #
    chr1 100 200
    """, from_string=True)

    b = a.remove_invalid()

    cleaned = pybedtools.BedTool("""
    chr1 100 200
    chr1 100 200
    chr1 100 200
    chr1 100 200
    chr1 100 200""", from_string=True)

    assert_raises(NotImplementedError, b.__eq__, cleaned)
    assert str(b) == str(cleaned)
Example #19
0
def test_history_step():
    a = pybedtools.example_bedtool('a.bed')
    b = pybedtools.example_bedtool('b.bed')
    c = a.intersect(b)
    d = c.subtract(a)

    tag = c.history[0].result_tag
    assert pybedtools.find_tagged(tag) == c

    assert_raises(ValueError, pybedtools.find_tagged, 'nonexistent')


    print d.history
    d.delete_temporary_history(ask=True, raw_input_func=lambda x: 'n')
    assert os.path.exists(a.fn)
    assert os.path.exists(b.fn)
    assert os.path.exists(c.fn)
    assert os.path.exists(d.fn)

    d.delete_temporary_history(ask=True, raw_input_func=lambda x: 'Yes')
    assert os.path.exists(a.fn)
    assert os.path.exists(b.fn)
    assert not os.path.exists(c.fn) # this is the only thing that should change
    assert os.path.exists(d.fn)

    a = pybedtools.example_bedtool('a.bed')
    b = pybedtools.example_bedtool('b.bed')
    c = a.intersect(b)
    d = c.subtract(a)
    d.delete_temporary_history(ask=False)
    assert os.path.exists(a.fn)
    assert os.path.exists(b.fn)
    assert not os.path.exists(c.fn) # this is the only thing that should change
    assert os.path.exists(d.fn)
Example #20
0
def _test_corr(old_func, new_func, sel_item):
    from nose.tools import assert_equal, assert_raises
    n_obs = 20
    n_dims = 10
    np.random.seed(0)
    y = np.random.rand(n_obs) * n_obs
    X = np.tile(y, [n_dims, 1]).T + np.random.randn(n_obs, n_dims)
    rho_fast = new_func(X, y)
    # test dimensionality
    assert_equal(rho_fast.ndim, 1)
    assert_equal(rho_fast.shape[0], n_dims)
    # test data
    rho_slow = np.ones(n_dims)
    for dim in range(n_dims):
        rho_slow[dim] = np.array(old_func(X[:, dim], y)).item(sel_item)
    np.testing.assert_array_equal(rho_fast.shape, rho_slow.shape)
    np.testing.assert_array_almost_equal(rho_fast, rho_slow)
    # test errors
    new_func(np.squeeze(X[:, 0]), y)
    assert_raises(ValueError, new_func, y, X)
    assert_raises(ValueError, new_func, X, y[1:])
    # test dtype
    X = np.argsort(X, axis=0) * 2  # ensure no bug at normalization
    y = np.argsort(y, axis=0) * 2
    rho_fast = new_func(X, y, dtype=int)
    rho_slow = np.ones(n_dims)
    for dim in range(n_dims):
        rho_slow[dim] = np.array(old_func(X[:, dim], y)).item(sel_item)
    np.testing.assert_array_almost_equal(rho_fast, rho_slow)
Example #21
0
    def test_otherException(self, mock_os_makedirs):
        mock_os_makedirs.side_effect = RuntimeError("Some other exception")

        dir_path = 'something'
        ntools.assert_raises(RuntimeError, file_utils.safe_create_dir, dir_path)

        mock_os_makedirs.assert_called_once_with(os.path.abspath(dir_path))
Example #22
0
def test_SVR():
    """
    Test Support Vector Regression
    """

    clf = svm.SVR(kernel='linear')
    clf.fit(X, Y)
    pred = clf.predict(T)

    assert_array_almost_equal(clf.dual_coef_, [[-0.1, 0.1]])
    assert_array_almost_equal(clf.coef_, [[0.2, 0.2]])
    assert_array_almost_equal(clf.support_vectors_, [[-1, -1], [1, 1]])
    assert_array_equal(clf.support_, [1, 3])
    assert_array_almost_equal(clf.intercept_, [1.5])
    assert_array_almost_equal(pred, [1.1, 2.3, 2.5])

    # the same with kernel='rbf'
    clf = svm.SVR(kernel='rbf')
    clf.fit(X, Y)
    pred = clf.predict(T)

    assert_array_almost_equal(clf.dual_coef_,
                              [[-0.014, -0.515, -0.013, 0.515, 0.013, 0.013]],
                              decimal=3)
    assert_raises(NotImplementedError, lambda: clf.coef_)
    assert_array_almost_equal(clf.support_vectors_, X)
    assert_array_almost_equal(clf.intercept_, [1.49997261])
    assert_array_almost_equal(pred, [1.10001274, 1.86682485, 1.73300377])
Example #23
0
def test_mail_response_attachments():
    sample = mail.MailResponse(
        To="receiver@localhost",
        Subject="Test message",
        From="sender@localhost",
        Body="Test from test_mail_response_attachments.",
    )
    readme_data = open("./README.md").read()

    assert_raises(AssertionError, sample.attach, data=readme_data, disposition="inline")

    sample.attach(filename="./README.md", content_type="text/plain", disposition="inline")
    assert len(sample.attachments) == 1
    assert sample.multipart

    msg = sample.to_message()
    assert_equal(len(msg.get_payload()), 2)

    sample.clear()
    assert len(sample.attachments) == 0
    assert not sample.multipart

    sample.attach(data=readme_data, filename="./README.md", content_type="text/plain")

    msg = sample.to_message()
    assert_equal(len(msg.get_payload()), 2)
    sample.clear()

    sample.attach(data=readme_data, content_type="text/plain")
    msg = sample.to_message()
    assert_equal(len(msg.get_payload()), 2)

    return sample
Example #24
0
 def test_with_raw_input_but_empty(self, mocked_raw_input):
     cmd = makesuperuser.Command()
     assert_raises(
         CommandError,
         cmd.handle,
         emailaddress=[]
     )
Example #25
0
 def test_several_fields_illogically_integerfield(self):
     field = form_fields.IntegerField()
     assert_raises(
         ValidationError,
         field.clean,
         ['>10', '<10']
     )
     assert_raises(
         ValidationError,
         field.clean,
         ['<10', '>10']
     )
     assert_raises(
         ValidationError,
         field.clean,
         ['<10', '>=10']
     )
     assert_raises(
         ValidationError,
         field.clean,
         ['<=10', '>10']
     )
     assert_raises(
         ValidationError,
         field.clean,
         ['<10', '<10']
     )
Example #26
0
 def test_key_error(self):
     """KeyError is raised if a config value doesn't exist.
     """
     with Flask(__name__).test_request_context():
         assert_raises(KeyError, self.env.config.__getitem__, 'YADDAYADDA')
         # The get() helper, on the other hand, simply returns None
         assert self.env.config.get('YADDAYADDA') == None
Example #27
0
def test_make_dig_points():
    """Test application of Polhemus HSP to info"""
    dig_points = _read_dig_points(hsp_fname)
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(dig_points=dig_points)
    assert_true(info['dig'])
    assert_array_equal(info['dig'][0]['r'], [-106.93, 99.80, 68.81])

    dig_points = _read_dig_points(elp_fname)
    nasion, lpa, rpa = dig_points[:3]
    info = create_info(ch_names=['Test Ch'], sfreq=1000., ch_types=None)
    assert_false(info['dig'])

    info['dig'] = _make_dig_points(nasion, lpa, rpa, dig_points[3:], None)
    assert_true(info['dig'])
    idx = [d['ident'] for d in info['dig']].index(FIFF.FIFFV_POINT_NASION)
    assert_array_equal(info['dig'][idx]['r'],
                       np.array([1.3930, 13.1613, -4.6967]))
    assert_raises(ValueError, _make_dig_points, nasion[:2])
    assert_raises(ValueError, _make_dig_points, None, lpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, rpa[:2])
    assert_raises(ValueError, _make_dig_points, None, None, None,
                  dig_points[:, :2])
    assert_raises(ValueError, _make_dig_points, None, None, None, None,
                  dig_points[:, :2])
Example #28
0
def test_hll_change_error_rate():
    hllcpp = khmer.HLLCounter(0.0040625, K)
    assert hllcpp.error_rate == 0.0040625

    # error rate is discrete, what we test here is if an error rate of 1%
    # rounds to the appropriate value
    hllcpp.error_rate = 0.01
    assert hllcpp.error_rate == 0.008125

    with assert_raises(TypeError):
        del hllcpp.error_rate

    with assert_raises(TypeError):
        hllcpp.error_rate = 5

    with assert_raises(ValueError):
        hllcpp.error_rate = 2.5

    with assert_raises(ValueError):
        hllcpp.error_rate = -10.

    # error rate can only be changed prior to first counting,
    hllcpp.consume_string('AAACCACTTGTGCATGTCAGTGCAGTCAGT')
    with assert_raises(AttributeError):
        hllcpp.error_rate = 0.3
Example #29
0
    def test_fatal_operational_exception(self, espy_mock):
        """Test an index attempt that experiences a operational exception that
        it can't recover from.
        """

        # It's mocks all the way down.
        sub_mock = mock.MagicMock()
        espy_mock.Elasticsearch.return_value = sub_mock

        # ESCrashStorage uses the "limited backoff" transaction executor.
        # In real life this will retry operational exceptions over time, but
        # in unit tests, we just want it to hurry up and fail.
        backoff_config = self.config
        backoff_config['backoff_delays'] = [0, 0, 0]
        backoff_config['wait_log_interval'] = 0

        es_storage = ESCrashStorage(config=self.config)

        crash_id = a_processed_crash['uuid']

        # It's bad but at least we expected it.
        failure_exception = elasticsearch.exceptions.ConnectionError
        sub_mock.index.side_effect = failure_exception

        # Submit a crash and ensure that it failed.
        assert_raises(
            elasticsearch.exceptions.ConnectionError,
            es_storage.save_raw_and_processed,
            a_raw_crash,
            None,
            a_processed_crash,
            crash_id
        )
def test_choices_functions():
    # When an id is repeated, the last value is assumed
    choices = model_helpers.Choices([
        ("choice1", 1),
        ("choice_xx", {"id": 3, "display": "xxx"}),
        ("choice2", {"id": 2, "extra_key": "extra_value"}),
        ("choice3", {"id": 3, "display": "A_Choice_3"}),
    ], order_by=None)

    tools.assert_equal(choices["choice1"], {"id": 1, "display": "Choice1"})
    tools.assert_equal(choices["choice2"], {"id": 2, "display": "Choice2", "extra_key": "extra_value"})
    tools.assert_equal(choices["choice3"], {"id": 3, "display": "A_Choice_3"})

    tools.assert_equal(choices.choice1, 1)
    tools.assert_equal(choices.choice2, 2)
    tools.assert_equal(choices.choice3, 3)

    tools.assert_equal(choices.get_display_name(1), "Choice1")
    tools.assert_equal(choices.get_display_name(2), "Choice2")
    tools.assert_equal(choices.get_display_name(3), "A_Choice_3")

    tools.assert_equal(choices.get_code_name(1), "choice1")
    tools.assert_equal(choices.get_code_name(2), "choice2")
    tools.assert_equal(choices.get_code_name(3), "choice3")

    tools.assert_equal(choices.get_value(2, "extra_key"), "extra_value")
    tools.assert_raises(KeyError, choices.get_value, choice_id=1, choice_key="extra_key")
    tools.assert_equal(choices.get_value(1, "extra_key", raise_exception=False), None)
def test_bad_describe_stack():
    cf_conn = boto3.client('cloudformation', region_name='us-east-1')
    with assert_raises(ClientError):
        cf_conn.describe_stacks(StackName="non_existent_stack")
Example #32
0
def test_concat_fail():
    a = cycler('a', range(3))
    b = cycler('b', range(3))
    assert_raises(ValueError, concat, a, b)
    assert_raises(ValueError, a.concat, b)
Example #33
0
def test_cycler_exceptions():
    assert_raises(TypeError, cycler)
    assert_raises(TypeError, cycler, 'c', 'rgb', lw=range(3))
    assert_raises(TypeError, cycler, 'c')
    assert_raises(TypeError, cycler, 'c', 'rgb', 'lw', range(3))
Example #34
0
def test_fail_getime():
    c1 = cycler(lw=range(15))
    assert_raises(ValueError, Cycler.__getitem__, c1, 0)
    assert_raises(ValueError, Cycler.__getitem__, c1, [0, 1])
Example #35
0
def test_mul_fails():
    c1 = cycler(c='rgb')
    assert_raises(TypeError, mul, c1, 2.0)
    assert_raises(TypeError, mul, c1, 'a')
    assert_raises(TypeError, mul, c1, [])
Example #36
0
def test_instance_with_nic_attach_detach():
    conn = boto.connect_vpc('the_key', 'the_secret')
    vpc = conn.create_vpc("10.0.0.0/16")
    subnet = conn.create_subnet(vpc.id, "10.0.0.0/18")

    security_group1 = conn.create_security_group(
        'test security group #1', 'this is a test security group')
    security_group2 = conn.create_security_group(
        'test security group #2', 'this is a test security group')

    reservation = conn.run_instances('ami-1234abcd',
                                     security_group_ids=[security_group1.id])
    instance = reservation.instances[0]

    eni = conn.create_network_interface(subnet.id, groups=[security_group2.id])

    # Check initial instance and ENI data
    instance.interfaces.should.have.length_of(1)

    eni.groups.should.have.length_of(1)
    set([group.id
         for group in eni.groups]).should.equal(set([security_group2.id]))

    # Attach
    with assert_raises(EC2ResponseError) as ex:
        conn.attach_network_interface(eni.id,
                                      instance.id,
                                      device_index=1,
                                      dry_run=True)
    ex.exception.error_code.should.equal('DryRunOperation')
    ex.exception.status.should.equal(400)
    ex.exception.message.should.equal(
        'An error occurred (DryRunOperation) when calling the AttachNetworkInterface operation: Request would have succeeded, but DryRun flag is set'
    )

    conn.attach_network_interface(eni.id, instance.id, device_index=1)

    # Check attached instance and ENI data
    instance.update()
    instance.interfaces.should.have.length_of(2)
    instance_eni = instance.interfaces[1]
    instance_eni.id.should.equal(eni.id)
    instance_eni.groups.should.have.length_of(2)
    set([group.id for group in instance_eni.groups
         ]).should.equal(set([security_group1.id, security_group2.id]))

    eni = conn.get_all_network_interfaces(
        filters={'network-interface-id': eni.id})[0]
    eni.groups.should.have.length_of(2)
    set([group.id for group in eni.groups
         ]).should.equal(set([security_group1.id, security_group2.id]))

    # Detach
    with assert_raises(EC2ResponseError) as ex:
        conn.detach_network_interface(instance_eni.attachment.id, dry_run=True)
    ex.exception.error_code.should.equal('DryRunOperation')
    ex.exception.status.should.equal(400)
    ex.exception.message.should.equal(
        'An error occurred (DryRunOperation) when calling the DetachNetworkInterface operation: Request would have succeeded, but DryRun flag is set'
    )

    conn.detach_network_interface(instance_eni.attachment.id)

    # Check detached instance and ENI data
    instance.update()
    instance.interfaces.should.have.length_of(1)

    eni = conn.get_all_network_interfaces(
        filters={'network-interface-id': eni.id})[0]
    eni.groups.should.have.length_of(1)
    set([group.id
         for group in eni.groups]).should.equal(set([security_group2.id]))

    # Detach with invalid attachment ID
    with assert_raises(EC2ResponseError) as cm:
        conn.detach_network_interface('eni-attach-1234abcd')
    cm.exception.code.should.equal('InvalidAttachmentID.NotFound')
    cm.exception.status.should.equal(400)
    cm.exception.request_id.should_not.be.none
Example #37
0
 def test_with_password_raises_ValueError_when_there_is_no_username(self):
     url = URLObject('https://github.com/')
     assert_raises(ValueError, lambda: url.with_password('1234'))
Example #38
0
def test_invalid_observable():
    assert_raises(InvalidReactionPatternException,
                  Observable, 'o1', 'invalid_pattern')
    assert len(model.observables) == 0
Example #39
0
def test_invalid_parameter():
    assert_raises(ValueError, Parameter, 'a', 'invalid_value')
    assert len(model.parameters) == 0
Example #40
0
def test_model_not_defined():
    assert_raises(ModelNotDefinedError, Monomer, 'A')
Example #41
0
def test_invalid_expression():
    assert_raises(ValueError, Expression, 'e1', 'invalid_expr')
    assert len(model.expressions) == 0
Example #42
0
def test_invalid_compartment():
    assert_raises(Exception, Compartment, 'c1', 'invalid_parent')
    assert len(model.compartments) == 0
Example #43
0
def test_invalid_state_value():
    assert_raises(ValueError, Monomer, 'A', ['a'], {'a': ['1', 'a']})
Example #44
0
def test_invalid_monomer_name():
    assert_raises(ValueError, Monomer, 'a', 123)
    assert len(model.monomers) == 0
Example #45
0
def test_dangling_bond():
    Monomer('A', ['a'])
    Parameter('kf', 1.0)
    assert_raises(DanglingBondError, as_reaction_pattern, A(a=1) % A(a=None))
Example #46
0
def test_expression_type():
    assert_raises(ValueError, Expression, 'A', 1)
Example #47
0
def test_duplicate_monomer_error():
    A = Monomer('A', ['a'])
    assert_raises(DuplicateMonomerError, (A(a=1) % A(a=1)), a=2)
Example #48
0
def test_invalid_site_name():
    assert_raises(ValueError, Monomer, 'A', ['1'])
Example #49
0
def test_compile_failures():
    ss = ['((C)', '())(', '=x', '!!', '&', '=2%()']
    for s in ss:
        with assert_raises(ValueError):
            fn = atsel_compile(s)
Example #50
0
def test_component_names_invalid():
    for name in 'a!', '!B', 'A!bC~`\\', '_!', '_!7', '__a01b  999x_x___!':
        assert_raises(InvalidComponentNameError, Component, name, _export=False)
def test_normalize_errors():
    """Check that invalid arguments yield ValueError"""
    assert_raises(ValueError, normalize, [[0]], axis=2)
    assert_raises(ValueError, normalize, [[0]], norm='l3')
Example #52
0
def test_invalid_state():
    Monomer('A', ['a', 'b'], {'a': ['a1', 'a2'], 'b': ['b1']})
    # Specify invalid state in Monomer.__call__
    assert_raises(ValueError, A, a='spam')
    # Specify invalid state in MonomerPattern.__call__
    assert_raises(ValueError, A(a='a1'), b='spam')
Example #53
0
def test_register_role_too_high():
    assert_raises(AAAException, aaa.register, 'foo', 'pwd', '[email protected]', role='admin')
def test_label_encoder_errors():
    """Check that invalid arguments yield ValueError"""
    le = LabelEncoder()
    assert_raises(ValueError, le.transform, [])
    assert_raises(ValueError, le.inverse_transform, [])
Example #55
0
def test_register_already_existing():
    assert_raises(AAAException, aaa.register, 'admin', 'pwd', '[email protected]')
Example #56
0
def test_validate_registration_no_code():
    assert_raises(AAAException, aaa.validate_registration, 'not_a_valid_code')
Example #57
0
def test_register_no_pwd():
    assert_raises(AssertionError, aaa.register, 'foo', None, '[email protected]')
Example #58
0
def test_register_no_role():
    assert_raises(AAAException, aaa.register, 'foo', 'pwd', '[email protected]', role='clown')
Example #59
0
def test_register_no_user():
    assert_raises(AssertionError, aaa.register, None, 'pwd', '[email protected]')
Example #60
0
def test_register_no_email():
    assert_raises(AssertionError, aaa.register, 'foo', 'pwd', None)