Best JavaScript code snippet using root
test_pep380.py
Source:test_pep380.py
1# -*- coding: utf-8 -*-2"""3Test suite for PEP 380 implementation4adapted from original tests written by Greg Ewing5see <http://www.cosc.canterbury.ac.nz/greg.ewing/python/yield-from/YieldFrom-Python3.1.2-rev5.zip>6"""7import unittest8import io9import sys10import inspect11import parser12from test.support import captured_stderr, disable_gc, gc_collect13class TestPEP380Operation(unittest.TestCase):14 """15 Test semantics.16 """17 def test_delegation_of_initial_next_to_subgenerator(self):18 """19 Test delegation of initial next() call to subgenerator20 """21 trace = []22 def g1():23 trace.append("Starting g1")24 yield from g2()25 trace.append("Finishing g1")26 def g2():27 trace.append("Starting g2")28 yield 4229 trace.append("Finishing g2")30 for x in g1():31 trace.append("Yielded %s" % (x,))32 self.assertEqual(trace,[33 "Starting g1",34 "Starting g2",35 "Yielded 42",36 "Finishing g2",37 "Finishing g1",38 ])39 def test_raising_exception_in_initial_next_call(self):40 """41 Test raising exception in initial next() call42 """43 trace = []44 def g1():45 try:46 trace.append("Starting g1")47 yield from g2()48 finally:49 trace.append("Finishing g1")50 def g2():51 try:52 trace.append("Starting g2")53 raise ValueError("spanish inquisition occurred")54 finally:55 trace.append("Finishing g2")56 try:57 for x in g1():58 trace.append("Yielded %s" % (x,))59 except ValueError as e:60 self.assertEqual(e.args[0], "spanish inquisition occurred")61 else:62 self.fail("subgenerator failed to raise ValueError")63 self.assertEqual(trace,[64 "Starting g1",65 "Starting g2",66 "Finishing g2",67 "Finishing g1",68 ])69 def test_delegation_of_next_call_to_subgenerator(self):70 """71 Test delegation of next() call to subgenerator72 """73 trace = []74 def g1():75 trace.append("Starting g1")76 yield "g1 ham"77 yield from g2()78 yield "g1 eggs"79 trace.append("Finishing g1")80 def g2():81 trace.append("Starting g2")82 yield "g2 spam"83 yield "g2 more spam"84 trace.append("Finishing g2")85 for x in g1():86 trace.append("Yielded %s" % (x,))87 self.assertEqual(trace,[88 "Starting g1",89 "Yielded g1 ham",90 "Starting g2",91 "Yielded g2 spam",92 "Yielded g2 more spam",93 "Finishing g2",94 "Yielded g1 eggs",95 "Finishing g1",96 ])97 def test_raising_exception_in_delegated_next_call(self):98 """99 Test raising exception in delegated next() call100 """101 trace = []102 def g1():103 try:104 trace.append("Starting g1")105 yield "g1 ham"106 yield from g2()107 yield "g1 eggs"108 finally:109 trace.append("Finishing g1")110 def g2():111 try:112 trace.append("Starting g2")113 yield "g2 spam"114 raise ValueError("hovercraft is full of eels")115 yield "g2 more spam"116 finally:117 trace.append("Finishing g2")118 try:119 for x in g1():120 trace.append("Yielded %s" % (x,))121 except ValueError as e:122 self.assertEqual(e.args[0], "hovercraft is full of eels")123 else:124 self.fail("subgenerator failed to raise ValueError")125 self.assertEqual(trace,[126 "Starting g1",127 "Yielded g1 ham",128 "Starting g2",129 "Yielded g2 spam",130 "Finishing g2",131 "Finishing g1",132 ])133 def test_delegation_of_send(self):134 """135 Test delegation of send()136 """137 trace = []138 def g1():139 trace.append("Starting g1")140 x = yield "g1 ham"141 trace.append("g1 received %s" % (x,))142 yield from g2()143 x = yield "g1 eggs"144 trace.append("g1 received %s" % (x,))145 trace.append("Finishing g1")146 def g2():147 trace.append("Starting g2")148 x = yield "g2 spam"149 trace.append("g2 received %s" % (x,))150 x = yield "g2 more spam"151 trace.append("g2 received %s" % (x,))152 trace.append("Finishing g2")153 g = g1()154 y = next(g)155 x = 1156 try:157 while 1:158 y = g.send(x)159 trace.append("Yielded %s" % (y,))160 x += 1161 except StopIteration:162 pass163 self.assertEqual(trace,[164 "Starting g1",165 "g1 received 1",166 "Starting g2",167 "Yielded g2 spam",168 "g2 received 2",169 "Yielded g2 more spam",170 "g2 received 3",171 "Finishing g2",172 "Yielded g1 eggs",173 "g1 received 4",174 "Finishing g1",175 ])176 def test_handling_exception_while_delegating_send(self):177 """178 Test handling exception while delegating 'send'179 """180 trace = []181 def g1():182 trace.append("Starting g1")183 x = yield "g1 ham"184 trace.append("g1 received %s" % (x,))185 yield from g2()186 x = yield "g1 eggs"187 trace.append("g1 received %s" % (x,))188 trace.append("Finishing g1")189 def g2():190 trace.append("Starting g2")191 x = yield "g2 spam"192 trace.append("g2 received %s" % (x,))193 raise ValueError("hovercraft is full of eels")194 x = yield "g2 more spam"195 trace.append("g2 received %s" % (x,))196 trace.append("Finishing g2")197 def run():198 g = g1()199 y = next(g)200 x = 1201 try:202 while 1:203 y = g.send(x)204 trace.append("Yielded %s" % (y,))205 x += 1206 except StopIteration:207 trace.append("StopIteration")208 self.assertRaises(ValueError,run)209 self.assertEqual(trace,[210 "Starting g1",211 "g1 received 1",212 "Starting g2",213 "Yielded g2 spam",214 "g2 received 2",215 ])216 def test_delegating_close(self):217 """218 Test delegating 'close'219 """220 trace = []221 def g1():222 try:223 trace.append("Starting g1")224 yield "g1 ham"225 yield from g2()226 yield "g1 eggs"227 finally:228 trace.append("Finishing g1")229 def g2():230 try:231 trace.append("Starting g2")232 yield "g2 spam"233 yield "g2 more spam"234 finally:235 trace.append("Finishing g2")236 g = g1()237 for i in range(2):238 x = next(g)239 trace.append("Yielded %s" % (x,))240 g.close()241 self.assertEqual(trace,[242 "Starting g1",243 "Yielded g1 ham",244 "Starting g2",245 "Yielded g2 spam",246 "Finishing g2",247 "Finishing g1"248 ])249 def test_handing_exception_while_delegating_close(self):250 """251 Test handling exception while delegating 'close'252 """253 trace = []254 def g1():255 try:256 trace.append("Starting g1")257 yield "g1 ham"258 yield from g2()259 yield "g1 eggs"260 finally:261 trace.append("Finishing g1")262 def g2():263 try:264 trace.append("Starting g2")265 yield "g2 spam"266 yield "g2 more spam"267 finally:268 trace.append("Finishing g2")269 raise ValueError("nybbles have exploded with delight")270 try:271 g = g1()272 for i in range(2):273 x = next(g)274 trace.append("Yielded %s" % (x,))275 g.close()276 except ValueError as e:277 self.assertEqual(e.args[0], "nybbles have exploded with delight")278 self.assertIsInstance(e.__context__, GeneratorExit)279 else:280 self.fail("subgenerator failed to raise ValueError")281 self.assertEqual(trace,[282 "Starting g1",283 "Yielded g1 ham",284 "Starting g2",285 "Yielded g2 spam",286 "Finishing g2",287 "Finishing g1",288 ])289 def test_delegating_throw(self):290 """291 Test delegating 'throw'292 """293 trace = []294 def g1():295 try:296 trace.append("Starting g1")297 yield "g1 ham"298 yield from g2()299 yield "g1 eggs"300 finally:301 trace.append("Finishing g1")302 def g2():303 try:304 trace.append("Starting g2")305 yield "g2 spam"306 yield "g2 more spam"307 finally:308 trace.append("Finishing g2")309 try:310 g = g1()311 for i in range(2):312 x = next(g)313 trace.append("Yielded %s" % (x,))314 e = ValueError("tomato ejected")315 g.throw(e)316 except ValueError as e:317 self.assertEqual(e.args[0], "tomato ejected")318 else:319 self.fail("subgenerator failed to raise ValueError")320 self.assertEqual(trace,[321 "Starting g1",322 "Yielded g1 ham",323 "Starting g2",324 "Yielded g2 spam",325 "Finishing g2",326 "Finishing g1",327 ])328 def test_value_attribute_of_StopIteration_exception(self):329 """330 Test 'value' attribute of StopIteration exception331 """332 trace = []333 def pex(e):334 trace.append("%s: %s" % (e.__class__.__name__, e))335 trace.append("value = %s" % (e.value,))336 e = StopIteration()337 pex(e)338 e = StopIteration("spam")339 pex(e)340 e.value = "eggs"341 pex(e)342 self.assertEqual(trace,[343 "StopIteration: ",344 "value = None",345 "StopIteration: spam",346 "value = spam",347 "StopIteration: spam",348 "value = eggs",349 ])350 def test_exception_value_crash(self):351 # There used to be a refcount error when the return value352 # stored in the StopIteration has a refcount of 1.353 def g1():354 yield from g2()355 def g2():356 yield "g2"357 return [42]358 self.assertEqual(list(g1()), ["g2"])359 def test_generator_return_value(self):360 """361 Test generator return value362 """363 trace = []364 def g1():365 trace.append("Starting g1")366 yield "g1 ham"367 ret = yield from g2()368 trace.append("g2 returned %s" % (ret,))369 ret = yield from g2(42)370 trace.append("g2 returned %s" % (ret,))371 yield "g1 eggs"372 trace.append("Finishing g1")373 def g2(v = None):374 trace.append("Starting g2")375 yield "g2 spam"376 yield "g2 more spam"377 trace.append("Finishing g2")378 if v:379 return v380 for x in g1():381 trace.append("Yielded %s" % (x,))382 self.assertEqual(trace,[383 "Starting g1",384 "Yielded g1 ham",385 "Starting g2",386 "Yielded g2 spam",387 "Yielded g2 more spam",388 "Finishing g2",389 "g2 returned None",390 "Starting g2",391 "Yielded g2 spam",392 "Yielded g2 more spam",393 "Finishing g2",394 "g2 returned 42",395 "Yielded g1 eggs",396 "Finishing g1",397 ])398 def test_delegation_of_next_to_non_generator(self):399 """400 Test delegation of next() to non-generator401 """402 trace = []403 def g():404 yield from range(3)405 for x in g():406 trace.append("Yielded %s" % (x,))407 self.assertEqual(trace,[408 "Yielded 0",409 "Yielded 1",410 "Yielded 2",411 ])412 def test_conversion_of_sendNone_to_next(self):413 """414 Test conversion of send(None) to next()415 """416 trace = []417 def g():418 yield from range(3)419 gi = g()420 for x in range(3):421 y = gi.send(None)422 trace.append("Yielded: %s" % (y,))423 self.assertEqual(trace,[424 "Yielded: 0",425 "Yielded: 1",426 "Yielded: 2",427 ])428 def test_delegation_of_close_to_non_generator(self):429 """430 Test delegation of close() to non-generator431 """432 trace = []433 def g():434 try:435 trace.append("starting g")436 yield from range(3)437 trace.append("g should not be here")438 finally:439 trace.append("finishing g")440 gi = g()441 next(gi)442 with captured_stderr() as output:443 gi.close()444 self.assertEqual(output.getvalue(), '')445 self.assertEqual(trace,[446 "starting g",447 "finishing g",448 ])449 def test_delegating_throw_to_non_generator(self):450 """451 Test delegating 'throw' to non-generator452 """453 trace = []454 def g():455 try:456 trace.append("Starting g")457 yield from range(10)458 finally:459 trace.append("Finishing g")460 try:461 gi = g()462 for i in range(5):463 x = next(gi)464 trace.append("Yielded %s" % (x,))465 e = ValueError("tomato ejected")466 gi.throw(e)467 except ValueError as e:468 self.assertEqual(e.args[0],"tomato ejected")469 else:470 self.fail("subgenerator failed to raise ValueError")471 self.assertEqual(trace,[472 "Starting g",473 "Yielded 0",474 "Yielded 1",475 "Yielded 2",476 "Yielded 3",477 "Yielded 4",478 "Finishing g",479 ])480 def test_attempting_to_send_to_non_generator(self):481 """482 Test attempting to send to non-generator483 """484 trace = []485 def g():486 try:487 trace.append("starting g")488 yield from range(3)489 trace.append("g should not be here")490 finally:491 trace.append("finishing g")492 try:493 gi = g()494 next(gi)495 for x in range(3):496 y = gi.send(42)497 trace.append("Should not have yielded: %s" % (y,))498 except AttributeError as e:499 self.assertIn("send", e.args[0])500 else:501 self.fail("was able to send into non-generator")502 self.assertEqual(trace,[503 "starting g",504 "finishing g",505 ])506 def test_broken_getattr_handling(self):507 """508 Test subiterator with a broken getattr implementation509 """510 class Broken:511 def __iter__(self):512 return self513 def __next__(self):514 return 1515 def __getattr__(self, attr):516 1/0517 def g():518 yield from Broken()519 with self.assertRaises(ZeroDivisionError):520 gi = g()521 self.assertEqual(next(gi), 1)522 gi.send(1)523 with self.assertRaises(ZeroDivisionError):524 gi = g()525 self.assertEqual(next(gi), 1)526 gi.throw(AttributeError)527 with captured_stderr() as output:528 gi = g()529 self.assertEqual(next(gi), 1)530 gi.close()531 self.assertIn('ZeroDivisionError', output.getvalue())532 def test_exception_in_initial_next_call(self):533 """534 Test exception in initial next() call535 """536 trace = []537 def g1():538 trace.append("g1 about to yield from g2")539 yield from g2()540 trace.append("g1 should not be here")541 def g2():542 yield 1/0543 def run():544 gi = g1()545 next(gi)546 self.assertRaises(ZeroDivisionError,run)547 self.assertEqual(trace,[548 "g1 about to yield from g2"549 ])550 def test_attempted_yield_from_loop(self):551 """552 Test attempted yield-from loop553 """554 trace = []555 def g1():556 trace.append("g1: starting")557 yield "y1"558 trace.append("g1: about to yield from g2")559 yield from g2()560 trace.append("g1 should not be here")561 def g2():562 trace.append("g2: starting")563 yield "y2"564 trace.append("g2: about to yield from g1")565 yield from gi566 trace.append("g2 should not be here")567 try:568 gi = g1()569 for y in gi:570 trace.append("Yielded: %s" % (y,))571 except ValueError as e:572 self.assertEqual(e.args[0],"generator already executing")573 else:574 self.fail("subgenerator didn't raise ValueError")575 self.assertEqual(trace,[576 "g1: starting",577 "Yielded: y1",578 "g1: about to yield from g2",579 "g2: starting",580 "Yielded: y2",581 "g2: about to yield from g1",582 ])583 def test_returning_value_from_delegated_throw(self):584 """585 Test returning value from delegated 'throw'586 """587 trace = []588 def g1():589 try:590 trace.append("Starting g1")591 yield "g1 ham"592 yield from g2()593 yield "g1 eggs"594 finally:595 trace.append("Finishing g1")596 def g2():597 try:598 trace.append("Starting g2")599 yield "g2 spam"600 yield "g2 more spam"601 except LunchError:602 trace.append("Caught LunchError in g2")603 yield "g2 lunch saved"604 yield "g2 yet more spam"605 class LunchError(Exception):606 pass607 g = g1()608 for i in range(2):609 x = next(g)610 trace.append("Yielded %s" % (x,))611 e = LunchError("tomato ejected")612 g.throw(e)613 for x in g:614 trace.append("Yielded %s" % (x,))615 self.assertEqual(trace,[616 "Starting g1",617 "Yielded g1 ham",618 "Starting g2",619 "Yielded g2 spam",620 "Caught LunchError in g2",621 "Yielded g2 yet more spam",622 "Yielded g1 eggs",623 "Finishing g1",624 ])625 def test_next_and_return_with_value(self):626 """627 Test next and return with value628 """629 trace = []630 def f(r):631 gi = g(r)632 next(gi)633 try:634 trace.append("f resuming g")635 next(gi)636 trace.append("f SHOULD NOT BE HERE")637 except StopIteration as e:638 trace.append("f caught %s" % (repr(e),))639 def g(r):640 trace.append("g starting")641 yield642 trace.append("g returning %s" % (r,))643 return r644 f(None)645 f(42)646 self.assertEqual(trace,[647 "g starting",648 "f resuming g",649 "g returning None",650 "f caught StopIteration()",651 "g starting",652 "f resuming g",653 "g returning 42",654 "f caught StopIteration(42,)",655 ])656 def test_send_and_return_with_value(self):657 """658 Test send and return with value659 """660 trace = []661 def f(r):662 gi = g(r)663 next(gi)664 try:665 trace.append("f sending spam to g")666 gi.send("spam")667 trace.append("f SHOULD NOT BE HERE")668 except StopIteration as e:669 trace.append("f caught %r" % (e,))670 def g(r):671 trace.append("g starting")672 x = yield673 trace.append("g received %s" % (x,))674 trace.append("g returning %s" % (r,))675 return r676 f(None)677 f(42)678 self.assertEqual(trace,[679 "g starting",680 "f sending spam to g",681 "g received spam",682 "g returning None",683 "f caught StopIteration()",684 "g starting",685 "f sending spam to g",686 "g received spam",687 "g returning 42",688 "f caught StopIteration(42,)",689 ])690 def test_catching_exception_from_subgen_and_returning(self):691 """692 Test catching an exception thrown into a693 subgenerator and returning a value694 """695 trace = []696 def inner():697 try:698 yield 1699 except ValueError:700 trace.append("inner caught ValueError")701 return 2702 def outer():703 v = yield from inner()704 trace.append("inner returned %r to outer" % v)705 yield v706 g = outer()707 trace.append(next(g))708 trace.append(g.throw(ValueError))709 self.assertEqual(trace,[710 1,711 "inner caught ValueError",712 "inner returned 2 to outer",713 2,714 ])715 def test_throwing_GeneratorExit_into_subgen_that_returns(self):716 """717 Test throwing GeneratorExit into a subgenerator that718 catches it and returns normally.719 """720 trace = []721 def f():722 try:723 trace.append("Enter f")724 yield725 trace.append("Exit f")726 except GeneratorExit:727 return728 def g():729 trace.append("Enter g")730 yield from f()731 trace.append("Exit g")732 try:733 gi = g()734 next(gi)735 gi.throw(GeneratorExit)736 except GeneratorExit:737 pass738 else:739 self.fail("subgenerator failed to raise GeneratorExit")740 self.assertEqual(trace,[741 "Enter g",742 "Enter f",743 ])744 def test_throwing_GeneratorExit_into_subgenerator_that_yields(self):745 """746 Test throwing GeneratorExit into a subgenerator that747 catches it and yields.748 """749 trace = []750 def f():751 try:752 trace.append("Enter f")753 yield754 trace.append("Exit f")755 except GeneratorExit:756 yield757 def g():758 trace.append("Enter g")759 yield from f()760 trace.append("Exit g")761 try:762 gi = g()763 next(gi)764 gi.throw(GeneratorExit)765 except RuntimeError as e:766 self.assertEqual(e.args[0], "generator ignored GeneratorExit")767 else:768 self.fail("subgenerator failed to raise GeneratorExit")769 self.assertEqual(trace,[770 "Enter g",771 "Enter f",772 ])773 def test_throwing_GeneratorExit_into_subgen_that_raises(self):774 """775 Test throwing GeneratorExit into a subgenerator that776 catches it and raises a different exception.777 """778 trace = []779 def f():780 try:781 trace.append("Enter f")782 yield783 trace.append("Exit f")784 except GeneratorExit:785 raise ValueError("Vorpal bunny encountered")786 def g():787 trace.append("Enter g")788 yield from f()789 trace.append("Exit g")790 try:791 gi = g()792 next(gi)793 gi.throw(GeneratorExit)794 except ValueError as e:795 self.assertEqual(e.args[0], "Vorpal bunny encountered")796 self.assertIsInstance(e.__context__, GeneratorExit)797 else:798 self.fail("subgenerator failed to raise ValueError")799 self.assertEqual(trace,[800 "Enter g",801 "Enter f",802 ])803 def test_yield_from_empty(self):804 def g():805 yield from ()806 self.assertRaises(StopIteration, next, g())807 def test_delegating_generators_claim_to_be_running(self):808 # Check with basic iteration809 def one():810 yield 0811 yield from two()812 yield 3813 def two():814 yield 1815 try:816 yield from g1817 except ValueError:818 pass819 yield 2820 g1 = one()821 self.assertEqual(list(g1), [0, 1, 2, 3])822 # Check with send823 g1 = one()824 res = [next(g1)]825 try:826 while True:827 res.append(g1.send(42))828 except StopIteration:829 pass830 self.assertEqual(res, [0, 1, 2, 3])831 # Check with throw832 class MyErr(Exception):833 pass834 def one():835 try:836 yield 0837 except MyErr:838 pass839 yield from two()840 try:841 yield 3842 except MyErr:843 pass844 def two():845 try:846 yield 1847 except MyErr:848 pass849 try:850 yield from g1851 except ValueError:852 pass853 try:854 yield 2855 except MyErr:856 pass857 g1 = one()858 res = [next(g1)]859 try:860 while True:861 res.append(g1.throw(MyErr))862 except StopIteration:863 pass864 # Check with close865 class MyIt(object):866 def __iter__(self):867 return self868 def __next__(self):869 return 42870 def close(self_):871 self.assertTrue(g1.gi_running)872 self.assertRaises(ValueError, next, g1)873 def one():874 yield from MyIt()875 g1 = one()876 next(g1)877 g1.close()878 def test_delegator_is_visible_to_debugger(self):879 def call_stack():880 return [f[3] for f in inspect.stack()]881 def gen():882 yield call_stack()883 yield call_stack()884 yield call_stack()885 def spam(g):886 yield from g887 def eggs(g):888 yield from g889 for stack in spam(gen()):890 self.assertTrue('spam' in stack)891 for stack in spam(eggs(gen())):892 self.assertTrue('spam' in stack and 'eggs' in stack)893 def test_custom_iterator_return(self):894 # See issue #15568895 class MyIter:896 def __iter__(self):897 return self898 def __next__(self):899 raise StopIteration(42)900 def gen():901 nonlocal ret902 ret = yield from MyIter()903 ret = None904 list(gen())905 self.assertEqual(ret, 42)906 def test_close_with_cleared_frame(self):907 # See issue #17669.908 #909 # Create a stack of generators: outer() delegating to inner()910 # delegating to innermost(). The key point is that the instance of911 # inner is created first: this ensures that its frame appears before912 # the instance of outer in the GC linked list.913 #914 # At the gc.collect call:915 # - frame_clear is called on the inner_gen frame.916 # - gen_dealloc is called on the outer_gen generator (the only917 # reference is in the frame's locals).918 # - gen_close is called on the outer_gen generator.919 # - gen_close_iter is called to close the inner_gen generator, which920 # in turn calls gen_close, and gen_yf.921 #922 # Previously, gen_yf would crash since inner_gen's frame had been923 # cleared (and in particular f_stacktop was NULL).924 def innermost():925 yield926 def inner():927 outer_gen = yield928 yield from innermost()929 def outer():930 inner_gen = yield931 yield from inner_gen932 with disable_gc():933 inner_gen = inner()934 outer_gen = outer()935 outer_gen.send(None)936 outer_gen.send(inner_gen)937 outer_gen.send(outer_gen)938 del outer_gen939 del inner_gen940 gc_collect()941def test_main():942 from test import support943 test_classes = [TestPEP380Operation]944 support.run_unittest(*test_classes)945if __name__ == '__main__':...
library_trace.js
Source:library_trace.js
1var LibraryTracing = {2 $EmscriptenTrace__deps: [3 'emscripten_trace_js_configure', 'emscripten_trace_configure_for_google_wtf',4 'emscripten_trace_js_enter_context', 'emscripten_trace_exit_context',5 'emscripten_trace_js_log_message', 'emscripten_trace_js_mark',6 'emscripten_get_now'7 ],8 $EmscriptenTrace__postset: 'EmscriptenTrace.init()',9 $EmscriptenTrace: {10 worker: null,11 collectorEnabled: false,12 googleWTFEnabled: false,13 testingEnabled: false,14 googleWTFData: {15 'scopeStack': [],16 'cachedScopes': {}17 },18 DATA_VERSION: 1,19 EVENT_ALLOCATE: 'allocate',20 EVENT_ANNOTATE_TYPE: 'annotate-type',21 EVENT_APPLICATION_NAME: 'application-name',22 EVENT_ASSOCIATE_STORAGE_SIZE: 'associate-storage-size',23 EVENT_ENTER_CONTEXT: 'enter-context',24 EVENT_EXIT_CONTEXT: 'exit-context',25 EVENT_FRAME_END: 'frame-end',26 EVENT_FRAME_RATE: 'frame-rate',27 EVENT_FRAME_START: 'frame-start',28 EVENT_FREE: 'free',29 EVENT_LOG_MESSAGE: 'log-message',30 EVENT_MEMORY_LAYOUT: 'memory-layout',31 EVENT_OFF_HEAP: 'off-heap',32 EVENT_REALLOCATE: 'reallocate',33 EVENT_REPORT_ERROR: 'report-error',34 EVENT_SESSION_NAME: 'session-name',35 EVENT_TASK_ASSOCIATE_DATA: 'task-associate-data',36 EVENT_TASK_END: 'task-end',37 EVENT_TASK_RESUME: 'task-resume',38 EVENT_TASK_START: 'task-start',39 EVENT_TASK_SUSPEND: 'task-suspend',40 EVENT_USER_NAME: 'user-name',41 init: function() {42 Module['emscripten_trace_configure'] = _emscripten_trace_js_configure;43 Module['emscripten_trace_configure_for_google_wtf'] = _emscripten_trace_configure_for_google_wtf;44 Module['emscripten_trace_enter_context'] = _emscripten_trace_js_enter_context;45 Module['emscripten_trace_exit_context'] = _emscripten_trace_exit_context;46 Module['emscripten_trace_log_message'] = _emscripten_trace_js_log_message;47 Module['emscripten_trace_mark'] = _emscripten_trace_js_mark;48 },49 // Work around CORS issues ...50 loadWorkerViaXHR: function(url, ready, scope) {51 var req = new XMLHttpRequest();52 req.addEventListener('load', function() {53 var blob = new Blob([this.responseText], { type: 'text/javascript' });54 var worker = new Worker(window.URL.createObjectURL(blob));55 if (ready) {56 ready.call(scope, worker);57 }58 }, req);59 req.open("get", url, false);60 req.send();61 },62 configure: function(collector_url, application) {63 EmscriptenTrace.now = _emscripten_get_now;64 var now = new Date();65 var session_id = now.getTime().toString() + '_' +66 Math.floor((Math.random() * 100) + 1).toString();67 EmscriptenTrace.loadWorkerViaXHR(collector_url + 'worker.js', function (worker) {68 EmscriptenTrace.worker = worker;69 EmscriptenTrace.worker.addEventListener('error', function (e) {70 console.log('TRACE WORKER ERROR:');71 console.log(e);72 }, false);73 EmscriptenTrace.worker.postMessage({ 'cmd': 'configure',74 'data_version': EmscriptenTrace.DATA_VERSION,75 'session_id': session_id,76 'url': collector_url });77 EmscriptenTrace.configured = true;78 EmscriptenTrace.collectorEnabled = true;79 EmscriptenTrace.postEnabled = true;80 });81 EmscriptenTrace.post([EmscriptenTrace.EVENT_APPLICATION_NAME, application]);82 EmscriptenTrace.post([EmscriptenTrace.EVENT_SESSION_NAME, now.toISOString()]);83 },84 configureForTest: function() {85 EmscriptenTrace.postEnabled = true;86 EmscriptenTrace.testingEnabled = true;87 EmscriptenTrace.now = function() { return 0.0; };88 },89 configureForGoogleWTF: function() {90 if (window && window.wtf) {91 EmscriptenTrace.googleWTFEnabled = true;92 } else {93 console.log('GOOGLE WTF NOT AVAILABLE TO ENABLE');94 }95 },96 post: function(entry) {97 if (EmscriptenTrace.postEnabled && EmscriptenTrace.collectorEnabled) {98 EmscriptenTrace.worker.postMessage({ 'cmd': 'post',99 'entry': entry });100 } else if (EmscriptenTrace.postEnabled && EmscriptenTrace.testingEnabled) {101 Module.print('Tracing ' + entry);102 }103 },104 googleWTFEnterScope: function(name) {105 var scopeEvent = EmscriptenTrace.googleWTFData['cachedScopes'][name];106 if (!scopeEvent) {107 scopeEvent = window.wtf.trace.events.createScope(name);108 EmscriptenTrace.googleWTFData['cachedScopes'][name] = scopeEvent;109 }110 var scope = scopeEvent();111 EmscriptenTrace.googleWTFData['scopeStack'].push(scope);112 },113 googleWTFExitScope: function() {114 var scope = EmscriptenTrace.googleWTFData['scopeStack'].pop();115 window.wtf.trace.leaveScope(scope);116 }117 },118 emscripten_trace_js_configure: function(collector_url, application) {119 EmscriptenTrace.configure(collector_url, application);120 },121 emscripten_trace_configure: function(collector_url, application) {122 EmscriptenTrace.configure(Pointer_stringify(collector_url),123 Pointer_stringify(application));124 },125 emscripten_trace_configure_for_test: function() {126 EmscriptenTrace.configureForTest();127 },128 emscripten_trace_configure_for_google_wtf: function() {129 EmscriptenTrace.configureForGoogleWTF();130 },131 emscripten_trace_set_enabled: function(enabled) {132 EmscriptenTrace.postEnabled = !!enabled;133 },134 emscripten_trace_set_session_username: function(username) {135 EmscriptenTrace.post(EmscriptenTrace.EVENT_USER_NAME, Pointer_stringify(username));136 },137 emscripten_trace_record_frame_start: function() {138 if (EmscriptenTrace.postEnabled) {139 var now = EmscriptenTrace.now();140 EmscriptenTrace.post([EmscriptenTrace.EVENT_FRAME_START, now]);141 }142 },143 emscripten_trace_record_frame_end: function() {144 if (EmscriptenTrace.postEnabled) {145 var now = EmscriptenTrace.now();146 EmscriptenTrace.post([EmscriptenTrace.EVENT_FRAME_END, now]);147 }148 },149 emscripten_trace_js_log_message: function(channel, message) {150 if (EmscriptenTrace.postEnabled) {151 var now = EmscriptenTrace.now();152 EmscriptenTrace.post([EmscriptenTrace.EVENT_LOG_MESSAGE, now,153 channel, message]);154 }155 },156 emscripten_trace_log_message: function(channel, message) {157 if (EmscriptenTrace.postEnabled) {158 var now = EmscriptenTrace.now();159 EmscriptenTrace.post([EmscriptenTrace.EVENT_LOG_MESSAGE, now,160 Pointer_stringify(channel),161 Pointer_stringify(message)]);162 }163 },164 emscripten_trace_js_mark: function(message) {165 if (EmscriptenTrace.postEnabled) {166 var now = EmscriptenTrace.now();167 EmscriptenTrace.post([EmscriptenTrace.EVENT_LOG_MESSAGE, now,168 "MARK", message]);169 }170 if (EmscriptenTrace.googleWTFEnabled) {171 window.wtf.trace.mark(message);172 }173 },174 emscripten_trace_mark: function(message) {175 if (EmscriptenTrace.postEnabled) {176 var now = EmscriptenTrace.now();177 EmscriptenTrace.post([EmscriptenTrace.EVENT_LOG_MESSAGE, now,178 "MARK", Pointer_stringify(message)]);179 }180 if (EmscriptenTrace.googleWTFEnabled) {181 window.wtf.trace.mark(Pointer_stringify(message));182 }183 },184 emscripten_trace_report_error: function(error) {185 var now = EmscriptenTrace.now();186 var callstack = (new Error).stack;187 EmscriptenTrace.post([EmscriptenTrace.EVENT_REPORT_ERROR, now,188 Pointer_stringify(error), callstack]);189 },190 emscripten_trace_record_allocation: function(address, size) {191 if (typeof Module['onMalloc'] === 'function') Module['onMalloc'](address, size);192 if (EmscriptenTrace.postEnabled) {193 var now = EmscriptenTrace.now();194 EmscriptenTrace.post([EmscriptenTrace.EVENT_ALLOCATE,195 now, address, size]);196 }197 },198 emscripten_trace_record_reallocation: function(old_address, new_address, size) {199 if (typeof Module['onRealloc'] === 'function') Module['onRealloc'](old_address, new_address, size);200 if (EmscriptenTrace.postEnabled) {201 var now = EmscriptenTrace.now();202 EmscriptenTrace.post([EmscriptenTrace.EVENT_REALLOCATE,203 now, old_address, new_address, size]);204 }205 },206 emscripten_trace_record_free: function(address) {207 if (typeof Module['onFree'] === 'function') Module['onFree'](address);208 if (EmscriptenTrace.postEnabled) {209 var now = EmscriptenTrace.now();210 EmscriptenTrace.post([EmscriptenTrace.EVENT_FREE,211 now, address]);212 }213 },214 emscripten_trace_annotate_address_type: function(address, type_name) {215 if (EmscriptenTrace.postEnabled) {216 EmscriptenTrace.post([EmscriptenTrace.EVENT_ANNOTATE_TYPE, address,217 Pointer_stringify(type_name)]);218 }219 },220 emscripten_trace_associate_storage_size: function(address, size) {221 if (EmscriptenTrace.postEnabled) {222 EmscriptenTrace.post([EmscriptenTrace.EVENT_ASSOCIATE_STORAGE_SIZE,223 address, size]);224 }225 },226 emscripten_trace_report_memory_layout: function() {227 if (EmscriptenTrace.postEnabled) {228 var memory_layout = {229 'static_base': STATIC_BASE,230 'static_top': STATICTOP,231 'stack_base': STACK_BASE,232 'stack_top': STACKTOP,233 'stack_max': STACK_MAX,234 'dynamic_base': DYNAMIC_BASE,235 'dynamic_top': HEAP32[DYNAMICTOP_PTR>>2],236 'total_memory': TOTAL_MEMORY237 };238 var now = EmscriptenTrace.now();239 EmscriptenTrace.post([EmscriptenTrace.EVENT_MEMORY_LAYOUT,240 now, memory_layout]);241 }242 },243 emscripten_trace_report_off_heap_data: function () {244 function openal_audiodata_size() {245 if (typeof AL == 'undefined' || !AL.currentContext) {246 return 0;247 }248 var totalMemory = 0;249 for (var i in AL.currentContext.buf) {250 var buffer = AL.currentContext.buf[i];251 for (var channel = 0; channel < buffer.numberOfChannels; ++channel) {252 totalMemory += buffer.getChannelData(channel).length * 4;253 }254 }255 return totalMemory;256 }257 if (EmscriptenTrace.postEnabled) {258 var off_heap_data = {259 'openal': openal_audiodata_size()260 }261 var now = EmscriptenTrace.now();262 EmscriptenTrace.post([EmscriptenTrace.EVENT_OFF_HEAP, now, off_heap_data]);263 }264 },265 emscripten_trace_js_enter_context: function(name) {266 if (EmscriptenTrace.postEnabled) {267 var now = EmscriptenTrace.now();268 EmscriptenTrace.post([EmscriptenTrace.EVENT_ENTER_CONTEXT,269 now, name]);270 }271 if (EmscriptenTrace.googleWTFEnabled) {272 EmscriptenTrace.googleWTFEnterScope(name);273 }274 },275 emscripten_trace_enter_context: function(name) {276 if (EmscriptenTrace.postEnabled) {277 var now = EmscriptenTrace.now();278 EmscriptenTrace.post([EmscriptenTrace.EVENT_ENTER_CONTEXT,279 now, Pointer_stringify(name)]);280 }281 if (EmscriptenTrace.googleWTFEnabled) {282 EmscriptenTrace.googleWTFEnterScope(Pointer_stringify(name));283 }284 },285 emscripten_trace_exit_context: function() {286 if (EmscriptenTrace.postEnabled) {287 var now = EmscriptenTrace.now();288 EmscriptenTrace.post([EmscriptenTrace.EVENT_EXIT_CONTEXT, now]);289 }290 if (EmscriptenTrace.googleWTFEnabled) {291 EmscriptenTrace.googleWTFExitScope();292 }293 },294 emscripten_trace_task_start: function(task_id, name) {295 if (EmscriptenTrace.postEnabled) {296 var now = EmscriptenTrace.now();297 EmscriptenTrace.post([EmscriptenTrace.EVENT_TASK_START,298 now, task_id, Pointer_stringify(name)]);299 }300 },301 emscripten_trace_task_associate_data: function(key, value) {302 if (EmscriptenTrace.postEnabled) {303 EmscriptenTrace.post([EmscriptenTrace.EVENT_TASK_ASSOCIATE_DATA,304 Pointer_stringify(key),305 Pointer_stringify(value)]);306 }307 },308 emscripten_trace_task_suspend: function(explanation) {309 if (EmscriptenTrace.postEnabled) {310 var now = EmscriptenTrace.now();311 EmscriptenTrace.post([EmscriptenTrace.EVENT_TASK_SUSPEND,312 now, Pointer_stringify(explanation)]);313 }314 },315 emscripten_trace_task_resume: function(task_id, explanation) {316 if (EmscriptenTrace.postEnabled) {317 var now = EmscriptenTrace.now();318 EmscriptenTrace.post([EmscriptenTrace.EVENT_TASK_RESUME,319 now, task_id, Pointer_stringify(explanation)]);320 }321 },322 emscripten_trace_task_end: function() {323 if (EmscriptenTrace.postEnabled) {324 var now = EmscriptenTrace.now();325 EmscriptenTrace.post([EmscriptenTrace.EVENT_TASK_END, now]);326 }327 },328 emscripten_trace_close: function() {329 EmscriptenTrace.collectorEnabled = false;330 EmscriptenTrace.googleWTFEnabled = false;331 EmscriptenTrace.postEnabled = false;332 EmscriptenTrace.testingEnabled = false;333 EmscriptenTrace.worker.postMessage({ 'cmd': 'close' });334 EmscriptenTrace.worker = null;335 },336};337autoAddDeps(LibraryTracing, '$EmscriptenTrace');...
trace.test.js
Source:trace.test.js
...24} from './span';25import * as traceSelectors from './trace';26import traceGenerator from '../demo/trace-generators';27import { numberSortComparator } from '../utils/sort';28const generatedTrace = traceGenerator.trace({ numberOfSpans: 45 });29it('getTraceId() should return the traceID', () => {30 expect(traceSelectors.getTraceId(generatedTrace)).toBe(generatedTrace.traceID);31});32it('hydrateSpansWithProcesses() should return the trace with processes on each span', () => {33 const hydratedTrace = traceSelectors.hydrateSpansWithProcesses(generatedTrace);34 hydratedTrace.spans.forEach((span) =>35 expect(getSpanProcess(span)).toBe(generatedTrace.processes[getSpanProcessId(span)])36 );37});38it('getTraceSpansAsMap() should return a map of all of the spans', () => {39 const spanMap = traceSelectors.getTraceSpansAsMap(generatedTrace);40 [...spanMap.entries()].forEach((pair) => {41 expect(pair[1]).toEqual(generatedTrace.spans.find((span) => getSpanId(span) === pair[0]));42 });...
trace_event.py
Source:trace_event.py
...59 args_to_log = {key: repr(value) for key, value in kwargs.iteritems()}60 trace_event_impl.add_trace_event("B", time.time(), "python", name, args_to_log)61 def trace_end(name):62 trace_event_impl.add_trace_event("E", time.time(), "python", name)63 def trace(name, **kwargs):64 return trace_event_impl.trace(name, **kwargs)65 def traced(fn):66 return trace_event_impl.traced(fn)67else:68 import contextlib69 def trace_enable():70 raise TraceException("Cannot enable trace_event. No trace_event_impl module found.")71 def trace_disable():72 pass73 def trace_is_enabled():74 return False75 def trace_flush():76 pass77 def trace_begin(self, name, **kwargs):78 pass79 def trace_end(self, name):80 pass81 @contextlib.contextmanager82 def trace(name, **kwargs):83 yield84 def traced(fn):85 return fn86trace_enable.__doc__ = """Enables tracing.87 Once enabled, the enabled bit propagates to forked processes and88 multiprocessing subprocesses. Regular child processes, e.g. those created via89 os.system/popen, or subprocess.Popen instances, will not get traced. You can,90 however, enable tracing on those subprocess manually.91 Trace files are multiprocess safe, so you can have multiple processes92 outputting to the same tracelog at once.93 log_file can be one of three things:94 None: a logfile is opened based on sys[argv], namely95 "./" + sys.argv[0] + ".json"96 string: a logfile of the given name is opened.97 file-like object: the fileno() is is used. The underlying file descriptor98 must support fcntl.lockf() operations.99 """100trace_disable.__doc__ = """Disables tracing, if enabled.101 Will not disable tracing on any existing child proceses that were forked102 from this process. You must disable them yourself.103 """104trace_flush.__doc__ = """Flushes any currently-recorded trace data to disk.105 trace_event records traces into an in-memory buffer for efficiency. Flushing106 is only done at process exit or when this method is called.107 """108trace_flush.__doc__ = """Returns whether tracing is enabled.109 """110trace_begin.__doc__ = """Records the beginning of an event of the given name.111 The building block for performance tracing. A typical example is:112 from trace_event import *113 def something_heavy():114 trace_begin("something_heavy")115 trace_begin("read")116 try:117 lines = open().readlines()118 finally:119 trace_end("read")120 trace_begin("parse")121 try:122 parse(lines)123 finally:124 trace_end("parse")125 trace_end("something_heavy")126 Note that a trace_end call must be issued for every trace_begin call. When127 tracing around blocks that might throw exceptions, you should use the trace function,128 or a try-finally pattern to ensure that the trace_end method is called.129 See the documentation for the @traced decorator for a simpler way to instrument130 functions and methods.131 """132trace_end.__doc__ = """Records the end of an event of the given name.133 See the documentation for trace_begin for more information.134 Make sure to issue a trace_end for every trace_begin issued. Failure to pair135 these calls will lead to bizarrely tall looking traces in the136 trace_event_viewer UI.137 """138trace.__doc__ = """Traces a block of code using a with statement.139 Example usage:140 from trace_event import *141 def something_heavy(lines):142 with trace("parse_lines", lines=lines):143 parse(lines)144 If tracing an entire function call, prefer the @traced decorator.145 """146traced.__doc__ = """147 Traces the provided function, using the function name for the actual generated event.148 Prefer this decorator over the explicit trace_begin and trace_end functions149 whenever you are tracing the start and stop of a function. It automatically150 issues trace_begin/end events, even when the wrapped function throws.151 You can also pass the function's argument names to traced, and the argument152 values will be added to the trace. Example usage:153 from trace_event import *154 @traced("url")155 def send_request(url):156 urllib2.urlopen(url).read()...
trace_data_unittest.py
Source:trace_data_unittest.py
1# Copyright 2014 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import base645import json6import os7import tempfile8import unittest9from py_utils import tempfile_ext10from tracing.trace_data import trace_data11class TraceDataTest(unittest.TestCase):12 def testHasTracesForChrome(self):13 d = trace_data.CreateFromRawChromeEvents([{'ph': 'B'}])14 self.assertTrue(d.HasTracesFor(trace_data.CHROME_TRACE_PART))15 def testHasNotTracesForCpu(self):16 d = trace_data.CreateFromRawChromeEvents([{'ph': 'B'}])17 self.assertFalse(d.HasTracesFor(trace_data.CPU_TRACE_DATA))18 def testGetTracesForChrome(self):19 d = trace_data.CreateFromRawChromeEvents([{'ph': 'B'}])20 ts = d.GetTracesFor(trace_data.CHROME_TRACE_PART)21 self.assertEqual(len(ts), 1)22 self.assertEqual(ts[0], {'traceEvents': [{'ph': 'B'}]})23 def testGetNoTracesForCpu(self):24 d = trace_data.CreateFromRawChromeEvents([{'ph': 'B'}])25 ts = d.GetTracesFor(trace_data.CPU_TRACE_DATA)26 self.assertEqual(ts, [])27class TraceDataBuilderTest(unittest.TestCase):28 def testAddTraceDataAndSerialize(self):29 with tempfile_ext.TemporaryFileName() as trace_path:30 with trace_data.TraceDataBuilder() as builder:31 builder.AddTraceFor(trace_data.CHROME_TRACE_PART,32 {'traceEvents': [1, 2, 3]})33 builder.Serialize(trace_path)34 self.assertTrue(os.path.exists(trace_path))35 self.assertGreater(os.stat(trace_path).st_size, 0) # File not empty.36 def testAddTraceForRaisesWithInvalidPart(self):37 with trace_data.TraceDataBuilder() as builder:38 with self.assertRaises(TypeError):39 builder.AddTraceFor('not_a_trace_part', {})40 def testAddTraceWithUnstructuredData(self):41 with trace_data.TraceDataBuilder() as builder:42 builder.AddTraceFor(trace_data.TELEMETRY_PART, 'unstructured trace',43 allow_unstructured=True)44 def testAddTraceRaisesWithImplicitUnstructuredData(self):45 with trace_data.TraceDataBuilder() as builder:46 with self.assertRaises(ValueError):47 builder.AddTraceFor(trace_data.TELEMETRY_PART, 'unstructured trace')48 def testAddTraceFileFor(self):49 original_data = {'msg': 'The answer is 42'}50 with tempfile.NamedTemporaryFile(delete=False, suffix='.json') as source:51 json.dump(original_data, source)52 with trace_data.TraceDataBuilder() as builder:53 builder.AddTraceFileFor(trace_data.CHROME_TRACE_PART, source.name)54 self.assertFalse(os.path.exists(source.name))55 out_data = builder.AsData().GetTraceFor(trace_data.CHROME_TRACE_PART)56 self.assertEqual(original_data, out_data)57 def testOpenTraceHandleFor(self):58 original_data = {'msg': 'The answer is 42'}59 with trace_data.TraceDataBuilder() as builder:60 with builder.OpenTraceHandleFor(61 trace_data.CHROME_TRACE_PART, suffix='.json') as handle:62 handle.write(json.dumps(original_data))63 out_data = builder.AsData().GetTraceFor(trace_data.CHROME_TRACE_PART)64 # Trace handle should be cleaned up.65 self.assertFalse(os.path.exists(handle.name))66 self.assertEqual(original_data, out_data)67 def testOpenTraceHandleForCompressedData(self):68 original_data = {'msg': 'The answer is 42'}69 # gzip.compress() does not work in python 2, so hardcode the encoded data.70 compressed_data = base64.b64decode(71 'H4sIAIDMblwAA6tWyi1OV7JSUArJSFVIzCsuTy1SyCxWMDFSquUCAA4QMtscAAAA')72 with trace_data.TraceDataBuilder() as builder:73 with builder.OpenTraceHandleFor(74 trace_data.CHROME_TRACE_PART, suffix='.json.gz') as handle:75 handle.write(compressed_data)76 out_data = builder.AsData().GetTraceFor(trace_data.CHROME_TRACE_PART)77 # Trace handle should be cleaned up.78 self.assertFalse(os.path.exists(handle.name))79 self.assertEqual(original_data, out_data)80 def testCantWriteAfterCleanup(self):81 with trace_data.TraceDataBuilder() as builder:82 builder.AddTraceFor(trace_data.CHROME_TRACE_PART,83 {'traceEvents': [1, 2, 3]})84 builder.CleanUpTraceData()85 with self.assertRaises(RuntimeError):86 builder.AddTraceFor(trace_data.CHROME_TRACE_PART,87 {'traceEvents': [1, 2, 3]})88 def testCleanupReraisesExceptions(self):89 with trace_data.TraceDataBuilder() as builder:90 try:91 raise Exception("test exception") # pylint: disable=broad-except92 except Exception: # pylint: disable=broad-except93 builder.RecordTraceDataException()94 with self.assertRaises(trace_data.TraceDataException):95 builder.CleanUpTraceData()96 def testCantWriteAfterFreeze(self):97 with trace_data.TraceDataBuilder() as builder:98 builder.AddTraceFor(trace_data.CHROME_TRACE_PART,99 {'traceEvents': [1, 2, 3]})100 builder.Freeze()101 with self.assertRaises(RuntimeError):102 builder.AddTraceFor(trace_data.CHROME_TRACE_PART,...
jsUnitTracer.js
Source:jsUnitTracer.js
...18 this._traceWindow.document.close();19 }20}21JsUnitTracer.prototype.warn = function() {22 this._trace(arguments[0], arguments[1], TRACE_LEVEL_WARNING);23}24JsUnitTracer.prototype.inform = function() {25 this._trace(arguments[0], arguments[1], TRACE_LEVEL_INFO);26}27JsUnitTracer.prototype.debug = function() {28 this._trace(arguments[0], arguments[1], TRACE_LEVEL_DEBUG);29}30JsUnitTracer.prototype._trace = function(message, value, traceLevel) {31 if (!top.shouldSubmitResults() && this._getChosenTraceLevel().matches(traceLevel)) {32 var traceString = message;33 if (value)34 traceString += ': ' + value;35 var prefix = this._testManager.getTestFileName() + ":" +36 this._testManager.getTestFunctionName() + " - ";37 this._writeToTraceWindow(prefix, traceString, traceLevel);38 }39}40JsUnitTracer.prototype._getChosenTraceLevel = function() {41 var levelNumber = eval(top.testManager.traceLevel.value);42 return traceLevelByLevelNumber(levelNumber);...
tracer.ts
Source:tracer.ts
1/*---------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 *--------------------------------------------------------------------------------------------*/5import * as vscode from 'vscode';6import * as Proto from '../protocol';7import Logger from './logger';8enum Trace {9 Off,10 Messages,11 Verbose,12}13namespace Trace {14 export function fromString(value: string): Trace {15 value = value.toLowerCase();16 switch (value) {17 case 'off':18 return Trace.Off;19 case 'messages':20 return Trace.Messages;21 case 'verbose':22 return Trace.Verbose;23 default:24 return Trace.Off;25 }26 }27}28export default class Tracer {29 private trace?: Trace;30 constructor(31 private readonly logger: Logger32 ) {33 this.updateConfiguration();34 }35 public updateConfiguration() {36 this.trace = Tracer.readTrace();37 }38 private static readTrace(): Trace {39 let result: Trace = Trace.fromString(vscode.workspace.getConfiguration().get<string>('typescript.tsserver.trace', 'off'));40 if (result === Trace.Off && !!process.env.TSS_TRACE) {41 result = Trace.Messages;42 }43 return result;44 }45 public traceRequest(serverId: string, request: Proto.Request, responseExpected: boolean, queueLength: number): void {46 if (this.trace === Trace.Off) {47 return;48 }49 let data: string | undefined = undefined;50 if (this.trace === Trace.Verbose && request.arguments) {51 data = `Arguments: ${JSON.stringify(request.arguments, null, 4)}`;52 }53 this.logTrace(serverId, `Sending request: ${request.command} (${request.seq}). Response expected: ${responseExpected ? 'yes' : 'no'}. Current queue length: ${queueLength}`, data);54 }55 public traceResponse(serverId: string, response: Proto.Response, startTime: number): void {56 if (this.trace === Trace.Off) {57 return;58 }59 let data: string | undefined = undefined;60 if (this.trace === Trace.Verbose && response.body) {61 data = `Result: ${JSON.stringify(response.body, null, 4)}`;62 }63 this.logTrace(serverId, `Response received: ${response.command} (${response.request_seq}). Request took ${Date.now() - startTime} ms. Success: ${response.success} ${!response.success ? '. Message: ' + response.message : ''}`, data);64 }65 public traceRequestCompleted(serverId: string, command: string, request_seq: number, startTime: number): any {66 if (this.trace === Trace.Off) {67 return;68 }69 this.logTrace(serverId, `Async response received: ${command} (${request_seq}). Request took ${Date.now() - startTime} ms.`);70 }71 public traceEvent(serverId: string, event: Proto.Event): void {72 if (this.trace === Trace.Off) {73 return;74 }75 let data: string | undefined = undefined;76 if (this.trace === Trace.Verbose && event.body) {77 data = `Data: ${JSON.stringify(event.body, null, 4)}`;78 }79 this.logTrace(serverId, `Event received: ${event.event} (${event.seq}).`, data);80 }81 public logTrace(serverId: string, message: string, data?: any): void {82 if (this.trace !== Trace.Off) {83 this.logger.logLevel('Trace', `<${serverId}> ${message}`, data);84 }85 }...
trace_event.gypi
Source:trace_event.gypi
1# Copyright 2015 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4{5 'variables': {6 'trace_event_sources' : [7 'trace_event/memory_allocator_attributes.h',8 'trace_event/memory_allocator_dump.cc',9 'trace_event/memory_allocator_dump.h',10 'trace_event/memory_dump_manager.cc',11 'trace_event/memory_dump_manager.h',12 'trace_event/memory_dump_provider.cc',13 'trace_event/memory_dump_provider.h',14 'trace_event/memory_dump_request_args.h',15 'trace_event/process_memory_dump.cc',16 'trace_event/process_memory_dump.h',17 'trace_event/process_memory_maps.cc',18 'trace_event/process_memory_maps.h',19 'trace_event/process_memory_maps_dump_provider.cc',20 'trace_event/process_memory_maps_dump_provider.h',21 'trace_event/process_memory_totals.cc',22 'trace_event/process_memory_totals.h',23 'trace_event/process_memory_totals_dump_provider.cc',24 'trace_event/process_memory_totals_dump_provider.h',25 'trace_event/trace_event.h',26 'trace_event/trace_event_android.cc',27 'trace_event/trace_event_argument.cc',28 'trace_event/trace_event_argument.h',29 'trace_event/trace_event_impl.cc',30 'trace_event/trace_event_impl.h',31 'trace_event/trace_event_impl_constants.cc',32 'trace_event/trace_event_memory.cc',33 'trace_event/trace_event_memory.h',34 'trace_event/trace_event_synthetic_delay.cc',35 'trace_event/trace_event_synthetic_delay.h',36 'trace_event/trace_event_system_stats_monitor.cc',37 'trace_event/trace_event_system_stats_monitor.h',38 'trace_event/trace_event_win.cc',39 'trace_event/trace_event_win.h',40 ],41 'trace_event_test_sources' : [42 'trace_event/memory_allocator_dump_unittest.cc',43 'trace_event/memory_dump_manager_unittest.cc',44 'trace_event/process_memory_maps_dump_provider_unittest.cc',45 'trace_event/process_memory_totals_dump_provider_unittest.cc',46 'trace_event/trace_event_argument_unittest.cc',47 'trace_event/trace_event_memory_unittest.cc',48 'trace_event/trace_event_synthetic_delay_unittest.cc',49 'trace_event/trace_event_system_stats_monitor_unittest.cc',50 'trace_event/trace_event_unittest.cc',51 'trace_event/trace_event_win_unittest.cc',52 ],53 },...
Using AI Code Generation
1var log4js = require('log4js');2var logger = log4js.getLogger();3logger.trace("Trace Message");4logger.debug("Debug Message");5logger.info("Info Message");6logger.warn("Warn Message");7logger.error("Error Message");8logger.fatal("Fatal Message");9var logger = log4js.getLogger('child');10logger.trace("Trace Message");11logger.debug("Debug Message");12logger.info("Info Message");13logger.warn("Warn Message");14logger.error("Error Message");15logger.fatal("Fatal Message");16var logger = log4js.getLogger('child.grandchild');17logger.trace("Trace Message");18logger.debug("Debug Message");19logger.info("Info Message");20logger.warn("Warn Message");21logger.error("Error Message");22logger.fatal("Fatal Message");23var logger = log4js.getLogger('child.grandchild.grandgrandchild');24logger.trace("Trace Message");25logger.debug("Debug Message");26logger.info("Info Message");27logger.warn("Warn Message");28logger.error("Error Message");29logger.fatal("Fatal Message");30var logger = log4js.getLogger('child.grandchild.grandgrandchild');31logger.trace("Trace Message");32logger.debug("Debug Message");33logger.info("Info Message");34logger.warn("Warn Message");35logger.error("Error Message");36logger.fatal("Fatal Message");37var logger = log4js.getLogger('child.grandchild.grandgrandchild');38logger.trace("Trace Message");39logger.debug("Debug Message");40logger.info("Info Message");41logger.warn("Warn Message");42logger.error("Error Message");43logger.fatal("Fatal Message");44var logger = log4js.getLogger('child.grandchild.grandgrandchild');45logger.trace("Trace Message");46logger.debug("Debug Message");47logger.info("Info Message");48logger.warn("Warn Message");49logger.error("Error Message");50logger.fatal("Fatal Message");51var logger = log4js.getLogger('child.grandchild.grandgrandchild');52logger.trace("Trace Message");53logger.debug("Debug Message");54logger.info("Info Message");55logger.warn("Warn Message");56logger.error("Error Message");
Using AI Code Generation
1var log4js = require('log4js');2log4js.configure({3 { type: 'console' },4 { type: 'file', filename: 'logs/test.log', category: 'test' }5});6var logger = log4js.getLogger('test');7logger.trace('Entering cheese testing');8logger.debug('Got cheese.');9logger.info('Cheese is Gouda.');10logger.warn('Cheese is quite smelly.');11logger.error('Cheese is too ripe!');12logger.fatal('Cheese was breeding ground for listeria.');13logger.trace('Exiting cheese testing');14var log4js = require('log4js');15log4js.configure({16 { type: 'console' },17 { type: 'file', filename: 'logs/test2.log', category: 'test2' }18});19var logger = log4js.getLogger('test2');20logger.trace('Entering cheese testing');21logger.debug('Got cheese.');22logger.info('Cheese is Gouda.');23logger.warn('Cheese is quite smelly.');24logger.error('Cheese is too ripe!');25logger.fatal('Cheese was breeding ground for listeria.');26logger.trace('Exiting cheese testing');27var log4js = require('log4js');28log4js.configure({29 { type: 'console' },30 { type: 'file', filename: 'logs/test3.log', category: 'test3' }31});32var logger = log4js.getLogger('test3');33logger.trace('Entering cheese testing');34logger.debug('Got cheese.');35logger.info('Cheese is Gouda.');36logger.warn('Cheese is quite smelly.');37logger.error('Cheese is too ripe!');38logger.fatal('Cheese was breeding ground for listeria.');39logger.trace('Exiting cheese testing');
Using AI Code Generation
1root.trace("my trace message");2root.info("my info message");3root.warn("my warn message");4root.error("my error message");5root.fatal("my fatal message");6root.setLevel("DEBUG");7var level = root.getLevel();8root.addAppender(appender);9root.removeAppender(appender);10root.removeAllAppenders();11var appenders = root.getAppenders();12var logger = root.getLogger("loggerName");13var loggers = root.getLoggers();14root.resetConfiguration();15root.shutdown();16root.setConfig(config);17var config = root.getConfig();18root.setConfig(config);19var config = root.getConfig();20var config = root.getConfig();21root.setConfig(config);22var config = root.getConfig();23var config = root.getConfig();
Using AI Code Generation
1root.trace("hello");2global.trace("hello");3this.trace("hello");4root.trace("hello");5global.trace("hello");6this.trace("hello");7root.trace("hello");8global.trace("hello");9this.trace("hello");10root.trace("hello");11global.trace("hello");12this.trace("hello");13root.trace("hello");14global.trace("hello");15this.trace("hello");16root.trace("hello");17global.trace("hello");18this.trace("hello");19root.trace("hello");20global.trace("hello");21this.trace("hello");22root.trace("hello");23global.trace("hello");24this.trace("hello");25root.trace("hello");26global.trace("hello");27this.trace("hello");28root.trace("hello");29global.trace("hello");30this.trace("hello");
Using AI Code Generation
1var root = this;2root.trace("Hello World!");3global.trace("Hello World!");4var root = this;5root.trace("Hello World!");6global.trace("Hello World!");7var root = this;8root.trace("Hello World!");9global.trace("Hello World!");10var root = this;11root.trace("Hello World!");12global.trace("Hello World!");13var root = this;14root.trace("Hello World!");15global.trace("Hello World!");16var root = this;17root.trace("Hello World!");18global.trace("Hello World!");19var root = this;20root.trace("Hello World!");21global.trace("Hello World!");22var root = this;23root.trace("Hello World!");24global.trace("Hello World!");25var root = this;26root.trace("Hello World!");27global.trace("Hello World!");28var root = this;29root.trace("Hello World!");30global.trace("Hello World!");31var root = this;32root.trace("Hello World!");33global.trace("Hello World!");34var root = this;35root.trace("Hello World!");36global.trace("
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!!