• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python tools.assert_raises函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nose.tools.assert_raises函数的典型用法代码示例。如果您正苦于以下问题:Python assert_raises函数的具体用法?Python assert_raises怎么用?Python assert_raises使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了assert_raises函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_fatal_failure

    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
        )
开发者ID:ahlfors,项目名称:socorro,代码行数:25,代码来源:test_crashstorage.py


示例2: test_mail_user_without_email

 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)
开发者ID:MrkGrgsn,项目名称:ckan,代码行数:7,代码来源:test_mailer.py


示例3: test_check_enum

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' 
开发者ID:Peque,项目名称:vispy,代码行数:31,代码来源:test_util.py


示例4: test_readonly_path

def test_readonly_path():
    path = Path.unit_circle()

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

    assert_raises(AttributeError, modify_vertices)
开发者ID:aseagram,项目名称:matplotlib,代码行数:7,代码来源:test_path.py


示例5: test_check_symmetric

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)
开发者ID:Afey,项目名称:scikit-learn,代码行数:28,代码来源:test_validation.py


示例6: test_sound_as_ep

 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)
开发者ID:Doppia,项目名称:Flexget,代码行数:7,代码来源:test_seriesparser.py


示例7: test_get_test_router

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)
开发者ID:cheekybastard,项目名称:rapidsms,代码行数:7,代码来源:test_base.py


示例8: test_mail_response_attachments

def test_mail_response_attachments():
    sample = mail.MailResponse(
        To="[email protected]",
        Subject="Test message",
        From="[email protected]",
        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
开发者ID:secretario,项目名称:salmon,代码行数:33,代码来源:message_tests.py


示例9: test_hll_change_error_rate

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
开发者ID:gsc0107,项目名称:khmer,代码行数:25,代码来源:test_hll.py


示例10: test_with_raw_input_but_empty

 def test_with_raw_input_but_empty(self, mocked_raw_input):
     cmd = makesuperuser.Command()
     assert_raises(
         CommandError,
         cmd.handle,
         emailaddress=[]
     )
开发者ID:adngdb,项目名称:socorro,代码行数:7,代码来源:test_makesuperuser.py


示例11: test_several_fields_illogically_integerfield

 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']
     )
开发者ID:adngdb,项目名称:socorro,代码行数:27,代码来源:test_form_fields.py


示例12: test_make_dig_points

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])
开发者ID:esdalmaijer,项目名称:mne-python,代码行数:27,代码来源:test_meas_info.py


示例13: test_key_error

 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
开发者ID:adamchainz,项目名称:flask-assets,代码行数:7,代码来源:test_config.py


示例14: test_fatal_operational_exception

    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
        )
开发者ID:ahlfors,项目名称:socorro,代码行数:33,代码来源:test_crashstorage.py


示例15: test_fail_fetch_haxby_simple

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')
开发者ID:bcipolli,项目名称:nilearn,代码行数:27,代码来源:test_func.py


示例16: test_SVR

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])
开发者ID:mosi,项目名称:scikit-learn,代码行数:28,代码来源:test_svm.py


示例17: test_quality_as_ep

 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)
开发者ID:Doppia,项目名称:Flexget,代码行数:7,代码来源:test_seriesparser.py


示例18: test_choices_functions

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)
开发者ID:rewardz,项目名称:django_model_helpers,代码行数:28,代码来源:test_choices.py


示例19: test_import_class

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)
开发者ID:cheekybastard,项目名称:rapidsms,代码行数:7,代码来源:test_base.py


示例20: _test_corr

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)
开发者ID:LauraGwilliams,项目名称:jr-tools,代码行数:29,代码来源:test_stats.py



注:本文中的nose.tools.assert_raises函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tools.assert_raises_regexp函数代码示例发布时间:2022-05-27
下一篇:
Python tools.assert_not_in函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap