Best Python code snippet using assertpy_python
base_demo.py
Source:base_demo.py
...12 def test_function(self):13 """æµè¯å½æ°"""14 # 彿°ä¸ç第ä¸ä¸ª"""注éå°±æ¯è¿ä¸ªå½æ°çdoc15 print(func_no_arg.__doc__)16 func_no_arg()17 func_with_arg("arg1 value", "arg2 value")18 # å¯ä»¥éè¿æå®åæ°åä¼ å19 func_with_arg(arg2="arg2 value", arg1="arg1 value")20 # é»è®¤åæ°å¯ä»¥ä¸ä¼ 21 func_with_default_arg("arg value")22 # é»è®¤åæ°ä¼ åå¯ä»¥è¦çé»è®¤å¼23 func_with_default_arg("arg value", "default value override")24 # ä¼ ä»»æåæ°,ä¸è½ä¼ å
³é®åå
¥å(å
¥åæå®åæ°å)25 func_with_any_arg("arg1 value", "arg2 value", 3)26 # ä¼ å
¥éå
³é®åå
¥å(å
¥å䏿å®åæ°å)åå
³é®åå
¥å(å
¥åæå®åæ°å)27 func_args_keyword("arg1 value", "arg2 value", 3, k1="k1 value", k2=2)28 def test_function_annotation(self):29 """æµè¯æ¹æ³æ³¨è§£"""30 func_annnotation(1, -1)31 def test_dispatch(self):32 """åæ´¾"""33 func_obj("str")34class BaseDemo(unittest.TestCase):35 def test_global_var(self):36 """æµè¯global"""37 func_global()38 # églobalçåé,pythonä¼å¨æ¤ä½ç¨åä¸,使ç¨globalçå¼å建ä¸ä¸ªååçå±é¨åé,æ¤åéè·å
¨å±åéæ¯ä¸¤ä¸ªåé39 no_use_global_var = "no_use_global_var override"40 # globalçåé,å°±æ¯è·å
¨å±çå鿝åä¸ä¸ª41 global global_var42 global_var = "global_var override"43 func_global()44 def test_non_local(self):45 """æµè¯non_local"""46 non_local_var = "non_local_var"47 def inner_fun():48 # 表示æ¤åé䏿¯å±é¨åé,ä¹ä¸æ¯å
¨å±åé,ç¨æ¥ä¿®æ¹å¤å±å½æ°çåé49 nonlocal non_local_var50 non_local_var = "non_local_var override"51 inner_fun()52 print(f"non_local_var:{non_local_var}")53 def test_exception(self):54 """æµè¯å¼å¸¸"""55 func_exception(True)56 func_exception(False)57 def test_equal(self):58 class EqualClass:59 def __init__(self, value):60 self.value = value61 def __eq__(self, __o):62 print("__eq__")63 return self.value == __o.value64 a = EqualClass("value")65 b = EqualClass("value")66 # ==夿ç¸ç,è°ç¨__eq__æ¹æ³67 self.assertTrue(a == b)68 # is夿æ¯å¦æ¯åä¸ä¸ªå¯¹è±¡69 self.assertFalse(a is b)70 def test_type(self):71 # isinstance夿æ¯å¦å±äºæå®ç±»å72 print(f"isinstance:{isinstance(1,int)}")73 print(f"type is int {type(1) is int}")74 def test_with(self):75 """76 1. expression被æ§è¡å¾å°è¿åå¼77 2. è°ç¨è¿åå¼ç__enter__æ¹æ³78 3. __enter__çè¿åå¼èµå¼ç»target79 4. æ§è¡withå80 5. è°ç¨expressionè¿åå¼ç__exit__æ¹æ³81 """82 with SimpleWith("without exception") as sw:83 print("do within without exception")84 with SimpleWith("with exception") as sw:85 print("do within with exceptioin")86 raise Exception87 # 妿__exit__è¿åFalse,åè¿ä¼åæåºå¼å¸¸88 try:89 with SimpleWith("with exception exit False", False) as sw:90 print("do within with exceptioin exit False")91 raise Exception92 except BaseException:93 print("handle exception")94 def test_copy(self):95 """æ·±å¤å¶åæµ
å¤å¶"""96 lst = [SimpleCopy("value")]97 # æµ
å¤å¶98 shallow_copy = copy.copy(lst)99 shallow_copy[0].value = "simple_copy value"100 print(f"shallow copy:{lst[0].value}")101 # æ·±å¤å¶102 lst = [SimpleCopy("value")]103 deep_copy = copy.deepcopy(lst)104 deep_copy[0].value = "deep_copy value"105 print(f"deep copy:{lst[0].value}")106 def test_approximate(self):107 """è¿ä¼¼"""108 # round(num[,n]):åèäºå
¥,nè¡¨ç¤ºå°æ°ä½109 print(f"round:{round(1.336,2)}")110 # æ ¼å¼åä¿ç两ä½å°æ°111 print("{:.2f}".format(321.33645))112class LoggerDemo(unittest.TestCase):113 def test_logging(self):114 """æ¥å¿"""115 formatter = "%(asctime)s - %(levelname)s - %(message)s"116 logging.basicConfig(filename=curdir / "file/tmp/log.log", level=logging.DEBUG, format=formatter)117 logger = logging.getLogger()118 ch = logging.StreamHandler()119 ch.setFormatter(logging.Formatter(formatter))120 # 妿é
ç½®çæ¯åå
¥å°æä»¶ç,é»è®¤ä¸ä¼è¾åºå°æ§å¶å°,å æ¤éè¦æ·»å ä¸ä¸ªStreamHandler,ææ¥å¿è¾å
¥å°æ§å¶å°121 logger.addHandler(ch)122 logger.debug("test_logging message")123def func_no_arg():124 """ä¸å¸¦åæ°"""125 print("func_no_arg")126def func_with_arg(arg1, arg2):127 """另忰"""128 print(f"func_with_arg, arg1:{arg1},arg2:{arg2}")129def func_with_default_arg(arg1, default_arg="default value"):130 """带é»è®¤åæ°"""131 print(f"func_with_default_arg, arg1:{arg1},default_arg:{default_arg}")132def func_with_any_arg(*args):133 """*argså¯ä»¥ä¼ ä»»æåæ°,argsæ¯ä¸ªtuple"""134 print(f"func_with_any_arg, args type:{type(args)}, args:{args}")135def func_args_keyword(*args, **kw):136 """带argsåkw,argsæ¥åéå
³é®ååæ°(å
¥å䏿å®åæ°å),kwæ¥æ¶å
³é®ååæ°(å
¥åæå®åæ°å),argsæ¯tuple,kwæ¯dict"""137 print(f"func_args_keyword, args type:{type(args)},args:{args},kw type:{type(kw)},kw:{kw}")...
test_expected_exception.py
Source: test_expected_exception.py
...109 "all err: arg1=a, arg2=b, args=(3, 4), kwargs=[('bar', 2), ('baz', 'dog'), ('foo', 1)]")110# helpers111def func_noop(*args, **kwargs):112 pass113def func_no_arg():114 raise RuntimeError('no arg err')115def func_one_arg(arg):116 raise RuntimeError('one arg err')117def func_multi_args(*args):118 raise RuntimeError('multi args err')119def func_kwargs(**kwargs):120 raise RuntimeError('kwargs err')121def func_all(arg1, arg2, *args, **kwargs):122 raise RuntimeError('all err: arg1=%s, arg2=%s, args=%s, kwargs=%s' % (arg1, arg2, args, [(k, kwargs[k]) for k in sorted(kwargs.keys())]))123class Foo(object):124 def bar(self):...
Check out the latest blogs from LambdaTest on this topic:
Have you ever struggled with handling hidden elements while automating a web or mobile application? I was recently automating an eCommerce application. I struggled with handling hidden elements on the web page.
These days, development teams depend heavily on feedback from automated tests to evaluate the quality of the system they are working on.
Even though several frameworks are available in the market for automation testing, Selenium is one of the most renowned open-source frameworks used by experts due to its numerous features and benefits.
People love to watch, read and interact with quality content — especially video content. Whether it is sports, news, TV shows, or videos captured on smartphones, people crave digital content. The emergence of OTT platforms has already shaped the way people consume content. Viewers can now enjoy their favorite shows whenever they want rather than at pre-set times. Thus, the OTT platform’s concept of viewing anything, anytime, anywhere has hit the right chord.
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!!