How to use start_tracing method in Playwright Python

Best Python code snippet using playwright-python

advanced_square_curve.py

Source:advanced_square_curve.py Github

copy

Full Screen

...15 }16 nb = NumberBox(scale_factor=1).move_to(2*UP, DOWN)17 self.add(nb)18 self.wait()19 nb.start_tracing(self, flash_dict)20 self.embed()212223class Happy2022(Scene):24 def construct(self):25 flash_dict = {26 "line_length": 0.5,27 "num_lines": 12,28 "flash_radius": 0.5,29 "line_stroke_width": 3,30 "run_time": 2,31 }32 TWO = NumberBoxGroup([3, 4, 10, 11])33 self.add(TWO)34 # TWO.start_tracing(self, flash_dict)353637class FinalWay2022(Scene):38 def construct(self):39 flash_dict = {40 "line_length": 0.5,41 "num_lines": 12,42 "flash_radius": 0.5,43 "line_stroke_width": 3,44 "run_time": 2,45 }46 nb = VGroup()47 nb_sub = VGroup()48 v = [2*UP, UP, ORIGIN, DOWN, 2*DOWN]49 h = [LEFT, ORIGIN, RIGHT]50 for i in v:51 for j in h:52 nb_sub.add(NumberBox(scale_factor=0.5).move_to(i+j))53 nb.add(nb_sub)54 nb = nb[0]55 nb2 = nb.copy()56 # NumberBox().start_tracing(self, flash_dict, 4, False)57 emp_list = [3, 4, 10, 11]58 emp_list2 = [4,7,10]59 just = 060 for i in emp_list:61 nb.remove(nb[i-just])62 just += 163 just = 064 for k in emp_list2:65 nb2.remove(nb2[k-just])66 just += 167 nb3 = nb.copy()68 nb4 = nb.copy() 69 self.add(nb.shift(5*RIGHT), nb2.shift(1.7*LEFT), nb3.shift(1.7*RIGHT), nb4.shift(5*LEFT))70 for i in range(len(nb)):71 if isinstance(nb[i], NumberBox):72 nb[i].start_tracing(self, flash_dict, 4, False)737475class Hope(Scene):76 def construct(self):77 flash_dict = {78 "line_length": 0.5,79 "num_lines": 12,80 "flash_radius": 0.5,81 "line_stroke_width": 3,82 "run_time": 2,83 }84 nb = VGroup()85 nb_sub = VGroup()86 v = [2*UP, UP, ORIGIN, DOWN, 2*DOWN]87 h = [LEFT, ORIGIN, RIGHT]88 for i in v:89 for j in h:90 nb_sub.add(NumberBox(scale_factor=0.5).move_to(i+j))91 nb.add(nb_sub)92 nb = nb[0]93 emp_list = [3, 4, 10, 11]94 just = 095 for i in emp_list:96 nb.remove(nb[i-just])97 just += 198 def get_2():99 return nb.copy()100 def doit(mob):101 for i in range(len(mob)):102 mob[i].start_tracing(self, flash_dict, 4, False)103 a = get_2()104 self.add(a)105 doit(a)106 self.wait(4)107108109class NumberBox(VGroup):110 def __init__(self, line_width: int = 0.6, scale_factor: int = 3.5, *vmobjects, **kwargs):111 super().__init__(*vmobjects, **kwargs)112 x, y = RIGHT, UP113 self.line_width = line_width114 self.scale_factor = scale_factor115 color_code = f"""116 vec3 blue = vec3{tuple(hex_to_rgb(BLUE))};117 vec3 red = vec3{tuple(hex_to_rgb(RED))};118 vec3 green = vec3{tuple(hex_to_rgb(GREEN))};119 color.rgb = mix(blue, red, (point.x));120 """121 self.square = Square().scale(self.scale_factor).set_color_by_code(122 color_code123 )124 self.dot_a = Dot(color=BLUE).move_to((-x+y)*self.scale_factor).scale(scale_factor*1.5)125 self.dot_b = Dot(color=RED).move_to((x+y)*self.scale_factor).scale(scale_factor*1.5)126 self.dot_c = Dot(color=RED).move_to((x-y)*self.scale_factor).scale(scale_factor*1.5)127 self.dot_d = Dot(color=BLUE).move_to((-x-y)*self.scale_factor).scale(scale_factor*1.5)128 self.dot_a.add_updater(129 lambda mob: mob.move_to(self.square.get_center() + (-x+y)*self.scale_factor)130 )131 self.dot_b.add_updater(132 lambda mob: mob.move_to(self.square.get_center() + (x+y)*self.scale_factor)133 )134 self.dot_c.add_updater(135 lambda mob: mob.move_to(self.square.get_center() + (x-y)*self.scale_factor)136 )137 self.dot_d.add_updater(138 lambda mob: mob.move_to(self.square.get_center() + (-x-y)*self.scale_factor)139 )140 self.dots = VGroup(141 self.dot_a,142 self.dot_b,143 self.dot_c,144 self.dot_d145 )146 self.ab = Line().set_color_by_code(color_code)147 self.bc = Line().set_color(RED)148 self.cd = Line().set_color_by_code(color_code)149 self.da = Line().set_color(BLUE)150 self.lines = VGroup(151 self.ab,152 self.bc,153 self.cd,154 self.da155 )156 self.trace = VGroup()157 self.add(158 self.square,159 self.trace,160 *self.dots161 )162 # self.scale(0.1)163 '''164 def move_to(self, point_or_mobject, aligned_edge=ORIGIN, coor_mask=np.array([1, 1, 1])):165 x, y = RIGHT, UP166 self.square.move_to(point_or_mobject, aligned_edge=aligned_edge, coor_mask=coor_mask)167 self.trace.move_to(point_or_mobject, aligned_edge=aligned_edge, coor_mask=coor_mask)168 self.dot_a.move_to(point_or_mobject + (-x+y)*self.scale_factor)169 self.dot_b.move_to(point_or_mobject + (x+y)*self.scale_factor)170 self.dot_c.move_to(point_or_mobject + (x-y)*self.scale_factor)171 self.dot_d.move_to(point_or_mobject + (-x-y)*self.scale_factor)172 return self 173 '''174175 def _get_dot_updater(self, tar: Mobject, rate: int = 0.07) -> FunctionType:176 return lambda mob, dt: mob.shift((tar.get_center() - mob.get_center()) * dt* rate * 1/self.scale_factor)177178 @staticmethod179 def _get_line_connection_updater(a: Dot, b: Dot):180 return lambda line: line.put_start_and_end_on(a.get_center(), b.get_center())181182 def _get_center(self):183 return (sum(self.square.get_center()))184185 def start_tracing(self, scene: Scene, flash_dict: dict = None, _time: float = 4, end_effect = True):186 # NOTE Using add(self.dots) will appear bugs!! Have to add them all187 self.add(*self.dots, self.lines)188 self.dot_a.clear_updaters()189 self.dot_b.clear_updaters()190 self.dot_c.clear_updaters()191 self.dot_d.clear_updaters()192 # self.add_updater(lambda mob, dt: mob.shift(dt*LEFT))193 # assert(self.dots[0] is self.dot_a)194 self.dot_a.add_updater((self._get_dot_updater(self.dot_b)))195 self.dot_b.add_updater((self._get_dot_updater(self.dot_c)))196 self.dot_c.add_updater((self._get_dot_updater(self.dot_d)))197 self.dot_d.add_updater((self._get_dot_updater(self.dot_a)))198 self.ab.add_updater(NumberBox._get_line_connection_updater(self.dot_a, self.dot_b))199 self.bc.add_updater(NumberBox._get_line_connection_updater(self.dot_b, self.dot_c))200 self.cd.add_updater(NumberBox._get_line_connection_updater(self.dot_c, self.dot_d))201 self.da.add_updater(NumberBox._get_line_connection_updater(self.dot_d, self.dot_a))202 self.trace.add_updater(203 lambda a, dt: a.add(204 *[mob.copy().clear_updaters().set_stroke(width=self.line_width) for mob in self.lines]205 )206 )207 if end_effect:208 scene.wait(_time)209 # scene.play(*[FadeOut(mb) for mb in [*self.dots]])210 scene.play(211 Flash(212 self.get_center(),213 **flash_dict214 ) if flash_dict else215 Flash(216 self.get_center(),217 )218 )219 return self220221class NumberBoxGroup(VGroup):222 def __init__(223 self, 224 null_array: list =[],225 scale_factor_: float=.5, 226 *vmobjects, 227 **kwargs):228 super().__init__(*vmobjects, **kwargs)229 # self.scale_factor_ = scale_factor_230 self.nb = NumberBox(scale_factor=scale_factor_)231 self.null_array = null_array232 num_array: VGroup = (self.nb*15).arrange_in_grid(5, 3, buff=0)233 # num_array: VGroup = self._form_group()234 '''for i in range(num_array.__len__()):235 if i in null_array:236 num_array[i].set_color(BLACK)'''237 self.add(*num_array)238239 def _form_group(self, row=5, col=3):240 nb = VGroup()241 v = [2*UP, UP, ORIGIN, DOWN, 2*DOWN]242 h = [LEFT, ORIGIN, RIGHT]243 for n1, i in enumerate(v):244 for n2, j in enumerate(h):245 if not (n1*3+n2) in self.null_array:246 nb.add(NumberBox(scale_factor=0.5).move_to(i+j))247 return nb248249 def start_tracing(self, scene: Scene, flash_dict: dict = None, _time: float = 4, end_effect=True):250 print(len(self))251 for i in range(len(self)):252 self[i].start_tracing(253 scene,254 flash_dict,255 # end_effect=False256 )257 if not end_effect:258 return self259 scene.wait(_time)260 scene.play(261 *[Flash(262 n._get_center(),263 **flash_dict264 ) if flash_dict else265 Flash(266 n._get_center(),267 ) for n in self]268 )269270271class CoolNumber(VGroup):272 def __init__(self, emp_list = [3, 4, 10, 11], *vmobjects, **kwargs):273 self.flash_dict = {274 "line_length": 0.5,275 "num_lines": 12,276 "flash_radius": 0.5,277 "line_stroke_width": 3,278 "run_time": 2,279 }280 super().__init__(*vmobjects, **kwargs)281 self.nb = VGroup()282 self.nb_sub = VGroup()283 v = [2*UP, UP, ORIGIN, DOWN, 2*DOWN]284 h = [LEFT, ORIGIN, RIGHT]285 for i in v:286 for j in h:287 self.nb_sub.add(NumberBox(scale_factor=0.5).move_to(i+j))288 self.nb.add(self.nb_sub)289 self.nb = self.nb[0]290 print(*self.nb)291 # NumberBox().start_tracing(self, flash_dict, 4, False)292 self.emp_list = emp_list293 just = 0294 for i in self.emp_list:295 self.nb.remove(self.nb[i-just])296 just += 1297 self.add(*self.nb)298299 def start_tracing(self):300 for i in range(len(self.nb)):301 if isinstance(self.nb[i], NumberBox):302 self.nb[i].start_tracing(self, self.flash_dict, 4, False)303304305class NormalNumber(VGroup):306 def __init__(self, emp_list = [3, 4, 10, 11], sf=0.5, *vmobjects, **kwargs):307 self.flash_dict = {308 "line_length": 0.5,309 "num_lines": 12,310 "flash_radius": 0.5,311 "line_stroke_width": 3,312 "run_time": 2,313 }314 super().__init__(*vmobjects, **kwargs)315 self.nb = VGroup()316 self.nb_sub = VGroup()317 v = [2*UP, UP, ORIGIN, DOWN, 2*DOWN]318 h = [LEFT, ORIGIN, RIGHT]319 for i in v:320 for j in h:321 self.nb_sub.add(Square(color=GREY).move_to(i+j).scale(sf))322 self.nb.add(self.nb_sub)323 self.nb = self.nb[0]324 print(*self.nb)325 # NumberBox().start_tracing(self, flash_dict, 4, False)326 self.emp_list = emp_list327 just = 0328 for i in self.emp_list:329 self.nb.remove(self.nb[i-just])330 just += 1331 self.add(*self.nb)332333334class LastTry(Scene):335 def construct(self):336 a = CoolNumber()337 self.add(a.move_to(5*LEFT))338 b = CoolNumber([4,7,10]).move_to(1.7*LEFT)339 c = CoolNumber().move_to(1.7*RIGHT)340 d = CoolNumber().move_to(5*RIGHT)341 self.add(b, c, d)342 a.start_tracing()343 b.start_tracing()344 c.start_tracing()345 d.start_tracing()346 self.wait(10)347348349class Final(Scene):350 def construct(self):351 fr: CameraFrame = self.camera.frame352 fr.save_state()353 a0 = NormalNumber()354 self.add(a0.move_to(5*LEFT))355 b0 = NormalNumber([4,7,10]).move_to(1.7*LEFT)356 c0 = NormalNumber().move_to(1.7*RIGHT)357 d0 = NormalNumber().move_to(5*RIGHT)358 e0 = NormalNumber([0,1,3,4,6,7,9,10,12,13]).move_to(5*RIGHT)359 self.add(b0, c0, e0)360 self.wait(2)361 tx1 = Text('新年快乐!', font='楷体', color=RED).scale(3).shift(4.2*UP)362 bx1 = SurroundingRectangle(tx1, color=YELLOW)363 p = VGroup(364 Text('回首2021', font='楷体'),365 Text('也许对你我来说并无乐趣', font='楷体'),366 Text('又或者你遇到了很多烦恼', font='楷体'),367 Text('但即便如此', font='楷体'),368 Text('拥有一个灰色的过去', font='楷体'),369 Text('也丝毫不会另我们', font='楷体'),370 Text('怀疑未来的灿烂色彩', font='楷体'),371 )372 fr.scale(1.5)373 self.play(fr.animate.scale(1.5), fr.animate.shift(4*RIGHT))374 p.arrange(DOWN)375 p.move_to(10.5*RIGHT + UP)376 self.play(Write(p[0]), run_time = 1.5)377 self.play(Write(p[1]), Write(p[2]), run_time =2)378 self.play(379 Write(p[3]),380 TransformMatchingShapes(e0, d0), run_time=3381 )382 a = CoolNumber()383 a.move_to(5*LEFT)384 b = CoolNumber([4,7,10]).move_to(1.7*LEFT)385 c = CoolNumber().move_to(1.7*RIGHT)386 d = CoolNumber().move_to(5*RIGHT)387 olds = [a0, b0, c0, d0]388 news = [a,b,c,d]389 self.play(390 Write(p[4]),391 *[TransformMatchingShapes(m1, m2) for m1, m2 in zip(olds, news)],392 rate_func=rush_into393 )394 self.wait(2)395 self.play(Write(p[5]))396 #a.start_tracing()397 #b.start_tracing()398 #c.start_tracing()399 #d.start_tracing()400 self.wait(1)401 self.play(Write(p[6]), run_time = 3)402 self.play(fr.animate.restore())403 self.play(404 fr.animate.shift(1.3*UP), 405 Write(tx1), 406 ShowCreation(bx1),407 *[FadeOut(mob) for mob in p]408 )409 flash_dict = {410 "line_length": 0.5,411 "num_lines": 12,412 "flash_radius": 0.5,413 "line_stroke_width": 3, ...

