How to use assert_raises_and_contains method in Testify

Best Python code snippet using Testify_python

assertions_test.py

Source:assertions_test.py Github

copy

Full Screen

...57 ascii_string = 'abc'58 unicode_string = u'ü and some more'59 def assert_with_unicode_msg():60 assert_equal(unicode_string, ascii_string)61 assertions.assert_raises_and_contains(AssertionError, 'abc', assert_with_unicode_msg)62 assertions.assert_raises_and_contains(AssertionError, 'and some more', assert_with_unicode_msg)63 def test_unicode_diff2(self):64 unicode_string = u'Thę quıćk brōwń fōx jumpęd ōvęr thę łąźy dōğ.'65 utf8_string = u'Thę quıćk brōwń fōx jumpęd ōvęr thę łąży dōğ.'66 def assert_with_unicode_msg():67 assertions.assert_equal(unicode_string, utf8_string)68 assertions.assert_raises_and_contains(AssertionError, 'łą<ź>y', assert_with_unicode_msg)69 assertions.assert_raises_and_contains(AssertionError, 'łą<ż>y', assert_with_unicode_msg)70 def test_unicode_diff3(self):71 unicode_string = u'münchen'72 utf8_string = unicode_string.encode('utf8')73 def assert_with_unicode_msg():74 assert_equal(unicode_string, utf8_string)75 for part in (76 (77 r"l: u'm\xfcnchen'" if six.PY2 else78 r"l: 'münchen'"79 ),80 (81 r"r: 'm\xc3\xbcnchen'" if six.PY2 else82 r"r: b'm\xc3\xbcnchen'"83 ),84 'l: münchen',85 'r: münchen',86 ):87 assertions.assert_raises_and_contains(88 AssertionError, part, assert_with_unicode_msg,89 )90 def test_bytes_diff(self):91 byte_string1 = b'm\xeenchen'92 byte_string2 = b'm\xaanchen'93 def assert_with_unicode_msg():94 assert_equal(byte_string1, byte_string2)95 for part in (96 (97 r"l: 'm\xeenchen'" if six.PY2 else98 r"l: b'm\xeenchen'"99 ),100 (101 r"r: 'm\xaanchen'" if six.PY2 else102 r"r: b'm\xaanchen'"103 ),104 'l: m<î>nchen',105 'r: m<ª>nchen'106 ):107 assertions.assert_raises_and_contains(108 AssertionError, part, assert_with_unicode_msg,109 )110 def test_utf8_diff(self):111 utf8_string1 = u'münchen'.encode('utf8')112 utf8_string2 = u'mënchen'.encode('utf8')113 def assert_with_unicode_msg():114 assert_equal(utf8_string1, utf8_string2)115 for content in (116 (117 r"l: 'm\xc3\xbcnchen'" if six.PY2 else118 r"l: b'm\xc3\xbcnchen'"119 ),120 (121 r"r: 'm\xc3\xabnchen'" if six.PY2 else122 r"r: b'm\xc3\xabnchen'"123 ),124 "l: m<ü>nchen",125 "r: m<ë>nchen",126 ):127 assertions.assert_raises_and_contains(AssertionError, content, assert_with_unicode_msg)128 def test_bytes_versus_unicode_diff(self):129 """Real-world example from https://github.com/Yelp/Testify/issues/144#issuecomment-14188539130 A good assert_equal implementation will clearly show that these have completely different character contents.131 """132 unicode_string = u'm\xc3\xbcnchen'133 byte_string = b'm\xc3\xbcnchen'134 def assert_with_unicode_msg():135 assert_equal(unicode_string, byte_string)136 for content in (137 (138 r"l: u'm\xc3\xbcnchen'" if six.PY2 else139 r"l: 'mã¼nchen'"140 ),141 (142 r"r: 'm\xc3\xbcnchen'" if six.PY2 else143 r"r: b'm\xc3\xbcnchen'"144 ),145 "l: m<ü>nchen",146 "r: m<ü>nchen",147 ):148 assertions.assert_raises_and_contains(AssertionError, content, assert_with_unicode_msg)149 def test_assert_truthy(self):150 assert_truthy(1)151 assert_truthy('False')152 assert_truthy([0])153 assert_truthy([''])154 assert_truthy(('',))155 assert_truthy({'a': 0})156 def test_assert_truthy_two_args_raises(self):157 with assertions.assert_raises(TypeError):158 assert_truthy('foo', 'bar')159 def test_assert_truthy_garbage_kwarg_raises(self):160 with assertions.assert_raises(TypeError):161 assert_truthy('foo', bar='baz')162 def test_assert_truthy_with_msg(self):163 with assertions.assert_raises_exactly(AssertionError, 'my_msg'):164 assert_truthy(0, message='my_msg')165 def test_assert_falsey(self):166 assert_falsey(None)167 assert_falsey(0)168 assert_falsey(0.0)169 assert_falsey('')170 assert_falsey(())171 assert_falsey([])172 assert_falsey({})173 def test_assert_falsey_two_args_raises(self):174 with assertions.assert_raises(TypeError):175 assert_falsey('foo', 'bar')176 def test_assert_falsey_garbage_kwarg_raises(self):177 with assertions.assert_raises(TypeError):178 assert_falsey('foo', bar='baz')179 def test_assert_falsey_with_msg(self):180 with assertions.assert_raises_exactly(AssertionError, 'my_msg'):181 assert_falsey(1, message='my_msg')182class AssertInTestCase(TestCase):183 def test_deprecated_msg_param(self):184 with warnings.catch_warnings(record=True) as w:185 assertions.assert_in(1, [1, 2], msg="This is a message")186 assertions.assert_equal(len(w), 1)187 assert issubclass(w[-1].category, DeprecationWarning)188 assertions.assert_in("msg is deprecated", str(w[-1].message))189 def test_message_param_not_deprecated(self):190 with warnings.catch_warnings(record=True) as w:191 assertions.assert_in(1, [1, 2], message="This is a message")192 assertions.assert_equal(len(w), 0)193class AssertNotInTestCase(TestCase):194 def test_deprecated_msg_param(self):195 with warnings.catch_warnings(record=True) as w:196 assertions.assert_not_in(3, [1, 2], msg="This is a message")197 assertions.assert_equal(len(w), 1)198 assert issubclass(w[-1].category, DeprecationWarning)199 assertions.assert_in("msg is deprecated", str(w[-1].message))200 def test_message_param_not_deprecated(self):201 with warnings.catch_warnings(record=True) as w:202 assertions.assert_not_in(3, [1, 2], message="This is a message")203 assertions.assert_equal(len(w), 0)204class AssertIsTestCase(TestCase):205 def test_deprecated_msg_param(self):206 with warnings.catch_warnings(record=True) as w:207 assertions.assert_is(None, None, msg="This is a message")208 assertions.assert_equal(len(w), 1)209 assert issubclass(w[-1].category, DeprecationWarning)210 assertions.assert_in("msg is deprecated", str(w[-1].message))211 def test_message_param_not_deprecated(self):212 with warnings.catch_warnings(record=True) as w:213 assertions.assert_is(None, None, message="This is a message")214 assertions.assert_equal(len(w), 0)215class AssertIsNotTestCase(TestCase):216 def test_deprecated_msg_param(self):217 with warnings.catch_warnings(record=True) as w:218 assertions.assert_is_not(False, None, msg="This is a message")219 assertions.assert_equal(len(w), 1)220 assert issubclass(w[-1].category, DeprecationWarning)221 assertions.assert_in("msg is deprecated", str(w[-1].message))222 def test_message_param_not_deprecated(self):223 with warnings.catch_warnings(record=True) as w:224 assertions.assert_is_not(False, None, message="This is a message")225 assertions.assert_equal(len(w), 0)226class AssertAllMatchRegexTestCase(TestCase):227 def test_deprecated_msg_param(self):228 with warnings.catch_warnings(record=True) as w:229 assertions.assert_all_match_regex("foo",230 ["foobar", "foobaz"],231 msg="This is a message")232 assertions.assert_equal(len(w), 1)233 assert issubclass(w[-1].category, DeprecationWarning)234 assertions.assert_in("msg is deprecated", str(w[-1].message))235 def test_message_param_not_deprecated(self):236 with warnings.catch_warnings(record=True) as w:237 assertions.assert_all_match_regex("foo",238 ["foobar", "foobaz"],239 message="This is a message")240 assertions.assert_equal(len(w), 0)241class AssertAnyMatchRegexTestCase(TestCase):242 def test_deprecated_msg_param(self):243 with warnings.catch_warnings(record=True) as w:244 assertions.assert_any_match_regex("foo",245 ["foobar", "barbaz"],246 msg="This is a message")247 assertions.assert_equal(len(w), 1)248 assert issubclass(w[-1].category, DeprecationWarning)249 assertions.assert_in("msg is deprecated", str(w[-1].message))250 def test_message_param_not_deprecated(self):251 with warnings.catch_warnings(record=True) as w:252 assertions.assert_any_match_regex("foo",253 ["foobar", "barbaz"],254 message="This is a message")255 assertions.assert_equal(len(w), 0)256class AssertAllNotMatchRegexTestCase(TestCase):257 def test_deprecated_msg_param(self):258 with warnings.catch_warnings(record=True) as w:259 assertions.assert_all_not_match_regex("qux",260 ["foobar", "barbaz"],261 msg="This is a message")262 assertions.assert_equal(len(w), 1)263 assert issubclass(w[-1].category, DeprecationWarning)264 assertions.assert_in("msg is deprecated", str(w[-1].message))265 def test_message_param_not_deprecated(self):266 with warnings.catch_warnings(record=True) as w:267 assertions.assert_all_not_match_regex("qux",268 ["foobar", "barbaz"],269 message="This is a message")270 assertions.assert_equal(len(w), 0)271class AssertSetsEqualTestCase(TestCase):272 def test_deprecated_msg_param(self):273 with warnings.catch_warnings(record=True) as w:274 assertions.assert_sets_equal({1, 2},275 {1, 2},276 msg="This is a message")277 assertions.assert_equal(len(w), 1)278 assert issubclass(w[-1].category, DeprecationWarning)279 assertions.assert_in("msg is deprecated", str(w[-1].message))280 def test_message_param_not_deprecated(self):281 with warnings.catch_warnings(record=True) as w:282 assertions.assert_sets_equal({1, 2},283 {1, 2},284 message="This is a message")285 assertions.assert_equal(len(w), 0)286class AssertDictsEqualTestCase(TestCase):287 def test_deprecated_msg_param(self):288 with warnings.catch_warnings(record=True) as w:289 assertions.assert_dicts_equal({"a": 1, "b": 2},290 {"a": 1, "b": 2},291 msg="This is a message")292 assertions.assert_equal(len(w), 1)293 assert issubclass(w[-1].category, DeprecationWarning)294 assertions.assert_in("msg is deprecated", str(w[-1].message))295 def test_message_param_not_deprecated(self):296 with warnings.catch_warnings(record=True) as w:297 assertions.assert_dicts_equal({"a": 1, "b": 2},298 {"a": 1, "b": 2},299 message="This is a message")300 assertions.assert_equal(len(w), 0)301class AssertDictSubsetTestCase_1(TestCase):302 def test_deprecated_msg_param(self):303 with warnings.catch_warnings(record=True) as w:304 assertions.assert_dict_subset({"a": 1, "b": 2},305 {"a": 1, "b": 2, "c": 3},306 msg="This is a message")307 assertions.assert_equal(len(w), 1)308 assert issubclass(w[-1].category, DeprecationWarning)309 assertions.assert_in("msg is deprecated", str(w[-1].message))310 def test_message_param_not_deprecated(self):311 with warnings.catch_warnings(record=True) as w:312 assertions.assert_dict_subset({"a": 1, "b": 2},313 {"a": 1, "b": 2, "c": 3},314 message="This is a message")315 assertions.assert_equal(len(w), 0)316class AssertSubsetTestCase(TestCase):317 def test_deprecated_msg_param(self):318 with warnings.catch_warnings(record=True) as w:319 assertions.assert_subset({1, 2},320 {1, 2, 3},321 msg="This is a message")322 assertions.assert_equal(len(w), 1)323 assert issubclass(w[-1].category, DeprecationWarning)324 assertions.assert_in("msg is deprecated", str(w[-1].message))325 def test_message_param_not_deprecated(self):326 with warnings.catch_warnings(record=True) as w:327 assertions.assert_subset({1, 2},328 {1, 2, 3},329 message="This is a message")330 assertions.assert_equal(len(w), 0)331class MyException(Exception):332 pass333class AssertRaisesAsContextManagerTestCase(TestCase):334 def test_fails_when_exception_is_not_raised(self):335 def exception_should_be_raised():336 with assertions.assert_raises(MyException):337 pass338 try:339 exception_should_be_raised()340 except AssertionError:341 pass342 else:343 assert_not_reached('AssertionError should have been raised')344 def test_passes_when_exception_is_raised(self):345 def exception_should_be_raised():346 with assertions.assert_raises(MyException):347 raise MyException348 exception_should_be_raised()349 def test_crashes_when_another_exception_class_is_raised(self):350 def assert_raises_an_exception_and_raise_another():351 with assertions.assert_raises(MyException):352 raise ValueError353 try:354 assert_raises_an_exception_and_raise_another()355 except ValueError:356 pass357 else:358 raise AssertionError('ValueError should have been raised')359class AssertRaisesAsCallableTestCase(TestCase):360 def test_fails_when_exception_is_not_raised(self):361 def raises_nothing():362 pass363 try:364 assertions.assert_raises(ValueError, raises_nothing)365 except AssertionError:366 pass367 else:368 assert_not_reached('AssertionError should have been raised')369 def test_passes_when_exception_is_raised(self):370 def raises_value_error():371 raise ValueError372 assertions.assert_raises(ValueError, raises_value_error)373 def test_fails_when_wrong_exception_is_raised(self):374 def raises_value_error():375 raise ValueError376 try:377 assertions.assert_raises(MyException, raises_value_error)378 except ValueError:379 pass380 else:381 assert_not_reached('ValueError should have been raised')382 def test_callable_is_called_with_all_arguments(self):383 class GoodArguments(Exception):384 pass385 arg1, arg2, kwarg = object(), object(), object()386 def check_arguments(*args, **kwargs):387 assert_equal((arg1, arg2), args)388 assert_equal({'kwarg': kwarg}, kwargs)389 raise GoodArguments390 assertions.assert_raises(GoodArguments, check_arguments, arg1, arg2, kwarg=kwarg)391class AssertRaisesSuchThatTestCase(TestCase):392 def test_fails_when_no_exception_is_raised(self):393 """Tests that the assertion fails when no exception is raised."""394 def exists(e):395 return True396 with assertions.assert_raises(AssertionError):397 with assertions.assert_raises_such_that(Exception, exists):398 pass399 def test_fails_when_wrong_exception_is_raised(self):400 """Tests that when an unexpected exception is raised, that it is401 passed through and the assertion fails."""402 def exists(e):403 return True404 # note: in assert_raises*, if the exception raised is not of the405 # expected type, that exception just falls through406 with assertions.assert_raises(Exception):407 with assertions.assert_raises_such_that(AssertionError, exists):408 raise Exception("the wrong exception")409 def test_fails_when_exception_test_fails(self):410 """Tests that when an exception of the right type that fails the411 passed in exception test is raised, the assertion fails."""412 def has_two_args(e):413 assertions.assert_length(e.args, 2)414 with assertions.assert_raises(AssertionError):415 with assertions.assert_raises_such_that(Exception, has_two_args):416 raise Exception("only one argument")417 def test_passes_when_correct_exception_is_raised(self):418 """Tests that when an exception of the right type that passes the419 exception test is raised, the assertion passes."""420 def has_two_args(e):421 assertions.assert_length(e.args, 2)422 with assertions.assert_raises_such_that(Exception, has_two_args):423 raise Exception("first", "second")424 def test_callable_is_called_with_all_arguments(self):425 """Tests that the callable form works properly, with all arguments426 passed through."""427 def message_is_foo(e):428 assert_equal(str(e), 'foo')429 class GoodArguments(Exception):430 pass431 arg1, arg2, kwarg = object(), object(), object()432 def check_arguments(*args, **kwargs):433 assert_equal((arg1, arg2), args)434 assert_equal({'kwarg': kwarg}, kwargs)435 raise GoodArguments('foo')436 assertions.assert_raises_such_that(GoodArguments, message_is_foo, check_arguments, arg1, arg2, kwarg=kwarg)437class AssertRaisesExactlyTestCase(TestCase):438 class MyException(ValueError):439 pass440 def test_passes_when_correct_exception_is_raised(self):441 with assertions.assert_raises_exactly(self.MyException, "first", "second"):442 raise self.MyException("first", "second")443 def test_fails_with_wrong_value(self):444 with assertions.assert_raises(AssertionError):445 with assertions.assert_raises_exactly(self.MyException, "first", "second"):446 raise self.MyException("red", "blue")447 def test_fails_with_different_class(self):448 class SpecialException(self.MyException):449 pass450 with assertions.assert_raises(AssertionError):451 with assertions.assert_raises_exactly(self.MyException, "first", "second"):452 raise SpecialException("first", "second")453 def test_fails_with_vague_class(self):454 with assertions.assert_raises(AssertionError):455 with assertions.assert_raises_exactly(Exception, "first", "second"):456 raise self.MyException("first", "second")457 def test_unexpected_exception_passes_through(self):458 class DifferentException(Exception):459 pass460 with assertions.assert_raises(DifferentException):461 with assertions.assert_raises_exactly(self.MyException, "first", "second"):462 raise DifferentException("first", "second")463class AssertRaisesAndContainsTestCase(TestCase):464 def test_fails_when_exception_is_not_raised(self):465 def raises_nothing():466 pass467 try:468 assertions.assert_raises_and_contains(ValueError, 'abc', raises_nothing)469 except AssertionError:470 pass471 else:472 assert_not_reached('AssertionError should have been raised')473 def test_fails_when_wrong_exception_is_raised(self):474 def raises_value_error():475 raise ValueError476 try:477 assertions.assert_raises_and_contains(MyException, 'abc', raises_value_error)478 except ValueError:479 pass480 else:481 assert_not_reached('ValueError should have been raised')482 def test_callable_is_called_with_all_arguments(self):483 class GoodArguments(Exception):484 pass485 arg1, arg2, kwarg = object(), object(), object()486 def check_arguments(*args, **kwargs):487 assert_equal((arg1, arg2), args)488 assert_equal({'kwarg': kwarg}, kwargs)489 raise GoodArguments('abc')490 assertions.assert_raises_and_contains(GoodArguments, 'abc', check_arguments, arg1, arg2, kwarg=kwarg)491 def test_fails_when_exception_does_not_contain_string(self):492 def raises_value_error():493 raise ValueError('abc')494 try:495 assertions.assert_raises_and_contains(ValueError, 'xyz', raises_value_error)496 except AssertionError:497 pass498 else:499 assert_not_reached('AssertionError should have been raised')500 def test_passes_when_exception_contains_string_with_matching_case(self):501 def raises_value_error():502 raise ValueError('abc')503 assertions.assert_raises_and_contains(ValueError, 'abc', raises_value_error)504 def test_passes_when_exception_contains_string_with_non_matching_case(self):505 def raises_value_error():506 raise ValueError('abc')507 assertions.assert_raises_and_contains(ValueError, 'ABC', raises_value_error)508 def test_passes_when_exception_contains_multiple_strings(self):509 def raises_value_error():510 raise ValueError('abc xyz')511 assertions.assert_raises_and_contains(ValueError, ['ABC', 'XYZ'], raises_value_error)512 def test_fails_when_exception_does_not_contains_all_strings(self):513 def raises_value_error():514 raise ValueError('abc xyz')515 try:516 assertions.assert_raises_and_contains(ValueError, ['ABC', '123'], raises_value_error)517 except AssertionError:518 pass519 else:520 assert_not_reached('AssertionError should have been raised')521class AssertDictSubsetTestCase(TestCase):522 def test_passes_with_subset(self):523 superset = {'one': 1, 'two': 2, 'three': 3}524 subset = {'one': 1}525 assert_dict_subset(subset, superset)526 def test_fails_with_wrong_key(self):527 superset = {'one': 1, 'two': 2, 'three': 3}528 subset = {'four': 4}529 assertions.assert_raises(AssertionError, assert_dict_subset, subset, superset)530 def test_fails_with_wrong_value(self):...

