def test_recolor_too_small(): # check exception is raised when image is too small colouring = np.array(Image.new('RGB', size=(20, 20))) wc = WordCloud(width=30, height=30, random_state=0, min_font_size=1).generate(THIS) image_colors = ImageColorGenerator(colouring) assert_raises_regex(ValueError, 'ImageColorGenerator is smaller than the canvas', wc.recolor, color_func=image_colors)
def test_recolor_too_small(): # check exception is raised when image is too small colouring = np.array(Image.new('RGB', size=(20, 20))) wc = WordCloud(width=30, height=30).generate(THIS) image_colors = ImageColorGenerator(colouring) assert_raises_regex(ValueError, 'ImageColorGenerator is smaller than the canvas', wc.recolor, color_func=image_colors)
def test_wrong_direction(self, context: AbstractContext, command_queue: AbstractCommandQueue) -> None: template = fft.FftTemplate( context, 1, (16, ), np.float32, np.complex64, (16, ), (9, ), ) with assert_raises_regex(ValueError, 'R2C transform must use FftMode.FORWARD'): template.instantiate(command_queue, fft.FftMode.INVERSE) template = fft.FftTemplate( context, 1, (16, ), np.complex64, np.float32, (9, ), (16, ), ) with assert_raises_regex(ValueError, 'C2R transform must use FftMode.INVERSE'): template.instantiate(command_queue, fft.FftMode.FORWARD)
def test_bad_padding(self, context: AbstractContext, command_queue: AbstractCommandQueue) -> None: with assert_raises_regex(ValueError, 'Source must not be padded'): fft.FftTemplate(context, 1, (16, 16), np.complex64, np.complex64, (17, 16), (16, 16)) with assert_raises_regex(ValueError, 'Destination must not be padded'): fft.FftTemplate(context, 1, (16, 16), np.complex64, np.complex64, (16, 16), (17, 16))
def test_length_mismatch(self, context: AbstractContext, command_queue: AbstractCommandQueue) -> None: with assert_raises_regex(ValueError, 'padded_shape_src and shape'): fft.FftTemplate(context, 1, (16, 16), np.float32, np.complex64, (16, ), (16, 16)) with assert_raises_regex(ValueError, 'padded_shape_dest and shape'): fft.FftTemplate(context, 1, (16, 16), np.float32, np.complex64, (16, 16), (16, ))
def test_bad_dtype_combination( self, context: AbstractContext, command_queue: AbstractCommandQueue) -> None: with assert_raises_regex(ValueError, 'Invalid combination of dtypes'): fft.FftTemplate(context, 1, (16, ), np.float32, np.complex128, (16, ), (16, )) with assert_raises_regex(ValueError, 'Invalid combination of dtypes'): fft.FftTemplate(context, 1, (16, ), np.int32, np.int32, (16, ), (16, ))
def makeSuite(self): with assert_raises_regex(ValueError, r'depends decorator needs at least one argument'): class TC(unittest.TestCase): @depends() def run_test_no_args(self): pass return [TC('run_test_no_args')]
def makeSuite(self): with assert_raises_regex(ValueError, r'Test \'run_test_self_dep\' cannot depend on itself'): class TC(unittest.TestCase): @depends(after='run_test_self_dep') def run_test_self_dep(self): pass return [TC('run_test_self_dep')]
def test_assert_response_ok_fails_with_reason(self): response = Mock() response.ok = False response.json = MagicMock( return_value={'message': 'this is my message'}) with assert_raises_regex(ZnailError, '.*this is my message.*'): ZnailComponent('1.2.3.4')._assert_response_ok(response)
def assert_raises_message(expected_error, expected_message, *args, **kwargs): """Assert that the correct error message is raised. Handles regex better than the default. """ expected_regex = re.escape(expected_message) return assert_raises_regex(expected_error, expected_regex, *args, **kwargs)
def test_health_check_fails_due_failed_check(self): url = 'http://1.2.3.4:80/api/healthcheck' body = '{"a": true, "b": false}' httpretty.register_uri(httpretty.GET, url, body=body) component = ZnailComponent('1.2.3.4') with assert_raises_regex(ZnailError, 'Health check failed: b'): component.health_check()
def test_from_constituency_trees_bad_tree(self): """Test that ``from_constituency_trees()`` raises exception for a bad tree.""" # read in the pre-computed constituency trees into a list trees = ["(S (NP (DT This) (NN theory)) (VP (VBD was) (VP (VBN developed) " "(PP (IN as) (NP (NP (NN part)) (PP (IN of) (NP (NP (NNS studies)) " "(PP (IN of) (NP (NN computer))) (VP (VBN based) (NP (JJ text) " "(NN generation))))))))) (. .))", "(S (NP (NNP RST)) (VP (VBZ establishes) (NP (NP (CD two) " "(JJ different) (NNS types)) (PP (IN of) (NP (NNS units))))) " "(. .)"] # now call the function assert_raises_regex(ValueError, r"check that the tree is correctly formatted", from_constituency_trees, trees, self.segmenter, self.parser)
def _unsuccessful_call_to_endpoint(self, endpoint, fn, args): url = 'http://1.2.3.4:80/api/{endpoint}'.format(endpoint=endpoint) body = '{"message": "my very unique error message"}' httpretty.register_uri(httpretty.POST, url, body=body, status=500) with assert_raises_regex(ZnailError, '.*: my very unique error message.*'): fn(*args)
def makeSuite(self): with assert_raises_regex( ValueError, r'depends decorator needs at least one argument'): class TC(unittest.TestCase): @depends() def run_test_no_args(self): pass return [TC('run_test_no_args')]
def makeSuite(self): with assert_raises_regex( ValueError, r'Test \'run_test_self_dep\' cannot depend on itself'): class TC(unittest.TestCase): @depends(after='run_test_self_dep') def run_test_self_dep(self): pass return [TC('run_test_self_dep')]
def test_read_extended_tape(self): nose.assert_equal( self.mntm1._read_extended_tape('10^10_1^00_00#^_', '^'), ('0', '1', '#')) nose.assert_equal( self.mntm1._read_extended_tape('1.10_1.00_0.#_', '.'), ('1', '1', '0')) nose.assert_equal( self.mntm1._read_extended_tape('10#^_00#^_00^_', '^'), ('#', '#', '0')) with nose.assert_raises_regex( tm_exceptions.MalformedExtendedTapeError, "head symbol was found on leftmost " + "end of the extended tape"): nose.assert_equal( self.mntm1._read_extended_tape('^10#_1^010#_00^', '^'), ('', '1', '0')) with nose.assert_raises_regex( tm_exceptions.MalformedExtendedTapeError, "no head symbol found on one of the " + "virtual tapes"): nose.assert_equal( self.mntm1._read_extended_tape('0^10#_1010#_00^_', '^'), ('0', '', '0')) with nose.assert_raises_regex( tm_exceptions.MalformedExtendedTapeError, "there must be 1 virtual head for " + "every tape separator symbol"): nose.assert_equal( self.mntm1._read_extended_tape('0^1010^10#^', '^'), ('0', '0', '#')) with nose.assert_raises_regex( tm_exceptions.MalformedExtendedTapeError, "more than one head symbol found on " + "one of the virtual tapes"): nose.assert_equal( self.mntm1._read_extended_tape('0^101010^_#^_', '^'), ('0', '0', '#'))
def test_get_model(): assert Connection is get_model(Connection) assert Connection is get_model('connections.Connection') assert_raises_regex(ValueError, "^<(class|type) 'object'>$", get_model, object) assert_raises_regex(ValueError, '^invalidmodelname$', get_model, 'invalidmodelname') assert_raises_regex(ValueError, '^invalid\.Model$', get_model, 'invalid.Model')
def assert_raises(exception, *args, glob=None, regex=None, match_case=None, **kwargs): """ Wrapper combining `nose.tools.assert_raises` and `nose.tools.assert_raises_regex`. Specify ``regex=pattern`` or ``glob=pattern`` to check error message of expected exception against the pattern. Value for `glob` must be a string, `regex` can be either a literal or compiled regex pattern. By default, the check will ignore case, if called with `glob` or a literal for `regex`. To enforce case sensitive check pass ``match_case=True``. Don't specify `match_case` if passing already compiled regex pattern. """ if glob is None and regex is None: return tools.assert_raises(exception, *args, **kwargs) if glob is not None and regex is not None: raise ValueError( "You should specify at most one of `glob` and `regex` parameters but not both" ) if glob is not None: if not isinstance(glob, str): raise ValueError("Glob pattern must be a string") pattern = fnmatch.translate(glob) # fnmatch adds special character to match the end of the string, so that when used # with re.match it, by default, matches the whole string. Here, it's going to be used # with re.search so it would be weird to enforce matching the suffix, but not the prefix. if pattern[-2:] == r"\Z": pattern = pattern[:-2] else: # regex is not None if match_case is not None and not isinstance(regex, str): raise ValueError( "Regex must be a string if `match_case` is specified when calling assert_raises_pattern" ) pattern = regex if isinstance(pattern, str) and not match_case: # ignore case by default pattern = re.compile(pattern, re.IGNORECASE) return tools.assert_raises_regex(exception, pattern, *args, **kwargs)
def assert_raises(exception, *args, glob=None, regex=None, match_case=None, **kwargs): """ Wrapper combining `nose.tools.assert_raises` and `nose.tools.assert_raises_regex`. Specify ``regex=pattern`` or ``glob=pattern`` to check error message of expected exception against the pattern. Value for `glob` must be a string, `regex` can be either a literal or compiled regex pattern. By default, the check will ignore case, if called with `glob` or a literal for `regex`. To enforce case sensitive check pass ``match_case=True``. Don't specify `match_case` if passing already compiled regex pattern. """ if glob is None and regex is None: return tools.assert_raises(exception, *args, **kwargs) pattern = get_pattern(glob, regex, match_case) return tools.assert_raises_regex(exception, pattern, *args, **kwargs)
def test_bad_data_type(): """ Notify if column data type is wrong """ patient = get_patient() bad_column_mapping = { 'column': 'data_proxima_consulta', 'data_type': 'omrs_datetime', 'commcare_data_type': 'cc_date', 'property': 'data_proxima_consulta' } with get_importer(bad_column_mapping) as importer: with assert_raises_regex( ConfigurationError, 'Errors importing from <OpenmrsImporter None admin@http://www.example.com/openmrs>:\n' 'Unable to deserialize value 1551564000000 ' 'in column "data_proxima_consulta" ' 'for case property "data_proxima_consulta". ' 'OpenMRS data type is given as "omrs_datetime". ' 'CommCare data type is given as "cc_date": ' "argument of type 'int' is not iterable"): get_case_properties(patient, importer)
def assert_raise_message(exception, message, function, *args, **kwargs): """Helper function to test error messages in exceptions""" assert_raises_regex( exception, re.escape(message), function, *args, **kwargs)
def test_timeit_invalid_return(): with nt.assert_raises_regex(SyntaxError, "outside function"): _ip.run_line_magic('timeit', 'return')
def assert_raises_message(expected_warning, expected_message, *args, **kwargs): expected_regex = re.escape(expected_message) return assert_raises_regex(expected_warning, expected_regex, *args, **kwargs)
def test_define_relationship_raises_for_duplicate(): define_relationship('r1', User, User) assert_raises_regex(KeyError, "^'r1'$", define_relationship, 'r1', User, User)
def _assert_stuff(i): with assert_raises_regex( logging.INFO, 'Did stuff to {} because of reasons that take up a whole line of text'.format( i.relname)): pass
def test_invalid_plan(self): plan = self.cufft.cufftHandle(123) # An invalid plan with assert_raises_regex(fft._Cufft.CufftError, "CUFFT_INVALID_PLAN"): self.cufft.cufftSetAutoAllocation(plan, False)
def test_unknown_error(self): with assert_raises_regex(fft._Cufft.CufftError, "cuFFT error 0x7b"): raise fft._Cufft.CufftError(123)
def test_LongitudeFormatter_bad_axes(): formatter = LongitudeFormatter() formatter.axis = Mock(axes=Mock(Axes, projection=ccrs.PlateCarree())) message = 'This formatter can only be used with cartopy axes.' with assert_raises_regex(TypeError, message): formatter(0)
def test_surface(): volume = np.random.uniform(10, 100) tau = np.random.uniform(.5, 5.) x = np.atleast_2d([tau, 0., 0.]) sigma = np.atleast_2d([volume/tau, 0., 0.]) v = np.zeros((1, 2)) surf = Surface(x, sigma, v) assert surf.boost_invariant, 'Surface should be boost-invariant.' assert_almost_equal( surf.volume, volume, delta=1e-12, msg='incorrect volume' ) ymax = np.random.uniform(.5, 2.) surf = Surface(x, sigma, v, ymax=ymax) assert_almost_equal( surf.volume, 2*ymax*volume, delta=1e-12, msg='incorrect volume' ) x = np.random.uniform(0, 10, size=(1, 4)) # ensure sigma is timelike (sigma^2 > 0) so that the volume is positive sigma = np.random.uniform([3, -1, -1, -1], [4, 1, 1, 1], size=(1, 4)) v = np.random.uniform(-.5, .5, size=(1, 3)) surf = Surface(x, sigma, v) assert not surf.boost_invariant, 'Surface should not be boost-invariant.' u = np.insert(v, 0, 1) / np.sqrt(1 - (v*v).sum()) volume = np.inner(sigma, u) assert_almost_equal( surf.volume, volume, delta=1e-12, msg='incorrect volume' ) with assert_warns_regex(Warning, 'ymax has no effect for 3D surfaces'): Surface(x, sigma, v, ymax=1.) with assert_warns_regex(Warning, 'total freeze-out volume is negative'): Surface(x, np.concatenate([[[0]], -v], axis=1), v) with assert_raises_regex(ValueError, 'invalid shape'): Surface( np.ones((1, 1)), np.ones((1, 1)), np.ones((1, 1)), ) with assert_raises_regex(ValueError, 'invalid shape'): Surface( np.ones((1, 4)), np.ones((1, 3)), np.ones((1, 2)), ) with assert_raises_regex(ValueError, 'invalid shape'): Surface( np.ones((2, 4)), np.ones((2, 4)), np.ones((3, 3)), )
def test_surface(): volume = np.random.uniform(10, 100) tau = np.random.uniform(.5, 5.) x = [tau, 0, 0] sigma = [volume/tau, 0, 0] v = [0, 0] surf = Surface(x, sigma, v) assert surf.boost_invariant, 'Surface should be boost-invariant.' assert_almost_equal( surf.volume, volume, delta=1e-12, msg='incorrect volume' ) ymax = np.random.uniform(.5, 2.) surf = Surface(x, sigma, v, ymax=ymax) assert_almost_equal( surf.volume, 2*ymax*volume, delta=1e-12, msg='incorrect volume' ) x = np.random.uniform(0, 10, size=(1, 4)) # ensure sigma is timelike (sigma^2 > 0) so that the volume is positive sigma = np.random.uniform([3, -1, -1, -1], [4, 1, 1, 1], size=(1, 4)) v = np.random.uniform(-.5, .5, size=(1, 3)) surf = Surface(x, sigma, v) assert not surf.boost_invariant, 'Surface should not be boost-invariant.' u = np.insert(v, 0, 1) / np.sqrt(1 - (v*v).sum()) volume = np.inner(sigma, u) assert_almost_equal( surf.volume, volume, delta=1e-12, msg='incorrect volume' ) with assert_warns_regex(Warning, 'ymax has no effect for a 3D surface'): Surface(x, sigma, v, ymax=np.random.rand()) with assert_warns_regex(Warning, 'total freeze-out volume is negative'): Surface(x, np.concatenate([[[0]], -v], axis=1), v) with assert_raises_regex( ValueError, 'number of spacetime dimensions of x, sigma, and/or v' ): Surface([1, 0], [1, 0], 0) with assert_raises_regex( ValueError, 'number of spacetime dimensions of x, sigma, and/or v' ): Surface( np.ones((1, 4)), np.ones((1, 3)), np.ones((1, 2)), ) with assert_raises_regex( ValueError, 'number of elements of x, sigma, and/or v do not match' ): Surface( np.ones((2, 4)), np.ones((2, 4)), np.ones((3, 3)), ) with assert_raises_regex( ValueError, 'number of elements of pi components do not match' ): Surface( np.ones((3, 4)), np.ones((3, 4)), np.ones((3, 3)), pi=dict( xx=np.ones(3), yy=np.ones(3), xy=np.ones(3), xz=np.ones(3), yz=np.ones(4), ) ) with assert_raises_regex( ValueError, 'number of elements of Pi do not match' ): Surface( np.ones((3, 4)), np.ones((3, 4)), np.ones((3, 3)), Pi=np.ones(4) )
def test_tiny_canvas(): # check exception if canvas too small for fallback w = WordCloud(max_words=50, width=1, height=1) assert_raises_regex(ValueError, 'canvas size is too small', w.generate, THIS)
def test_tiny_canvas(): # check exception if canvas too small for fallback w = WordCloud(max_words=50, width=1, height=1) assert_raises_regex(ValueError, "Couldn't find space to draw", w.generate, THIS)
def test_send_request_with_unknown_mehtod(self): component = ZnailComponent('1.2.3.4') with assert_raises_regex(ZnailError, 'Unknown method: other'): component._send_request('my_endpoint', 'my_data', method='other')
def test_LongitudeFormatter_bad_projection(): formatter = LongitudeFormatter() formatter.axis = Mock(axes=Mock(GeoAxes, projection=ccrs.Orthographic())) message = 'This formatter cannot be used with non-rectangular projections.' with assert_raises_regex(TypeError, message): formatter(0)
def test_assert_response_ok_fails_without_reason(self): response = Mock() response.ok = False response.json = MagicMock(side_effect=[Exception()]) with assert_raises_regex(ZnailError, '.*unknown.*'): ZnailComponent('1.2.3.4')._assert_response_ok(response)