Full Screen

Full Screen

test_docgen.py

Source:test_docgen.py Github

copy

Full Screen

...30def test_basic():31 descs = {"fun":fun}32 ds = DocStorage().from_dict(descs)33 t = Tracer(ds)34 t.start_tracing()35 fun(1, ("g", 3), 8)36 fun(2., ("a", 1.), "a")37 t.end_tracing()38 desc = ds.descs['fun']39 inputcells = desc.inputcells40 assert len(inputcells) == 341 assert isinstance(inputcells[0], model.SomeUnion)42 assert isinstance(inputcells[1], model.SomeTuple)43 assert isinstance(inputcells[2], model.SomeUnion)44 assert isinstance(desc.retval, model.SomeString)45 cs = sorted(desc.call_sites.keys())46 assert len(cs) == 247 f_name = cut_pyc(__file__)48 assert len(cs[0]) == 149 assert len(cs[1]) == 150 assert cs[1][0].filename == f_name51 # lines are counted from 052 num = test_basic.func_code.co_firstlineno53 assert cs[1][0].lineno == num + 4 or cs[1][0].lineno == num + 554 assert cs[0][0].filename == f_name55 assert cs[0][0].lineno == num + 5 or cs[0][0].lineno == num + 456 if 0:57 pds = PermaDocStorage(DocStorageAccessor(ds))58 assert pds.get_function_names() == ['fun']59 sig = pds.get_function_signature('fun')60 assert sig[0][0][0] == 'a'61 assert isinstance(sig[0][0][1], model.SomeUnion)62 assert len(pds.get_function_callpoints('fun')) == 26364class AClass(object):65 """ Class docstring66 """67 def __init__(self, b="blah"):68 pass69 70 def exposed_method(self, a, b, c):71 """ method docstring72 """73 return self._hidden_method()74 75 def _hidden_method(self):76 """ should not appear77 """78 return "z"7980class ANotherClass(AClass):81 def another_exposed_method(self, a):82 # no docstring83 return a8485def test_class():86 descs = {'AClass':AClass}87 ds = DocStorage().from_dict(descs)88 t = Tracer(ds)89 t.start_tracing()90 s = AClass()91 s.exposed_method(1, 2., [1,2,3])92 t.end_tracing()93 desc = ds.descs['AClass']94 inputcells = desc.fields['__init__'].inputcells95 assert len(inputcells) == 296 assert isinstance(inputcells[0], model.SomeInstance)97 #assert inputcells[0].classdef.classdesc.pyobj is SomeClass98 # XXX: should work99 assert isinstance(inputcells[1], model.SomeString)100 f_name = __file__101 if f_name.endswith('.pyc'):102 f_name = f_name[:-1]103 cs = sorted(desc.fields['__init__'].call_sites.keys())104 assert len(cs) == 1105 assert len(cs[0]) == 1106 assert cs[0][0].filename == f_name107 assert cs[0][0].lineno == test_class.func_code.co_firstlineno + 4108 # method check109 assert sorted(desc.getfields()) == ['__init__', 'exposed_method']110 inputcells = desc.fields['exposed_method'].inputcells111 assert len(inputcells) == 4112 assert isinstance(inputcells[0], model.SomeInstance)113 #assert inputcells[0].classdef.classdesc.pyobj is SomeClass114 # XXX should work115 assert isinstance(inputcells[1], model.SomeInt)116 assert isinstance(inputcells[2], model.SomeFloat)117 assert isinstance(inputcells[3], model.SomeList)118 assert isinstance(desc.fields['exposed_method'].retval, model.SomeString)119 if 0:120 pds = PermaDocStorage(DocStorageAccessor(ds))121 assert pds.get_class_names() == ['AClass']122 assert len(pds.get_function_signature('AClass.exposed_method')[0]) == 4123124def other_fun():125 pass126127def test_add_desc():128 ds = DocStorage().from_dict({})129 ds.add_desc("one", fun)130 ds.add_desc("one", other_fun)131 assert sorted(ds.descs.keys()) == ["one", "one_1"]132 assert isinstance(ds.descs["one"], FunctionDesc)133 assert isinstance(ds.descs["one_1"], FunctionDesc)134 assert ds.descs["one"].pyobj is fun135 assert ds.descs["one_1"].pyobj is other_fun136 assert ds.desc_cache[ds.descs["one"]] is ds.descs["one"]137 assert ds.desc_cache[ds.descs["one_1"]] is ds.descs["one_1"]138139def test_while_call():140 ds = DocStorage().from_dict({"other_fun":other_fun})141 t = Tracer(ds)142 t.start_tracing()143 for x in xrange(8):144 other_fun()145 t.end_tracing()146 desc = ds.descs["other_fun"]147 assert len(desc.call_sites.keys()) == 1148 #assert isinstance(desc.call_sites.values()[0][0], py.code.Frame)149 if 0:150 pds = PermaDocStorage(DocStorageAccessor(ds))151 assert len(pds.get_function_callpoints("other_fun")) == 1152153class A(object):154 def method(self, x):155 self.x = x156157class B:158 def method(self, x):159 self.x = x160161def test_without_init():162 ds = DocStorage().from_dict({'A':A, 'B':B})163 t = Tracer(ds)164 t.start_tracing()165 x = A()166 y = B()167 x.method(3)168 y.method(4)169 t.end_tracing()170 assert isinstance(ds.descs['A'].fields['method'].inputcells[1],171 model.SomeInt)172 assert isinstance(ds.descs['B'].fields['method'].inputcells[1],173 model.SomeInt)174 if 0:175 pds = PermaDocStorage(DocStorageAccessor(ds))176177def test_local_changes():178 class testclass(object):179 def __init__(self):180 self.foo = 0181 def bar(self, x):182 self.foo = x183 ds = DocStorage().from_dict({'testclass': testclass})184 t = Tracer(ds)185 t.start_tracing()186 c = testclass()187 c.bar(1)188 t.end_tracing()189 desc = ds.descs['testclass']190 methdesc = desc.fields['bar']191 #assert methdesc.old_dict != methdesc.new_dict192 assert methdesc.get_local_changes() == {'foo': set(['changed'])}193 return ds194195def test_local_changes_nochange():196 class testclass(object):197 def __init__(self):198 self.foo = 0199 def bar(self, x):200 self.foo = x201 ds = DocStorage().from_dict({'testclass': testclass})202 t = Tracer(ds)203 t.start_tracing()204 c = testclass()205 t.end_tracing()206 desc = ds.descs['testclass']207 methdesc = desc.fields['bar']208 assert methdesc.get_local_changes() == {}209 return ds210211def test_multiple_classes_with_same_init():212 class A:213 def __init__(self, x):214 self.x = x215 216 class B(A):217 pass218 219 ds = DocStorage().from_dict({'A':A, 'B':B})220 t = Tracer(ds)221 t.start_tracing()222 c = A(3)223 d = B(4)224 t.end_tracing()225 assert len(ds.descs['A'].fields['__init__'].call_sites) == 1226 assert len(ds.descs['B'].fields['__init__'].call_sites) == 1227 return ds228229def test_exception_raise():230 def x():231 1/0232 233 def y():234 try:235 x()236 except ZeroDivisionError:237 pass238 239 def z():240 y()241 242 ds = DocStorage().from_dict({'x':x, 'y':y, 'z':z})243 t = Tracer(ds)244 t.start_tracing()245 z()246 t.end_tracing()247 assert ds.descs['x'].exceptions.keys() == [ZeroDivisionError]248 assert ds.descs['y'].exceptions.keys() == [ZeroDivisionError]249 assert ds.descs['z'].exceptions.keys() == []250 return ds251252def test_subclass():253 descs = {'ANotherClass': ANotherClass}254 ds = DocStorage().from_dict(descs)255 t = Tracer(ds)256 t.start_tracing()257 s = ANotherClass('blah blah')258 s.another_exposed_method(1)259 t.end_tracing()260 desc = ds.descs['ANotherClass']261 assert len(desc.fields) == 4262 inputcells = desc.fields['__init__'].inputcells263 assert len(inputcells) == 2264 inputcells = desc.fields['another_exposed_method'].inputcells265 assert len(inputcells) == 2266 bases = desc.bases267 assert len(bases) == 2268 return ds269 270def test_bases():271 class A:272 pass273 274 class B:275 pass276 277 class C(A,B):278 pass279 280 ds = DocStorage().from_dict({'C':C, 'B':B})281 dsa = DocStorageAccessor(ds)282 for desc in dsa.get_possible_base_classes('C'):283 assert desc is ds.descs['B'] or desc.is_degenerated284 return ds285286def test_desc_from_pyobj():287 class A:288 pass289290 class B(A):291 pass292293 ds = DocStorage().from_dict({'A': A, 'B': B})294 dsa = DocStorageAccessor(ds)295 assert dsa.desc_from_pyobj(A, 'A') is ds.descs['A']296 return ds297298def test_method_origin():299 class A:300 def foo(self):301 pass302303 class B(A):304 def bar(self):305 pass306307 class C(B):308 pass309310 ds = DocStorage().from_dict({'C': C, 'B': B})311 dsa = DocStorageAccessor(ds)312 origin = dsa.get_method_origin('C.bar')313 assert origin is ds.descs['B']314 return ds315316def test_multiple_methods():317 class A(object):318 def meth(self):319 pass320 321 class B(A):322 pass323 324 class C(A):325 pass326 327 ds = DocStorage().from_dict({'C':C, 'B':B})328 dsa = DocStorageAccessor(ds)329 t = Tracer(ds)330 t.start_tracing()331 B().meth()332 C().meth()333 t.end_tracing()334 assert len(ds.descs['B'].fields['meth'].call_sites) == 1335 assert len(ds.descs['C'].fields['meth'].call_sites) == 1336 return ds337338def test_is_private():339 # XXX implicit test, but so are the rest :|340 class Foo(object):341 def foo(self):342 pass343 def _foo(self):344 pass345 def __foo(self):346 pass347 def trigger__foo(self):348 self.__foo()349 def __foo__(self):350 pass351352 ds = DocStorage().from_dict({'Foo': Foo})353 dsa = DocStorageAccessor(ds)354 t = Tracer(ds)355 t.start_tracing()356 f = Foo()357 f.foo()358 f._foo()359 f.trigger__foo()360 f.__foo__()361 t.end_tracing()362 assert sorted(ds.descs['Foo'].getfields()) == ['__foo__', 'foo',363 'trigger__foo']364365def setup_fs_project():366 temp = py.test.ensuretemp('test_get_initpkg_star_items')367 temp.ensure("pkg/func.py").write(py.code.Source("""\368 def func(arg1):369 "docstring"370 """))371 temp.ensure('pkg/someclass.py').write(py.code.Source("""\372 class SomeClass(object):373 " docstring someclass "374 def __init__(self, somevar):375 self.somevar = somevar376 377 def get_somevar(self):378 " get_somevar docstring "379 return self.somevar380 SomeInstance = SomeClass(10)381 """))382 temp.ensure('pkg/somesubclass.py').write(py.code.Source("""\383 from someclass import SomeClass384 class SomeSubClass(SomeClass):385 " docstring somesubclass "386 #def get_somevar(self):387 # return self.somevar + 1388 """))389 temp.ensure('pkg/somenamespace.py').write(py.code.Source("""\390 from pkg.main.sub import func391 import py392 393 def foo():394 return 'bar'395396 def baz(qux):397 return qux398399 quux = py.code.Source('print "foo"')400 """))401 temp.ensure("pkg/__init__.py").write(py.code.Source("""\402 from py.initpkg import initpkg403 initpkg(__name__, exportdefs = {404 'main.sub.func': ("./func.py", "func"),405 'main.SomeClass': ('./someclass.py', 'SomeClass'),406 #'main.SomeInstance': ('./someclass.py', 'SomeInstance'),407 'main.SomeSubClass': ('./somesubclass.py', 'SomeSubClass'),408 'other': ('./somenamespace.py', '*'),409 })410 """))411 return temp, 'pkg'412413def setup_pkg_docstorage():414 pkgdir, pkgname = setup_fs_project()415 py.std.sys.path.insert(0, str(pkgdir))416 # XXX test_get_initpkg_star_items depends on package not417 # being imported already418 for key in py.std.sys.modules.keys():419 if key == pkgname or key.startswith(pkgname + "."):420 del py.std.sys.modules[key]421 pkg = __import__(pkgname)422 ds = DocStorage().from_pkg(pkg)423 return pkg, ds424425def test_get_initpkg_star_items():426 pkg, ds = setup_pkg_docstorage()427 sit = get_star_import_tree(pkg.other, 'pkg.other')428 assert sorted(sit.keys()) == ['pkg.other.baz', 'pkg.other.foo']429 t = Tracer(ds)430 t.start_tracing()431 pkg.main.sub.func("a1")432 pkg.main.SomeClass(3).get_somevar()433 pkg.main.SomeSubClass(4).get_somevar()434 t.end_tracing()435 assert isinstance(ds.descs['main.sub.func'].inputcells[0], model.SomeString)436 desc = ds.descs['main.SomeClass']437 assert ds.descs['main.SomeClass.get_somevar'] is desc.fields['get_somevar']438 cell = desc.fields['get_somevar'].inputcells[0]439 assert isinstance(cell, model.SomeInstance)440 assert cell.classdef.cls is desc.pyobj441 desc = ds.descs['main.SomeSubClass']442 assert ds.descs['main.SomeSubClass.get_somevar'] is desc.fields['get_somevar']443 cell = desc.fields['get_somevar'].inputcells[0]444 assert isinstance(cell, model.SomeInstance) ...

Full Screen

Full Screen

log_helping.py

Source:log_helping.py Github

copy

Full Screen

...38 if type(traces) == list:39 self.traces.extend(traces)40 if type(traces) == str:41 self.traces.append(traces)42 def start_tracing(self):43 for trace in self.traces:44 LOGGER.debug("setting traces for %s", trace)45 self.tracer.enable_logging(trace, self.log_level)46 def stop_tracing(self):47 for trace in self.traces:48 LOGGER.debug("stopping traces for %s", trace)49 self.tracer.disable_logging(trace)50 def get_logging(self):51 return self.tracer.get_messages()52 def wait_until_message_received(self, message, timeout):53 self.tracer.wait_until_message_received(message, timeout)54 def _format_event_data(self, e, format="string"):55 if format == "string":56 message = " reception date: {} message: '{}' error:{}".format(57 e.reception_date, e.attr_value.value, e.err58 )59 elif format == "dict":60 message = {61 "reception date": e.reception_date,62 "message": e.attr_value.value,63 "error": e.err,64 }65 return message66 def get_printable_messages(self):67 messages = self.tracer.get_messages()68 msg_counter = 069 printout = ""70 for message in messages:71 msg_counter += 172 printout += str(msg_counter) + self._format_event_data(message) + "\n"73 return printout74 def get_messages_as_list_dict(self):75 messages = self.tracer.get_messages()76 return [self._format_event_data(message, format="dict") for message in messages]77# abstraction of Device logging implemenetation is set by implementation object and mappoing is defined in shim dictionary78class DeviceLogging:79 def __init__(self, implementation="TracerHelper"):80 if implementation == "TracerHelper":81 self.implementation = DeviceLoggingImplWithTraceHelper()82 self._shim = {83 "set_logging_level": self.implementation.set_logging_level,84 "update_traces": self.implementation.update_traces,85 "stop_tracing": self.implementation.stop_tracing,86 "get_logging": self.implementation.get_logging,87 "start_tracing": self.implementation.start_tracing,88 "wait_until_message_received": self.implementation.wait_until_message_received,89 "get_printable_messages": self.implementation.get_printable_messages,90 "get_messages_as_list_dict": self.implementation.get_messages_as_list_dict,91 }92 elif implementation == "DeviceLoggingImplWithDBDirect":93 self.implementation = DeviceLoggingImplWithDBDirect()94 self._shim = {95 "set_logging_level": self.implementation.set_logging_level,96 "update_traces": self.implementation.update_devices_to_be_logged,97 "stop_tracing": self.implementation.stop_tracing,98 "get_logging": self.implementation.get_logging,99 "start_tracing": self.implementation.start_tracing,100 "wait_until_message_received": self.implementation.wait_until_message_received,101 "get_printable_messages": self.implementation.get_printable_messages,102 "get_messages_as_list_dict": self.implementation.get_messages_as_list_dict,103 }104 else:105 raise Exception(106 "unknown implentation of Device logging {}".format(implementation)107 )108 def set_logging_level(self, level):109 self._shim["set_logging_level"](level)110 def update_traces(self, traces):111 self._shim["update_traces"](traces)112 def start_tracing(self):113 self._shim["start_tracing"]()114 def stop_tracing(self):115 self._shim["stop_tracing"]()116 def get_logging(self):117 return self._shim["get_logging"]()118 def wait_until_message_received(self, message, timeout):119 self._shim["wait_until_message_received"](message, timeout)120 def get_printable_messages(self):121 return self._shim["get_printable_messages"]()122 def get_messages_as_list_dict(self):123 return self._shim["get_messages_as_list_dict"]()124class DeviceLoggingImplWithDBDirect:125 def __init__(self, es=None):126 if es == None:127 self.local = self.is_local()128 if self.local:129 es = Elasticsearch(130 [131 {132 "host": "{}-{}".format(133 "elastic-logging", os.environ.get("HELM_RELEASE")134 ),135 "port": 9200,136 }137 ]138 )139 else:140 es = Elasticsearch([{"host": "192.168.93.94", "port": 9200}])141 else:142 # injected es is assumed to be local143 self.local = True144 self.es = es145 # assumes the search is always only on todays logs146 if self.local:147 index = "logstash-{}".format(date.today().strftime("%Y.%m.%d"))148 else:149 index = "filebeat-{}".format(date.today().strftime("%Y.%m.%d"))150 self.search = Search(using=es, index=index)151 self.containers_to_devices = {}152 self.Qs = None153 self.start_time = None154 self.running = False155 self.source_includes = [156 "ska_log_message",157 "ska_log_timestamp",158 "kubernetes.container_name",159 "kubernetes.pod_name",160 ]161 def is_local(self, port=9200, elastic_name="elastic-logging"):162 HELM_RELEASE = os.environ.get("HELM_RELEASE")163 elastic_host = "{}-{}".format(elastic_name, HELM_RELEASE)164 tracer = TraceHelper()165 return tracer.check_port(elastic_host, port) == 0166 def start_tracing(self):167 self.start_time = datetime.now()168 self.running = True169 def set_logging_level(self, level):170 # TODO implement filtering based on log level171 self.logging = level172 def get_logging(self):173 # TODO implement filtering based on log level174 return self.logging175 def wait_until_message_received(self, message, timeout):176 # returns immediately as this behaviour cant be done by this object177 return178 def _update_containers_to_devices(self, device, container):179 if container in self.containers_to_devices.keys():180 self.containers_to_devices[container] += "/{}".format(device)...

