Best Python code snippet using Testify_python
assertions_test.py
Source:assertions_test.py
...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 ValueError...
_token_test.py
Source:_token_test.py
...133 assert not isinstance(goat(1, 2, 3), goat(1, 2))134 assert goat == goat()135 def test_no_class_attributes(self):136 t = token(token, a=1)137 with assert_raises_exactly(TypeError, 'token objects are read-only'):138 t.properties = {'b':2}139 with assert_raises_exactly(TypeError, 'token objects are read-only'):140 del t.children141 def test_no_object_attributes(self):142 t = token(token, a=1)143 with assert_raises_exactly(TypeError, 'token objects are read-only'):144 t.properties = {'b':2}145 with assert_raises_exactly(TypeError, 'token objects are read-only'):146 del t.children147 def test_class_attrs_immutable(self):148 with assert_raises_exactly(149 TypeError,150 "'FrozenDict' object does not support item assignment",151 ):152 token.properties['b'] = 2153 with assert_raises_exactly(154 AttributeError,155 "'tuple' object has no attribute 'append'",156 ):157 token.children.append('wat')158 def test_object_attrs_immutable(self):159 t = token(token, a=1)160 with assert_raises_exactly(161 TypeError,162 "'FrozenDict' object does not support item assignment",163 ):164 t.properties['b'] = 2165 with assert_raises_exactly(166 AttributeError,167 "'tuple' object has no attribute 'append'",168 ):169 t.children.append('wat')170class QuestionableFeatures(T.TestCase):171 """172 I might decide to delete these features later,173 but this is how they work at this moment.174 """175 def test_copy(self):176 """secondary interface for copying tokens"""177 t1 = token()178 t2 = t1.copy()179 assert t1 == t2, (t1, t2)180 def test_generator_support(self):181 """This will naturally go away if i factor out .copy"""182 t1 = token()183 t3 = t1.copy(children=(token() for i in range(3)))184 assert len(t3.children) == 3185 assert type(t3.children) is tuple186 t4 = t1.copy(properties=((i, i) for i in range(3)))187 assert len(t4.properties) == 3188 from collections import Mapping189 assert isinstance(t4.properties, Mapping)190 def test_default_property_deletion(self):191 class MyToken(token):192 "an example with a default property"193 properties = {'a':1}194 m1 = MyToken()195 assert len(m1.properties) == 1196 m1 = MyToken(a=token.undefined)197 assert len(m1.properties) == 0, dict(m1.properties)198class MetaTokenTest(T.TestCase):199 """Disabled test for tokenType"""200 __test__ = True201 def test_repr(self):202 """token classes should have a simple representation"""203 assert str(token) == "('token',)"204 assert repr(token) == repr(token())205 # a copy of token206 token2 = token(a=1)207 assert repr(token2) == "('token', {'a': 1})", repr(token2)208 class token3(token):209 """a subclass of `token'"""210 pass211 assert repr(token3) == "('token3',)"212 def test_eq(self):213 """Two tokens that are indistinguishable are equal."""214 class Animal(token):215 """A token for animals."""216 a1 = Animal217 # E0102: class already defined218 # pylint:disable=E0102219 class Animal(token):220 """A somewhat different token for animals."""221 a2 = Animal222 assert a1 == a2223 a3 = a1(224 token,225 token,226 )227 assert a1 != a3 != a2228 class Animal(Animal):229 """Yet another Animal token."""230 children = (token, token)231 assert a3 == Animal232 assert a1 != Animal != a2233 assert a3 == Animal()234 assert a1 != Animal() != a2235from contextlib import contextmanager236@contextmanager237def assert_raises_exactly(exception_type, *args, **attrs):238 try:239 yield240 except Exception, exception:241 assert type(exception) is exception_type, type(exception)242 assert exception.args == args, exception.args243 assert exception.__dict__ == attrs, exception.__dict__244 else:245 raise AssertionError('No exception raised!')246if __name__ == '__main__':247 import pytest248 import sys...
util_test.py
Source:util_test.py
1from __future__ import unicode_literals2import pytest3from testing.util import assert_raises_exactly4def test_assert_raise_exactly_passing():5 with assert_raises_exactly(ValueError, 'herpderp'):6 raise ValueError('herpderp')7def test_assert_raises_exactly_mismatched_type():8 with pytest.raises(AssertionError):9 with assert_raises_exactly(ValueError, 'herpderp'):10 raise TypeError('herpderp')11def test_assert_raises_mismatched_message():12 with pytest.raises(AssertionError):13 with assert_raises_exactly(ValueError, 'herpderp'):14 raise ValueError('harpdarp')15def test_assert_raises_does_not_raise():16 with pytest.raises(AssertionError):17 with assert_raises_exactly(ValueError, 'herpderp'):18 pass19def test_assert_raises_subclass():20 class MyClass(ValueError):21 pass22 with pytest.raises(AssertionError):23 with assert_raises_exactly(ValueError, 'herpderp'):...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!