Full Screen

Full Screen

proxy_test.py

Source:proxy_test.py Github

copy

Full Screen

...18 self.value_proxy = proxy.ValueProxy(19 validator, self.namespace, self.config_key)20 def test_extract_value_unset(self):21 expected = [self.name, self.config_key]22 assert_raises_and_contains(23 errors.ConfigurationError,24 expected,25 lambda: self.value_proxy.value)26 def test_get_value_fails_validation(self):27 expected = [self.name, self.config_key]28 validator = mock.Mock(side_effect=validation.ValidationError)29 _ = proxy.ValueProxy( # noqa: F84130 validator,31 self.namespace,32 'something.broken')33 assert_raises_and_contains(34 errors.ConfigurationError,35 expected,36 lambda: self.value_proxy.value)37class TestValueProxy(object):38 @pytest.fixture(autouse=True)39 def setup_configuration_values(self):40 self.value_cache = {41 'something': 2,42 'something.string': 'the stars',43 'zero': 0,44 'the_date': datetime.datetime(2012, 3, 14, 4, 4, 4),45 'the_list': range(3),46 }47 def test_proxy(self):...

Full Screen

Full Screen

validation_test.py

Source:validation_test.py Github

copy

Full Screen

...56 actual = validation.validate_regex(pattern)57 assert_equal(pattern, actual.pattern)58 def test_validate_regex_failed(self):59 pattern = "((this) regex is broken"60 assert_raises_and_contains(61 errors.ValidationError,62 pattern,63 validation.validate_regex,64 pattern)65 def test_validate_regex_none(self):66 assert_raises_and_contains(67 errors.ValidationError,68 'None',69 validation.validate_regex,70 None)71class TestBuildListOfTypeValidator(object):72 def test_build_list_of_type_ints_success(self):73 validator = validation.build_list_type_validator(74 validation.validate_int)75 assert_equal(validator(['0', '1', '2']), [0, 1, 2])76 def test_build_list_of_type_float_failed(self):77 validator = validation.build_list_type_validator(78 validation.validate_float)79 assert_raises_and_contains(80 errors.ValidationError, 'Invalid float: a', validator, ['0.1', 'a'])81 def test_build_list_of_type_empty_list(self):82 validator = validation.build_list_type_validator(83 validation.validate_string)84 assert_equal(validator([]), [])85 def test_build_list_of_type_not_a_list(self):86 validator = validation.build_list_type_validator(87 validation.validate_any)88 assert_raises_and_contains(89 errors.ValidationError, 'Invalid iterable', validator, None)90class TestBuildMappingTypeValidator(object):91 def test_build_map_from_list_of_pairs(self):92 pair_validator = validation.build_map_type_validator(lambda i: i)93 expected = {0: 0, 1: 1, 2: 2}94 assert_equal(pair_validator(enumerate(range(3))), expected)95 def test_build_map_from_list_of_dicts(self):96 def map_by_id(d):97 return d['id'], d['value']98 map_validator = validation.build_map_type_validator(map_by_id)99 expected = {'a': 'b', 'c': 'd'}100 source = [dict(id='a', value='b'), dict(id='c', value='d')]101 assert_equal(map_validator(source), expected)102class TestValidateLogLevel(object):103 def test_valid_log_level(self):104 assert_equal(validation.validate_log_level('WARN'), logging.WARN)105 assert_equal(validation.validate_log_level('DEBUG'), logging.DEBUG)106 def test_invalid_log_level(self):107 assert_raises_and_contains(108 errors.ValidationError,109 'UNKNOWN',110 validation.validate_log_level,...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful