Best Python code snippet using autotest_python
test_bool.py
Source:test_bool.py
...89 self.assertEqual(b**i, int(b)**i)90 self.assertIsNot(b**i, bool(int(b)**i))91 for a in False, True:92 for b in False, True:93 self.assertIs(a&b, bool(int(a)&int(b)))94 self.assertIs(a|b, bool(int(a)|int(b)))95 self.assertIs(a^b, bool(int(a)^int(b)))96 self.assertEqual(a&int(b), int(a)&int(b))97 self.assertIsNot(a&int(b), bool(int(a)&int(b)))98 self.assertEqual(a|int(b), int(a)|int(b))99 self.assertIsNot(a|int(b), bool(int(a)|int(b)))100 self.assertEqual(a^int(b), int(a)^int(b))101 self.assertIsNot(a^int(b), bool(int(a)^int(b)))102 self.assertEqual(int(a)&b, int(a)&int(b))103 self.assertIsNot(int(a)&b, bool(int(a)&int(b)))104 self.assertEqual(int(a)|b, int(a)|int(b))105 self.assertIsNot(int(a)|b, bool(int(a)|int(b)))106 self.assertEqual(int(a)^b, int(a)^int(b))107 self.assertIsNot(int(a)^b, bool(int(a)^int(b)))108 self.assertIs(1==1, True)109 self.assertIs(1==0, False)110 self.assertIs(0<1, True)111 self.assertIs(1<0, False)112 self.assertIs(0<=0, True)113 self.assertIs(1<=0, False)114 self.assertIs(1>0, True)115 self.assertIs(1>1, False)116 self.assertIs(1>=1, True)117 self.assertIs(0>=1, False)118 self.assertIs(0!=1, True)119 self.assertIs(0!=0, False)120 x = [1]121 self.assertIs(x is x, True)122 self.assertIs(x is not x, False)123 self.assertIs(1 in x, True)124 self.assertIs(0 in x, False)125 self.assertIs(1 not in x, False)126 self.assertIs(0 not in x, True)127 x = {1: 2}128 self.assertIs(x is x, True)129 self.assertIs(x is not x, False)130 self.assertIs(1 in x, True)131 self.assertIs(0 in x, False)132 self.assertIs(1 not in x, False)133 self.assertIs(0 not in x, True)134 self.assertIs(not True, False)135 self.assertIs(not False, True)136 def test_convert(self):137 self.assertRaises(TypeError, bool, 42, 42)138 self.assertIs(bool(10), True)139 self.assertIs(bool(1), True)140 self.assertIs(bool(-1), True)141 self.assertIs(bool(0), False)142 self.assertIs(bool("hello"), True)143 self.assertIs(bool(""), False)144 self.assertIs(bool(), False)145 def test_format(self):146 self.assertEqual("%d" % False, "0")147 self.assertEqual("%d" % True, "1")148 self.assertEqual("%x" % False, "0")149 self.assertEqual("%x" % True, "1")150 def test_hasattr(self):151 self.assertIs(hasattr([], "append"), True)152 self.assertIs(hasattr([], "wobble"), False)153 def test_callable(self):154 self.assertIs(callable(len), True)155 self.assertIs(callable(1), False)156 def test_isinstance(self):157 self.assertIs(isinstance(True, bool), True)158 self.assertIs(isinstance(False, bool), True)159 self.assertIs(isinstance(True, int), True)160 self.assertIs(isinstance(False, int), True)161 self.assertIs(isinstance(1, bool), False)162 self.assertIs(isinstance(0, bool), False)163 def test_issubclass(self):164 self.assertIs(issubclass(bool, int), True)165 self.assertIs(issubclass(int, bool), False)166 def test_haskey(self):167 self.assertIs(1 in {}, False)168 self.assertIs(1 in {1:1}, True)169 with test_support.check_py3k_warnings():170 self.assertIs({}.has_key(1), False)171 self.assertIs({1:1}.has_key(1), True)172 def test_string(self):173 self.assertIs("xyz".endswith("z"), True)174 self.assertIs("xyz".endswith("x"), False)175 self.assertIs("xyz0123".isalnum(), True)176 self.assertIs("@#$%".isalnum(), False)177 self.assertIs("xyz".isalpha(), True)178 self.assertIs("@#$%".isalpha(), False)179 self.assertIs("0123".isdigit(), True)180 self.assertIs("xyz".isdigit(), False)181 self.assertIs("xyz".islower(), True)182 self.assertIs("XYZ".islower(), False)183 self.assertIs(" ".isspace(), True)184 self.assertIs("XYZ".isspace(), False)185 self.assertIs("X".istitle(), True)186 self.assertIs("x".istitle(), False)187 self.assertIs("XYZ".isupper(), True)188 self.assertIs("xyz".isupper(), False)189 self.assertIs("xyz".startswith("x"), True)190 self.assertIs("xyz".startswith("z"), False)191 if test_support.have_unicode:192 self.assertIs(unicode("xyz", 'ascii').endswith(unicode("z", 'ascii')), True)193 self.assertIs(unicode("xyz", 'ascii').endswith(unicode("x", 'ascii')), False)194 self.assertIs(unicode("xyz0123", 'ascii').isalnum(), True)195 self.assertIs(unicode("@#$%", 'ascii').isalnum(), False)196 self.assertIs(unicode("xyz", 'ascii').isalpha(), True)197 self.assertIs(unicode("@#$%", 'ascii').isalpha(), False)198 self.assertIs(unicode("0123", 'ascii').isdecimal(), True)199 self.assertIs(unicode("xyz", 'ascii').isdecimal(), False)200 self.assertIs(unicode("0123", 'ascii').isdigit(), True)201 self.assertIs(unicode("xyz", 'ascii').isdigit(), False)202 self.assertIs(unicode("xyz", 'ascii').islower(), True)203 self.assertIs(unicode("XYZ", 'ascii').islower(), False)204 self.assertIs(unicode("0123", 'ascii').isnumeric(), True)205 self.assertIs(unicode("xyz", 'ascii').isnumeric(), False)206 self.assertIs(unicode(" ", 'ascii').isspace(), True)207 self.assertIs(unicode("XYZ", 'ascii').isspace(), False)208 self.assertIs(unicode("X", 'ascii').istitle(), True)209 self.assertIs(unicode("x", 'ascii').istitle(), False)210 self.assertIs(unicode("XYZ", 'ascii').isupper(), True)211 self.assertIs(unicode("xyz", 'ascii').isupper(), False)212 self.assertIs(unicode("xyz", 'ascii').startswith(unicode("x", 'ascii')), True)213 self.assertIs(unicode("xyz", 'ascii').startswith(unicode("z", 'ascii')), False)214 def test_boolean(self):215 self.assertEqual(True & 1, 1)216 self.assertNotIsInstance(True & 1, bool)217 self.assertIs(True & True, True)218 self.assertEqual(True | 1, 1)219 self.assertNotIsInstance(True | 1, bool)220 self.assertIs(True | True, True)221 self.assertEqual(True ^ 1, 0)222 self.assertNotIsInstance(True ^ 1, bool)223 self.assertIs(True ^ True, False)224 def test_fileclosed(self):225 try:226 f = file(test_support.TESTFN, "w")227 self.assertIs(f.closed, False)228 f.close()229 self.assertIs(f.closed, True)230 finally:231 os.remove(test_support.TESTFN)232 def test_types(self):233 # types are always true.234 for t in [bool, complex, dict, file, float, int, list, long, object,235 set, str, tuple, type]:236 self.assertIs(bool(t), True)237 def test_operator(self):238 import operator239 self.assertIs(operator.truth(0), False)240 self.assertIs(operator.truth(1), True)241 with test_support.check_py3k_warnings():242 self.assertIs(operator.isCallable(0), False)243 self.assertIs(operator.isCallable(len), True)244 self.assertIs(operator.isNumberType(None), False)245 self.assertIs(operator.isNumberType(0), True)246 self.assertIs(operator.not_(1), False)247 self.assertIs(operator.not_(0), True)248 self.assertIs(operator.isSequenceType(0), False)249 self.assertIs(operator.isSequenceType([]), True)250 self.assertIs(operator.contains([], 1), False)251 self.assertIs(operator.contains([1], 1), True)252 self.assertIs(operator.isMappingType(1), False)253 self.assertIs(operator.isMappingType({}), True)254 self.assertIs(operator.lt(0, 0), False)255 self.assertIs(operator.lt(0, 1), True)256 self.assertIs(operator.is_(True, True), True)257 self.assertIs(operator.is_(True, False), False)258 self.assertIs(operator.is_not(True, True), False)259 self.assertIs(operator.is_not(True, False), True)260 def test_marshal(self):261 import marshal262 self.assertIs(marshal.loads(marshal.dumps(True)), True)263 self.assertIs(marshal.loads(marshal.dumps(False)), False)264 def test_pickle(self):265 import pickle266 self.assertIs(pickle.loads(pickle.dumps(True)), True)267 self.assertIs(pickle.loads(pickle.dumps(False)), False)268 self.assertIs(pickle.loads(pickle.dumps(True, True)), True)269 self.assertIs(pickle.loads(pickle.dumps(False, True)), False)270 def test_cpickle(self):271 import cPickle272 self.assertIs(cPickle.loads(cPickle.dumps(True)), True)273 self.assertIs(cPickle.loads(cPickle.dumps(False)), False)274 self.assertIs(cPickle.loads(cPickle.dumps(True, True)), True)275 self.assertIs(cPickle.loads(cPickle.dumps(False, True)), False)276 def test_mixedpickle(self):277 import pickle, cPickle278 self.assertIs(pickle.loads(cPickle.dumps(True)), True)279 self.assertIs(pickle.loads(cPickle.dumps(False)), False)280 self.assertIs(pickle.loads(cPickle.dumps(True, True)), True)281 self.assertIs(pickle.loads(cPickle.dumps(False, True)), False)282 self.assertIs(cPickle.loads(pickle.dumps(True)), True)283 self.assertIs(cPickle.loads(pickle.dumps(False)), False)284 self.assertIs(cPickle.loads(pickle.dumps(True, True)), True)285 self.assertIs(cPickle.loads(pickle.dumps(False, True)), False)286 def test_picklevalues(self):287 import pickle, cPickle288 # Test for specific backwards-compatible pickle values289 self.assertEqual(pickle.dumps(True), "I01\n.")290 self.assertEqual(pickle.dumps(False), "I00\n.")291 self.assertEqual(cPickle.dumps(True), "I01\n.")292 self.assertEqual(cPickle.dumps(False), "I00\n.")293 self.assertEqual(pickle.dumps(True, True), "I01\n.")294 self.assertEqual(pickle.dumps(False, True), "I00\n.")295 self.assertEqual(cPickle.dumps(True, True), "I01\n.")296 self.assertEqual(cPickle.dumps(False, True), "I00\n.")297 def test_convert_to_bool(self):298 # Verify that TypeError occurs when bad things are returned299 # from __nonzero__(). This isn't really a bool test, but...
tests.py
Source:tests.py
...59 elif kwds:60 f = stack.callback(_exit, **kwds)61 else:62 f = stack.callback(_exit)63 self.assertIs(f, _exit)64 # for wrapper in stack._exit_callbacks:65 # self.assertIs(wrapper.__wrapped__, _exit)66 # self.assertNotEqual(wrapper.__name__, _exit.__name__)67 # self.assertIsNone(wrapper.__doc__, _exit.__doc__)68 self.assertEqual(result, expected)69 def test_push(self):70 exc_raised = ZeroDivisionError71 def _expect_exc(exc_type, exc, exc_tb):72 self.assertIs(exc_type, exc_raised)73 def _suppress_exc(*exc_details):74 return True75 def _expect_ok(exc_type, exc, exc_tb):76 self.assertIsNone(exc_type)77 self.assertIsNone(exc)78 self.assertIsNone(exc_tb)79 class ExitCM(object):80 def __init__(self, check_exc):81 self.check_exc = check_exc82 def __enter__(self):83 self.fail("Should not be called!")84 def __exit__(self, *exc_details):85 self.check_exc(*exc_details)86 with ExitStack() as stack:87 stack.push(_expect_ok)88 self.assertIs(tuple(stack._exit_callbacks)[-1], _expect_ok)89 cm = ExitCM(_expect_ok)90 stack.push(cm)91 # self.assertIs(stack._exit_callbacks[-1].__self__, cm)92 stack.push(_suppress_exc)93 self.assertIs(tuple(stack._exit_callbacks)[-1], _suppress_exc)94 cm = ExitCM(_expect_exc)95 stack.push(cm)96 # self.assertIs(stack._exit_callbacks[-1].__self__, cm)97 stack.push(_expect_exc)98 self.assertIs(tuple(stack._exit_callbacks)[-1], _expect_exc)99 stack.push(_expect_exc)100 self.assertIs(tuple(stack._exit_callbacks)[-1], _expect_exc)101 1/0102 def test_enter_context(self):103 class TestCM(object):104 def __enter__(self):105 result.append(1)106 def __exit__(self, *exc_details):107 result.append(3)108 result = []109 cm = TestCM()110 with ExitStack() as stack:111 @stack.callback # Registered first => cleaned up last112 def _exit():113 result.append(4)114 self.assertIsNotNone(_exit)115 stack.enter_context(cm)116 # self.assertIs(stack._exit_callbacks[-1].__self__, cm)117 result.append(2)118 self.assertEqual(result, [1, 2, 3, 4])119 def test_close(self):120 result = []121 with ExitStack() as stack:122 @stack.callback123 def _exit():124 result.append(1)125 self.assertIsNotNone(_exit)126 stack.close()127 result.append(2)128 self.assertEqual(result, [1, 2])129 def test_pop_all(self):130 result = []131 with ExitStack() as stack:132 @stack.callback133 def _exit():134 result.append(3)135 self.assertIsNotNone(_exit)136 new_stack = stack.pop_all()137 result.append(1)138 result.append(2)139 new_stack.close()140 self.assertEqual(result, [1, 2, 3])141 def test_exit_raise(self):142 with self.assertRaises(ZeroDivisionError):143 with ExitStack() as stack:144 stack.push(lambda *exc: False)145 1/0146 def test_exit_suppress(self):147 with ExitStack() as stack:148 stack.push(lambda *exc: True)149 1/0150 def test_exit_exception_chaining_reference(self):151 # Sanity check to make sure that ExitStack chaining matches152 # actual nested with statements153 exc_chain = []154 class RaiseExc:155 def __init__(self, exc):156 self.exc = exc157 def __enter__(self):158 return self159 def __exit__(self, *exc_details):160 exc_chain.append(exc_details[0])161 raise self.exc162 class RaiseExcWithContext:163 def __init__(self, outer, inner):164 self.outer = outer165 self.inner = inner166 def __enter__(self):167 return self168 def __exit__(self, *exc_details):169 try:170 exc_chain.append(exc_details[0])171 raise self.inner172 except:173 exc_chain.append(sys.exc_info()[0])174 raise self.outer175 class SuppressExc:176 def __enter__(self):177 return self178 def __exit__(self, *exc_details):179 type(self).saved_details = exc_details180 return True181 try:182 with RaiseExc(IndexError):183 with RaiseExcWithContext(KeyError, AttributeError):184 with SuppressExc():185 with RaiseExc(ValueError):186 1 / 0187 except IndexError as exc:188 # self.assertIsInstance(exc.__context__, KeyError)189 # self.assertIsInstance(exc.__context__.__context__, AttributeError)190 # Inner exceptions were suppressed191 # self.assertIsNone(exc.__context__.__context__.__context__)192 exc_chain.append(type(exc))193 assert tuple(exc_chain) == (ZeroDivisionError, None, AttributeError, KeyError, IndexError)194 else:195 self.fail("Expected IndexError, but no exception was raised")196 # Check the inner exceptions197 inner_exc = SuppressExc.saved_details[1]198 self.assertIsInstance(inner_exc, ValueError)199 # self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)200 def test_exit_exception_chaining(self):201 # Ensure exception chaining matches the reference behaviour202 exc_chain = []203 def raise_exc(exc):204 frame_exc = sys.exc_info()[0]205 if frame_exc is not None:206 exc_chain.append(frame_exc)207 exc_chain.append(exc)208 raise exc209 saved_details = None210 def suppress_exc(*exc_details):211 nonlocal saved_details212 saved_details = exc_details213 assert exc_chain[-1] == exc_details[0]214 exc_chain[-1] = None215 return True216 try:217 with ExitStack() as stack:218 stack.callback(raise_exc, IndexError)219 stack.callback(raise_exc, KeyError)220 stack.callback(raise_exc, AttributeError)221 stack.push(suppress_exc)222 stack.callback(raise_exc, ValueError)223 1 / 0224 except IndexError as exc:225 # self.assertIsInstance(exc.__context__, KeyError)226 # self.assertIsInstance(exc.__context__.__context__, AttributeError)227 # Inner exceptions were suppressed228 # self.assertIsNone(exc.__context__.__context__.__context__)229 assert tuple(exc_chain) == (ZeroDivisionError, None, AttributeError, KeyError, IndexError)230 else:231 self.fail("Expected IndexError, but no exception was raised")232 # Check the inner exceptions233 inner_exc = saved_details[1]234 self.assertIsInstance(inner_exc, ValueError)235 # self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)236 def test_exit_exception_non_suppressing(self):237 # http://bugs.python.org/issue19092238 def raise_exc(exc):239 raise exc240 def suppress_exc(*exc_details):241 return True242 try:243 with ExitStack() as stack:244 stack.callback(lambda: None)245 stack.callback(raise_exc, IndexError)246 except Exception as exc:247 self.assertIsInstance(exc, IndexError)248 else:249 self.fail("Expected IndexError, but no exception was raised")250 try:251 with ExitStack() as stack:252 stack.callback(raise_exc, KeyError)253 stack.push(suppress_exc)254 stack.callback(raise_exc, IndexError)255 except Exception as exc:256 self.assertIsInstance(exc, KeyError)257 else:258 self.fail("Expected KeyError, but no exception was raised")259 def _test_exit_exception_with_correct_context(self):260 # http://bugs.python.org/issue20317261 @contextmanager262 def gets_the_context_right(exc):263 try:264 yield265 finally:266 raise exc267 exc1 = Exception(1)268 exc2 = Exception(2)269 exc3 = Exception(3)270 exc4 = Exception(4)271 # The contextmanager already fixes the context, so prior to the272 # fix, ExitStack would try to fix it *again* and get into an273 # infinite self-referential loop274 try:275 with ExitStack() as stack:276 stack.enter_context(gets_the_context_right(exc4))277 stack.enter_context(gets_the_context_right(exc3))278 stack.enter_context(gets_the_context_right(exc2))279 raise exc1280 except Exception as exc:281 self.assertIs(exc, exc4)282 self.assertIs(exc.__context__, exc3)283 self.assertIs(exc.__context__.__context__, exc2)284 self.assertIs(exc.__context__.__context__.__context__, exc1)285 self.assertIsNone(286 exc.__context__.__context__.__context__.__context__)287 def _test_exit_exception_with_existing_context(self):288 # Addresses a lack of test coverage discovered after checking in a289 # fix for issue 20317 that still contained debugging code.290 def raise_nested(inner_exc, outer_exc):291 try:292 raise inner_exc293 finally:294 raise outer_exc295 exc1 = Exception(1)296 exc2 = Exception(2)297 exc3 = Exception(3)298 exc4 = Exception(4)299 exc5 = Exception(5)300 try:301 with ExitStack() as stack:302 stack.callback(raise_nested, exc4, exc5)303 stack.callback(raise_nested, exc2, exc3)304 raise exc1305 except Exception as exc:306 self.assertIs(exc, exc5)307 self.assertIs(exc.__context__, exc4)308 self.assertIs(exc.__context__.__context__, exc3)309 self.assertIs(exc.__context__.__context__.__context__, exc2)310 self.assertIs(311 exc.__context__.__context__.__context__.__context__, exc1)312 self.assertIsNone(313 exc.__context__.__context__.__context__.__context__.__context__)314 def test_body_exception_suppress(self):315 def suppress_exc(*exc_details):316 return True317 try:318 with ExitStack() as stack:319 stack.push(suppress_exc)320 1/0321 except IndexError as exc:322 self.fail("Expected no exception, got IndexError")323 def test_exit_exception_chaining_suppress(self):324 with ExitStack() as stack:325 stack.push(lambda *exc: True)326 stack.push(lambda *exc: 1/0)327 stack.push(lambda *exc: {}[1])328 def test_excessive_nesting(self):329 # The original implementation would die with RecursionError here330 with ExitStack() as stack:331 for i in range(10000):332 stack.callback(int)333 def test_instance_bypass(self):334 class Example(object): pass335 cm = Example()336 cm.__exit__ = object()337 stack = ExitStack()338 self.assertRaises(AttributeError, stack.enter_context, cm)339 stack.push(cm)340 self.assertIs(tuple(stack._exit_callbacks)[-1], cm)341if __name__ == '__main__':...
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!!