Full Screen

Full Screen

panic.py

Source:panic.py Github

copy

Full Screen

...52 self._debug_print("PanicLogger::initialize")53 # Initialize Logger base class54 Logger.initialize(self)55 # Call start_tracing earlier to stop execution earlier56 self.start_tracing()57 def start_tracing(self):58 self._debug_print("start_tracing")59 trace_name, trace_path = self.get_trace_name("Enter <<trace name>> to start panic tracing? :")60 if trace_name:61 self.set_trace_path(trace_path, trace_name)62 self.get_build_info()63 # TODO Problem, there is no Sideband.bin info yet64 # Quick Fix65 # Start tracing, wait 100ms, Stop tracing, fetch sideband info66 Logger.start_tracing(self)67 time.sleep(0.2)68 Logger.stop_tracing(self)69 time.sleep(0.2)70 Logger.get_sideband_data(self)71 self.dump_kernel()72 self.dump_linux_gate()73 self.dump_kernel_modules()74 Logger.start_tracing(self)75 print ""76 print "Panic tracing activated"77 print "If panic happens, wait 10s and reboot device."78 print ""79 print "When device boot up run following command:"80 print "sat-panic-fetch " + self.trace_name81 sys.exit(0)82 else:83 print "Panic Tracer did not get started"84 def stop_tracing(self):85 return86 def get_data(self):87 return88 def get_trace_data(self):...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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