How to use parseLiteral method in autotest

Best Python code snippet using autotest_python

sptparse.js

Source:sptparse.js Github

copy

Full Screen

...122 expectToken('{');123 while((tok=getNextToken()) !== '}') {124 switch(tok) {125 case 'CONTAINER':126 object.container = parseLiteral();127 break;128 case 'KEY':129 object.key = parseLiteral();130 break;131 case 'PARENT':132 object.parent = parseLiteral();133 break;134 case 'FLAG':135 object.flags = parseFlags();136 break;137 case 'NAME':138 object.name = parseMLString();139 break;140 case 'NAME2':141 object.name2 = parseMLString();142 break;143 case 'MAGIC':144 object.parent = parseLiteral();145 break;146 default:147 failParser(`Unexpected token ${tok} in OBJECT definition`)148 }149 }150 context.objects.push(object);151}152const parseDamage = () => {153 expectToken('{');154 let damage = [ getNextToken() ];155 expectToken(',');156 damage.push( getNextToken() );157 expectToken('}');158 return damage;159}160const parseRoom = context => {161 let room = {};162 let tok;163 expectToken('{');164 while((tok=getNextToken()) !== '}') {165 switch(tok) {166 case 'FLAG':167 room.flags = parseFlags();168 break;169 case 'DAMAGE':170 room.damage = parseDamage();171 break;172 case 'KEY':173 room.key = parseLiteral();174 break;175 case 'NAME':176 room.name = parseMLString();177 break;178 case 'LEVEL':179 room.level = parseLiteral();180 break;181 case 'LIFE':182 room.life = parseLiteral();183 break;184 case 'LOCATION':185 room.level = parseLiteral();186 break; 187 default:188 failParser(`Unexpected token ${tok} in ROOM definition`) 189 }190 }191 context.rooms.push(room);192}193const parseAgent = context => {194 let agent = {};195 let tok;196 expectToken('{');197 while((tok=getNextToken()) !== '}') {198 switch(tok) {199 case 'KEY':200 agent.key = parseLiteral();201 break;202 case 'FLAG':203 agent.flag = parseFlags();204 break;205 case 'LIVE':206 case 'LIFE':207 agent.life = parseLiteral();208 break; 209 case 'BOOST':210 agent.boost = parseLiteral();211 break;212 case 'DAMAGE':213 agent.damage = parseDamage();214 break; 215 case 'GIVE':216 agent.give = parseLiteral();217 break;218 case 'PATH':219 agent.path = parseLiteral();220 break;221 case 'TRACK':222 agent.track = parseLiteral();223 break;224 case 'ROOM':225 agent.room = parseLiteral();226 break;227 case 'ANIM':228 agent.anim = parseLiteral();229 break;230 case 'NAME':231 agent.name = parseMLString();232 break;233 case 'TXT0':234 agent.txt0 = parseMLString();235 break;236 case 'TXT1':237 agent.txt1 = parseMLString();238 break;239 case 'TXT2':240 agent.txt2 = parseMLString();241 break;242 case 'TXT3':243 agent.txt3 = parseMLString();244 break; 245 default:246 failParser(`Unexpected token ${tok} in AGENT definition`) 247 }248 }249 context.agents.push(agent);250}251const parseQuest = context => {252 let quest = {253 objects: [],254 rooms: [],255 agents: [],256 };257 let tok;258 expectToken('{');259 while((tok=getNextToken()) !== '}') {260 switch(tok) {261 case 'KEY':262 quest.key = parseLiteral();263 break;264 case 'QUESTINTRO':265 quest.intro = parseMLString();266 break;267 case 'ENTRANCE':268 quest.entrance = parseLiteral();269 break;270 case 'LAND':271 quest.land = parseLiteral();272 // ASSERT number?273 break;274 case 'LINK':275 expectToken('{');276 quest.link = [ getNextToken() ];277 expectToken(',');278 quest.link.push( getNextToken() );279 expectToken('}');280 break;281 case 'QUESTNAME':282 quest.name = parseMLString();283 break;284 case 'AGENT':285 parseAgent(quest);286 break;287 case 'OBJECT':288 parseObject(quest);289 break;290 case 'ROOM':291 parseRoom(quest);292 break;293 default:294 failParser(`Unexpected token ${tok} in QUEST definition`)295 }296 }297 context.quests.push(quest);298}299const parseCondition = () => {300 let cond = {};301 let tok;302 expectToken('{');303 while((tok=getNextToken()) !== '}') {304 switch(tok.toUpperCase()) {305 case 'OBJECT':306 cond.object = parseLiteral();307 break;308 case 'OBJECTWEAR':309 cond.objectWear = parseLiteral();310 break;311 case 'OBJECTINVENT':312 cond.objectInvent = parseLiteral();313 break;314 case 'OBJECTHAND':315 cond.objectHand = parseLiteral();316 break;317 case 'CHANGELEVEL':318 cond.changeLevel = parseLiteral();319 break;320 case 'CLICK':321 expectToken('{');322 expectToken('}');323 cond.click = null;324 break;325 case 'CLOSEPANEL':326 expectToken('{');327 expectToken('}');328 cond.closePanel = true;329 break;330 case 'COLLID':331 cond.collId = parseLiteral();332 break;333 case 'COLLIDEX':334 expectToken('{');335 cond.collIdex = [ getNextToken() ];336 expectToken(',');337 cond.collIdex.push(getNextToken());338 expectToken(',');339 cond.collIdex.push(getNextToken());340 expectToken('}');341 break;342 case 'GOTO':343 cond.goto = parseLiteral();344 break;345 case 'MONSTERCOUNT':346 expectToken('{');347 cond.monsterCount = [ getNextToken() ];348 expectToken(',');349 cond.monsterCount.push(getNextToken());350 expectToken('}');351 break;352 case 'MSG':353 cond.msg = parseLiteral();354 break;355 case 'PROJECTILEHIT':356 expectToken('{');357 expectToken('}');358 cond.projectileHit = true;359 break;360 case 'SENSEWEAR':361 expectToken('{');362 cond.senseWear = [ getNextToken() ];363 expectToken(',');364 cond.senseWear.push(getNextToken());365 expectToken('}');366 break;367 case 'SENSEOBJMAGIC':368 cond.senseObjMagic = parseLiteral();369 break;370 case 'TIMER':371 cond.timer = parseLiteral();372 break;373 case 'ENDANIM':374 cond.endAnim = null;375 expectToken('{');376 tok = getNextToken();377 if (tok !== '}') {378 cond.endAnim = tok;379 expectToken('}');380 }381 break;382 case 'VEQ':383 expectToken('{');384 cond.vEq = [ getNextToken() ];385 expectToken(',');386 cond.vEq.push(getNextToken());387 expectToken('}');388 break;389 case 'VNE':390 expectToken('{');391 cond.vNe = [ getNextToken() ];392 expectToken(',');393 cond.vNe.push(getNextToken());394 expectToken('}');395 break;396 case 'VGE':397 expectToken('{');398 cond.vGe = [ getNextToken() ];399 expectToken(',');400 cond.vGe.push(getNextToken());401 expectToken('}');402 break;403 case 'VLT':404 expectToken('{');405 cond.vLt = [ getNextToken() ];406 expectToken(',');407 cond.vLt.push(getNextToken());408 expectToken('}');409 break;410 default:411 failParser(`Unexpected token ${tok} in STATE.MULTI.CONDITION definition`)412 }413 }414 return cond;415}416const parseMulti = () => {417 let multi = [];418 let tok;419 expectToken('{');420 while((tok=getNextToken()) !== '}') {421 switch(tok.toUpperCase()) {422 case 'CONDITION':423 multi.push(parseCondition());424 break;425 default:426 failParser(`Unexpected token ${tok} in STATE.MULTI definition`)427 }428 }429 return multi;430}431const parseProjectile = () => {432 let proj = {};433 expectToken('{');434 while((tok=getNextToken()) !== '}') {435 switch(tok) {436 case 'KEY':437 proj.key = parseLiteral();438 break;439 case 'DAMAGEMIN':440 proj.damageMin = parseLiteral();441 break;442 case 'DAMAGEMAX':443 proj.damageMax = parseLiteral();444 break;445 case 'SPEED':446 proj.speed = parseLiteral();447 break;448 case 'ROTATION':449 proj.rotation = parseLiteral();450 break;451 case 'YOFFSET':452 proj.yOffset = parseLiteral();453 break;454 default:455 failParser(`Unexpected token ${tok} in STATE.ACTION.PROJECTILE definition`)456 }457 }458 return proj;459}460const parseAction = () => {461 let action = {};462 let tok;463 expectToken('{');464 while((tok=getNextToken()) !== '}') {465 switch(tok.toUpperCase()) {466 case 'OBJECT':467 action.object = parseLiteral();468 break;469 case 'EFFECT':470 action.effect = parseLiteral();471 break;472 case 'FREEZE':473 expectToken('{');474 action.freeze = [ getNextToken() ];475 expectToken(',');476 action.freeze.push( getNextToken() );477 expectToken('}');478 break;479 case 'OBJECTMOUSE':480 action.objectMouse = parseLiteral();481 break;482 case 'PLAYSONG':483 action.playSong = parseLiteral();484 break;485 case 'SETLOADING':486 action.setLoading = parseLiteral();487 break;488 case 'SOUND':489 action.sound = parseLiteral();490 break;491 case 'CAMERAFROM':492 expectToken('{');493 action.cameraFrom = [ getNextToken() ];494 expectToken(',');495 action.cameraFrom.push( getNextToken() );496 expectToken('}');497 break;498 case 'CAMERATO':499 expectToken('{');500 action.cameraTo = [ getNextToken() ];501 expectToken(',');502 action.cameraTo.push( getNextToken() );503 expectToken('}');504 break;505 case 'CAMERATIME':506 expectToken('{');507 action.cameraTime = [ getNextToken() ];508 tok = getNextToken();509 if (tok === ',') {510 action.cameraTime.push( getNextToken() );511 expectToken('}');512 } else if (tok !== '}') {513 failParser(`Invalid CAMERATIME definition`)514 }515 break;516 case 'CHARGECRISTAL':517 expectToken('{');518 expectToken('}');519 break;520 case 'HIT':521 action.hit = parseLiteral();522 break;523 case 'FMV':524 action.fmv = parseLiteral();525 break;526 case 'HITEX':527 expectToken('{');528 action.hitEx = [ getNextToken() ];529 expectToken(',');530 action.hitEx.push( getNextToken() );531 expectToken('}');532 break;533 case 'MONSTER':534 action.monster = parseLiteral();535 break;536 case 'PROJECTILE':537 action.projectile = parseProjectile();538 break;539 case 'RANDPANEL':540 action.randPanel = parseLiteral();541 break;542 case 'REMOVEOBJECT':543 action.removeObject = parseLiteral();544 break;545 case 'MSG':546 action.msg = parseLiteral();547 break;548 case 'TELEPORT2ND':549 action.teleport2nd = parseLiteral();550 break;551 case 'VSET':552 expectToken('{');553 action.vSet = [ getNextToken() ];554 expectToken(',');555 action.vSet.push( getNextToken() );556 expectToken('}');557 break;558 case 'VADD':559 expectToken('{');560 action.vAdd = [ getNextToken() ];561 expectToken(',');562 action.vAdd.push( getNextToken() );563 expectToken('}');564 break;565 default:566 failParser(`Unexpected token ${tok} in STATE.ACTION definition`)567 }568 }569 return action;570}571const parseState = context => {572 let state = {};573 let tok;574 expectToken('{');575 while((tok=getNextToken()) !== '}') {576 switch(tok.toUpperCase()) {577 case 'KEY':578 state.key = parseLiteral();579 break;580 case 'FLAG':581 state.flags = parseFlags();582 break;583 case 'CHANGELEVEL':584 state.changeLevel = parseLiteral();585 break;586 case 'CONDITION':587 state.condition = parseLiteral();588 break;589 case 'TEXT':590 state.text = parseMLString();591 break;592 case 'GOTO':593 state.goto = parseLiteral();594 break;595 case 'SETLOWCOLLID':596 state.lowCollid = parseLiteral();597 break;598 case 'SETCOLLID':599 state.setCollid = parseLiteral();600 break;601 case 'CLEARCOLLID':602 state.clearCollid = parseLiteral();603 break;604 case 'SKELFILE':605 state.skelFile = parseLiteral();606 break;607 case 'SKELNAME':608 state.skelName = parseLiteral();609 break;610 case 'SKELANIM':611 state.skelAnim = parseLiteral();612 break;k613 case 'FRAME':614 state.frame = parseLiteral();615 break;616 case 'JUMP':617 state.jump = parseLiteral();618 break;619 case 'FAIL':620 state.fail = parseMLString();621 break;622 case 'FAILPANEL':623 state.failPanel = parseMLString();624 break;625 case 'TEXTPANEL':626 state.textPanel = parseMLString();627 break;628 case 'OBJECT':629 state.object = parseLiteral();630 break;631 case 'MULTI':632 state.multi = parseMulti();633 break;634 case 'ACTION':635 state.action = parseAction();636 break;637 case 'MSG':638 state.msg = parseLiteral();639 break;640 default:641 failParser(`Unexpected token ${tok} in STATE definition`)642 }643 }644 context.states.push(state);645}646const parseTrap = context => {647 let trap = {648 states: [],649 };650 let tok;651 expectToken('{');652 while((tok=getNextToken()) !== '}') {653 switch(tok.toUpperCase()) {654 case 'KEY':655 trap.key = parseLiteral();656 break;657 case 'FLAG':658 trap.flags = parseFlags();659 break;660 case 'NAME':661 trap.name = parseMLString();662 break;663 case 'SKELFILE':664 trap.skelfile = parseLiteral();665 break;666 case 'STATE':667 parseState(trap);668 break;669 default:670 failParser(`Unexpected token ${tok} in TRAP definition`)671 }672 }673 context.traps.push(trap);674}675const parseNode = context => {676 let node = {};677 let tok;678 expectToken('{');679 while((tok=getNextToken()) !== '}') {680 switch(tok) {681 case 'KEY':682 node.key = parseLiteral();683 break;684 case 'ANIM':685 node.anim = parseLiteral();686 break;687 case 'SKEL':688 node.skel = parseLiteral();689 break; 690 case 'WAIT':691 node.wait = parseLiteral();692 break;693 default:694 failParser(`Unexpected token ${tok} in NODE definition`)695 }696 }697 context.nodes.push(node);698}699const parsePath = context => {700 let path = {701 nodes: [],702 };703 let tok;704 expectToken('{');705 while((tok=getNextToken()) !== '}') {706 switch(tok) {707 case 'KEY':708 path.key = parseLiteral();709 break;710 case 'FLAG':711 path.flags = parseFlags();712 break;713 case 'NODE':714 parseNode(path);715 break;716 default:717 failParser(`Unexpected token ${tok} in PATH definition`)718 }719 }720 context.paths.push(path);721}722const parseSPT = () => {...

Full Screen

Full Screen

scalars-test.ts

Source:scalars-test.ts Github

copy

Full Screen

...57 'Int cannot represent non-integer value: { value: 1 }',58 );59 });60 it('parseLiteral', () => {61 function parseLiteral(str: string) {62 return GraphQLInt.parseLiteral(parseValueToAST(str), undefined);63 }64 expect(parseLiteral('1')).to.equal(1);65 expect(parseLiteral('0')).to.equal(0);66 expect(parseLiteral('-1')).to.equal(-1);67 expect(() => parseLiteral('9876504321')).to.throw(68 'Int cannot represent non 32-bit signed integer value: 9876504321',69 );70 expect(() => parseLiteral('-9876504321')).to.throw(71 'Int cannot represent non 32-bit signed integer value: -9876504321',72 );73 expect(() => parseLiteral('1.0')).to.throw(74 'Int cannot represent non-integer value: 1.0',75 );76 expect(() => parseLiteral('null')).to.throw(77 'Int cannot represent non-integer value: null',78 );79 expect(() => parseLiteral('""')).to.throw(80 'Int cannot represent non-integer value: ""',81 );82 expect(() => parseLiteral('"123"')).to.throw(83 'Int cannot represent non-integer value: "123"',84 );85 expect(() => parseLiteral('false')).to.throw(86 'Int cannot represent non-integer value: false',87 );88 expect(() => parseLiteral('[1]')).to.throw(89 'Int cannot represent non-integer value: [1]',90 );91 expect(() => parseLiteral('{ value: 1 }')).to.throw(92 'Int cannot represent non-integer value: {value: 1}',93 );94 expect(() => parseLiteral('ENUM_VALUE')).to.throw(95 'Int cannot represent non-integer value: ENUM_VALUE',96 );97 expect(() => parseLiteral('$var')).to.throw(98 'Int cannot represent non-integer value: $var',99 );100 });101 it('serialize', () => {102 function serialize(value: unknown) {103 return GraphQLInt.serialize(value);104 }105 expect(serialize(1)).to.equal(1);106 expect(serialize('123')).to.equal(123);107 expect(serialize(0)).to.equal(0);108 expect(serialize(-1)).to.equal(-1);109 expect(serialize(1e5)).to.equal(100000);110 expect(serialize(false)).to.equal(0);111 expect(serialize(true)).to.equal(1);112 const customValueOfObj = {113 value: 5,114 valueOf() {115 return this.value;116 },117 };118 expect(serialize(customValueOfObj)).to.equal(5);119 // The GraphQL specification does not allow serializing non-integer values120 // as Int to avoid accidental data loss.121 expect(() => serialize(0.1)).to.throw(122 'Int cannot represent non-integer value: 0.1',123 );124 expect(() => serialize(1.1)).to.throw(125 'Int cannot represent non-integer value: 1.1',126 );127 expect(() => serialize(-1.1)).to.throw(128 'Int cannot represent non-integer value: -1.1',129 );130 expect(() => serialize('-1.1')).to.throw(131 'Int cannot represent non-integer value: "-1.1"',132 );133 // Maybe a safe JavaScript int, but bigger than 2^32, so not134 // representable as a GraphQL Int135 expect(() => serialize(9876504321)).to.throw(136 'Int cannot represent non 32-bit signed integer value: 9876504321',137 );138 expect(() => serialize(-9876504321)).to.throw(139 'Int cannot represent non 32-bit signed integer value: -9876504321',140 );141 // Too big to represent as an Int in JavaScript or GraphQL142 expect(() => serialize(1e100)).to.throw(143 'Int cannot represent non 32-bit signed integer value: 1e+100',144 );145 expect(() => serialize(-1e100)).to.throw(146 'Int cannot represent non 32-bit signed integer value: -1e+100',147 );148 expect(() => serialize('one')).to.throw(149 'Int cannot represent non-integer value: "one"',150 );151 // Doesn't represent number152 expect(() => serialize('')).to.throw(153 'Int cannot represent non-integer value: ""',154 );155 expect(() => serialize(NaN)).to.throw(156 'Int cannot represent non-integer value: NaN',157 );158 expect(() => serialize(Infinity)).to.throw(159 'Int cannot represent non-integer value: Infinity',160 );161 expect(() => serialize([5])).to.throw(162 'Int cannot represent non-integer value: [5]',163 );164 });165 });166 describe('GraphQLFloat', () => {167 it('parseValue', () => {168 function parseValue(value: unknown) {169 return GraphQLFloat.parseValue(value);170 }171 expect(parseValue(1)).to.equal(1);172 expect(parseValue(0)).to.equal(0);173 expect(parseValue(-1)).to.equal(-1);174 expect(parseValue(0.1)).to.equal(0.1);175 expect(parseValue(Math.PI)).to.equal(Math.PI);176 expect(() => parseValue(NaN)).to.throw(177 'Float cannot represent non numeric value: NaN',178 );179 expect(() => parseValue(Infinity)).to.throw(180 'Float cannot represent non numeric value: Infinity',181 );182 expect(() => parseValue(undefined)).to.throw(183 'Float cannot represent non numeric value: undefined',184 );185 expect(() => parseValue(null)).to.throw(186 'Float cannot represent non numeric value: null',187 );188 expect(() => parseValue('')).to.throw(189 'Float cannot represent non numeric value: ""',190 );191 expect(() => parseValue('123')).to.throw(192 'Float cannot represent non numeric value: "123"',193 );194 expect(() => parseValue('123.5')).to.throw(195 'Float cannot represent non numeric value: "123.5"',196 );197 expect(() => parseValue(false)).to.throw(198 'Float cannot represent non numeric value: false',199 );200 expect(() => parseValue(true)).to.throw(201 'Float cannot represent non numeric value: true',202 );203 expect(() => parseValue([0.1])).to.throw(204 'Float cannot represent non numeric value: [0.1]',205 );206 expect(() => parseValue({ value: 0.1 })).to.throw(207 'Float cannot represent non numeric value: { value: 0.1 }',208 );209 });210 it('parseLiteral', () => {211 function parseLiteral(str: string) {212 return GraphQLFloat.parseLiteral(parseValueToAST(str), undefined);213 }214 expect(parseLiteral('1')).to.equal(1);215 expect(parseLiteral('0')).to.equal(0);216 expect(parseLiteral('-1')).to.equal(-1);217 expect(parseLiteral('0.1')).to.equal(0.1);218 expect(parseLiteral(Math.PI.toString())).to.equal(Math.PI);219 expect(() => parseLiteral('null')).to.throw(220 'Float cannot represent non numeric value: null',221 );222 expect(() => parseLiteral('""')).to.throw(223 'Float cannot represent non numeric value: ""',224 );225 expect(() => parseLiteral('"123"')).to.throw(226 'Float cannot represent non numeric value: "123"',227 );228 expect(() => parseLiteral('"123.5"')).to.throw(229 'Float cannot represent non numeric value: "123.5"',230 );231 expect(() => parseLiteral('false')).to.throw(232 'Float cannot represent non numeric value: false',233 );234 expect(() => parseLiteral('[0.1]')).to.throw(235 'Float cannot represent non numeric value: [0.1]',236 );237 expect(() => parseLiteral('{ value: 0.1 }')).to.throw(238 'Float cannot represent non numeric value: {value: 0.1}',239 );240 expect(() => parseLiteral('ENUM_VALUE')).to.throw(241 'Float cannot represent non numeric value: ENUM_VALUE',242 );243 expect(() => parseLiteral('$var')).to.throw(244 'Float cannot represent non numeric value: $var',245 );246 });247 it('serialize', () => {248 function serialize(value: unknown) {249 return GraphQLFloat.serialize(value);250 }251 expect(serialize(1)).to.equal(1.0);252 expect(serialize(0)).to.equal(0.0);253 expect(serialize('123.5')).to.equal(123.5);254 expect(serialize(-1)).to.equal(-1.0);255 expect(serialize(0.1)).to.equal(0.1);256 expect(serialize(1.1)).to.equal(1.1);257 expect(serialize(-1.1)).to.equal(-1.1);258 expect(serialize('-1.1')).to.equal(-1.1);259 expect(serialize(false)).to.equal(0.0);260 expect(serialize(true)).to.equal(1.0);261 const customValueOfObj = {262 value: 5.5,263 valueOf() {264 return this.value;265 },266 };267 expect(serialize(customValueOfObj)).to.equal(5.5);268 expect(() => serialize(NaN)).to.throw(269 'Float cannot represent non numeric value: NaN',270 );271 expect(() => serialize(Infinity)).to.throw(272 'Float cannot represent non numeric value: Infinity',273 );274 expect(() => serialize('one')).to.throw(275 'Float cannot represent non numeric value: "one"',276 );277 expect(() => serialize('')).to.throw(278 'Float cannot represent non numeric value: ""',279 );280 expect(() => serialize([5])).to.throw(281 'Float cannot represent non numeric value: [5]',282 );283 });284 });285 describe('GraphQLString', () => {286 it('parseValue', () => {287 function parseValue(value: unknown) {288 return GraphQLString.parseValue(value);289 }290 expect(parseValue('foo')).to.equal('foo');291 expect(() => parseValue(undefined)).to.throw(292 'String cannot represent a non string value: undefined',293 );294 expect(() => parseValue(null)).to.throw(295 'String cannot represent a non string value: null',296 );297 expect(() => parseValue(1)).to.throw(298 'String cannot represent a non string value: 1',299 );300 expect(() => parseValue(NaN)).to.throw(301 'String cannot represent a non string value: NaN',302 );303 expect(() => parseValue(false)).to.throw(304 'String cannot represent a non string value: false',305 );306 expect(() => parseValue(['foo'])).to.throw(307 'String cannot represent a non string value: ["foo"]',308 );309 expect(() => parseValue({ value: 'foo' })).to.throw(310 'String cannot represent a non string value: { value: "foo" }',311 );312 });313 it('parseLiteral', () => {314 function parseLiteral(str: string) {315 return GraphQLString.parseLiteral(parseValueToAST(str), undefined);316 }317 expect(parseLiteral('"foo"')).to.equal('foo');318 expect(parseLiteral('"""bar"""')).to.equal('bar');319 expect(() => parseLiteral('null')).to.throw(320 'String cannot represent a non string value: null',321 );322 expect(() => parseLiteral('1')).to.throw(323 'String cannot represent a non string value: 1',324 );325 expect(() => parseLiteral('0.1')).to.throw(326 'String cannot represent a non string value: 0.1',327 );328 expect(() => parseLiteral('false')).to.throw(329 'String cannot represent a non string value: false',330 );331 expect(() => parseLiteral('["foo"]')).to.throw(332 'String cannot represent a non string value: ["foo"]',333 );334 expect(() => parseLiteral('{ value: "foo" }')).to.throw(335 'String cannot represent a non string value: {value: "foo"}',336 );337 expect(() => parseLiteral('ENUM_VALUE')).to.throw(338 'String cannot represent a non string value: ENUM_VALUE',339 );340 expect(() => parseLiteral('$var')).to.throw(341 'String cannot represent a non string value: $var',342 );343 });344 it('serialize', () => {345 function serialize(value: unknown) {346 return GraphQLString.serialize(value);347 }348 expect(serialize('string')).to.equal('string');349 expect(serialize(1)).to.equal('1');350 expect(serialize(-1.1)).to.equal('-1.1');351 expect(serialize(true)).to.equal('true');352 expect(serialize(false)).to.equal('false');353 const valueOf = () => 'valueOf string';354 const toJSON = () => 'toJSON string';355 const valueOfAndToJSONValue = { valueOf, toJSON };356 expect(serialize(valueOfAndToJSONValue)).to.equal('valueOf string');357 const onlyToJSONValue = { toJSON };358 expect(serialize(onlyToJSONValue)).to.equal('toJSON string');359 expect(() => serialize(NaN)).to.throw(360 'String cannot represent value: NaN',361 );362 expect(() => serialize([1])).to.throw(363 'String cannot represent value: [1]',364 );365 const badObjValue = {};366 expect(() => serialize(badObjValue)).to.throw(367 'String cannot represent value: {}',368 );369 const badValueOfObjValue = { valueOf: 'valueOf string' };370 expect(() => serialize(badValueOfObjValue)).to.throw(371 'String cannot represent value: { valueOf: "valueOf string" }',372 );373 });374 });375 describe('GraphQLBoolean', () => {376 it('parseValue', () => {377 function parseValue(value: unknown) {378 return GraphQLBoolean.parseValue(value);379 }380 expect(parseValue(true)).to.equal(true);381 expect(parseValue(false)).to.equal(false);382 expect(() => parseValue(undefined)).to.throw(383 'Boolean cannot represent a non boolean value: undefined',384 );385 expect(() => parseValue(null)).to.throw(386 'Boolean cannot represent a non boolean value: null',387 );388 expect(() => parseValue(0)).to.throw(389 'Boolean cannot represent a non boolean value: 0',390 );391 expect(() => parseValue(1)).to.throw(392 'Boolean cannot represent a non boolean value: 1',393 );394 expect(() => parseValue(NaN)).to.throw(395 'Boolean cannot represent a non boolean value: NaN',396 );397 expect(() => parseValue('')).to.throw(398 'Boolean cannot represent a non boolean value: ""',399 );400 expect(() => parseValue('false')).to.throw(401 'Boolean cannot represent a non boolean value: "false"',402 );403 expect(() => parseValue([false])).to.throw(404 'Boolean cannot represent a non boolean value: [false]',405 );406 expect(() => parseValue({ value: false })).to.throw(407 'Boolean cannot represent a non boolean value: { value: false }',408 );409 });410 it('parseLiteral', () => {411 function parseLiteral(str: string) {412 return GraphQLBoolean.parseLiteral(parseValueToAST(str), undefined);413 }414 expect(parseLiteral('true')).to.equal(true);415 expect(parseLiteral('false')).to.equal(false);416 expect(() => parseLiteral('null')).to.throw(417 'Boolean cannot represent a non boolean value: null',418 );419 expect(() => parseLiteral('0')).to.throw(420 'Boolean cannot represent a non boolean value: 0',421 );422 expect(() => parseLiteral('1')).to.throw(423 'Boolean cannot represent a non boolean value: 1',424 );425 expect(() => parseLiteral('0.1')).to.throw(426 'Boolean cannot represent a non boolean value: 0.1',427 );428 expect(() => parseLiteral('""')).to.throw(429 'Boolean cannot represent a non boolean value: ""',430 );431 expect(() => parseLiteral('"false"')).to.throw(432 'Boolean cannot represent a non boolean value: "false"',433 );434 expect(() => parseLiteral('[false]')).to.throw(435 'Boolean cannot represent a non boolean value: [false]',436 );437 expect(() => parseLiteral('{ value: false }')).to.throw(438 'Boolean cannot represent a non boolean value: {value: false}',439 );440 expect(() => parseLiteral('ENUM_VALUE')).to.throw(441 'Boolean cannot represent a non boolean value: ENUM_VALUE',442 );443 expect(() => parseLiteral('$var')).to.throw(444 'Boolean cannot represent a non boolean value: $var',445 );446 });447 it('serialize', () => {448 function serialize(value: unknown) {449 return GraphQLBoolean.serialize(value);450 }451 expect(serialize(1)).to.equal(true);452 expect(serialize(0)).to.equal(false);453 expect(serialize(true)).to.equal(true);454 expect(serialize(false)).to.equal(false);455 expect(456 serialize({457 value: true,458 valueOf() {459 return (this as { value: boolean }).value;460 },461 }),462 ).to.equal(true);463 expect(() => serialize(NaN)).to.throw(464 'Boolean cannot represent a non boolean value: NaN',465 );466 expect(() => serialize('')).to.throw(467 'Boolean cannot represent a non boolean value: ""',468 );469 expect(() => serialize('true')).to.throw(470 'Boolean cannot represent a non boolean value: "true"',471 );472 expect(() => serialize([false])).to.throw(473 'Boolean cannot represent a non boolean value: [false]',474 );475 expect(() => serialize({})).to.throw(476 'Boolean cannot represent a non boolean value: {}',477 );478 });479 });480 describe('GraphQLID', () => {481 it('parseValue', () => {482 function parseValue(value: unknown) {483 return GraphQLID.parseValue(value);484 }485 expect(parseValue('')).to.equal('');486 expect(parseValue('1')).to.equal('1');487 expect(parseValue('foo')).to.equal('foo');488 expect(parseValue(1)).to.equal('1');489 expect(parseValue(0)).to.equal('0');490 expect(parseValue(-1)).to.equal('-1');491 // Maximum and minimum safe numbers in JS492 expect(parseValue(9007199254740991)).to.equal('9007199254740991');493 expect(parseValue(-9007199254740991)).to.equal('-9007199254740991');494 expect(() => parseValue(undefined)).to.throw(495 'ID cannot represent value: undefined',496 );497 expect(() => parseValue(null)).to.throw(498 'ID cannot represent value: null',499 );500 expect(() => parseValue(0.1)).to.throw('ID cannot represent value: 0.1');501 expect(() => parseValue(NaN)).to.throw('ID cannot represent value: NaN');502 expect(() => parseValue(Infinity)).to.throw(503 'ID cannot represent value: Inf',504 );505 expect(() => parseValue(false)).to.throw(506 'ID cannot represent value: false',507 );508 expect(() => GraphQLID.parseValue(['1'])).to.throw(509 'ID cannot represent value: ["1"]',510 );511 expect(() => GraphQLID.parseValue({ value: '1' })).to.throw(512 'ID cannot represent value: { value: "1" }',513 );514 });515 it('parseLiteral', () => {516 function parseLiteral(str: string) {517 return GraphQLID.parseLiteral(parseValueToAST(str), undefined);518 }519 expect(parseLiteral('""')).to.equal('');520 expect(parseLiteral('"1"')).to.equal('1');521 expect(parseLiteral('"foo"')).to.equal('foo');522 expect(parseLiteral('"""foo"""')).to.equal('foo');523 expect(parseLiteral('1')).to.equal('1');524 expect(parseLiteral('0')).to.equal('0');525 expect(parseLiteral('-1')).to.equal('-1');526 // Support arbitrary long numbers even if they can't be represented in JS527 expect(parseLiteral('90071992547409910')).to.equal('90071992547409910');528 expect(parseLiteral('-90071992547409910')).to.equal('-90071992547409910');529 expect(() => parseLiteral('null')).to.throw(530 'ID cannot represent a non-string and non-integer value: null',531 );532 expect(() => parseLiteral('0.1')).to.throw(533 'ID cannot represent a non-string and non-integer value: 0.1',534 );535 expect(() => parseLiteral('false')).to.throw(536 'ID cannot represent a non-string and non-integer value: false',537 );538 expect(() => parseLiteral('["1"]')).to.throw(539 'ID cannot represent a non-string and non-integer value: ["1"]',540 );541 expect(() => parseLiteral('{ value: "1" }')).to.throw(542 'ID cannot represent a non-string and non-integer value: {value: "1"}',543 );544 expect(() => parseLiteral('ENUM_VALUE')).to.throw(545 'ID cannot represent a non-string and non-integer value: ENUM_VALUE',546 );547 expect(() => parseLiteral('$var')).to.throw(548 'ID cannot represent a non-string and non-integer value: $var',549 );550 });551 it('serialize', () => {552 function serialize(value: unknown) {553 return GraphQLID.serialize(value);554 }555 expect(serialize('string')).to.equal('string');556 expect(serialize('false')).to.equal('false');557 expect(serialize('')).to.equal('');558 expect(serialize(123)).to.equal('123');559 expect(serialize(0)).to.equal('0');560 expect(serialize(-1)).to.equal('-1');561 const valueOf = () => 'valueOf ID';...

Full Screen

Full Screen

BlockFunction.py

Source:BlockFunction.py Github

copy

Full Screen

1from OpenBullet2Python.LoliScript.LineParser import LineParser, ParseLabel, \2 ParseEnum, ParseLiteral, Lookahead, SetBool, ParseToken, \3 ParseInt, EnsureIdentifier4from OpenBullet2Python.Blocks.BlockBase import ReplaceValuesRecursive, \5 InsertVariable, ReplaceValues6from OpenBullet2Python.Functions.Encoding.Encode import ToBase64, \7 FromBase648from OpenBullet2Python.Functions.Crypto.Crypto import Crypto9from OpenBullet2Python.Functions.UserAgent.UserAgent import UserAgent10from OpenBullet2Python.Extensions import Unescape11from urllib.parse import quote, unquote12from datetime import datetime13from datetime import timezone14import base6415import re16from random import randint17import random18import time19import math20from enum import Enum21from OpenBullet2Python.Models.CVar import CVar22from html import escape, unescape23def RandomString(localInputString:str):24 _lowercase = "abcdefghijklmnopqrstuvwxyz"25 _uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"26 _digits = "0123456789"27 _symbols = "\\!\"£$%&/()=?^'{}[]@#,;.:-_*+"28 _hex = _digits + "abcdef"29 _udChars = _uppercase + _digits30 _ldChars = _lowercase + _digits31 _upperlwr = _lowercase + _uppercase32 _ludChars = _lowercase + _uppercase + _digits33 _allChars = _lowercase + _uppercase + _digits + _symbols34 outputString = localInputString35 if "?l" in str(outputString):36 while "?l" in str(outputString):37 outputString = outputString.replace("?l",random.choice(list(_lowercase)),1)38 if "?u" in str(outputString):39 while "?u" in str(outputString):40 outputString = outputString.replace("?u",random.choice(list(_uppercase)),1)41 if "?d" in str(outputString):42 while "?d" in str(outputString):43 outputString = outputString.replace("?d",random.choice(list(_digits)),1)44 if "?s" in str(outputString):45 while "?s" in str(outputString):46 outputString = outputString.replace("?s",random.choice(list(_symbols)),1)47 if "?h" in str(outputString):48 while "?h" in str(outputString):49 outputString = outputString.replace("?h",random.choice(list(_hex)),1)50 if "?a" in str(outputString):51 while "?a" in str(outputString):52 outputString = outputString.replace("?a",random.choice(list(_allChars)),1)53 if "?m" in str(outputString):54 while "?m" in str(outputString):55 outputString = outputString.replace("?m",random.choice(list(_udChars)),1)56 if "?n" in str(outputString):57 while "?n" in str(outputString):58 outputString = outputString.replace("?n",random.choice(list(_ldChars)),1)59 if "?i" in str(outputString):60 while "?i" in str(outputString):61 outputString = outputString.replace("?i",random.choice(list(_ludChars)),1)62 if "?f" in str(outputString):63 while "?f" in str(outputString):64 outputString = outputString.replace("?f",random.choice(list(_upperlwr)),1)65 return outputString66def RandomNum(minNum,maxNum,padNum:bool):67 try:68 randomNumString = str(randint(int(minNum),int(maxNum)))69 except Exception:70 print("Failed to parse int")71 return ""72 73 if padNum: randomNumString = randomNumString.rjust(len(str(maxNum)),"0")74 return randomNumString75 76class FunctionType(str, Enum):77 Constant = "Constant"78 Base64Encode = "Base64Encode"79 Base64Decode = "Base64Decode"80 Hash = "Hash"81 HMAC = "HMAC"82 Translate = "Translate"83 DateToUnixTime = "DateToUnixTime"84 Length = "Length"85 ToLowercase = "ToLowercase"86 ToUppercase = "ToUppercase"87 Replace = "Replace"88 RegexMatch = "RegexMatch"89 URLEncode = "URLEncode"90 URLDecode = "URLDecode"91 Unescape = "Unescape"92 HTMLEntityEncode = "HTMLEntityEncode"93 HTMLEntityDecode = "HTMLEntityDecode"94 UnixTimeToDate = "UnixTimeToDate"95 CurrentUnixTime = "CurrentUnixTime"96 UnixTimeToISO8601 = "UnixTimeToISO8601"97 RandomNum = "RandomNum"98 RandomString = "RandomString"99 Ceil = "Ceil"100 Floor = "Floor"101 Round = "Round"102 Compute = "Compute"103 CountOccurrences = "CountOccurrences"104 ClearCookies = "ClearCookies"105 RSAEncrypt = "RSAEncrypt"106 RSADecrypt = "RSADecrypt"107 RSAPKCS1PAD2 = "RSAPKCS1PAD2"108 Delay = "Delay"109 CharAt = "CharAt"110 Substring = "Substring"111 ReverseString = "ReverseString"112 Trim = "Trim"113 GetRandomUA = "GetRandomUA"114 AESEncrypt = "AESEncrypt"115 AESDecrypt = "AESDecrypt"116 PBKDF2PKCS5 = "PBKDF2PKCS5"117class BlockFunction:118 def __init__(self):119 self.VariableName = "" 120 self.IsCapture = False 121 self.InputString = "" 122 self.function_type = ""123 self.CreateEmpty = True124 self.Dict = {}125 self.UseRegex = False126 127 # Replace128 self.ReplaceWhat = ""129 self.ReplaceWith = ""130 # Hashing 131 self.HashType = ""132 self.InputBase64 = False133 self.KeyBase64 = False134 self.HmacBase64 = False135 self.RandomZeroPad = False136 self.UserAgentBrowser = "Chrome"137 self.UserAgentSpecifyBrowser = False138 # PBKDF2PKCS5139 self.KdfSalt = ""140 self.KdfSaltSize = 8141 self.KdfIterations = 1142 self.KdfKeySize = 16143 self.KdfAlgorithm = "SHA1"144 # Translate145 self.TranslationDictionary = {}146 self.StopAfterFirstMatch = True147 def FromLS(self,line:LineParser):148 if str(line.current).startswith("!"):149 return None150 self.Dict = {} 151 self.Dict["IsCapture"] = False152 153 self.Dict["VariableName"] = ""154 self.Dict["InputString"] = ""155 self.Dict["Booleans"] = {}156 function_type = ParseEnum(line)157 self.Dict["function_type"] = function_type158 self.function_type = function_type159 if function_type == FunctionType.Constant:160 pass161 elif function_type == FunctionType.Hash:162 HashType = ParseEnum(line)163 self.Dict["HashType"] = HashType164 self.HashType = HashType165 while Lookahead(line) == "Boolean":166 boolean_name, boolean_value = SetBool(line,self)167 self.Dict["Booleans"][boolean_name] = boolean_value168 169 elif function_type == FunctionType.HMAC:170 HashType = ParseEnum(line)171 self.Dict["HashType"] = HashType172 self.HashType = HashType173 HmacKey = ParseLiteral(line)174 self.Dict["HmacKey"] = HmacKey175 self.HmacKey = HmacKey176 while Lookahead(line) == "Boolean":177 boolean_name, boolean_value = SetBool(line,self)178 self.Dict["Booleans"][boolean_name] = boolean_value179 elif function_type == FunctionType.Translate:180 while Lookahead(line) == "Boolean":181 boolean_name, boolean_value = SetBool(line,self)182 self.Dict["Booleans"][boolean_name] = boolean_value183 self.Dict["TranslationDictionary"] = {}184 while line.current and Lookahead(line) == "Parameter":185 EnsureIdentifier(line, "KEY")186 k = ParseLiteral(line)187 EnsureIdentifier(line, "VALUE")188 v = ParseLiteral(line)189 self.Dict["TranslationDictionary"][k] = v190 self.TranslationDictionary[k] = v191 elif function_type == FunctionType.DateToUnixTime:192 self.Dict["DateFormat"] = ParseLiteral(line)193 elif function_type == FunctionType.UnixTimeToDate:194 DateFormat = ParseLiteral(line)195 self.DateFormat = DateFormat196 self.Dict["DateFormat"] = DateFormat197 if Lookahead(line) != "Literal":198 self.InputString = DateFormat199 self.DateFormat ="yyyy-MM-dd:HH-mm-ss"200 self.Dict["InputString"] = "yyyy-MM-dd:HH-mm-ss"201 elif function_type == FunctionType.Replace:202 ReplaceWhat = ParseLiteral(line)203 self.Dict["ReplaceWhat"] = ReplaceWhat204 self.ReplaceWhat = ReplaceWhat205 206 ReplaceWith = ParseLiteral(line)207 self.Dict["ReplaceWith"] = ReplaceWith208 self.ReplaceWith = ReplaceWith209 if Lookahead(line) == "Boolean":210 boolean_name, boolean_value = SetBool(line,self)211 self.Dict["Booleans"][boolean_name] = boolean_value212 elif function_type == FunctionType.RegexMatch:213 self.Dict["RegexMatch"] = ParseLiteral(line)214 elif function_type == FunctionType.RandomNum:215 if Lookahead(line) == "Literal":216 RandomMin = ParseLiteral(line)217 RandomMax = ParseLiteral(line)218 self.Dict["RandomMin"] = RandomMin219 self.Dict["RandomMax"] = RandomMax220 self.RandomMin = RandomMin221 self.RandomMax = RandomMax222 # Support for old integer definition of Min and Max223 else:224 RandomMin = ParseLiteral(line)225 RandomMax = ParseLiteral(line)226 self.Dict["RandomMin"] = RandomMin227 self.Dict["RandomMax"] = RandomMax228 self.RandomMin = RandomMin229 self.RandomMax = RandomMax230 231 if Lookahead(line) == "Boolean":232 boolean_name, boolean_value = SetBool(line,self)233 self.Dict["Booleans"][boolean_name] = boolean_value234 235 elif function_type == FunctionType.CountOccurrences:236 StringToFind = ParseLiteral(line)237 self.StringToFind = StringToFind238 self.Dict["StringToFind"] = StringToFind239 elif function_type == FunctionType.CharAt:240 charIndex = ParseLiteral(line)241 self.charIndex = charIndex242 self.Dict["CharIndex"] = charIndex243 elif function_type == FunctionType.Substring:244 SubstringIndex = ParseLiteral(line)245 SubstringLength = ParseLiteral(line)246 self.SubstringIndex = SubstringIndex247 self.SubstringLength = SubstringLength248 self.Dict["SubstringIndex"] = SubstringIndex249 self.Dict["SubstringLength"] = SubstringLength250 elif function_type == FunctionType.RSAEncrypt:251 self.Dict["RsaN"] = ParseLiteral(line)252 self.Dict["RsaE"] = ParseLiteral(line)253 if Lookahead(line) == "Boolean":254 boolean_name, boolean_value = SetBool(line,self)255 self.Dict["Booleans"][boolean_name] = boolean_value256 elif function_type == FunctionType.RSAPKCS1PAD2:257 self.Dict["RsaN"] = ParseLiteral(line)258 self.Dict["RsaE"] = ParseLiteral(line)259 260 elif function_type == FunctionType.GetRandomUA:261 if ParseToken(line,"Parameter", False, False) == "BROWSER":262 EnsureIdentifier(line,"BROWSER")263 UserAgentBrowser = ParseEnum(line)264 self.UserAgentBrowser = UserAgentBrowser265 self.UserAgentSpecifyBrowser = True266 self.Dict["UserAgentBrowser"] = UserAgentBrowser267 self.Dict["Booleans"]["UserAgentSpecifyBrowser"] = True268 elif function_type == FunctionType.AESDecrypt:269 pass270 elif function_type == FunctionType.AESEncrypt:271 self.Dict["AesKey"] = ParseLiteral(line)272 self.Dict["AesIV"] = ParseLiteral(line)273 self.Dict["AesMode"] = ParseEnum(line)274 self.Dict["AesPadding"] = ParseEnum(line)275 elif function_type == FunctionType.PBKDF2PKCS5:276 if Lookahead(line) == "Literal":277 self.KdfSalt = ParseLiteral(line)278 self.KdfIterations = ParseInt(line)279 self.KdfKeySize = ParseInt(line)280 self.KdfAlgorithm = ParseEnum(line)281 else:282 self.KdfSaltSize = ParseInt(line)283 self.KdfIterations = ParseInt(line)284 self.KdfKeySize = ParseInt(line)285 self.KdfAlgorithm = ParseEnum(line)286 else:287 pass288 if Lookahead(line) == "Literal":289 inputString = ParseLiteral(line)290 self.InputString = inputString291 self.Dict["InputString"] = inputString292 # Try to parse the arrow, otherwise just return the block as is with default var name and var / cap choice293 if not ParseToken(line,"Arrow",False,True):294 return self.Dict295 296 # Parse the VAR / CAP297 varType = ParseToken(line,"Parameter",True,True)298 if str(varType.upper()) == "VAR" or str(varType.upper()) == "CAP":299 if str(varType.upper()) == "CAP":300 self.Dict["IsCapture"] = True301 self.isCapture = True302 # Parse the variable/capture name303 VariableName = ParseToken(line,"Literal",True,True)304 self.VariableName = VariableName305 self.Dict["VariableName"] = VariableName306 def Process(self,BotData):307 localInputStrings = ReplaceValuesRecursive(self.InputString,BotData)308 outputs = []309 for localInputString in localInputStrings:310 # localInputString = localInputStrings[i]311 outputString = ""312 if self.function_type == FunctionType.Constant:313 outputString = localInputString314 elif self.function_type == FunctionType.Base64Encode:315 outputString = ToBase64(localInputString)316 elif self.function_type == FunctionType.Base64Decode:317 outputString = FromBase64(localInputString)318 elif self.function_type == FunctionType.Length:319 outputString = str(len(localInputString))320 elif self.function_type == FunctionType.ToLowercase:321 outputString = localInputString.lower()322 elif self.function_type == FunctionType.ToUppercase:323 outputString = localInputString.upper()324 elif self.function_type == FunctionType.Replace:325 if self.UseRegex:326 outputString = re.sub(ReplaceValues(self.ReplaceWhat,BotData), ReplaceValues(self.ReplaceWith,BotData), localInputString)327 else:328 outputString = localInputString.replace(ReplaceValues(self.ReplaceWhat,BotData),ReplaceValues(self.ReplaceWith,BotData))329 elif self.function_type == FunctionType.URLEncode:330 outputString = quote(localInputString,errors="replace")331 elif self.function_type == FunctionType.URLDecode:332 outputString = unquote(localInputString)333 elif self.function_type == FunctionType.Hash:334 outputString = self.GetHash(localInputString,self.HashType,self.InputBase64).lower()335 elif self.function_type == FunctionType.HMAC:336 outputString = self.Hmac(localInputString,self.HashType,self.HmacKey,self.InputBase64,self.KeyBase64,self.HmacBase64)337 elif self.function_type == FunctionType.RandomNum:338 outputString = RandomNum(ReplaceValues(self.RandomMin,BotData),ReplaceValues(self.RandomMax,BotData),self.RandomZeroPad)339 elif self.function_type == FunctionType.RandomString:340 outputString = localInputString341 outputString = RandomString(outputString)342 elif self.function_type == FunctionType.CurrentUnixTime:343 outputString = str(int(time.time()))344 elif self.function_type == FunctionType.Ceil:345 outputString = str(math.ceil(float(localInputString)))346 elif self.function_type == FunctionType.Floor:347 outputString = str(math.floor(float(localInputString)))348 elif self.function_type == FunctionType.Round:349 outputString = str(round(float(localInputString)))350 elif self.function_type == FunctionType.CountOccurrences:351 outputString = str(localInputString.count(self.StringToFind))352 elif self.function_type == FunctionType.CharAt:353 outputString = str(localInputString[int(ReplaceValues(self.charIndex,BotData))])354 elif self.function_type == FunctionType.ReverseString:355 charArray = list(localInputString)356 charArray.reverse()357 outputString = "".join(charArray)358 elif self.function_type == FunctionType.Substring:359 outputString = localInputString[int(ReplaceValues(self.SubstringIndex,BotData)): int(ReplaceValues(self.SubstringIndex,BotData)) + int(ReplaceValues(self.SubstringLength, BotData))]360 elif self.function_type == FunctionType.GetRandomUA:361 if self.UserAgentSpecifyBrowser:362 outputString = UserAgent.ForBrowser(self.UserAgentBrowser)363 else:364 outputString = UserAgent.Random()365 elif self.function_type == FunctionType.Trim:366 outputString = localInputString.strip()367 elif self.function_type == FunctionType.UnixTimeToDate:368 # Static dateformat because dates369 outputString = datetime.fromtimestamp(int(localInputString),timezone.utc).strftime("%Y-%m-%d:%H-%M-%S")370 elif self.function_type == FunctionType.PBKDF2PKCS5:371 outputString = Crypto.PBKDF2PKCS5(localInputString, ReplaceValues(self.KdfSalt, BotData), self.KdfSaltSize, self.KdfIterations, self.KdfKeySize, self.KdfAlgorithm)372 elif self.function_type == FunctionType.Translate:373 outputString = localInputString374 for entryKey, entryValue in self.TranslationDictionary.items():375 if entryKey in outputString:376 outputString = outputString.replace(entryKey, entryValue)377 if self.StopAfterFirstMatch: break378 elif self.function_type == FunctionType.Unescape:379 outputString = Unescape(localInputString)380 elif self.function_type == FunctionType.UnixTimeToISO8601:381 outputString = datetime.fromtimestamp(int(localInputString),timezone.utc).isoformat()382 elif self.function_type == FunctionType.ClearCookies:383 BotData.CookiesSet(CVar("COOKIES",{},False,True))384 elif self.function_type == FunctionType.HTMLEntityEncode:385 outputString = escape(localInputString)386 elif self.function_type == FunctionType.HTMLEntityDecode:387 outputString = unescape(localInputString)388 else:389 pass390 outputs.append(outputString)391 print(f"Executed function {self.function_type} on input {localInputStrings} with outcome {outputString}")392 isList = len(outputs) > 1 or "[*]" in self.InputString or "(*)" in self.InputString or "{*}" in self.InputString393 InsertVariable(BotData,self.IsCapture,isList,outputs,self.VariableName,self.CreateEmpty)394 def GetHash(self,baseString:str,hashAlg:str,inputBase64:bool):395 if not inputBase64:396 rawInput = baseString.encode('utf-8')397 else:398 try:399 rawInput = base64.b64decode(baseString.encode('utf-8'))400 except Exception:401 # In case the input is not base64 encoded402 return ""403 digest = bytearray()404 if hashAlg == "MD4":405 digest = Crypto.MD4(rawInput)406 elif hashAlg == "MD5":407 digest = Crypto.MD5(rawInput)408 elif hashAlg == "SHA1":409 digest = Crypto.SHA1(rawInput)410 elif hashAlg == "SHA256":411 digest = Crypto.SHA256(rawInput)412 elif hashAlg == "SHA384":413 digest = Crypto.SHA384(rawInput)414 elif hashAlg == "SHA512":415 digest = Crypto.SHA512(rawInput)416 return digest.hex()417 def Hmac(self, baseString:str,hashAlg,key:str,inputBase64:bool,keyBase64:bool,outputBase64:bool):418 rawInput = bytearray()419 rawKey = bytearray()420 signature = bytearray()421 if inputBase64:422 rawInput = base64.b64decode(baseString.encode('utf-8'))423 else:424 rawInput = baseString.encode('utf-8')425 if keyBase64:426 rawKey = base64.b64decode(key.encode('utf-8'))427 else:428 rawKey = key.encode('utf-8')429 if hashAlg == "MD5":430 signature = Crypto.HMACMD5(rawInput,rawKey)431 elif hashAlg == "SHA1":432 signature = Crypto.HMACSHA1(rawInput,rawKey)433 elif hashAlg == "SHA256":434 signature = Crypto.HMACSHA256(rawInput,rawKey)435 elif hashAlg == "SHA384":436 signature = Crypto.HMACSHA384(rawInput,rawKey)437 elif hashAlg == "SHA512":438 signature = Crypto.HMACSHA512(rawInput,rawKey)439 else:440 return ""441 if outputBase64:442 return base64.b64encode(signature).decode("utf-8")443 else:...

Full Screen

Full Screen

scalars-test.js

Source:scalars-test.js Github

copy

Full Screen

...27 value: 128 })).to.throw('Int cannot represent non-integer value: { value: 1 }');29 });30 it('parseLiteral', () => {31 function parseLiteral(str) {32 return GraphQLInt.parseLiteral(parseValueToAST(str));33 }34 expect(parseLiteral('1')).to.equal(1);35 expect(parseLiteral('0')).to.equal(0);36 expect(parseLiteral('-1')).to.equal(-1);37 expect(() => parseLiteral('9876504321')).to.throw('Int cannot represent non 32-bit signed integer value: 9876504321');38 expect(() => parseLiteral('-9876504321')).to.throw('Int cannot represent non 32-bit signed integer value: -9876504321');39 expect(() => parseLiteral('1.0')).to.throw('Int cannot represent non-integer value: 1.0');40 expect(() => parseLiteral('null')).to.throw('Int cannot represent non-integer value: null');41 expect(() => parseLiteral('""')).to.throw('Int cannot represent non-integer value: ""');42 expect(() => parseLiteral('"123"')).to.throw('Int cannot represent non-integer value: "123"');43 expect(() => parseLiteral('false')).to.throw('Int cannot represent non-integer value: false');44 expect(() => parseLiteral('[1]')).to.throw('Int cannot represent non-integer value: [1]');45 expect(() => parseLiteral('{ value: 1 }')).to.throw('Int cannot represent non-integer value: {value: 1}');46 expect(() => parseLiteral('ENUM_VALUE')).to.throw('Int cannot represent non-integer value: ENUM_VALUE');47 expect(() => parseLiteral('$var')).to.throw('Int cannot represent non-integer value: $var');48 });49 });50 describe('GraphQLFloat', () => {51 it('parseValue', () => {52 function parseValue(value) {53 return GraphQLFloat.parseValue(value);54 }55 expect(parseValue(1)).to.equal(1);56 expect(parseValue(0)).to.equal(0);57 expect(parseValue(-1)).to.equal(-1);58 expect(parseValue(0.1)).to.equal(0.1);59 expect(parseValue(Math.PI)).to.equal(Math.PI);60 expect(() => parseValue(NaN)).to.throw('Float cannot represent non numeric value: NaN');61 expect(() => parseValue(Infinity)).to.throw('Float cannot represent non numeric value: Infinity');62 expect(() => parseValue(undefined)).to.throw('Float cannot represent non numeric value: undefined');63 expect(() => parseValue(null)).to.throw('Float cannot represent non numeric value: null');64 expect(() => parseValue('')).to.throw('Float cannot represent non numeric value: ""');65 expect(() => parseValue('123')).to.throw('Float cannot represent non numeric value: "123"');66 expect(() => parseValue('123.5')).to.throw('Float cannot represent non numeric value: "123.5"');67 expect(() => parseValue(false)).to.throw('Float cannot represent non numeric value: false');68 expect(() => parseValue(true)).to.throw('Float cannot represent non numeric value: true');69 expect(() => parseValue([0.1])).to.throw('Float cannot represent non numeric value: [0.1]');70 expect(() => parseValue({71 value: 0.172 })).to.throw('Float cannot represent non numeric value: { value: 0.1 }');73 });74 it('parseLiteral', () => {75 function parseLiteral(str) {76 return GraphQLFloat.parseLiteral(parseValueToAST(str));77 }78 expect(parseLiteral('1')).to.equal(1);79 expect(parseLiteral('0')).to.equal(0);80 expect(parseLiteral('-1')).to.equal(-1);81 expect(parseLiteral('0.1')).to.equal(0.1);82 expect(parseLiteral(Math.PI.toString())).to.equal(Math.PI);83 expect(() => parseLiteral('null')).to.throw('Float cannot represent non numeric value: null');84 expect(() => parseLiteral('""')).to.throw('Float cannot represent non numeric value: ""');85 expect(() => parseLiteral('"123"')).to.throw('Float cannot represent non numeric value: "123"');86 expect(() => parseLiteral('"123.5"')).to.throw('Float cannot represent non numeric value: "123.5"');87 expect(() => parseLiteral('false')).to.throw('Float cannot represent non numeric value: false');88 expect(() => parseLiteral('[0.1]')).to.throw('Float cannot represent non numeric value: [0.1]');89 expect(() => parseLiteral('{ value: 0.1 }')).to.throw('Float cannot represent non numeric value: {value: 0.1}');90 expect(() => parseLiteral('ENUM_VALUE')).to.throw('Float cannot represent non numeric value: ENUM_VALUE');91 expect(() => parseLiteral('$var')).to.throw('Float cannot represent non numeric value: $var');92 });93 });94 describe('GraphQLString', () => {95 it('parseValue', () => {96 function parseValue(value) {97 return GraphQLString.parseValue(value);98 }99 expect(parseValue('foo')).to.equal('foo');100 expect(() => parseValue(undefined)).to.throw('String cannot represent a non string value: undefined');101 expect(() => parseValue(null)).to.throw('String cannot represent a non string value: null');102 expect(() => parseValue(1)).to.throw('String cannot represent a non string value: 1');103 expect(() => parseValue(NaN)).to.throw('String cannot represent a non string value: NaN');104 expect(() => parseValue(false)).to.throw('String cannot represent a non string value: false');105 expect(() => parseValue(['foo'])).to.throw('String cannot represent a non string value: ["foo"]');106 expect(() => parseValue({107 value: 'foo'108 })).to.throw('String cannot represent a non string value: { value: "foo" }');109 });110 it('parseLiteral', () => {111 function parseLiteral(str) {112 return GraphQLString.parseLiteral(parseValueToAST(str));113 }114 expect(parseLiteral('"foo"')).to.equal('foo');115 expect(parseLiteral('"""bar"""')).to.equal('bar');116 expect(() => parseLiteral('null')).to.throw('String cannot represent a non string value: null');117 expect(() => parseLiteral('1')).to.throw('String cannot represent a non string value: 1');118 expect(() => parseLiteral('0.1')).to.throw('String cannot represent a non string value: 0.1');119 expect(() => parseLiteral('false')).to.throw('String cannot represent a non string value: false');120 expect(() => parseLiteral('["foo"]')).to.throw('String cannot represent a non string value: ["foo"]');121 expect(() => parseLiteral('{ value: "foo" }')).to.throw('String cannot represent a non string value: {value: "foo"}');122 expect(() => parseLiteral('ENUM_VALUE')).to.throw('String cannot represent a non string value: ENUM_VALUE');123 expect(() => parseLiteral('$var')).to.throw('String cannot represent a non string value: $var');124 });125 });126 describe('GraphQLBoolean', () => {127 it('parseValue', () => {128 function parseValue(value) {129 return GraphQLBoolean.parseValue(value);130 }131 expect(parseValue(true)).to.equal(true);132 expect(parseValue(false)).to.equal(false);133 expect(() => parseValue(undefined)).to.throw('Boolean cannot represent a non boolean value: undefined');134 expect(() => parseValue(null)).to.throw('Boolean cannot represent a non boolean value: null');135 expect(() => parseValue(0)).to.throw('Boolean cannot represent a non boolean value: 0');136 expect(() => parseValue(1)).to.throw('Boolean cannot represent a non boolean value: 1');137 expect(() => parseValue(NaN)).to.throw('Boolean cannot represent a non boolean value: NaN');138 expect(() => parseValue('')).to.throw('Boolean cannot represent a non boolean value: ""');139 expect(() => parseValue('false')).to.throw('Boolean cannot represent a non boolean value: "false"');140 expect(() => parseValue([false])).to.throw('Boolean cannot represent a non boolean value: [false]');141 expect(() => parseValue({142 value: false143 })).to.throw('Boolean cannot represent a non boolean value: { value: false }');144 });145 it('parseLiteral', () => {146 function parseLiteral(str) {147 return GraphQLBoolean.parseLiteral(parseValueToAST(str));148 }149 expect(parseLiteral('true')).to.equal(true);150 expect(parseLiteral('false')).to.equal(false);151 expect(() => parseLiteral('null')).to.throw('Boolean cannot represent a non boolean value: null');152 expect(() => parseLiteral('0')).to.throw('Boolean cannot represent a non boolean value: 0');153 expect(() => parseLiteral('1')).to.throw('Boolean cannot represent a non boolean value: 1');154 expect(() => parseLiteral('0.1')).to.throw('Boolean cannot represent a non boolean value: 0.1');155 expect(() => parseLiteral('""')).to.throw('Boolean cannot represent a non boolean value: ""');156 expect(() => parseLiteral('"false"')).to.throw('Boolean cannot represent a non boolean value: "false"');157 expect(() => parseLiteral('[false]')).to.throw('Boolean cannot represent a non boolean value: [false]');158 expect(() => parseLiteral('{ value: false }')).to.throw('Boolean cannot represent a non boolean value: {value: false}');159 expect(() => parseLiteral('ENUM_VALUE')).to.throw('Boolean cannot represent a non boolean value: ENUM_VALUE');160 expect(() => parseLiteral('$var')).to.throw('Boolean cannot represent a non boolean value: $var');161 });162 });163 describe('GraphQLID', () => {164 it('parseValue', () => {165 function parseValue(value) {166 return GraphQLID.parseValue(value);167 }168 expect(parseValue('')).to.equal('');169 expect(parseValue('1')).to.equal('1');170 expect(parseValue('foo')).to.equal('foo');171 expect(parseValue(1)).to.equal('1');172 expect(parseValue(0)).to.equal('0');173 expect(parseValue(-1)).to.equal('-1'); // Maximum and minimum safe numbers in JS174 expect(parseValue(9007199254740991)).to.equal('9007199254740991');175 expect(parseValue(-9007199254740991)).to.equal('-9007199254740991');176 expect(() => parseValue(undefined)).to.throw('ID cannot represent value: undefined');177 expect(() => parseValue(null)).to.throw('ID cannot represent value: null');178 expect(() => parseValue(0.1)).to.throw('ID cannot represent value: 0.1');179 expect(() => parseValue(NaN)).to.throw('ID cannot represent value: NaN');180 expect(() => parseValue(Infinity)).to.throw('ID cannot represent value: Inf');181 expect(() => parseValue(false)).to.throw('ID cannot represent value: false');182 expect(() => GraphQLID.parseValue(['1'])).to.throw('ID cannot represent value: ["1"]');183 expect(() => GraphQLID.parseValue({184 value: '1'185 })).to.throw('ID cannot represent value: { value: "1" }');186 });187 it('parseLiteral', () => {188 function parseLiteral(str) {189 return GraphQLID.parseLiteral(parseValueToAST(str));190 }191 expect(parseLiteral('""')).to.equal('');192 expect(parseLiteral('"1"')).to.equal('1');193 expect(parseLiteral('"foo"')).to.equal('foo');194 expect(parseLiteral('"""foo"""')).to.equal('foo');195 expect(parseLiteral('1')).to.equal('1');196 expect(parseLiteral('0')).to.equal('0');197 expect(parseLiteral('-1')).to.equal('-1'); // Support arbitrary long numbers even if they can't be represented in JS198 expect(parseLiteral('90071992547409910')).to.equal('90071992547409910');199 expect(parseLiteral('-90071992547409910')).to.equal('-90071992547409910');200 expect(() => parseLiteral('null')).to.throw('ID cannot represent a non-string and non-integer value: null');201 expect(() => parseLiteral('0.1')).to.throw('ID cannot represent a non-string and non-integer value: 0.1');202 expect(() => parseLiteral('false')).to.throw('ID cannot represent a non-string and non-integer value: false');203 expect(() => parseLiteral('["1"]')).to.throw('ID cannot represent a non-string and non-integer value: ["1"]');204 expect(() => parseLiteral('{ value: "1" }')).to.throw('ID cannot represent a non-string and non-integer value: {value: "1"}');205 expect(() => parseLiteral('ENUM_VALUE')).to.throw('ID cannot represent a non-string and non-integer value: ENUM_VALUE');206 expect(() => parseLiteral('$var')).to.throw('ID cannot represent a non-string and non-integer value: $var');207 });208 });...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful