当前位置: 首页>>代码示例>>Python>>正文


Python tools.assert_raises函数代码示例

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


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


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