Best JavaScript code snippet using wpt
grammar_parser.py
Source:grammar_parser.py
...35class GeneratedParser(Parser):36 @memoize37 def start(self) -> Optional[Grammar]:38 # start: grammar $39 mark = self.mark()40 cut = False41 if (42 (grammar := self.grammar())43 and44 (endmarker := self.expect('ENDMARKER'))45 ):46 return grammar47 self.reset(mark)48 if cut: return None49 return None50 @memoize51 def grammar(self) -> Optional[Grammar]:52 # grammar: metas rules | rules53 mark = self.mark()54 cut = False55 if (56 (metas := self.metas())57 and58 (rules := self.rules())59 ):60 return Grammar ( rules , metas )61 self.reset(mark)62 if cut: return None63 cut = False64 if (65 (rules := self.rules())66 ):67 return Grammar ( rules , [ ] )68 self.reset(mark)69 if cut: return None70 return None71 @memoize72 def metas(self) -> Optional[MetaList]:73 # metas: meta metas | meta74 mark = self.mark()75 cut = False76 if (77 (meta := self.meta())78 and79 (metas := self.metas())80 ):81 return [ meta ] + metas82 self.reset(mark)83 if cut: return None84 cut = False85 if (86 (meta := self.meta())87 ):88 return [ meta ]89 self.reset(mark)90 if cut: return None91 return None92 @memoize93 def meta(self) -> Optional[MetaTuple]:94 # meta: "@" NAME NEWLINE | "@" NAME NAME NEWLINE | "@" NAME STRING NEWLINE95 mark = self.mark()96 cut = False97 if (98 (literal := self.expect("@"))99 and100 (name := self.name())101 and102 (newline := self.expect('NEWLINE'))103 ):104 return ( name . string , None )105 self.reset(mark)106 if cut: return None107 cut = False108 if (109 (literal := self.expect("@"))110 and111 (a := self.name())112 and113 (b := self.name())114 and115 (newline := self.expect('NEWLINE'))116 ):117 return ( a . string , b . string )118 self.reset(mark)119 if cut: return None120 cut = False121 if (122 (literal := self.expect("@"))123 and124 (name := self.name())125 and126 (string := self.string())127 and128 (newline := self.expect('NEWLINE'))129 ):130 return ( name . string , literal_eval ( string . string ) )131 self.reset(mark)132 if cut: return None133 return None134 @memoize135 def rules(self) -> Optional[RuleList]:136 # rules: rule rules | rule137 mark = self.mark()138 cut = False139 if (140 (rule := self.rule())141 and142 (rules := self.rules())143 ):144 return [ rule ] + rules145 self.reset(mark)146 if cut: return None147 cut = False148 if (149 (rule := self.rule())150 ):151 return [ rule ]152 self.reset(mark)153 if cut: return None154 return None155 @memoize156 def rule(self) -> Optional[Rule]:157 # rule: rulename memoflag? ":" alts NEWLINE INDENT more_alts DEDENT | rulename memoflag? ":" NEWLINE INDENT more_alts DEDENT | rulename memoflag? ":" alts NEWLINE158 mark = self.mark()159 cut = False160 if (161 (rulename := self.rulename())162 and163 (opt := self.memoflag(),)164 and165 (literal := self.expect(":"))166 and167 (alts := self.alts())168 and169 (newline := self.expect('NEWLINE'))170 and171 (indent := self.expect('INDENT'))172 and173 (more_alts := self.more_alts())174 and175 (dedent := self.expect('DEDENT'))176 ):177 return Rule ( rulename [ 0 ] , rulename [ 1 ] , Rhs ( alts . alts + more_alts . alts ) , memo = opt )178 self.reset(mark)179 if cut: return None180 cut = False181 if (182 (rulename := self.rulename())183 and184 (opt := self.memoflag(),)185 and186 (literal := self.expect(":"))187 and188 (newline := self.expect('NEWLINE'))189 and190 (indent := self.expect('INDENT'))191 and192 (more_alts := self.more_alts())193 and194 (dedent := self.expect('DEDENT'))195 ):196 return Rule ( rulename [ 0 ] , rulename [ 1 ] , more_alts , memo = opt )197 self.reset(mark)198 if cut: return None199 cut = False200 if (201 (rulename := self.rulename())202 and203 (opt := self.memoflag(),)204 and205 (literal := self.expect(":"))206 and207 (alts := self.alts())208 and209 (newline := self.expect('NEWLINE'))210 ):211 return Rule ( rulename [ 0 ] , rulename [ 1 ] , alts , memo = opt )212 self.reset(mark)213 if cut: return None214 return None215 @memoize216 def rulename(self) -> Optional[RuleName]:217 # rulename: NAME '[' NAME '*' ']' | NAME '[' NAME ']' | NAME218 mark = self.mark()219 cut = False220 if (221 (name := self.name())222 and223 (literal := self.expect('['))224 and225 (type := self.name())226 and227 (literal_1 := self.expect('*'))228 and229 (literal_2 := self.expect(']'))230 ):231 return ( name . string , type . string + "*" )232 self.reset(mark)233 if cut: return None234 cut = False235 if (236 (name := self.name())237 and238 (literal := self.expect('['))239 and240 (type := self.name())241 and242 (literal_1 := self.expect(']'))243 ):244 return ( name . string , type . string )245 self.reset(mark)246 if cut: return None247 cut = False248 if (249 (name := self.name())250 ):251 return ( name . string , None )252 self.reset(mark)253 if cut: return None254 return None255 @memoize256 def memoflag(self) -> Optional[str]:257 # memoflag: '(' 'memo' ')'258 mark = self.mark()259 cut = False260 if (261 (literal := self.expect('('))262 and263 (literal_1 := self.expect('memo'))264 and265 (literal_2 := self.expect(')'))266 ):267 return "memo"268 self.reset(mark)269 if cut: return None270 return None271 @memoize272 def alts(self) -> Optional[Rhs]:273 # alts: alt "|" alts | alt274 mark = self.mark()275 cut = False276 if (277 (alt := self.alt())278 and279 (literal := self.expect("|"))280 and281 (alts := self.alts())282 ):283 return Rhs ( [ alt ] + alts . alts )284 self.reset(mark)285 if cut: return None286 cut = False287 if (288 (alt := self.alt())289 ):290 return Rhs ( [ alt ] )291 self.reset(mark)292 if cut: return None293 return None294 @memoize295 def more_alts(self) -> Optional[Rhs]:296 # more_alts: "|" alts NEWLINE more_alts | "|" alts NEWLINE297 mark = self.mark()298 cut = False299 if (300 (literal := self.expect("|"))301 and302 (alts := self.alts())303 and304 (newline := self.expect('NEWLINE'))305 and306 (more_alts := self.more_alts())307 ):308 return Rhs ( alts . alts + more_alts . alts )309 self.reset(mark)310 if cut: return None311 cut = False312 if (313 (literal := self.expect("|"))314 and315 (alts := self.alts())316 and317 (newline := self.expect('NEWLINE'))318 ):319 return Rhs ( alts . alts )320 self.reset(mark)321 if cut: return None322 return None323 @memoize324 def alt(self) -> Optional[Alt]:325 # alt: items '$' action | items '$' | items action | items326 mark = self.mark()327 cut = False328 if (329 (items := self.items())330 and331 (literal := self.expect('$'))332 and333 (action := self.action())334 ):335 return Alt ( items + [ NamedItem ( None , NameLeaf ( 'ENDMARKER' ) ) ] , action = action )336 self.reset(mark)337 if cut: return None338 cut = False339 if (340 (items := self.items())341 and342 (literal := self.expect('$'))343 ):344 return Alt ( items + [ NamedItem ( None , NameLeaf ( 'ENDMARKER' ) ) ] , action = None )345 self.reset(mark)346 if cut: return None347 cut = False348 if (349 (items := self.items())350 and351 (action := self.action())352 ):353 return Alt ( items , action = action )354 self.reset(mark)355 if cut: return None356 cut = False357 if (358 (items := self.items())359 ):360 return Alt ( items , action = None )361 self.reset(mark)362 if cut: return None363 return None364 @memoize365 def items(self) -> Optional[NamedItemList]:366 # items: named_item items | named_item367 mark = self.mark()368 cut = False369 if (370 (named_item := self.named_item())371 and372 (items := self.items())373 ):374 return [ named_item ] + items375 self.reset(mark)376 if cut: return None377 cut = False378 if (379 (named_item := self.named_item())380 ):381 return [ named_item ]382 self.reset(mark)383 if cut: return None384 return None385 @memoize386 def named_item(self) -> Optional[NamedItem]:387 # named_item: NAME '=' ~ item | item | lookahead388 mark = self.mark()389 cut = False390 if (391 (name := self.name())392 and393 (literal := self.expect('='))394 and395 (cut := True)396 and397 (item := self.item())398 ):399 return NamedItem ( name . string , item )400 self.reset(mark)401 if cut: return None402 cut = False403 if (404 (item := self.item())405 ):406 return NamedItem ( None , item )407 self.reset(mark)408 if cut: return None409 cut = False410 if (411 (it := self.lookahead())412 ):413 return NamedItem ( None , it )414 self.reset(mark)415 if cut: return None416 return None417 @memoize418 def lookahead(self) -> Optional[LookaheadOrCut]:419 # lookahead: '&' ~ atom | '!' ~ atom | '~'420 mark = self.mark()421 cut = False422 if (423 (literal := self.expect('&'))424 and425 (cut := True)426 and427 (atom := self.atom())428 ):429 return PositiveLookahead ( atom )430 self.reset(mark)431 if cut: return None432 cut = False433 if (434 (literal := self.expect('!'))435 and436 (cut := True)437 and438 (atom := self.atom())439 ):440 return NegativeLookahead ( atom )441 self.reset(mark)442 if cut: return None443 cut = False444 if (445 (literal := self.expect('~'))446 ):447 return Cut ( )448 self.reset(mark)449 if cut: return None450 return None451 @memoize452 def item(self) -> Optional[Item]:453 # item: '[' ~ alts ']' | atom '?' | atom '*' | atom '+' | atom '.' atom '+' | atom454 mark = self.mark()455 cut = False456 if (457 (literal := self.expect('['))458 and459 (cut := True)460 and461 (alts := self.alts())462 and463 (literal_1 := self.expect(']'))464 ):465 return Opt ( alts )466 self.reset(mark)467 if cut: return None468 cut = False469 if (470 (atom := self.atom())471 and472 (literal := self.expect('?'))473 ):474 return Opt ( atom )475 self.reset(mark)476 if cut: return None477 cut = False478 if (479 (atom := self.atom())480 and481 (literal := self.expect('*'))482 ):483 return Repeat0 ( atom )484 self.reset(mark)485 if cut: return None486 cut = False487 if (488 (atom := self.atom())489 and490 (literal := self.expect('+'))491 ):492 return Repeat1 ( atom )493 self.reset(mark)494 if cut: return None495 cut = False496 if (497 (sep := self.atom())498 and499 (literal := self.expect('.'))500 and501 (node := self.atom())502 and503 (literal_1 := self.expect('+'))504 ):505 return Gather ( sep , node )506 self.reset(mark)507 if cut: return None508 cut = False509 if (510 (atom := self.atom())511 ):512 return atom513 self.reset(mark)514 if cut: return None515 return None516 @memoize517 def atom(self) -> Optional[Plain]:518 # atom: '(' ~ alts ')' | NAME | STRING519 mark = self.mark()520 cut = False521 if (522 (literal := self.expect('('))523 and524 (cut := True)525 and526 (alts := self.alts())527 and528 (literal_1 := self.expect(')'))529 ):530 return Group ( alts )531 self.reset(mark)532 if cut: return None533 cut = False534 if (535 (name := self.name())536 ):537 return NameLeaf ( name . string )538 self.reset(mark)539 if cut: return None540 cut = False541 if (542 (string := self.string())543 ):544 return StringLeaf ( string . string )545 self.reset(mark)546 if cut: return None547 return None548 @memoize549 def action(self) -> Optional[str]:550 # action: "{" ~ target_atoms "}"551 mark = self.mark()552 cut = False553 if (554 (literal := self.expect("{"))555 and556 (cut := True)557 and558 (target_atoms := self.target_atoms())559 and560 (literal_1 := self.expect("}"))561 ):562 return target_atoms563 self.reset(mark)564 if cut: return None565 return None566 @memoize567 def target_atoms(self) -> Optional[str]:568 # target_atoms: target_atom target_atoms | target_atom569 mark = self.mark()570 cut = False571 if (572 (target_atom := self.target_atom())573 and574 (target_atoms := self.target_atoms())575 ):576 return target_atom + " " + target_atoms577 self.reset(mark)578 if cut: return None579 cut = False580 if (581 (target_atom := self.target_atom())582 ):583 return target_atom584 self.reset(mark)585 if cut: return None586 return None587 @memoize588 def target_atom(self) -> Optional[str]:589 # target_atom: "{" ~ target_atoms "}" | NAME | NUMBER | STRING | "?" | ":" | !"}" OP590 mark = self.mark()591 cut = False592 if (593 (literal := self.expect("{"))594 and595 (cut := True)596 and597 (target_atoms := self.target_atoms())598 and599 (literal_1 := self.expect("}"))600 ):601 return "{" + target_atoms + "}"602 self.reset(mark)603 if cut: return None604 cut = False...
FizzBuzzPickle.py
Source:FizzBuzzPickle.py
1"""FizzBuzz implemented using a Python pickle bomb (tested in version 3.6)2Author: @PAndaContron3Python has a serialization library called pickle, which is actually a full bytecode VM that allows for arbitrary code execution.4This allows for "pickle bombs" to be created; data which, when deserialized, executes code instead of returning an object.5However, since pickle bytecode isn't really designed to be used this way, it's very inflexible.6A workaround would be to use the eval function to run python code, but that's boring; it would just be a slightly modified version of an existing program.7This pickle bytecode is equivalent to the following python code:8operator.getitem(list(map(print, itertools.starmap(operator.add, zip(itertools.starmap(operator.add, zip(map(functools.partial(operator.mul, 'Fizz'), map(functools.partial(operator.gt, 1), itertools.starmap(operator.mod, zip(itertools.count(1), itertools.repeat(3))))), map(functools.partial(operator.mul, 'Buzz'), map(functools.partial(operator.gt, 1), itertools.starmap(operator.mod, zip(itertools.count(1), itertools.repeat(5))))))), itertools.starmap(operator.mul, zip(map(operator.not_, map(functools.partial(operator.gt, 1), itertools.starmap(operator.mul, zip(itertools.starmap(operator.mod, zip(itertools.count(1), itertools.repeat(3))), itertools.starmap(operator.mod, zip(itertools.count(1), itertools.repeat(5))))))), map(str, range(1, 101)))))))), 0)9"""10import pickle11pickle.loads(b'coperator\ngetitem\n(c__builtin__\nlist\n(c__builtin__\nmap\n(c__builtin__\nprint\ncitertools\nstarmap\n(coperator\nadd\nc__builtin__\nzip\n(citertools\nstarmap\n(coperator\nadd\nc__builtin__\nzip\n(c__builtin__\nmap\n(cfunctools\npartial\n(coperator\nmul\nVFizz\ntRc__builtin__\nmap\n(cfunctools\npartial\n(coperator\ngt\nI1\ntRcitertools\nstarmap\n(coperator\nmod\nc__builtin__\nzip\n(citertools\ncount\n(I1\ntRcitertools\nrepeat\n(I3\ntRtRtRtRtRc__builtin__\nmap\n(cfunctools\npartial\n(coperator\nmul\nVBuzz\ntRc__builtin__\nmap\n(cfunctools\npartial\n(coperator\ngt\nI1\ntRcitertools\nstarmap\n(coperator\nmod\nc__builtin__\nzip\n(citertools\ncount\n(I1\ntRcitertools\nrepeat\n(I5\ntRtRtRtRtRtRtRcitertools\nstarmap\n(coperator\nmul\nc__builtin__\nzip\n(c__builtin__\nmap\n(coperator\nnot_\nc__builtin__\nmap\n(cfunctools\npartial\n(coperator\ngt\nI1\ntRcitertools\nstarmap\n(coperator\nmul\nc__builtin__\nzip\n(citertools\nstarmap\n(coperator\nmod\nc__builtin__\nzip\n(citertools\ncount\n(I1\ntRcitertools\nrepeat\n(I3\ntRtRtRcitertools\nstarmap\n(coperator\nmod\nc__builtin__\nzip\n(citertools\ncount\n(I1\ntRcitertools\nrepeat\n(I5\ntRtRtRtRtRtRtRc__builtin__\nmap\n(c__builtin__\nstr\nc__builtin__\nrange\n(I1\nI101\ntRtRtRtRtRtRtRtRI0\ntR.')12"""Pickletools disassembly:13 0: c GLOBAL 'operator getitem'14 18: ( MARK15 19: c GLOBAL '__builtin__ list'16 37: ( MARK17 38: c GLOBAL '__builtin__ map'18 55: ( MARK19 56: c GLOBAL '__builtin__ print'20 75: c GLOBAL 'itertools starmap'21 94: ( MARK22 95: c GLOBAL 'operator add'23 109: c GLOBAL '__builtin__ zip'24 126: ( MARK25 127: c GLOBAL 'itertools starmap'26 146: ( MARK27 147: c GLOBAL 'operator add'28 161: c GLOBAL '__builtin__ zip'29 178: ( MARK30 179: c GLOBAL '__builtin__ map'31 196: ( MARK32 197: c GLOBAL 'functools partial'33 216: ( MARK34 217: c GLOBAL 'operator mul'35 231: V UNICODE 'Fizz'36 237: t TUPLE (MARK at 216)37 238: R REDUCE38 239: c GLOBAL '__builtin__ map'39 256: ( MARK40 257: c GLOBAL 'functools partial'41 276: ( MARK42 277: c GLOBAL 'operator gt'43 290: I INT 144 293: t TUPLE (MARK at 276)45 294: R REDUCE46 295: c GLOBAL 'itertools starmap'47 314: ( MARK48 315: c GLOBAL 'operator mod'49 329: c GLOBAL '__builtin__ zip'50 346: ( MARK51 347: c GLOBAL 'itertools count'52 364: ( MARK53 365: I INT 154 368: t TUPLE (MARK at 364)55 369: R REDUCE56 370: c GLOBAL 'itertools repeat'57 388: ( MARK58 389: I INT 359 392: t TUPLE (MARK at 388)60 393: R REDUCE61 394: t TUPLE (MARK at 346)62 395: R REDUCE63 396: t TUPLE (MARK at 314)64 397: R REDUCE65 398: t TUPLE (MARK at 256)66 399: R REDUCE67 400: t TUPLE (MARK at 196)68 401: R REDUCE69 402: c GLOBAL '__builtin__ map'70 419: ( MARK71 420: c GLOBAL 'functools partial'72 439: ( MARK73 440: c GLOBAL 'operator mul'74 454: V UNICODE 'Buzz'75 460: t TUPLE (MARK at 439)76 461: R REDUCE77 462: c GLOBAL '__builtin__ map'78 479: ( MARK79 480: c GLOBAL 'functools partial'80 499: ( MARK81 500: c GLOBAL 'operator gt'82 513: I INT 183 516: t TUPLE (MARK at 499)84 517: R REDUCE85 518: c GLOBAL 'itertools starmap'86 537: ( MARK87 538: c GLOBAL 'operator mod'88 552: c GLOBAL '__builtin__ zip'89 569: ( MARK90 570: c GLOBAL 'itertools count'91 587: ( MARK92 588: I INT 193 591: t TUPLE (MARK at 587)94 592: R REDUCE95 593: c GLOBAL 'itertools repeat'96 611: ( MARK97 612: I INT 598 615: t TUPLE (MARK at 611)99 616: R REDUCE100 617: t TUPLE (MARK at 569)101 618: R REDUCE102 619: t TUPLE (MARK at 537)103 620: R REDUCE104 621: t TUPLE (MARK at 479)105 622: R REDUCE106 623: t TUPLE (MARK at 419)107 624: R REDUCE108 625: t TUPLE (MARK at 178)109 626: R REDUCE110 627: t TUPLE (MARK at 146)111 628: R REDUCE112 629: c GLOBAL 'itertools starmap'113 648: ( MARK114 649: c GLOBAL 'operator mul'115 663: c GLOBAL '__builtin__ zip'116 680: ( MARK117 681: c GLOBAL '__builtin__ map'118 698: ( MARK119 699: c GLOBAL 'operator not_'120 714: c GLOBAL '__builtin__ map'121 731: ( MARK122 732: c GLOBAL 'functools partial'123 751: ( MARK124 752: c GLOBAL 'operator gt'125 765: I INT 1126 768: t TUPLE (MARK at 751)127 769: R REDUCE128 770: c GLOBAL 'itertools starmap'129 789: ( MARK130 790: c GLOBAL 'operator mul'131 804: c GLOBAL '__builtin__ zip'132 821: ( MARK133 822: c GLOBAL 'itertools starmap'134 841: ( MARK135 842: c GLOBAL 'operator mod'136 856: c GLOBAL '__builtin__ zip'137 873: ( MARK138 874: c GLOBAL 'itertools count'139 891: ( MARK140 892: I INT 1141 895: t TUPLE (MARK at 891)142 896: R REDUCE143 897: c GLOBAL 'itertools repeat'144 915: ( MARK145 916: I INT 3146 919: t TUPLE (MARK at 915)147 920: R REDUCE148 921: t TUPLE (MARK at 873)149 922: R REDUCE150 923: t TUPLE (MARK at 841)151 924: R REDUCE152 925: c GLOBAL 'itertools starmap'153 944: ( MARK154 945: c GLOBAL 'operator mod'155 959: c GLOBAL '__builtin__ zip'156 976: ( MARK157 977: c GLOBAL 'itertools count'158 994: ( MARK159 995: I INT 1160 998: t TUPLE (MARK at 994)161 999: R REDUCE162 1000: c GLOBAL 'itertools repeat'163 1018: ( MARK164 1019: I INT 5165 1022: t TUPLE (MARK at 1018)166 1023: R REDUCE167 1024: t TUPLE (MARK at 976)168 1025: R REDUCE169 1026: t TUPLE (MARK at 944)170 1027: R REDUCE171 1028: t TUPLE (MARK at 821)172 1029: R REDUCE173 1030: t TUPLE (MARK at 789)174 1031: R REDUCE175 1032: t TUPLE (MARK at 731)176 1033: R REDUCE177 1034: t TUPLE (MARK at 698)178 1035: R REDUCE179 1036: c GLOBAL '__builtin__ map'180 1053: ( MARK181 1054: c GLOBAL '__builtin__ str'182 1071: c GLOBAL '__builtin__ range'183 1090: ( MARK184 1091: I INT 1185 1094: I INT 101186 1099: t TUPLE (MARK at 1090)187 1100: R REDUCE188 1101: t TUPLE (MARK at 1053)189 1102: R REDUCE190 1103: t TUPLE (MARK at 680)191 1104: R REDUCE192 1105: t TUPLE (MARK at 648)193 1106: R REDUCE194 1107: t TUPLE (MARK at 126)195 1108: R REDUCE196 1109: t TUPLE (MARK at 94)197 1110: R REDUCE198 1111: t TUPLE (MARK at 55)199 1112: R REDUCE200 1113: t TUPLE (MARK at 37)201 1114: R REDUCE202 1115: I INT 0203 1118: t TUPLE (MARK at 18)204 1119: R REDUCE205 1120: . STOP206highest protocol among opcodes = 0...
test_txproc_functional.py
Source:test_txproc_functional.py
1import pytest2from tests.common import *3@pytest.mark.parametrize("tx_input, expected_output",4 [5 pytest.param([("deposit", 1, 1, 1.0)],6 [[1, 1.0, 0.0, 1.0, "false"]],7 marks=[pytest.mark.deposit, pytest.mark.basic],8 id="deposit_basic"),9 pytest.param([("deposit", 1, 1, 0.0)],10 [[1, 0.0, 0.0, 0.0, "false"]],11 marks=pytest.mark.deposit,12 id="deposit_0.0"),13 pytest.param([("deposit", 1, 1, 1.0),14 ("deposit", 1, 2, 0.1),15 ("deposit", 1, 3, 1000)],16 [[1, 1001.1, 0.0, 1001.1, "false"]],17 marks=pytest.mark.deposit,18 id="multiple_deposit"),19 pytest.param([("deposit", 1, 1, 1.0),20 ("deposit", 1, 1, 0.1)],21 [[1, 1.0, 0.0, 1.0, "false"]],22 marks=pytest.mark.deposit,23 id="duplicate_deposit"),24 pytest.param([("deposit", 1, 1, 1.0),25 ("withdrawal", 1, 2, 0.1)],26 [[1, 0.9, 0.0, 0.9, "false"]],27 marks=[pytest.mark.withdrawal, pytest.mark.basic],28 id="withdraw_basic"),29 pytest.param([("deposit", 1, 1, 1.0),30 ("withdrawal", 1, 2, 0.1),31 ("withdrawal", 1, 2, 0.1)],32 [[1, 0.9, 0.0, 0.9, "false"]],33 marks=pytest.mark.withdrawal,34 id="duplicate_withdrawal"),35 pytest.param([("deposit", 1, 1, 1.0),36 ("withdrawal", 1, 2, 1.0)],37 [[1, 0.0, 0.0, 0.0, "false"]],38 marks=pytest.mark.withdrawal,39 id="withdrawal_all_funds"),40 pytest.param([("deposit", 1, 1, 1.0),41 ("withdrawal", 1, 2, 1.1)],42 [[1, 1.0, 0.0, 1.0, "false"]],43 marks=[pytest.mark.withdrawal, pytest.mark.ignored],44 id="withdraw_more_than_avail"),45 pytest.param([("deposit", 1, 1, 1.0),46 ("deposit", 1, 2, 1.1),47 ("dispute", 1, 1)],48 [[1, 1.1, 1.0, 2.1, "false"]],49 marks=[pytest.mark.dispute, pytest.mark.basic],50 id="dispute_basic"),51 pytest.param([("deposit", 1, 1, 1.0),52 ("withdrawal", 1, 2, 0.5),53 ("dispute", 1, 2)],54 [[1, 0.5, 0.0, 0.5, "false"]],55 marks=[pytest.mark.dispute, pytest.mark.ignored],56 id="dispute_on_withdrawal"),57 pytest.param([("deposit", 1, 1, 1.0),58 ("withdrawal", 1, 2, 0.5),59 ("dispute", 1, 1)],60 [[1, -0.5, 1.0, 0.5, "false"]],61 marks=pytest.mark.dispute,62 id="dispute_after_half_withdrawn"),63 pytest.param([("deposit", 1, 1, 1.0),64 ("dispute", 1, 1),65 ("dispute", 1, 1)],66 [[1, 0.0, 1.0, 1.0, "false"]],67 marks=[pytest.mark.dispute, pytest.mark.duplicate],68 id="dispute_duplicate"),69 pytest.param([("deposit", 1, 1, 1.0),70 ("dispute", 1, 1),71 ("deposit", 2, 2, 10.0),72 ("dispute", 2, 2)],73 [[1, 0.0, 1.0, 1.0, "false"],74 [2, 0.0, 10.0, 10.0, "false"]],75 marks=[pytest.mark.dispute],76 id="dispute_multiple"),77 pytest.param([("deposit", 1, 1, 1.0),78 ("dispute", 1, 1),79 ("withdrawal", 1, 2, 0.1)],80 [[1, 0.0, 1.0, 1.0, "false"]],81 marks=[pytest.mark.dispute, pytest.mark.withdrawal],82 id="withdraw_disputed"),83 pytest.param([("deposit", 1, 1, 1.0),84 ("dispute", 1, 1),85 ("resolve", 1, 1)],86 [[1, 1.0, 0.0, 1.0, "false"]],87 marks=[pytest.mark.dispute, pytest.mark.resolve, pytest.mark.basic],88 id="resolve_basic"),89 pytest.param([("deposit", 1, 1, 1.0),90 ("dispute", 1, 1),91 ("chargeback", 1, 1),92 ("resolve", 1, 1)],93 [[1, 0.0, 0.0, 0.0, "true"]],94 marks=[pytest.mark.dispute, pytest.mark.resolve, pytest.mark.ignored],95 id="resolve_after_chargeback"),96 pytest.param([("deposit", 1, 1, 1.0),97 ("dispute", 1, 1),98 ("chargeback", 1, 1)],99 [[1, 0.0, 0.0, 0.0, "true"]],100 marks=[pytest.mark.chargeback, pytest.mark.basic],101 id="chargeback_basic"),102 pytest.param([("deposit", 1, 1, 1.0),103 ("chargeback", 1, 1)],104 [[1, 1.0, 0.0, 1.0, "false"]],105 marks=[pytest.mark.chargeback, pytest.mark.ignored],106 id="chargeback_no_dispute"),107 pytest.param([("deposit", 1, 1, 1.0),108 ("dispute", 1, 1),109 ("resolve", 1, 1),110 ("chargeback", 1, 1)],111 [[1, 1.0, 0.0, 1.0, "false"]],112 marks=[pytest.mark.chargeback, pytest.mark.ignored],113 id="chargeback_resolved"),114 pytest.param([("deposit", 1, 1, 1.0),115 ("withdrawal", 1, 2, 0.5),116 ("chargeback", 1, 2)],117 [[1, 0.5, 0.0, 0.5, "false"]],118 marks=[pytest.mark.chargeback, pytest.mark.ignored],119 id="chargeback_on_withdrawal"),120 ])121def test_basic_tx_processing(tx_input, expected_output):122 assert_dataframes_match(process_all_tx(tx_input), expected_df(expected_output))123@pytest.mark.parametrize("tx_input",124 [125 pytest.param([("withdrawal", 1, 1, 1.0)],126 marks=[pytest.mark.withdrawal, pytest.mark.ignored],127 id="withdrawal_no_account"),128 pytest.param([("dispute", 1, 2)],129 marks=[pytest.mark.dispute, pytest.mark.ignored],130 id="dispute_no_tx"),131 pytest.param([("resolve", 1, 1)],132 marks=[pytest.mark.resolve, pytest.mark.ignored],133 id="resolve_no_tx"),134 pytest.param([("chargeback", 1, 1)],135 marks=[pytest.mark.chargeback, pytest.mark.ignored],136 id="chargeback_no_tx"),137 ])138def test_no_tx(tx_input):139 assert process_all_tx(tx_input).empty140@pytest.mark.parametrize("tx_input, expected_output",141 [142 pytest.param([("dispute", 1, 2)],143 [[1, 100.0, 0.0, 100.0, "false"]],144 marks=[pytest.mark.discarded, pytest.mark.dispute],145 id="dispute_on_discarded"),146 pytest.param([("resolve", 1, 2)],147 [[1, 100.0, 0.0, 100.0, "false"]],148 marks=[pytest.mark.discarded, pytest.mark.resolve],149 id="resolve_on_discarded"),150 pytest.param([("chargeback", 1, 2)],151 [[1, 100.0, 0.0, 100.0, "false"]],152 marks=[pytest.mark.discarded, pytest.mark.chargeback],153 id="dispute_on_chargeback"),154 ])155def test_on_discarded_tx(tx_input, expected_output):156 input_too_large_withdrawal = [("deposit", 1, 1, 100.0),157 ("withdrawal", 1, 2, 101.0)]158 assert_dataframes_match(process_all_tx(input_too_large_withdrawal + tx_input),159 expected_df(expected_output))160@pytest.mark.parametrize("tx_input, expected_output",161 [162 pytest.param([("deposit", 1, 2, 10.0)],163 [[1, 0.0, 0.0, 0.0, "true"]],164 marks=[pytest.mark.on_locked, pytest.mark.deposit],165 id="deposit_on_locked"),166 pytest.param([("withdrawal", 1, 2, 10.0)],167 [[1, 0.0, 0.0, 0.0, "true"]],168 marks=[pytest.mark.on_locked, pytest.mark.withdrawal],169 id="withdrawal_on_locked"),170 pytest.param([("dispute", 1, 1)],171 [[1, 0.0, 0.0, 0.0, "true"]],172 marks=[pytest.mark.on_locked, pytest.mark.dispute],173 id="dispute_on_locked"),174 pytest.param([("resolve", 1, 1)],175 [[1, 0.0, 0.0, 0.0, "true"]],176 marks=[pytest.mark.on_locked, pytest.mark.resolve],177 id="resolve_on_locked"),178 pytest.param([("chargeback", 1, 1)],179 [[1, 0.0, 0.0, 0.0, "true"]],180 marks=[pytest.mark.on_locked, pytest.mark.chargeback],181 id="chargeback_on_locked"),182 ])183def test_on_locked_acc(tx_input, expected_output):184 input_locked_acc = [("deposit", 1, 1, 100.0),185 ("dispute", 1, 1),186 ("chargeback", 1, 1)]187 assert_dataframes_match(process_all_tx(input_locked_acc + tx_input),188 expected_df(expected_output))189def test_dispute_on_wrong_account():190 tx_input = [("deposit", 1, 1, 100.0),191 ("deposit", 2, 2, 10.0),192 ("dispute", 1, 2)]193 expected_output = [[1, 100.0, 0.0, 100.0, "false"],194 [2, 0.0, 10.0, 10.0, "false"]]195 assert_dataframes_match(process_all_tx(tx_input + tx_input),...
structures.py
Source:structures.py
...16def istestfunc(func):17 return hasattr(func, "__call__") and getattr(18 func, "__name__", "<lambda>"19 ) != "<lambda>"20def get_empty_parameterset_mark(config, argnames, func):21 requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)22 if requested_mark in ("", None, "skip"):23 mark = MARK_GEN.skip24 elif requested_mark == "xfail":25 mark = MARK_GEN.xfail(run=False)26 else:27 raise LookupError(requested_mark)28 fs, lineno = getfslineno(func)29 reason = "got empty parameter set %r, function %s at %s:%d" % (30 argnames, func.__name__, fs, lineno31 )32 return mark(reason=reason)33class ParameterSet(namedtuple("ParameterSet", "values, marks, id")):34 @classmethod35 def param(cls, *values, **kw):36 marks = kw.pop("marks", ())37 if isinstance(marks, MarkDecorator):38 marks = marks,39 else:40 assert isinstance(marks, (tuple, list, set))41 def param_extract_id(id=None):42 return id43 id_ = param_extract_id(**kw)44 return cls(values, marks, id_)45 @classmethod46 def extract_from(cls, parameterset, legacy_force_tuple=False):47 """48 :param parameterset:49 a legacy style parameterset that may or may not be a tuple,50 and may or may not be wrapped into a mess of mark objects51 :param legacy_force_tuple:52 enforce tuple wrapping so single argument tuple values53 don't get decomposed and break tests54 """55 if isinstance(parameterset, cls):56 return parameterset57 if not isinstance(parameterset, MarkDecorator) and legacy_force_tuple:58 return cls.param(parameterset)59 newmarks = []60 argval = parameterset61 while isinstance(argval, MarkDecorator):62 newmarks.append(63 MarkDecorator(Mark(argval.markname, argval.args[:-1], argval.kwargs))64 )65 argval = argval.args[-1]66 assert not isinstance(argval, ParameterSet)67 if legacy_force_tuple:68 argval = argval,69 if newmarks:70 warnings.warn(MARK_PARAMETERSET_UNPACKING)71 return cls(argval, marks=newmarks, id=None)72 @classmethod73 def _for_parametrize(cls, argnames, argvalues, func, config):74 if not isinstance(argnames, (tuple, list)):75 argnames = [x.strip() for x in argnames.split(",") if x.strip()]76 force_tuple = len(argnames) == 177 else:78 force_tuple = False79 parameters = [80 ParameterSet.extract_from(x, legacy_force_tuple=force_tuple)81 for x in argvalues82 ]83 del argvalues84 if not parameters:85 mark = get_empty_parameterset_mark(config, argnames, func)86 parameters.append(87 ParameterSet(values=(NOTSET,) * len(argnames), marks=[mark], id=None)88 )89 return argnames, parameters90@attr.s(frozen=True)91class Mark(object):92 #: name of the mark93 name = attr.ib(type=str)94 #: positional arguments of the mark decorator95 args = attr.ib(type="List[object]")96 #: keyword arguments of the mark decorator97 kwargs = attr.ib(type="Dict[str, object]")98 def combined_with(self, other):99 """100 :param other: the mark to combine with101 :type other: Mark102 :rtype: Mark103 combines by appending aargs and merging the mappings104 """105 assert self.name == other.name106 return Mark(107 self.name, self.args + other.args, dict(self.kwargs, **other.kwargs)108 )109@attr.s110class MarkDecorator(object):111 """ A decorator for test functions and test classes. When applied112 it will create :class:`MarkInfo` objects which may be113 :ref:`retrieved by hooks as item keywords <excontrolskip>`.114 MarkDecorator instances are often created like this::115 mark1 = pytest.mark.NAME # simple MarkDecorator116 mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator117 and can then be applied as decorators to test functions::118 @mark2119 def test_function():120 pass121 When a MarkDecorator instance is called it does the following:122 1. If called with a single class as its only positional argument and no123 additional keyword arguments, it attaches itself to the class so it124 gets applied automatically to all test cases found in that class.125 2. If called with a single function as its only positional argument and126 no additional keyword arguments, it attaches a MarkInfo object to the127 function, containing all the arguments already stored internally in128 the MarkDecorator.129 3. When called in any other case, it performs a 'fake construction' call,130 i.e. it returns a new MarkDecorator instance with the original131 MarkDecorator's content updated with the arguments passed to this132 call.133 Note: The rules above prevent MarkDecorator objects from storing only a134 single function or class reference as their positional argument with no135 additional keyword or positional arguments.136 """137 mark = attr.ib(validator=attr.validators.instance_of(Mark))138 name = alias("mark.name")139 args = alias("mark.args")140 kwargs = alias("mark.kwargs")141 @property142 def markname(self):143 return self.name # for backward-compat (2.4.1 had this attr)144 def __eq__(self, other):145 return self.mark == other.mark if isinstance(other, MarkDecorator) else False146 def __repr__(self):147 return "<MarkDecorator %r>" % (self.mark,)148 def with_args(self, *args, **kwargs):149 """ return a MarkDecorator with extra arguments added150 unlike call this can be used even if the sole argument is a callable/class151 :return: MarkDecorator152 """153 mark = Mark(self.name, args, kwargs)154 return self.__class__(self.mark.combined_with(mark))155 def __call__(self, *args, **kwargs):156 """ if passed a single callable argument: decorate it with mark info.157 otherwise add *args/**kwargs in-place to mark information. """158 if args and not kwargs:159 func = args[0]160 is_class = inspect.isclass(func)161 if len(args) == 1 and (istestfunc(func) or is_class):162 if is_class:163 store_mark(func, self.mark)164 else:165 store_legacy_markinfo(func, self.mark)166 store_mark(func, self.mark)167 return func168 return self.with_args(*args, **kwargs)169def get_unpacked_marks(obj):170 """171 obtain the unpacked marks that are stored on an object172 """173 mark_list = getattr(obj, "pytestmark", [])174 if not isinstance(mark_list, list):175 mark_list = [mark_list]176 return [getattr(mark, "mark", mark) for mark in mark_list] # unpack MarkDecorator177def store_mark(obj, mark):178 """store a Mark on an object179 this is used to implement the Mark declarations/decorators correctly180 """181 assert isinstance(mark, Mark), mark182 # always reassign name to avoid updating pytestmark183 # in a reference that was only borrowed184 obj.pytestmark = get_unpacked_marks(obj) + [mark]185def store_legacy_markinfo(func, mark):186 """create the legacy MarkInfo objects and put them onto the function187 """188 if not isinstance(mark, Mark):189 raise TypeError("got {mark!r} instead of a Mark".format(mark=mark))190 holder = getattr(func, mark.name, None)191 if holder is None:192 holder = MarkInfo.for_mark(mark)193 setattr(func, mark.name, holder)194 else:195 holder.add_mark(mark)196def transfer_markers(funcobj, cls, mod):197 """198 this function transfers class level markers and module level markers199 into function level markinfo objects200 this is the main reason why marks are so broken201 the resolution will involve phasing out function level MarkInfo objects202 """203 for obj in (cls, mod):204 for mark in get_unpacked_marks(obj):205 if not _marked(funcobj, mark):206 store_legacy_markinfo(funcobj, mark)207def _marked(func, mark):208 """ Returns True if :func: is already marked with :mark:, False otherwise.209 This can happen if marker is applied to class and the test file is210 invoked more than once.211 """212 try:213 func_mark = getattr(func, getattr(mark, "combined", mark).name)214 except AttributeError:215 return False216 return any(mark == info.combined for info in func_mark)217@attr.s218class MarkInfo(object):219 """ Marking object created by :class:`MarkDecorator` instances. """220 _marks = attr.ib(convert=list)221 @_marks.validator222 def validate_marks(self, attribute, value):223 for item in value:224 if not isinstance(item, Mark):225 raise ValueError(226 "MarkInfo expects Mark instances, got {!r} ({!r})".format(227 item, type(item)228 )229 )230 combined = attr.ib(231 repr=False,232 default=attr.Factory(233 lambda self: reduce(Mark.combined_with, self._marks), takes_self=True234 ),235 )236 name = alias("combined.name", warning=MARK_INFO_ATTRIBUTE)237 args = alias("combined.args", warning=MARK_INFO_ATTRIBUTE)238 kwargs = alias("combined.kwargs", warning=MARK_INFO_ATTRIBUTE)239 @classmethod240 def for_mark(cls, mark):241 return cls([mark])242 def __repr__(self):243 return "<MarkInfo {!r}>".format(self.combined)244 def add_mark(self, mark):245 """ add a MarkInfo with the given args and kwargs. """246 self._marks.append(mark)247 self.combined = self.combined.combined_with(mark)248 def __iter__(self):249 """ yield MarkInfo objects each relating to a marking-call. """250 return map(MarkInfo.for_mark, self._marks)251class MarkGenerator(object):252 """ Factory for :class:`MarkDecorator` objects - exposed as253 a ``pytest.mark`` singleton instance. Example::254 import pytest255 @pytest.mark.slowtest256 def test_function():257 pass258 will set a 'slowtest' :class:`MarkInfo` object...
mark.py
Source:mark.py
...110 else:111 if selectuntil:112 keywordexpr = None113 if matchexpr:114 if not matchmark(colitem, matchexpr):115 deselected.append(colitem)116 continue117 remaining.append(colitem)118 if deselected:119 config.hook.pytest_deselected(items=deselected)120 items[:] = remaining121class MarkMapping:122 """Provides a local mapping for markers where item access123 resolves to True if the marker is present. """124 def __init__(self, keywords):125 mymarks = set()126 for key, value in keywords.items():127 if isinstance(value, MarkInfo) or isinstance(value, MarkDecorator):128 mymarks.add(key)129 self._mymarks = mymarks130 def __getitem__(self, name):131 return name in self._mymarks132class KeywordMapping:133 """Provides a local mapping for keywords.134 Given a list of names, map any substring of one of these names to True.135 """136 def __init__(self, names):137 self._names = names138 def __getitem__(self, subname):139 for name in self._names:140 if subname in name:141 return True142 return False143def matchmark(colitem, markexpr):144 """Tries to match on any marker names, attached to the given colitem."""145 return eval(markexpr, {}, MarkMapping(colitem.keywords))146def matchkeyword(colitem, keywordexpr):147 """Tries to match given keyword expression to given collector item.148 Will match on the name of colitem, including the names of its parents.149 Only matches names of items which are either a :class:`Class` or a150 :class:`Function`.151 Additionally, matches on names in the 'extra_keyword_matches' set of152 any item, as well as names directly assigned to test functions.153 """154 mapped_names = set()155 # Add the names of the current item and any parent items156 import pytest157 for item in colitem.listchain():158 if not isinstance(item, pytest.Instance):159 mapped_names.add(item.name)160 # Add the names added as extra keywords to current or parent items161 for name in colitem.listextrakeywords():162 mapped_names.add(name)163 # Add the names attached to the current function through direct assignment164 if hasattr(colitem, 'function'):165 for name in colitem.function.__dict__:166 mapped_names.add(name)167 mapping = KeywordMapping(mapped_names)168 if " " not in keywordexpr:169 # special case to allow for simple "-k pass" and "-k 1.3"170 return mapping[keywordexpr]171 elif keywordexpr.startswith("not ") and " " not in keywordexpr[4:]:172 return not mapping[keywordexpr[4:]]173 return eval(keywordexpr, {}, mapping)174def pytest_configure(config):175 config._old_mark_config = MARK_GEN._config176 if config.option.strict:177 MARK_GEN._config = config178def pytest_unconfigure(config):179 MARK_GEN._config = getattr(config, '_old_mark_config', None)180class MarkGenerator:181 """ Factory for :class:`MarkDecorator` objects - exposed as182 a ``pytest.mark`` singleton instance. Example::183 import pytest184 @pytest.mark.slowtest185 def test_function():186 pass187 will set a 'slowtest' :class:`MarkInfo` object188 on the ``test_function`` object. """189 _config = None190 def __getattr__(self, name):191 if name[0] == "_":192 raise AttributeError("Marker name must NOT start with underscore")193 if self._config is not None:194 self._check(name)195 return MarkDecorator(Mark(name, (), {}))196 def _check(self, name):197 try:198 if name in self._markers:199 return200 except AttributeError:201 pass202 self._markers = l = set()203 for line in self._config.getini("markers"):204 beginning = line.split(":", 1)205 x = beginning[0].split("(", 1)[0]206 l.add(x)207 if name not in self._markers:208 raise AttributeError("%r not a registered marker" % (name,))209def istestfunc(func):210 return hasattr(func, "__call__") and \211 getattr(func, "__name__", "<lambda>") != "<lambda>"212class MarkDecorator:213 """ A decorator for test functions and test classes. When applied214 it will create :class:`MarkInfo` objects which may be215 :ref:`retrieved by hooks as item keywords <excontrolskip>`.216 MarkDecorator instances are often created like this::217 mark1 = pytest.mark.NAME # simple MarkDecorator218 mark2 = pytest.mark.NAME(name1=value) # parametrized MarkDecorator219 and can then be applied as decorators to test functions::220 @mark2221 def test_function():222 pass223 When a MarkDecorator instance is called it does the following:224 1. If called with a single class as its only positional argument and no225 additional keyword arguments, it attaches itself to the class so it226 gets applied automatically to all test cases found in that class.227 2. If called with a single function as its only positional argument and228 no additional keyword arguments, it attaches a MarkInfo object to the229 function, containing all the arguments already stored internally in230 the MarkDecorator.231 3. When called in any other case, it performs a 'fake construction' call,232 i.e. it returns a new MarkDecorator instance with the original233 MarkDecorator's content updated with the arguments passed to this234 call.235 Note: The rules above prevent MarkDecorator objects from storing only a236 single function or class reference as their positional argument with no237 additional keyword or positional arguments.238 """239 def __init__(self, mark):240 assert isinstance(mark, Mark), repr(mark)241 self.mark = mark242 name = alias('mark.name')243 args = alias('mark.args')244 kwargs = alias('mark.kwargs')245 @property246 def markname(self):247 return self.name # for backward-compat (2.4.1 had this attr)248 def __eq__(self, other):249 return self.mark == other.mark250 def __repr__(self):251 return "<MarkDecorator %r>" % (self.mark,)252 def __call__(self, *args, **kwargs):253 """ if passed a single callable argument: decorate it with mark info.254 otherwise add *args/**kwargs in-place to mark information. """255 if args and not kwargs:256 func = args[0]257 is_class = inspect.isclass(func)258 if len(args) == 1 and (istestfunc(func) or is_class):259 if is_class:260 if hasattr(func, 'pytestmark'):261 mark_list = func.pytestmark262 if not isinstance(mark_list, list):263 mark_list = [mark_list]264 # always work on a copy to avoid updating pytestmark265 # from a superclass by accident266 mark_list = mark_list + [self]267 func.pytestmark = mark_list268 else:269 func.pytestmark = [self]270 else:271 holder = getattr(func, self.name, None)272 if holder is None:273 holder = MarkInfo(self.mark)274 setattr(func, self.name, holder)275 else:276 holder.add_mark(self.mark)277 return func278 mark = Mark(self.name, args, kwargs)279 return self.__class__(self.mark.combined_with(mark))280class Mark(namedtuple('Mark', 'name, args, kwargs')):281 def combined_with(self, other):282 assert self.name == other.name283 return Mark(284 self.name, self.args + other.args,285 dict(self.kwargs, **other.kwargs))286class MarkInfo(object):287 """ Marking object created by :class:`MarkDecorator` instances. """288 def __init__(self, mark):289 assert isinstance(mark, Mark), repr(mark)290 self.combined = mark291 self._marks = [mark]292 name = alias('combined.name')293 args = alias('combined.args')294 kwargs = alias('combined.kwargs')295 def __repr__(self):296 return "<MarkInfo {0!r}>".format(self.combined)297 def add_mark(self, mark):298 """ add a MarkInfo with the given args and kwargs. """299 self._marks.append(mark)300 self.combined = self.combined.combined_with(mark)301 def __iter__(self):302 """ yield MarkInfo objects each relating to a marking-call. """303 return imap(MarkInfo, self._marks)...
tokens.py
Source:tokens.py
1class Token(object):2 def __init__(self, start_mark, end_mark):3 self.start_mark = start_mark4 self.end_mark = end_mark5 def __repr__(self):6 attributes = [key for key in self.__dict__7 if not key.endswith('_mark')]8 attributes.sort()9 arguments = ', '.join(['%s=%r' % (key, getattr(self, key))10 for key in attributes])11 return '%s(%s)' % (self.__class__.__name__, arguments)12#class BOMToken(Token):13# id = '<byte order mark>'14class DirectiveToken(Token):15 id = '<directive>'16 def __init__(self, name, value, start_mark, end_mark):17 self.name = name18 self.value = value19 self.start_mark = start_mark20 self.end_mark = end_mark21class DocumentStartToken(Token):22 id = '<document start>'23class DocumentEndToken(Token):24 id = '<document end>'25class StreamStartToken(Token):26 id = '<stream start>'27 def __init__(self, start_mark=None, end_mark=None,28 encoding=None):29 self.start_mark = start_mark30 self.end_mark = end_mark31 self.encoding = encoding32class StreamEndToken(Token):33 id = '<stream end>'34class BlockSequenceStartToken(Token):35 id = '<block sequence start>'36class BlockMappingStartToken(Token):37 id = '<block mapping start>'38class BlockEndToken(Token):39 id = '<block end>'40class FlowSequenceStartToken(Token):41 id = '['42class FlowMappingStartToken(Token):43 id = '{'44class FlowSequenceEndToken(Token):45 id = ']'46class FlowMappingEndToken(Token):47 id = '}'48class KeyToken(Token):49 id = '?'50class ValueToken(Token):51 id = ':'52class BlockEntryToken(Token):53 id = '-'54class FlowEntryToken(Token):55 id = ','56class AliasToken(Token):57 id = '<alias>'58 def __init__(self, value, start_mark, end_mark):59 self.value = value60 self.start_mark = start_mark61 self.end_mark = end_mark62class AnchorToken(Token):63 id = '<anchor>'64 def __init__(self, value, start_mark, end_mark):65 self.value = value66 self.start_mark = start_mark67 self.end_mark = end_mark68class TagToken(Token):69 id = '<tag>'70 def __init__(self, value, start_mark, end_mark):71 self.value = value72 self.start_mark = start_mark73 self.end_mark = end_mark74class ScalarToken(Token):75 id = '<scalar>'76 def __init__(self, value, plain, start_mark, end_mark, style=None):77 self.value = value78 self.plain = plain79 self.start_mark = start_mark80 self.end_mark = end_mark...
events.py
Source:events.py
1# Abstract classes.2class Event(object):3 def __init__(self, start_mark=None, end_mark=None):4 self.start_mark = start_mark5 self.end_mark = end_mark6 def __repr__(self):7 attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']8 if hasattr(self, key)]9 arguments = ', '.join(['%s=%r' % (key, getattr(self, key))10 for key in attributes])11 return '%s(%s)' % (self.__class__.__name__, arguments)12class NodeEvent(Event):13 def __init__(self, anchor, start_mark=None, end_mark=None):14 self.anchor = anchor15 self.start_mark = start_mark16 self.end_mark = end_mark17class CollectionStartEvent(NodeEvent):18 def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,19 flow_style=None):20 self.anchor = anchor21 self.tag = tag22 self.implicit = implicit23 self.start_mark = start_mark24 self.end_mark = end_mark25 self.flow_style = flow_style26class CollectionEndEvent(Event):27 pass28# Implementations.29class StreamStartEvent(Event):30 def __init__(self, start_mark=None, end_mark=None, encoding=None):31 self.start_mark = start_mark32 self.end_mark = end_mark33 self.encoding = encoding34class StreamEndEvent(Event):35 pass36class DocumentStartEvent(Event):37 def __init__(self, start_mark=None, end_mark=None,38 explicit=None, version=None, tags=None):39 self.start_mark = start_mark40 self.end_mark = end_mark41 self.explicit = explicit42 self.version = version43 self.tags = tags44class DocumentEndEvent(Event):45 def __init__(self, start_mark=None, end_mark=None,46 explicit=None):47 self.start_mark = start_mark48 self.end_mark = end_mark49 self.explicit = explicit50class AliasEvent(NodeEvent):51 pass52class ScalarEvent(NodeEvent):53 def __init__(self, anchor, tag, implicit, value,54 start_mark=None, end_mark=None, style=None):55 self.anchor = anchor56 self.tag = tag57 self.implicit = implicit58 self.value = value59 self.start_mark = start_mark60 self.end_mark = end_mark61 self.style = style62class SequenceStartEvent(CollectionStartEvent):63 pass64class SequenceEndEvent(CollectionEndEvent):65 pass66class MappingStartEvent(CollectionStartEvent):67 pass68class MappingEndEvent(CollectionEndEvent):...
events.pyi
Source:events.pyi
1from typing import Any2class Event:3 start_mark: Any4 end_mark: Any5 def __init__(self, start_mark=..., end_mark=...) -> None: ...6class NodeEvent(Event):7 anchor: Any8 start_mark: Any9 end_mark: Any10 def __init__(self, anchor, start_mark=..., end_mark=...) -> None: ...11class CollectionStartEvent(NodeEvent):12 anchor: Any13 tag: Any14 implicit: Any15 start_mark: Any16 end_mark: Any17 flow_style: Any18 def __init__(self, anchor, tag, implicit, start_mark=..., end_mark=..., flow_style=...) -> None: ...19class CollectionEndEvent(Event): ...20class StreamStartEvent(Event):21 start_mark: Any22 end_mark: Any23 encoding: Any24 def __init__(self, start_mark=..., end_mark=..., encoding=...) -> None: ...25class StreamEndEvent(Event): ...26class DocumentStartEvent(Event):27 start_mark: Any28 end_mark: Any29 explicit: Any30 version: Any31 tags: Any32 def __init__(self, start_mark=..., end_mark=..., explicit=..., version=..., tags=...) -> None: ...33class DocumentEndEvent(Event):34 start_mark: Any35 end_mark: Any36 explicit: Any37 def __init__(self, start_mark=..., end_mark=..., explicit=...) -> None: ...38class AliasEvent(NodeEvent): ...39class ScalarEvent(NodeEvent):40 anchor: Any41 tag: Any42 implicit: Any43 value: Any44 start_mark: Any45 end_mark: Any46 style: Any47 def __init__(self, anchor, tag, implicit, value, start_mark=..., end_mark=..., style=...) -> None: ...48class SequenceStartEvent(CollectionStartEvent): ...49class SequenceEndEvent(CollectionEndEvent): ...50class MappingStartEvent(CollectionStartEvent): ......
Using AI Code Generation
1wpt.mark('markName1');2wpt.mark('markName2');3wpt.mark('markName3');4wpt.mark('markName4');5wpt.mark('markName5');6wpt.mark('markName6');7wpt.mark('markName7');8wpt.mark('markName8');9wpt.mark('markName9');10wpt.mark('markName10');11wpt.mark('markName11');12wpt.mark('markName12');13wpt.mark('markName13');14wpt.mark('markName14');15wpt.mark('markName15');16wpt.mark('markName16');17wpt.mark('markName17');18wpt.mark('markName18');19wpt.mark('markName19');
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new wpt();3 if (err) {4 return console.log(err);5 }6 console.log(data);7});8var wpt = require('wpt');9var wpt = new wpt();10 if (err) {11 return console.log(err);12 }13 console.log(data);14});15var wpt = require('wpt');16var wpt = new wpt();17 if (err) {18 return console.log(err);19 }20 console.log(data);21});22var wpt = require('wpt');23var wpt = new wpt();24 if (err) {25 return console.log(err);26 }27 console.log(data);28});29var wpt = require('wpt');30var wpt = new wpt();31 if (err) {32 return console.log(err);33 }34 console.log(data);35});36var wpt = require('wpt');37var wpt = new wpt();
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.9b3d8c8d7a04c4b4d4b4f1c8e4e4c4f4');3var params = {4};5wpt.runTest('www.google.com', params, function(err, data) {6 if(err) {7 console.log('Error: ' + err);8 }9 else {10 console.log('Test Status: ' + data.statusText);11 console.log('Test ID: ' + data.data.testId);12 console.log('Test URL: ' + data.data.summary);13 console.log('Test Results: ' + data.data.testUrl);14 console.log('Test Video: ' + data.data.userUrl);15 console.log('Test JSON: ' + data.data.jsonUrl);16 }17});18var wpt = require('webpagetest');19var wpt = new WebPageTest('www.webpagetest.org', 'A.9b3d8c8d7a04c4b4d4b4f1c8e4e4c4f4');20var params = {
Using AI Code Generation
1var wpt = require('webpagetest');2var test = new wpt('A.8d1b1e2b1b9c3b7d8e3c3c7f0e2c2d2', 'www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test %s started at %s', data.data.testId, data.data.from);5 test.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log('Test %s completed at %s', data.data.testId, data.data.completed);8 console.log('First View (ms): %d', data.data.median.firstView.loadTime);9 console.log('Repeat View (ms): %d', data.data.median.repeatView.loadTime);10 });11});12test.getTestResults('140430_1S_1S', function(err, data) {13 if (err) return console.error(err);14 console.log('Test %s completed at %s', data.data.testId, data.data.completed);15 console.log('First View (ms): %d', data.data.median.firstView.loadTime);16 console.log('Repeat View (ms): %d', data.data.median.repeatView.loadTime);17});18test.getTestStatus('140430_1S_1S', function(err, data) {19 if (err) return console.error(err);20 console.log('Test %s is %s', data.data.testId, data.data.statusText);21 console.log('Test %s completed at %s', data.data.testId, data.data.completed);22 console.log('First View (ms): %d', data.data.median.firstView.loadTime);23 console.log('Repeat View (ms): %d', data.data.median.repeatView.loadTime);24});25test.getLocations(function(err, data) {26 if (err) return console.error(err);27 console.log(data);28});29test.getTesters(function(err, data) {30 if (err) return console.error(err);31 console.log(data);32});33test.getTesters('Dulles:Chrome', function(err, data) {34 if (err) return console.error(err);35 console.log(data);36});37test.getTesters('Dulles:Chrome', 'all', function
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!!