How to use runner.run method in qawolf

Best JavaScript code snippet using qawolf

expressionParserTest.ts

Source:expressionParserTest.ts Github

copy

Full Screen

...139});140QUnit.test("Run one condition", function (assert) {141 var runner = new ConditionRunner("{a} > 5");142 var values = { a: 6 };143 assert.equal(runner.run(values), true, "6 > 5");144 values = { a: 5 };145 assert.equal(runner.run(values), false, "5 > 5");146 var values2 = { b: 5 };147 assert.equal(runner.run(values2), false, "undefined > 5");148});149QUnit.test("Run complex condition", function (assert) {150 var runner = new ConditionRunner(151 "{age} >= 21 and ({sex} = 'male' or {kids} > 1)"152 );153 var values = { age: 21, sex: "male", kids: 1 };154 assert.equal(runner.run(values), true, "21 >= 21 and (male = male or 1 > 1)");155 var values = { age: 21, sex: "female", kids: 1 };156 assert.equal(157 runner.run(values),158 false,159 "21 >= 21 and (male = female or 1 > 1)"160 );161 var values = { age: 21, sex: "female", kids: 2 };162 assert.equal(163 runner.run(values),164 true,165 "21 >= 21 and (male = female or 2 > 1)"166 );167 var values = { age: 20, sex: "male", kids: 2 };168 assert.equal(169 runner.run(values),170 false,171 "20 >= 21 and (male = male or 2 > 1)"172 );173});174QUnit.test("Run condition with nested properties", function (assert) {175 var runner = new ConditionRunner("{age.min} >= 35 and ({age.max} <= 80");176 var values = { age: { min: 36, max: 40 } };177 assert.equal(runner.run(values), true, "min > 35 max < 80");178 values.age.min = 21;179 assert.equal(runner.run(values), false, "min < 35 max < 80");180});181QUnit.test("Condition check #303", function (assert) {182 var runner = new ConditionRunner(183 "({question-fruit} = 'fruit-apple' and {question-apple-variety} = 'apple-variety-red-delicious') or ({question-fruit} = 'fruit-orange' and {question-orange-variety} = 'orange-variety-blood')"184 );185 var values = {};186 assert.equal(runner.run(values), false, "nothing was set");187 values = {188 "question-fruit": "fruit-apple",189 "question-apple-variety": "apple-variety-red-delicious",190 };191 assert.equal(runner.run(values), true, "The first part is correct");192 values["question-fruit"] = "fruit-orange";193 assert.equal(runner.run(values), false, "the value is incorrect");194 values["question-orange-variety"] = "orange-variety-blood";195 assert.equal(runner.run(values), true, "The second part is correct");196});197QUnit.test("Condition check empty for undefined variables #323", function (198 assert199) {200 var runner = new ConditionRunner("{var1} empty");201 var values = {};202 assert.equal(runner.run(values), true, "it is empty");203 values = { var1: 1 };204 assert.equal(runner.run(values), false, "it is not empty");205});206QUnit.test("Condition check for undefined variables #323", function (assert) {207 var runner = new ConditionRunner("{var1} < 3 or {var1} empty");208 var values = {};209 assert.equal(runner.run(values), true, "empty should work");210 values = { var1: 1 };211 assert.equal(runner.run(values), true, "1 < 3");212 values = { var1: 5 };213 assert.equal(runner.run(values), false, "5 > 3");214});215QUnit.test("Check non equal, #377", function (assert) {216 var runner = new ConditionRunner("{var1} != 3");217 var values = {};218 assert.equal(runner.run(values), true, "empty should give true");219 values = { var1: 1 };220 assert.equal(runner.run(values), true, "1 != 3");221 values = { var1: 3 };222 assert.equal(runner.run(values), false, "3 == 3");223});224QUnit.test("Condition check for undefined #518", function (assert) {225 var runner = new ConditionRunner("{var1} == undefined");226 var values = {};227 assert.equal(runner.run(values), true, "undefined should work");228 values = { var1: undefined };229 assert.equal(runner.run(values), true, "undefined should work");230 values = { var1: "a" };231 assert.equal(runner.run(values), false, "string is not undefined");232 runner = new ConditionRunner("{var1} != undefined");233 values = {};234 assert.equal(runner.run(values), false, "undefined should work");235 values = { var1: undefined };236 assert.equal(runner.run(values), false, "undefined should work");237 values = { var1: "a" };238 assert.equal(runner.run(values), true, "string is not undefined");239});240QUnit.test("Run sum function", function (assert) {241 var runner = new ExpressionRunner("sum({var1},{var2},{var3},{var4})");242 var values = { var1: 2, var2: 3, var3: 4, var4: 5 };243 assert.equal(runner.run(values), 14, "2 + 3 + 4 + 5 == 14");244 values.var1 = 1;245 assert.equal(runner.run(values), 13, "1 + 3 + 4 + 5 == 13");246});247QUnit.test("Run sum function with arrays, Bug #1808", function (assert) {248 var runner = new ExpressionRunner("sum({var1},{var2})");249 var values = { var1: [2, 5], var2: 3 };250 assert.equal(runner.run(values), 10, "2 + 5 + 3 == 10");251});252QUnit.test("Run min function", function (assert) {253 var runner = new ExpressionRunner("min({var1},{var2})");254 var values = { var1: [4, 2, 5], var2: 3 };255 assert.equal(runner.run(values), 2, "4, 2, 5, 3, min is 2");256});257QUnit.test("Run max function", function (assert) {258 var runner = new ExpressionRunner("max({var1},{var2})");259 var values = { var1: [4, 2, 5, 3], var2: 3 };260 assert.equal(runner.run(values), 5, "4, 2, 5, 3, max is 5");261});262QUnit.test("Run min/max functions with zeros, Bug #2229", function (assert) {263 var runner = new ExpressionRunner("min({var1},{var2})");264 var values = { var1: 0, var2: 3 };265 assert.equal(runner.run(values), 0, "0, 3, min is 0");266 runner = new ExpressionRunner("max({var1},{var2})");267 values = { var1: 0, var2: -3 };268 assert.equal(runner.run(values), 0, "0, -3, max is 0");269});270QUnit.test("Run age function", function (assert) {271 var runner = new ConditionRunner("age({bithday}) >= 21");272 var values = { bithday: new Date(1974, 1, 1) };273 assert.equal(runner.run(values), true, "true, bithday of 1974 >= 21");274 var curDate = new Date(Date.now());275 values.bithday = new Date(curDate.getFullYear() - 10, 1, 1);276 assert.equal(runner.run(values), false, "false, the person is 10 years old");277});278QUnit.test("Run age function with empty value", function (assert) {279 var runner = new ConditionRunner("age({bithday}) >= 21");280 var runner2 = new ConditionRunner("age({bithday}) < 21");281 var values = {};282 assert.equal(runner.run(values), false, "1. false, bithday is empty");283 assert.equal(runner2.run(values), false, "2. false, bithday is empty");284});285QUnit.test("Run function with properties", function (assert) {286 function isEqual(params: any[]): any {287 return this.propValue == params[0];288 }289 FunctionFactory.Instance.register("isEqual", isEqual);290 var runner = new ConditionRunner("isEqual({val}) == true");291 var values = { val: 3 };292 var properties = { propValue: 3 };293 assert.equal(runner.run(values, properties), true, "3 = 3");294 properties.propValue = 5;295 assert.equal(runner.run(values, properties), false, "3 != 5");296 FunctionFactory.Instance.unregister("isEqual");297});298QUnit.test("Support true/false constants, #643", function (assert) {299 var runner = new ConditionRunner("true && {year} >= 21");300 var values = { year: 22 };301 assert.equal(runner.run(values), true, "true, true && 22 >= 21");302 values = { year: 20 };303 assert.equal(runner.run(values), false, "false, true && 20 >= 21");304 runner = new ConditionRunner("true or {year} >= 21");305 values = { year: 22 };306 assert.equal(runner.run(values), true, "true, true or 22 >= 21");307 values = { year: 20 };308 assert.equal(runner.run(values), true, "true, true or 20 >= 21");309 runner = new ConditionRunner("false && {year} >= 21");310 values = { year: 22 };311 assert.equal(runner.run(values), false, "false, false && 22 >= 21");312 values = { year: 20 };313 assert.equal(runner.run(values), false, "false, false && 20 >= 21");314 runner = new ConditionRunner("false or {year} >= 21");315 values = { year: 22 };316 assert.equal(runner.run(values), true, "true, false or 22 >= 21");317 values = { year: 20 };318 assert.equal(runner.run(values), false, "false, false or 20 >= 21");319});320QUnit.test("true/false as string, bug#729", function (assert) {321 var runner = new ConditionRunner("{isTrue} = 'true'");322 var values = { isTrue: "true" };323 assert.equal(runner.run(values), true, "true, 'true' = 'true'");324});325QUnit.test("true/false as constant in the left", function (assert) {326 var runner = new ConditionRunner("true = {isTrue}");327 var values = { isTrue: "false" };328 assert.equal(runner.run(values), false, "false, true = false");329});330QUnit.test("Constant string with dash (-) doens't work correctly", function (331 assert332) {333 var runner = new ConditionRunner("{a} = '01-01-2018'");334 var values = { a: "01-01" };335 assert.equal(runner.run(values), false, "'01-01' = '01-01-2018'");336 values.a = "01-01-2018";337 assert.equal(runner.run(values), true, "'01-01-2018' = '01-01-2018'");338});339QUnit.test("Bug with contains, bug#781", function (assert) {340 var runner = new ConditionRunner("{ResultaatSelectie} contains '1'");341 var values = { ResultaatSelectie: ["1"] };342 assert.equal(runner.run(values), true, "['1'] contains '1'");343 values = { ResultaatSelectie: ["2"] };344 assert.equal(runner.run(values), false, "['2'] contains '1'");345});346QUnit.test("Check contains with empty array, Bug #2193", function (assert) {347 var runner = new ConditionRunner("[] contains 'C1'");348 assert.equal(runner.run({}), false, "[] doesn't contain 'C1'");349 var parser = new ConditionsParser();350 var operand = parser.parseExpression("[] contains 'C1'");351 assert.ok(operand, "The expression parse correctly");352});353QUnit.test("contains as equal", function (assert) {354 var runner = new ConditionRunner("{val} contains 'value'");355 var values = { val: "value" };356 assert.equal(runner.run(values), true, "'value' contains 'value'");357});358QUnit.test("contains for complex object", function (assert) {359 var runner = new ConditionRunner("{val} contains {item}");360 var values = { val: [{ id: 1 }, { id: 2 }], item: { id: 1 } };361 assert.equal(runner.run(values), true, "works with compelx object");362});363QUnit.test("0 is not an empty value", function (assert) {364 var runner = new ConditionRunner("{val} = 0");365 var values = { val: 0 };366 assert.equal(runner.run(values), true, "0 = 0");367});368QUnit.test(369 "0 is not an empty value (variable with complex identifier). Bug T2441 (https://surveyjs.answerdesk.io/internal/ticket/details/T2441)",370 function (assert) {371 var runner = new ConditionRunner("{complexIdentifier} = 0");372 var values = { complexIdentifier: 0 };373 assert.equal(runner.run(values), true, "0 = 0");374 }375);376QUnit.test("Bug with contains, support string.indexof, bug#831", function (377 assert378) {379 var runner = new ConditionRunner("{str} contains '1'");380 var values = { str: "12345" };381 assert.equal(runner.run(values), true, "'12345' contains '1'");382 values = { str: "2345" };383 assert.equal(runner.run(values), false, "'2345' contains '1'");384 runner = new ConditionRunner("{str} notcontains '1'");385 assert.equal(runner.run(values), true, "'2345' notcontains '1'");386 values = { str: "12345" };387 assert.equal(runner.run(values), false, "'12345' notcontains '1'");388});389QUnit.test("Bug with contains, bug#1039", function (assert) {390 var runner = new ConditionRunner("{ValueType} contains '3b'");391 var values = { ValueType: ["3b"] };392 assert.equal(runner.run(values), true, "['3b'] contains '3b'");393 values = { ValueType: ["1"] };394 assert.equal(runner.run(values), false, "['1'] contains '3b'");395});396QUnit.test("Add support for array for cotains operator, issue#1366", function (397 assert398) {399 var runner = new ConditionRunner("{value} contains ['a', 'b']");400 var values = { value: ["a", "b"] };401 assert.equal(runner.run(values), true, "['a', 'b'] contains ['a', 'b']");402 values = { value: ["a", "c"] };403 assert.equal(runner.run(values), false, "['a', 'c'] contains ['a', 'b']");404 values = { value: ["a", "b", "c"] };405 assert.equal(runner.run(values), true, "['a', 'b', 'c'] contains ['a', 'b']");406});407QUnit.test("Escape quotes, bug#786", function (assert) {408 var runner = new ConditionRunner("{text} = 'I\\'m here'");409 var values = { text: "I'm here" };410 assert.equal(runner.run(values), true, "text equals I'm here");411 var runner = new ConditionRunner(412 "'I said: \\\"I\\'m here\\\"' contains {text}"413 );414 var values = { text: "I'm here" };415 assert.equal(runner.run(values), true, "I said contains text");416});417QUnit.test("Support equals and notequals, #781", function (assert) {418 var runner = new ConditionRunner("{a} equals 1");419 var values = { a: 1 };420 assert.equal(runner.run(values), true, "1 equals 1");421 values = { a: 2 };422 assert.equal(runner.run(values), false, "2 equals 1");423});424QUnit.test("Allow differnt symbols in variable name, bug#803", function (425 assert426) {427 var runner = new ConditionRunner("{complex name #$%?dd} = 1");428 var values = { "complex name #$%?dd": 1 };429 assert.equal(runner.run(values), true, "1= 1");430 values = { "complex name #$%?dd": 2 };431 assert.equal(runner.run(values), false, "2 <> 1");432});433QUnit.test("Support array", function (assert) {434 var runner = new ConditionRunner("{a} equals [1, 2]");435 var values = { a: [1, 2] };436 assert.equal(runner.run(values), true, "[1, 2] equals [1, 2]");437 values = { a: [2] };438 assert.equal(runner.run(values), false, "[2] equals [1, 2]");439 values = { a: [2, 1] };440 assert.equal(runner.run(values), true, "[2, 1] equals [1, 2]");441});442QUnit.test("ExpressionOperand: Simple expression", function (assert) {443 var runner = new ConditionRunner("{a} - 1 > 5");444 var values = { a: 7 };445 assert.equal(runner.run(values), true, "6 > 5");446 values = { a: 6 };447 assert.equal(runner.run(values), false, "5 > 5");448});449QUnit.test("ExpressionOperand: brackets", function (assert) {450 var runner = new ConditionRunner("({a} + {b}) * 2 >= 10");451 var values = { a: 1, b: 3 };452 assert.equal(runner.run(values), false, "(1 + 3) * 2 >= 10");453});454QUnit.test("ExpressionOperand: brackets 2", function (assert) {455 var runner = new ConditionRunner("({a} + {b} + {c}) / 3 >= 3");456 var values = { a: 1, b: 3, c: 2 };457 assert.equal(runner.run(values), false, "(1 + 3 + 2) / 3 >= 3");458 values.c = 5;459 assert.equal(runner.run(values), true, "(1 + 3 + 4) / 3 >= 3");460});461QUnit.test("ConditionRunner: (1+2)*3", function (assert) {462 var runner = new ExpressionRunner("(1+2)*3");463 assert.equal(runner.run({}), 9, "(1+2)*3 is 9");464});465QUnit.test("ConditionRunner: (1+2)*(3+2) / 5", function (assert) {466 var runner = new ExpressionRunner("(1+2)*(3+2) / 5");467 assert.equal(runner.run({}), 3, "(1+2)*(3+2) / 5 is 3");468});469QUnit.test("ConditionRunner: 10 % 3", function (assert) {470 var runner = new ExpressionRunner("10 % 3");471 assert.equal(runner.run({}), 1, "10 % 3 is 1");472 var condition = new ConditionRunner("({val1} + {val2}) % 2 = 0");473 assert.equal(condition.run({ val1: 1, val2: 3 }), true, "(1+3)%2=0");474 assert.equal(condition.run({ val1: 2, val2: 3 }), false, "(2+3)%2=0");475});476QUnit.test("ExpressionRunner: sumInArray", function (assert) {477 var runner = new ExpressionRunner("sumInArray({a}, 'val1')");478 var values = { a: [{ val1: 10 }, { val2: 10 }, { val1: 20 }] };479 assert.equal(runner.run(values), 30, "10 + 20");480 values = { a: [{ val2: 1 }] };481 assert.equal(runner.run(values), 0, "There is no values");482});483QUnit.test("ExpressionRunner: sumInArray, for objects", function (assert) {484 var runner = new ExpressionRunner("sumInArray({a}, 'val1')");485 var values = {486 a: { row1: { val1: 10 }, row2: { val2: 10 }, row3: { val1: 20 } },487 };488 assert.equal(runner.run(values), 30, "10 + 20");489});490QUnit.test("ExpressionRunner: countInArray", function (assert) {491 var runner = new ExpressionRunner("countInArray({a}, 'val1')");492 var values = { a: [{ val1: 10 }, { val2: 10 }, { val1: 20 }] };493 assert.equal(runner.run(values), 2, "10 + 20");494 values = { a: [{ val2: 1 }] };495 assert.equal(runner.run(values), 0, "There is no values");496 var emptyValue = { a: {} };497 assert.equal(runner.run(emptyValue), 0, "object is empty");498});499QUnit.test("ConditionRunner, iif simple", function (assert) {500 var runner = new ExpressionRunner("iif({a}, 'high', 'low')");501 var values = { a: true };502 assert.equal(runner.run(values), "high", "true");503 values.a = false;504 assert.equal(runner.run(values), "low", "false");505});506QUnit.test("ExpressionRunner, iif with expression", function (assert) {507 var runner = new ExpressionRunner("iif({a} + {b} > 20, 'high', 'low')");508 var values = { a: 10, b: 20 };509 assert.equal(runner.run(values), "high", "10 + 20 > 20");510 values.b = 5;511 assert.equal(runner.run(values), "low", "10 + 5 < 20");512});513QUnit.test("ConditionRunner, iif nested using", function (assert) {514 var runner = new ExpressionRunner(515 "iif({a} + {b} > 20, 'high', iif({a} + {b} > 10, 'medium', 'low'))"516 );517 var values = { a: 10, b: 20 };518 assert.equal(runner.run(values), "high", "10 + 20 > 20");519 values.b = 5;520 assert.equal(runner.run(values), "medium", "10 + 5 > 10 && 10 + 5 < 20");521 values.a = 1;522 assert.equal(runner.run(values), "low", "1 + 5 < 10");523});524QUnit.test("ConditionRunner, iif nested using 2", function (assert) {525 var runner = new ExpressionRunner(526 "iif(({a} + {b}) > 20, ({a} * 5 + {b}), iif({a} + {b} > 10, 5*({a}+ {b}), {a}))"527 );528 var values = { a: 10, b: 20 };529 assert.equal(runner.run(values), 10 * 5 + 20, "10 + 20 > 20");530 values.b = 5;531 assert.equal(runner.run(values), 5 * (10 + 5), "10 + 5 > 10 && 10 + 5 < 20");532 values.a = 1;533 assert.equal(runner.run(values), 1, "1 + 5 < 10");534});535function avg(params: any[]): any {536 var res = 0;537 for (var i = 0; i < params.length; i++) {538 res += params[i];539 }540 return params.length > 0 ? res / params.length : 0;541}542QUnit.test(543 "ConditionRunner, iif nested using with function, Bug T1302, (https://surveyjs.answerdesk.io/ticket/details/T1302)",544 function (assert) {545 function incValue(params: any[]): any {546 return params[0] + 1;547 }548 FunctionFactory.Instance.register("incValue", incValue);549 var runner = new ExpressionRunner(550 'incValue(iif(({REVIEW_COVER} contains "REVIEW_SM") and ({REVIEW_COVER} contains "REVIEW_GL"), ({RATES_PROPERTY_SD}+{RATES_LIABILITY_SD}+{RATES_SEXUAL_MOL_END_SD}), iif(({REVIEW_COVER} notcontains "REVIEW_SM") and ({REVIEW_COVER} contains "REVIEW_GL"), ({RATES_PROPERTY_SD}+{RATES_LIABILITY_SD}), ({RATES_PROPERTY_SD}))))'551 );552 var values = {553 REVIEW_COVER: ["REVIEW_SM", "REVIEW_GL"],554 RATES_PROPERTY_SD: 1,555 RATES_LIABILITY_SD: 2,556 RATES_SEXUAL_MOL_END_SD: 3,557 };558 assert.equal(559 runner.run(values),560 1 + 2 + 3 + 1,561 "the first condition is calling"562 );563 FunctionFactory.Instance.unregister("incValue");564 }565);566QUnit.test("ConditionRunner, ^ operator", function (assert) {567 var runner = new ExpressionRunner("{a} ^ 3 + {b} ^ 0.5");568 var values = { a: 10, b: 400 };569 assert.equal(runner.run(values), 1020, "10^3 + 400^0.5 = 1000 + 20");570});571QUnit.test("Variable may have '-' and '+' in their names", function (assert) {572 var runner = new ConditionRunner("{2-3+4} = 1");573 var values = { "2-3+4": 1 };574 assert.equal(runner.run(values), true, "1 = 1");575 values = { "2-3+4": 2 };576 assert.equal(runner.run(values), false, "2 != 1");577});578QUnit.test("Variable equals 0x1 works incorrectly, Bug#1180", function (579 assert580) {581 var runner = new ConditionRunner("{val} notempty");582 var values = { val: "0x1" };583 assert.equal(runner.run(values), true, "0x1 is not empty");584 runner = new ConditionRunner("{val} = 2");585 values = { val: "0x1" };586 assert.equal(runner.run(values), false, "0x1 is not 2");587 values = { val: "0x2" };588 assert.equal(runner.run(values), true, "0x2 is not 2");589});590QUnit.test("notempty with 0 and false, bug#1792", function (assert) {591 var runner = new ConditionRunner("{val} notempty");592 var values: any = { val: 0 };593 assert.equal(runner.run(values), true, "0 is not empty");594 values.val = "0";595 assert.equal(runner.run(values), true, "'0' is not empty");596 values.val = false;597 assert.equal(runner.run(values), true, "false is not empty");598});599QUnit.test("contain and noncontain for null arrays", function (assert) {600 var runner = new ConditionRunner("{val} contain 1");601 var values = {};602 assert.equal(603 runner.run(values),604 false,605 "underfined doesn't contain 1 - false"606 );607 runner = new ConditionRunner("{val} notcontain 1");608 values = {};609 assert.equal(runner.run(values), true, "underfined doesn't contain 1 - true");610});611QUnit.test("length for undefined arrays", function (assert) {612 var runner = new ConditionRunner("{val.length} = 0");613 assert.equal(runner.run({ val: [] }), true, "empty array length returns 0");614 assert.equal(runner.run({}), true, "underfined length returns 0");615});616QUnit.test("contain and noncontain for strings", function (assert) {617 var runner = new ConditionRunner("{val} contain 'ab'");618 var values = {};619 assert.equal(620 runner.run(values),621 false,622 "contains: underfined doesn't contain 'ab' - false"623 );624 values = { val: "ba" };625 assert.equal(626 runner.run(values),627 false,628 "contains: 'ba' doesn't contain 'ab' - false"629 );630 values = { val: "babc" };631 assert.equal(632 runner.run(values),633 true,634 "contains: 'babc' contains 'ab' - true"635 );636 runner = new ConditionRunner("{val} notcontain 'ab'");637 values = {};638 assert.equal(639 runner.run(values),640 true,641 "notcontains: underfined doesn't contain 'ab' - true"642 );643 values = { val: "ba" };644 assert.equal(645 runner.run(values),646 true,647 "notcontains: 'ba' doesn't contain 'ab' - true"648 );649 values = { val: "babc" };650 assert.equal(651 runner.run(values),652 false,653 "notcontains: 'babc' contains 'ab' - false"654 );655});656QUnit.test(657 "ConditionRunner: 7 * (({q1} * 0.4) + ({q2} * 0.6)), bug# 1423",658 function (assert) {659 var runner = new ExpressionRunner("7 * ((10 * 0.4) + (20 * 0.6))");660 assert.equal(661 runner.run({}),662 7 * (4 + 12),663 "7 * ((10 * 0.4) + (20 * 0.6)) is 112"664 );665 }666);667QUnit.test("0x digits", function (assert) {668 var runner = new ExpressionRunner("0x1 + 0x2 + {x}");669 var values = { x: 0x3 };670 assert.equal(runner.run(values), 6, "0x: 1 + 2 + 3 equal 6");671});672QUnit.test("dont fault in invalid input", function (assert) {673 var condRunner = new ConditionRunner("2 @ 2");674 assert.notOk(condRunner.canRun());675 var exprRunner = new ExpressionRunner("00101 @@ 0101");676 assert.notOk(exprRunner.canRun());677});678QUnit.test("Get variables in expression", function (assert) {679 var runner = new ExpressionRunner(680 "{val1} - {val2} + myFunc({val3}, {val4.prop}) < {val5} and {val6}=1"681 );682 var vars = runner.getVariables();683 assert.equal(vars.length, 6, "There are 6 variables in expression");684 assert.equal(vars[0], "val1", "the first variable");685 assert.equal(vars[5], "val6", "the last variable");686});687QUnit.test("Test binary operator anyof", function (assert) {688 var runner = new ConditionRunner("{value} anyof ['a', 'b']");689 var values = { value: ["a", "c"] };690 assert.equal(runner.run(values), true, "['a', 'c'] anyof ['a', 'b']");691 values = { value: ["a", "b"] };692 assert.equal(runner.run(values), true, "['a', 'b'] anyof ['a', 'b']");693 values = { value: ["c", "d"] };694 assert.equal(runner.run(values), false, "['c', 'd'] anyof ['a', 'b']");695 values = { value: [] };696 assert.equal(runner.run(values), false, "[] anyof ['a', 'b']");697 values = { value: null };698 assert.equal(runner.run(values), false, "null anyof ['a', 'b']");699});700QUnit.test("Test operator anyof for non-array var", function (assert) {701 var runner = new ConditionRunner("{value} anyof ['a', 'b', 'c']");702 var values = { value: "a" };703 assert.equal(runner.run(values), true, "'a' anyof ['a', 'b', 'c']");704 values.value = "e";705 assert.equal(runner.run(values), false, "'e' anyof ['a', 'b', 'c']");706});707QUnit.test("Test binary operator allof", function (assert) {708 var runner = new ConditionRunner("{value} allof ['a', 'b']");709 var values = { value: ["a", "c"] };710 assert.equal(runner.run(values), false, "['a', 'c'] allof ['a', 'b']");711 values = { value: ["a", "b", "c"] };712 assert.equal(runner.run(values), true, "['a', 'b', 'c'] allof ['a', 'b']");713 values = { value: ["c", "d"] };714 assert.equal(runner.run(values), false, "['c', 'd'] allof ['a', 'b']");715});716QUnit.test("Compare object with string", function (assert) {717 var runner = new ConditionRunner("{value} = '1'");718 var values: any = { value: 1 };719 assert.equal(runner.run(values), true, "1 = '1'");720});721QUnit.test("Compare undefined object with string", function (assert) {722 var runner = new ConditionRunner("{value} = 'undefined'");723 var values: any = {};724 assert.equal(runner.run(values), true, "undefined = 'undefined'");725});726QUnit.test("Compare two underfined variables", function (assert) {727 var values: any = { v1: undefined, v2: undefined };728 assert.equal(729 new ConditionRunner("{v1} = {v2}").run(values),730 true,731 "undefined = undefined"732 );733 assert.equal(734 new ConditionRunner("{v1} != {v2}").run(values),735 false,736 "undefined != undefined"737 );738 assert.equal(739 new ConditionRunner("{v1} <= {v2}").run(values),740 true,741 "undefined <= undefined"742 );743 assert.equal(744 new ConditionRunner("{v1} >= {v2}").run(values),745 true,746 "undefined >= undefined"747 );748 assert.equal(749 new ConditionRunner("{v1} < {v2}").run(values),750 false,751 "undefined < undefined"752 );753 assert.equal(754 new ConditionRunner("{v1} > {v2}").run(values),755 false,756 "undefined > undefined"757 );758 values.v1 = 1;759 assert.equal(760 new ConditionRunner("{v1} > {v2}").run(values),761 false,762 "1 > undefined"763 );764 assert.equal(765 new ConditionRunner("{v1} < {v2}").run(values),766 false,767 "1 < undefined"768 );769});770QUnit.test("Support apostrophes in value name", function (assert) {771 var runner = new ConditionRunner("{a'b\"c} = 1");772 var values: any = { "a'b\"c": 1 };773 assert.equal(runner.run(values), true, "1 = 1");774 values = { "a'b\"c": 2 };775 assert.equal(runner.run(values), false, "2 = 1");776});777QUnit.test("String as numbers", function (assert) {778 var runner = new ExpressionRunner("({a} + {b}) * {c}");779 var values: any = { a: "2", b: "3", c: "4" };780 assert.equal(runner.run(values), 20, "convert strings to numbers");781});782QUnit.test(783 "True/False strings do not work, Bug #https://surveyjs.answerdesk.io/ticket/details/T2425",784 function (assert) {785 var runner = new ConditionRunner("{a} = 'True'");786 var values: any = { a: "False" };787 assert.equal(runner.run(values), false, "'True' = 'False'");788 values.a = "True";789 assert.equal(runner.run(values), true, "'True' = 'True'");790 values.a = false;791 assert.equal(runner.run(values), false, "false = 'True'");792 values.a = true;793 assert.equal(runner.run(values), true, "true = 'True'");794 runner = new ConditionRunner("{a} = 'False'");795 values.a = "False";796 assert.equal(runner.run(values), true, "'False' = 'False'");797 values.a = "True";798 assert.equal(runner.run(values), false, "'True' = 'False'");799 values.a = false;800 assert.equal(runner.run(values), true, "'False' = false");801 values.a = true;802 assert.equal(runner.run(values), false, "'False'=true");803 }804);805QUnit.test("Use dot, '.' in names", function (assert) {806 var runner = new ConditionRunner("{a.b.c.d} = 1");807 var values: any = { "a.b.c.d": 1 };808 assert.equal(runner.run(values), true, "1 = 1");809});810QUnit.test("Async function", function (assert) {811 function asyncFunc(params: any): any {812 this.returnResult(params[0] * 3);813 return false;814 }815 FunctionFactory.Instance.register("asyncFunc", asyncFunc, true);816 var runner = new ConditionRunner("asyncFunc({a}) = 15");817 var runnerResult = null;818 runner.onRunComplete = function (result: any) {819 runnerResult = result;820 };821 assert.equal(runner.isAsync, true, "The condition is async");822 var values = { a: 3 };823 runner.run(values);824 assert.equal(runnerResult, false, "3*3 = 15");825 values.a = 5;826 runner.run(values);827 assert.equal(runnerResult, true, "5*3 = 15");828 FunctionFactory.Instance.unregister("asyncFunc");829});830QUnit.test("Use onRunComplete for sync functions", function (assert) {831 function syncFunc(params: any): any {832 return params[0] * 3;833 }834 FunctionFactory.Instance.register("syncFunc", syncFunc);835 var runner = new ConditionRunner("syncFunc({a}) = 15");836 var runnerResult = null;837 runner.onRunComplete = function (result: any) {838 runnerResult = result;839 };840 assert.equal(runner.isAsync, false, "The condition is sync");841 var values = { a: 3 };842 runner.run(values);843 assert.equal(runnerResult, false, "3*3 = 15");844 values.a = 5;845 runner.run(values);846 assert.equal(runnerResult, true, "5*3 = 15");847 FunctionFactory.Instance.unregister("syncFunc");848});849QUnit.test("Several async functions in expression", function (assert) {850 var returnResult1: (res: any) => void;851 var returnResult2: (res: any) => void;852 var returnResult3: (res: any) => void;853 function asyncFunc1(params: any): any {854 returnResult1 = this.returnResult;855 return false;856 }857 function asyncFunc2(params: any): any {858 returnResult2 = this.returnResult;859 return false;860 }861 function asyncFunc3(params: any): any {862 returnResult3 = this.returnResult;863 return false;864 }865 FunctionFactory.Instance.register("asyncFunc1", asyncFunc1, true);866 FunctionFactory.Instance.register("asyncFunc2", asyncFunc2, true);867 FunctionFactory.Instance.register("asyncFunc3", asyncFunc3, true);868 var runner = new ConditionRunner(869 "asyncFunc1() + asyncFunc2() + asyncFunc3() = 10"870 );871 var runnerResult = null;872 runner.onRunComplete = function (result: any) {873 runnerResult = result;874 };875 assert.equal(runner.isAsync, true, "The condition is async");876 var values = { a: 3 };877 runner.run(values);878 assert.equal(879 runnerResult,880 null,881 "It is not ready, async functions do not return anything"882 );883 returnResult2(2);884 assert.equal(885 runnerResult,886 null,887 "It is not ready, asyncfunc1 and asyncfunc3 functions do not return anything"888 );889 returnResult1(7);890 assert.equal(891 runnerResult,892 null,893 "It is not ready, asyncfunc3 function doesn't return anything"894 );895 returnResult3(1);896 assert.equal(runnerResult, true, "evulate successfull");897 FunctionFactory.Instance.unregister("asyncFunc1");898 FunctionFactory.Instance.unregister("asyncFunc2");899 FunctionFactory.Instance.unregister("asyncFunc3");900});901QUnit.test("isString function", function (assert) {902 function isString(params: any[]): any {903 return typeof params[0] == "string";904 }905 FunctionFactory.Instance.register("isString", isString);906 var runner = new ConditionRunner("isString({val}) == true");907 var values: any = { val: "3" };908 var properties = {};909 assert.equal(runner.run(values, properties), false, "3 is Numeric");910 values.val = false;911 assert.equal(runner.run(values, properties), false, "false is boolean");912 values.val = "abc";913 assert.equal(runner.run(values, properties), true, "'abc' is string");914 values.val = "0x2323";915 assert.equal(runner.run(values, properties), false, "'0x2323' is number");916 values.val = "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8";917 assert.equal(918 runner.run(values, properties),919 true,920 "'0xbe0eb53f46cd790cd13851d5eff43d12404d33e8' is string"921 );922 FunctionFactory.Instance.unregister("isString");923});924QUnit.test('express with iif and "[" inside, Bug#1942', function (assert) {925 // prettier-ignore926 var expression = "{val1} + iif({val2} = \"item2\", \"[\" + {val1} + \"]\", \"x\")";927 var runner = new ExpressionRunner(expression);928 var values: any = { val1: "1", val2: "item2" };929 assert.equal(runner.run(values), "1[1]", "val1 + [val1]");930 values.val2 = "item1";931 assert.equal(runner.run(values), "1x", "1 + 'x'");932 values.val1 = undefined;933 assert.equal(runner.run(values), "x", "undefined + 'x'");934 // prettier-ignore935 expression = "{val1} + \"x\"";936 var runner = new ExpressionRunner(expression);937 assert.equal(runner.run(values), "x", "undefined + 'x' without iif");938 expression = '{val1} + "[" + {val1} + "]"';939 var runner = new ExpressionRunner(expression);940 assert.equal(941 runner.run(values),942 "[]",943 "undefined + '[' + undefined + ']' without iif"944 );945});946QUnit.test('expression with "{", Bug#2337', function (assert) {947 // prettier-ignore948 var expression = "{val1} + '\{ text' + '\}'";949 var runner = new ExpressionRunner(expression);950 var values: any = { val1: "1" };951 assert.equal(runner.run(values), "1{ text}", "{");952 expression = "{val1} + '{ text' + '}'";953 runner = new ExpressionRunner(expression);954 var values: any = { val1: "1" };955 assert.equal(runner.run(values), "1{ text}", "{ without escape");...

Full Screen

Full Screen

gulp-reinstall.spec.js

Source:gulp-reinstall.spec.js Github

copy

Full Screen

1const path = require('path');2const chai = require('chai');3const Vinyl = require('vinyl');4const commandRunner = require('../lib/command-runner');5const reinstall = require('..');6const should = chai.should();7function fixture(file) {8 const filepath = path.join(__dirname, file);9 return new Vinyl({10 path: filepath,11 cwd: __dirname,12 base: path.join(__dirname, path.dirname(file)),13 contents: null,14 });15}16function mockRunner() {17 const mock = (cmd) => {18 mock.called += 1;19 mock.commands.push(cmd);20 return Promise.resolve();21 };22 mock.called = 0;23 mock.commands = [];24 return mock;25}26let originalRun;27describe('gulp-install', function () {28 beforeEach(function () {29 originalRun = commandRunner.run;30 commandRunner.run = mockRunner();31 });32 afterEach(function () {33 commandRunner.run = originalRun;34 });35 it('should run `npm install` if stream contains `package.json`', function (done) {36 const file = fixture('package.json');37 const stream = reinstall();38 stream.on('error', (err) => {39 should.exist(err);40 done(err);41 });42 stream.on('data', () => {});43 stream.on('end', () => {44 commandRunner.run.called.should.equal(1);45 commandRunner.run.commands[0].cmd.should.equal('npm');46 commandRunner.run.commands[0].args.should.eql(['install']);47 done();48 });49 stream.write(file);50 stream.end();51 });52 it('should run `npm install --production` if stream contains `package.json` and `production` option is set', function (done) {53 const file = fixture('package.json');54 const stream = reinstall({ production: true });55 stream.on('error', (err) => {56 should.exist(err);57 done(err);58 });59 stream.on('data', () => {});60 stream.on('end', () => {61 commandRunner.run.called.should.equal(1);62 commandRunner.run.commands[0].cmd.should.equal('npm');63 commandRunner.run.commands[0].args.should.eql([64 'install',65 '--production',66 ]);67 done();68 });69 stream.write(file);70 stream.end();71 });72 it('should run `npm install --ignore-scripts` if stream contains `package.json` and `ignoreScripts` option is set', function (done) {73 const file = fixture('package.json');74 const stream = reinstall({ ignoreScripts: true });75 stream.on('error', (err) => {76 should.exist(err);77 done(err);78 });79 stream.on('data', () => {});80 stream.on('end', () => {81 commandRunner.run.called.should.equal(1);82 commandRunner.run.commands[0].cmd.should.equal('npm');83 commandRunner.run.commands[0].args.should.eql([84 'install',85 '--ignore-scripts',86 ]);87 done();88 });89 stream.write(file);90 stream.end();91 });92 it('should run `bower install --config.interactive=false` if stream contains `bower.json`', function (done) {93 const file = fixture('bower.json');94 const stream = reinstall();95 stream.on('error', (err) => {96 should.exist(err);97 done(err);98 });99 stream.on('data', () => {});100 stream.on('end', () => {101 commandRunner.run.called.should.equal(1);102 commandRunner.run.commands[0].cmd.should.equal('bower');103 commandRunner.run.commands[0].args.should.eql([104 'install',105 '--config.interactive=false',106 ]);107 done();108 });109 stream.write(file);110 stream.end();111 });112 it('should run `bower install --production --config.interactive=false` if stream contains `bower.json`', function (done) {113 const file = fixture('bower.json');114 const stream = reinstall({ production: true });115 stream.on('error', (err) => {116 should.exist(err);117 done(err);118 });119 stream.on('data', () => {});120 stream.on('end', () => {121 commandRunner.run.called.should.equal(1);122 commandRunner.run.commands[0].cmd.should.equal('bower');123 commandRunner.run.commands[0].args.should.eql([124 'install',125 '--config.interactive=false',126 '--production',127 ]);128 done();129 });130 stream.write(file);131 stream.end();132 });133 it('should run both `npm install` and `bower install --config.interactive=false` if stream contains both `package.json` and `bower.json`', function (done) {134 const files = [fixture('package.json'), fixture('bower.json')];135 const stream = reinstall();136 stream.on('error', (err) => {137 should.exist(err);138 done(err);139 });140 stream.on('data', () => {});141 stream.on('end', () => {142 commandRunner.run.called.should.equal(2);143 commandRunner.run.commands[0].cmd.should.equal('npm');144 commandRunner.run.commands[0].args.should.eql(['install']);145 commandRunner.run.commands[1].cmd.should.equal('bower');146 commandRunner.run.commands[1].args.should.eql([147 'install',148 '--config.interactive=false',149 ]);150 done();151 });152 files.forEach((file) => stream.write(file));153 stream.end();154 });155 it('should run both `npm install --production` and `bower install --production --config.interactive=false` if stream contains both `package.json` and `bower.json`', function (done) {156 const files = [fixture('package.json'), fixture('bower.json')];157 const stream = reinstall({ production: true });158 stream.on('error', (err) => {159 should.exist(err);160 done(err);161 });162 stream.on('data', () => {});163 stream.on('end', () => {164 commandRunner.run.called.should.equal(2);165 commandRunner.run.commands[0].cmd.should.equal('npm');166 commandRunner.run.commands[0].args.should.eql([167 'install',168 '--production',169 ]);170 commandRunner.run.commands[1].cmd.should.equal('bower');171 commandRunner.run.commands[1].args.should.eql([172 'install',173 '--config.interactive=false',174 '--production',175 ]);176 done();177 });178 files.forEach((file) => stream.write(file));179 stream.end();180 });181 it('should be able to specify different args for different commands', function (done) {182 const files = [fixture('package.json'), fixture('bower.json')];183 const stream = reinstall({184 bower: ['--allow-root'],185 npm: ['--silent'],186 });187 stream.on('error', (err) => {188 should.exist(err);189 done(err);190 });191 stream.on('data', () => {});192 stream.on('end', () => {193 commandRunner.run.called.should.equal(2);194 commandRunner.run.commands[0].cmd.should.equal('npm');195 commandRunner.run.commands[0].args.should.eql(['install', '--silent']);196 commandRunner.run.commands[1].cmd.should.equal('bower');197 commandRunner.run.commands[1].args.should.eql([198 'install',199 '--config.interactive=false',200 '--allow-root',201 ]);202 done();203 });204 files.forEach((file) => stream.write(file));205 stream.end();206 });207 it('should be able to specify different args using objects for different commands', function (done) {208 const files = [fixture('package.json'), fixture('bower.json')];209 const stream = reinstall({210 bower: { allowRoot: true, silent: true },211 npm: { registry: 'https://my.own-registry.com' },212 });213 stream.on('error', (err) => {214 should.exist(err);215 done(err);216 });217 stream.on('data', () => {});218 stream.on('end', () => {219 commandRunner.run.called.should.equal(2);220 commandRunner.run.commands[0].cmd.should.equal('npm');221 commandRunner.run.commands[0].args.should.eql([222 'install',223 '--registry=https://my.own-registry.com',224 ]);225 commandRunner.run.commands[1].cmd.should.equal('bower');226 commandRunner.run.commands[1].args.should.eql([227 'install',228 '--config.interactive=false',229 '--allow-root',230 '--silent',231 ]);232 done();233 });234 files.forEach((file) => stream.write(file));235 stream.end();236 });237 it('should be able to specify a different single argument using a string for different commands', function (done) {238 const files = [fixture('package.json'), fixture('bower.json')];239 const stream = reinstall({240 bower: '--silent',241 npm: '--registry=https://my.own-registry.com',242 });243 stream.on('error', (err) => {244 should.exist(err);245 done(err);246 });247 stream.on('data', () => {});248 stream.on('end', () => {249 commandRunner.run.called.should.equal(2);250 commandRunner.run.commands[0].cmd.should.equal('npm');251 commandRunner.run.commands[0].args.should.eql([252 'install',253 '--registry=https://my.own-registry.com',254 ]);255 commandRunner.run.commands[1].cmd.should.equal('bower');256 commandRunner.run.commands[1].args.should.eql([257 'install',258 '--config.interactive=false',259 '--silent',260 ]);261 done();262 });263 files.forEach((file) => stream.write(file));264 stream.end();265 });266 it('should be able to any command for any file', function (done) {267 const files = [268 fixture('package.json'),269 fixture('config.js'),270 fixture('blaha.yml'),271 ];272 const stream = reinstall({273 jspm: 'install',274 blaha: ['one', 'two', '--three'],275 commands: {276 'package.json': 'yarn',277 'config.js': 'jspm',278 'blaha.yml': 'blaha',279 },280 });281 stream.on('error', (err) => {282 should.exist(err);283 done(err);284 });285 stream.on('data', () => {});286 stream.on('end', () => {287 commandRunner.run.called.should.equal(3);288 commandRunner.run.commands[0].cmd.should.equal('yarn');289 commandRunner.run.commands[0].args.should.eql([]);290 commandRunner.run.commands[1].cmd.should.equal('jspm');291 commandRunner.run.commands[1].args.should.eql(['install']);292 commandRunner.run.commands[2].cmd.should.equal('blaha');293 commandRunner.run.commands[2].args.should.eql(['one', 'two', '--three']);294 done();295 });296 files.forEach((file) => stream.write(file));297 stream.end();298 });299 it('should run `bower install --allow-root --config.interactive=false` if stream contains `bower.json`', function (done) {300 const files = [fixture('bower.json')];301 const stream = reinstall({ allowRoot: true });302 stream.on('error', (err) => {303 should.exist(err);304 done(err);305 });306 stream.on('data', () => {});307 stream.on('end', () => {308 commandRunner.run.called.should.equal(1);309 commandRunner.run.commands[0].cmd.should.equal('bower');310 commandRunner.run.commands[0].args.should.eql([311 'install',312 '--config.interactive=false',313 '--allow-root',314 ]);315 done();316 });317 files.forEach((file) => stream.write(file));318 stream.end();319 });320 it('should run `tsd reinstall --save` if stream contains `tsd.json`', function (done) {321 const file = fixture('tsd.json');322 const stream = reinstall();323 stream.on('error', (err) => {324 should.exist(err);325 done(err);326 });327 stream.on('data', () => {});328 stream.on('end', () => {329 commandRunner.run.called.should.equal(1);330 commandRunner.run.commands[0].cmd.should.equal('tsd');331 commandRunner.run.commands[0].args.should.eql(['reinstall', '--save']);332 done();333 });334 stream.write(file);335 stream.end();336 });337 it('should run `pip install -r requirements.txt` if stream contains `requirements.txt`', function (done) {338 const file = fixture('requirements.txt');339 const stream = reinstall();340 stream.on('error', (err) => {341 should.exist(err);342 done(err);343 });344 stream.on('data', () => {});345 stream.on('end', () => {346 commandRunner.run.called.should.equal(1);347 commandRunner.run.commands[0].cmd.should.equal('pip');348 commandRunner.run.commands[0].args.should.eql([349 'install',350 '-r',351 'requirements.txt',352 ]);353 done();354 });355 stream.write(file);356 stream.end();357 });358 it('should run `npm install --no-optional` if `noOptional` option is set', function (done) {359 const files = [fixture('package.json')];360 const stream = reinstall({ noOptional: true });361 stream.on('error', (err) => {362 should.exist(err);363 done(err);364 });365 stream.on('data', () => {});366 stream.on('end', () => {367 commandRunner.run.called.should.equal(1);368 commandRunner.run.commands[0].cmd.should.equal('npm');369 commandRunner.run.commands[0].args.should.eql([370 'install',371 '--no-optional',372 ]);373 done();374 });375 files.forEach((file) => stream.write(file));376 stream.end();377 });378 it('should run `npm install --dev --no-shrinkwrap` if args option is the appropriate array', function (done) {379 const files = [fixture('package.json')];380 const stream = reinstall({381 args: ['--dev', '--no-shrinkwrap'],382 });383 stream.on('error', (err) => {384 should.exist(err);385 done(err);386 });387 stream.on('data', () => {});388 stream.on('end', () => {389 commandRunner.run.called.should.equal(1);390 commandRunner.run.commands[0].cmd.should.equal('npm');391 commandRunner.run.commands[0].args.should.eql([392 'install',393 '--dev',394 '--no-shrinkwrap',395 ]);396 done();397 });398 files.forEach((file) => stream.write(file));399 stream.end();400 });401 it("should run `npm install --dev` if args option is '--dev'", function (done) {402 const files = [fixture('package.json')];403 const stream = reinstall({404 args: '--dev',405 });406 stream.on('error', (err) => {407 should.exist(err);408 done(err);409 });410 stream.on('data', () => {});411 stream.on('end', () => {412 commandRunner.run.called.should.equal(1);413 commandRunner.run.commands[0].cmd.should.equal('npm');414 commandRunner.run.commands[0].args.should.eql(['install', '--dev']);415 done();416 });417 files.forEach((file) => stream.write(file));418 stream.end();419 });420 it('should run `npm install` even if args option is in an invalid format', function (done) {421 const files = [fixture('package.json')];422 const stream = reinstall({423 args: 42,424 });425 stream.on('error', (err) => {426 should.exist(err);427 done(err);428 });429 stream.on('data', () => {});430 stream.on('end', () => {431 commandRunner.run.called.should.equal(1);432 commandRunner.run.commands[0].cmd.should.equal('npm');433 commandRunner.run.commands[0].args.should.eql(['install', '42']);434 done();435 });436 files.forEach((file) => stream.write(file));437 stream.end();438 });439 it('should set `cwd` correctly to be able to run the same command in multiple folders', function (done) {440 const files = [fixture('dir1/package.json'), fixture('dir2/package.json')];441 const stream = reinstall();442 stream.on('error', (err) => {443 should.exist(err);444 done(err);445 });446 stream.on('data', () => {});447 stream.on('end', () => {448 commandRunner.run.called.should.equal(2);449 commandRunner.run.commands[0].cmd.should.equal('npm');450 commandRunner.run.commands[0].args.should.eql(['install']);451 commandRunner.run.commands[0].cwd.should.equal(452 path.join(__dirname, 'dir1')453 );454 commandRunner.run.commands[1].cmd.should.equal('npm');455 commandRunner.run.commands[1].args.should.eql(['install']);456 commandRunner.run.commands[1].cwd.should.equal(457 path.join(__dirname, 'dir2')458 );459 done();460 });461 files.forEach((file) => stream.write(file));462 stream.end();463 });464 it('should call given callback when done', function (done) {465 const files = [fixture('package.json')];466 const stream = reinstall(() => {467 commandRunner.run.called.should.equal(1);468 commandRunner.run.commands[0].cmd.should.equal('npm');469 commandRunner.run.commands[0].args.should.eql(['install']);470 done();471 });472 stream.on('error', (err) => {473 should.exist(err);474 done(err);475 });476 stream.on('data', () => {});477 files.forEach((file) => stream.write(file));478 stream.end();479 });480 it('should allow both options and a callback', function (done) {481 const files = [fixture('package.json')];482 const stream = reinstall({ commands: { 'package.json': 'yarn' } }, () => {483 commandRunner.run.called.should.equal(1);484 commandRunner.run.commands[0].cmd.should.equal('yarn');485 commandRunner.run.commands[0].args.should.eql([]);486 done();487 });488 stream.on('error', (err) => {489 should.exist(err);490 done(err);491 });492 stream.on('data', () => {});493 files.forEach((file) => stream.write(file));494 stream.end();495 });...

Full Screen

Full Screen

unbox.js

Source:unbox.js Github

copy

Full Screen

1const assert = require("assert");2const CommandRunner = require("../commandrunner");3const MemoryLogger = require("../memorylogger");4const fs = require("fs-extra");5const tmp = require("tmp");6const path = require("path");7describe("truffle unbox [ @standalone ]", () => {8 let config;9 const logger = new MemoryLogger();10 beforeEach("set up config for logger", () => {11 tempDir = tmp.dirSync({ unsafeCleanup: true });12 config = { working_directory: tempDir.name };13 config.logger = logger;14 });15 afterEach("clear working_directory", () => {16 tempDir.removeCallback();17 });18 describe("when run without arguments", () => {19 it("unboxes truffle-init-default", done => {20 CommandRunner.run("unbox --force", config, () => {21 assert(22 fs.pathExistsSync(23 path.join(tempDir.name, "contracts", "ConvertLib.sol")24 ),25 "ConvertLib.sol does not exist"26 );27 assert(28 fs.pathExistsSync(29 path.join(tempDir.name, "contracts", "Migrations.sol")30 ),31 "Migrations.sol does not exist"32 );33 assert(34 fs.pathExistsSync(35 path.join(tempDir.name, "contracts", "MetaCoin.sol")36 ),37 "MetaCoin.sol does not exist"38 );39 done();40 });41 }).timeout(20000);42 });43 describe("when run with arguments", () => {44 describe("valid input", () => {45 describe("full url", () => {46 it("unboxes successfully", done => {47 CommandRunner.run(48 "unbox https://github.com/truffle-box/bare-box",49 config,50 () => {51 const output = logger.contents();52 assert(output.includes("Unbox successful."));53 done();54 }55 );56 }).timeout(20000);57 });58 describe("full url + branch", () => {59 it("unboxes successfully", done => {60 CommandRunner.run(61 "unbox https://github.com/truffle-box/bare-box#truffle-test-branch",62 config,63 () => {64 const output = logger.contents();65 assert(output.includes("Unbox successful."));66 done();67 }68 );69 }).timeout(20000);70 });71 describe("full url + branch + relativePath", () => {72 it("unboxes successfully", done => {73 CommandRunner.run(74 "unbox https://github.com/truffle-box/bare-box#truffle-test-branch:path/to/subDir --force",75 config,76 () => {77 const output = logger.contents();78 assert(output.includes("Unbox successful."));79 done();80 }81 );82 }).timeout(20000);83 });84 describe("origin/master", () => {85 it("unboxes successfully", done => {86 CommandRunner.run("unbox truffle-box/bare-box", config, () => {87 const output = logger.contents();88 assert(output.includes("Unbox successful."));89 done();90 });91 }).timeout(20000);92 });93 describe("origin/master#branch", () => {94 it("unboxes successfully", done => {95 CommandRunner.run(96 "unbox truffle-box/bare-box#truffle-test-branch",97 config,98 () => {99 const output = logger.contents();100 assert(output.includes("Unbox successful."));101 done();102 }103 );104 }).timeout(20000);105 });106 describe("origin/master#branch:relativePath", () => {107 it("unboxes successfully", done => {108 CommandRunner.run(109 "unbox truffle-box/bare-box#truffle-test-branch:path/to/subDir --force",110 config,111 () => {112 const output = logger.contents();113 assert(output.includes("Unbox successful."));114 done();115 }116 );117 }).timeout(20000);118 });119 describe("official truffle box", () => {120 it("unboxes successfully", done => {121 CommandRunner.run("unbox bare", config, () => {122 const output = logger.contents();123 assert(output.includes("Unbox successful."));124 done();125 });126 }).timeout(20000);127 });128 describe("official truffle-box", () => {129 it("unboxes successfully", done => {130 CommandRunner.run("unbox bare-box", config, () => {131 const output = logger.contents();132 assert(output.includes("Unbox successful."));133 done();134 });135 }).timeout(20000);136 });137 describe("official truffle box + branch", () => {138 it("unboxes successfully", done => {139 CommandRunner.run("unbox bare#truffle-test-branch", config, () => {140 const output = logger.contents();141 assert(output.includes("Unbox successful."));142 done();143 });144 }).timeout(20000);145 });146 describe("official truffle box + branch + relativePath", () => {147 it("unboxes successfully", done => {148 CommandRunner.run(149 "unbox bare#truffle-test-branch:path/to/subDir --force",150 config,151 () => {152 const output = logger.contents();153 assert(output.includes("Unbox successful."));154 done();155 }156 );157 }).timeout(20000);158 });159 describe("git@ ssh", () => {160 it("unboxes successfully", done => {161 CommandRunner.run(162 "unbox git@github.com:truffle-box/bare-box",163 config,164 () => {165 const output = logger.contents();166 assert(output.includes("Unbox successful."));167 done();168 }169 );170 }).timeout(20000);171 });172 describe("with an invalid git@ ssh", () => {173 it("logs an error", done => {174 CommandRunner.run(175 "unbox git@github.com:truffle-box/bare-boxer",176 config,177 () => {178 const output = logger.contents();179 assert(output.includes("doesn't exist."));180 done();181 }182 );183 }).timeout(20000);184 });185 describe("git@ ssh + branch", () => {186 it("unboxes successfully", done => {187 CommandRunner.run(188 "unbox git@github.com:truffle-box/bare-box#truffle-test-branch",189 config,190 () => {191 const output = logger.contents();192 assert(output.includes("Unbox successful."));193 done();194 }195 );196 }).timeout(20000);197 });198 describe("git@ ssh + branch + relativePath", () => {199 it("unboxes successfully", done => {200 CommandRunner.run(201 "unbox git@github.com:truffle-box/bare-box#truffle-test-branch:path/to/subDir --force",202 config,203 () => {204 const output = logger.contents();205 assert(output.includes("Unbox successful."));206 done();207 }208 );209 }).timeout(20000);210 });211 });212 describe("with invalid input", () => {213 describe("invalid full url", () => {214 it("throws an error", done => {215 CommandRunner.run(216 "unbox https://github.com/truffle-box/bare-boxing",217 config,218 () => {219 const output = logger.contents();220 assert(output.includes("doesn't exist."));221 done();222 }223 );224 }).timeout(20000);225 });226 describe("invalid origin/master", () => {227 it("throws an error", done => {228 CommandRunner.run("unbox truffle-box/bare-boxer", config, () => {229 const output = logger.contents();230 assert(output.includes("doesn't exist."));231 done();232 });233 }).timeout(20000);234 });235 describe("invalid official truffle box", () => {236 it("throws an error", done => {237 CommandRunner.run("unbox barer", config, () => {238 const output = logger.contents();239 assert(output.includes("doesn't exist."));240 done();241 });242 }).timeout(20000);243 });244 describe("invalid git@ ssh", () => {245 it("throws an error", done => {246 CommandRunner.run(247 "unbox git@github.com:truffle-box/bare-boxer",248 config,249 () => {250 const output = logger.contents();251 assert(output.includes("doesn't exist."));252 done();253 }254 );255 }).timeout(20000);256 });257 describe("absolutePaths", () => {258 it("throws an error", done => {259 CommandRunner.run("unbox bare:/path/to/subDir", config, () => {260 const output = logger.contents();261 assert(output.includes("not allowed!"));262 done();263 });264 }).timeout(20000);265 });266 describe("invalid box format", () => {267 it("throws an error", done => {268 CommandRunner.run("unbox /bare/", config, () => {269 const output = logger.contents();270 assert(output.includes("invalid format"));271 done();272 });273 }).timeout(20000);274 });275 });276 });277 describe("when truffle-box.json contains commands", () => {278 it("unboxes successfully and outputs commands", done => {279 CommandRunner.run("unbox bare", config, () => {280 const output = logger.contents();281 assert(output.includes("Unbox successful."));282 assert(output.includes("Test contracts:"));283 done();284 });285 }).timeout(20000);286 });...

Full Screen

Full Screen

cli-test-runner.spec.ts

Source:cli-test-runner.spec.ts Github

copy

Full Screen

1import { AlsatianCliOptions } from "../../../cli/alsatian-cli-options";2import { CliTestRunner } from "../../../cli/cli-test-runner";3import {4 Expect,5 Setup,6 SpyOn,7 Teardown,8 Test,9 TestCase,10 TestOutcome,11 TestRunner12} from "../../../core/alsatian-core";13import { TapBark } from "tap-bark";14export class CliTestRunnerTests {15 private originalTestPlan: any;16 @Setup17 private spyProcess() {18 this.originalTestPlan = Reflect.getMetadata(19 "alsatian:test-plan",20 Expect21 );22 SpyOn(TapBark.tapParser, "on").andStub();23 SpyOn(process, "exit").andStub();24 SpyOn(process.stderr, "write").andStub();25 SpyOn(process.stdout, "write").andStub();26 }27 @Teardown28 private resetProcess() {29 (process.exit as any).restore();30 (process.stdout.write as any).restore();31 (process.stderr.write as any).restore();32 (TapBark.tapParser.on as any).restore();33 Reflect.defineMetadata(34 "alsatian:test-plan",35 this.originalTestPlan,36 Expect37 );38 }39 @TestCase(null)40 @TestCase(undefined)41 public nullOrUndefinedTestRunnerThrowsError(testRunner: TestRunner) {42 Expect(() => new CliTestRunner(testRunner)).toThrowError(43 TypeError,44 "testRunner must not be null or undefined."45 );46 }47/*48 @Test()49 public async createFunction() {50 Expect(CliTestRunner.create()).toBeDefined();51 }52*/53 @Test()54 public async noTestFixturesExitsWithError() {55 const cliTestRunner = new CliTestRunner(new TestRunner());56 const cliOptions = new AlsatianCliOptions([]);57 await cliTestRunner.run(cliOptions);58 Expect(process.exit).toHaveBeenCalledWith(1);59 }60 @Test()61 public async noTestFixturesPrintsErrorMessageWithNewLine() {62 const cliTestRunner = new CliTestRunner(new TestRunner());63 const cliOptions = new AlsatianCliOptions([]);64 await cliTestRunner.run(cliOptions);65 Expect(process.stderr.write).toHaveBeenCalledWith("no tests to run.\n");66 }67 @Test()68 public async onePassingTestFixturesExitsWithNoError() {69 const testRunner = new TestRunner();70 const cliTestRunner = new CliTestRunner(testRunner);71 const testRunnerRunSpy = SpyOn(testRunner, "run");72 testRunnerRunSpy.andReturn(73 new Promise((cliResolve, cliReject) => {74 cliResolve();75 })76 );77 testRunnerRunSpy.andStub();78 const cliOptions = new AlsatianCliOptions([]);79 await cliTestRunner.run(cliOptions);80 Expect(process.exit).not.toHaveBeenCalledWith(1);81 }82 @Test()83 public async runThrowsErrorExitsWithError(outcome: TestOutcome) {84 const testRunner = new TestRunner();85 const cliTestRunner = new CliTestRunner(testRunner);86 const testRunnerRunSpy = SpyOn(testRunner, "run");87 testRunnerRunSpy.andCall(() => {88 throw new Error();89 });90 const cliOptions = new AlsatianCliOptions([]);91 await cliTestRunner.run(cliOptions);92 Expect(process.exit).toHaveBeenCalledWith(1);93 }94 @TestCase("something bad")95 @TestCase("another even worse thing")96 @TestCase("awfully terrible")97 @Test()98 public async runThrowsErrorOutputsErrorMessage(errorMessage: string) {99 const testRunner = new TestRunner();100 const cliTestRunner = new CliTestRunner(testRunner);101 const testRunnerRunSpy = SpyOn(testRunner, "run");102 testRunnerRunSpy.andCall(() => {103 throw new Error(errorMessage);104 });105 const cliOptions = new AlsatianCliOptions([]);106 await cliTestRunner.run(cliOptions);107 Expect(process.stderr.write).toHaveBeenCalledWith(errorMessage + "\n");108 }109 @Test()110 public async tapRequestedPipesOutputDirectlyToProcessStdOut() {111 const testRunner = new TestRunner();112 SpyOn(testRunner.outputStream, "pipe");113 const cliTestRunner = new CliTestRunner(testRunner);114 const testRunnerRunSpy = SpyOn(testRunner, "run");115 testRunnerRunSpy.andReturn(116 new Promise((cliResolve, cliReject) => {117 cliResolve();118 })119 );120 testRunnerRunSpy.andStub();121 const cliOptions = new AlsatianCliOptions(["--tap"]);122 await cliTestRunner.run(cliOptions);123 Expect(testRunner.outputStream.pipe).toHaveBeenCalledWith(124 process.stdout125 );126 }127 @Test()128 public async tapRequestedWithAliasPipesOutputDirectlyToProcessStdOut() {129 const testRunner = new TestRunner();130 SpyOn(testRunner.outputStream, "pipe");131 const cliTestRunner = new CliTestRunner(testRunner);132 const testRunnerRunSpy = SpyOn(testRunner, "run");133 testRunnerRunSpy.andReturn(134 new Promise((cliResolve, cliReject) => {135 cliResolve();136 })137 );138 testRunnerRunSpy.andStub();139 const cliOptions = new AlsatianCliOptions(["-T"]);140 await cliTestRunner.run(cliOptions);141 Expect(testRunner.outputStream.pipe).toHaveBeenCalledWith(142 process.stdout143 );144 }145 @Test()146 public async versionRequestedOutputsCurrentVersionNumber() {147 const testRunner = new TestRunner();148 SpyOn(testRunner.outputStream, "pipe");149 const cliTestRunner = new CliTestRunner(testRunner);150 SpyOn(testRunner, "run");151 const cliOptions = new AlsatianCliOptions(["--version"]);152 await cliTestRunner.run(cliOptions);153 const packageJson = await import("../../../package.json");154 Expect(process.stdout.write).toHaveBeenCalledWith(155 "alsatian version " + packageJson.version156 );157 }158 @Test()159 public async versionRequestedWithAliasOutputsCurrentVersionNumber() {160 const testRunner = new TestRunner();161 SpyOn(testRunner.outputStream, "pipe");162 const cliTestRunner = new CliTestRunner(testRunner);163 SpyOn(testRunner, "run");164 const cliOptions = new AlsatianCliOptions(["-v"]);165 await cliTestRunner.run(cliOptions);166 const packageJson = await import("../../../package.json");167 Expect(process.stdout.write).toHaveBeenCalledWith(168 "alsatian version " + packageJson.version169 );170 }171 @Test()172 public async versionRequestedDoesntCallTestRunnerRun() {173 const testRunner = new TestRunner();174 SpyOn(testRunner.outputStream, "pipe");175 const cliTestRunner = new CliTestRunner(testRunner);176 SpyOn(testRunner, "run");177 const cliOptions = new AlsatianCliOptions(["--version"]);178 await cliTestRunner.run(cliOptions);179 Expect(testRunner.run).not.toHaveBeenCalled();180 }181 @Test()182 public async versionRequestedWithAliasPipesOutputDirectlyToProcessStdOut() {183 const testRunner = new TestRunner();184 SpyOn(testRunner.outputStream, "pipe");185 const cliTestRunner = new CliTestRunner(testRunner);186 SpyOn(testRunner, "run");187 const cliOptions = new AlsatianCliOptions(["--version"]);188 await cliTestRunner.run(cliOptions);189 Expect(testRunner.run).not.toHaveBeenCalled();190 }191 @Test()192 public async helpRequestedOutputsCurrentVersionNumber() {193 const testRunner = new TestRunner();194 SpyOn(testRunner.outputStream, "pipe");195 const cliTestRunner = new CliTestRunner(testRunner);196 SpyOn(testRunner, "run");197 const cliOptions = new AlsatianCliOptions(["--help"]);198 await cliTestRunner.run(cliOptions);199 const packageJson = await import("../../../package.json");200 Expect(process.stdout.write).toHaveBeenCalledWith(201 "\n\n" +202 "alsatian version " +203 packageJson.version +204 "\n" +205 "=========================\n" +206 "CLI options\n" +207 "=========================\n" +208 "HELP: --help / -h " +209 "(outputs CLI information)\n" +210 "VERSION: --version / -v " +211 "(outputs the version of the CLI)\n" +212 "TAP: --tap / -T " +213 "(runs alsatian with TAP output)\n" +214 "TIMEOUT: --timeout [number] / -t [number] " +215 "(sets the timeout period for tests in milliseconds - default 500)\n" +216 "HIDE PROGRESS: --hide-progress / -H (hides progress from console)\n" +217 "\n"218 );219 }220 @Test()221 public async helpRequestedWithAliasOutputsCurrentVersionNumber() {222 const testRunner = new TestRunner();223 SpyOn(testRunner.outputStream, "pipe");224 const cliTestRunner = new CliTestRunner(testRunner);225 SpyOn(testRunner, "run");226 const cliOptions = new AlsatianCliOptions(["-h"]);227 await cliTestRunner.run(cliOptions);228 const packageJson = await import("../../../package.json");229 Expect(process.stdout.write).toHaveBeenCalledWith(230 "\n\n" +231 "alsatian version " +232 packageJson.version +233 "\n" +234 "=========================\n" +235 "CLI options\n" +236 "=========================\n" +237 "HELP: --help / -h " +238 "(outputs CLI information)\n" +239 "VERSION: --version / -v " +240 "(outputs the version of the CLI)\n" +241 "TAP: --tap / -T " +242 "(runs alsatian with TAP output)\n" +243 "TIMEOUT: --timeout [number] / -t [number] " +244 "(sets the timeout period for tests in milliseconds - default 500)\n" +245 "HIDE PROGRESS: --hide-progress / -H (hides progress from console)\n" +246 "\n"247 );248 }249 @Test()250 public async helpRequestedDoesntCallTestRunnerRun() {251 const testRunner = new TestRunner();252 SpyOn(testRunner.outputStream, "pipe");253 const cliTestRunner = new CliTestRunner(testRunner);254 SpyOn(testRunner, "run");255 const cliOptions = new AlsatianCliOptions(["--help"]);256 await cliTestRunner.run(cliOptions);257 Expect(testRunner.run).not.toHaveBeenCalled();258 }259 @Test()260 public async helpRequestedWithAliasPipesOutputDirectlyToProcessStdOut() {261 const testRunner = new TestRunner();262 SpyOn(testRunner.outputStream, "pipe");263 const cliTestRunner = new CliTestRunner(testRunner);264 SpyOn(testRunner, "run");265 const cliOptions = new AlsatianCliOptions(["-h"]);266 await cliTestRunner.run(cliOptions);267 Expect(testRunner.run).not.toHaveBeenCalled();268 }...

Full Screen

Full Screen

basics.js

Source:basics.js Github

copy

Full Screen

2const expect = require('chai').expect;3const runner = require('../../runner');4describe('basics', function() {5 it('should handle basic code evaluation', function(done) {6 runner.run({7 language: 'javascript',8 code: 'console.log(42)'9 }, function(buffer) {10 expect(buffer.stdout).to.equal('42\n');11 done();12 });13 });14 it('should handle JSON.stringify ', function(done) {15 runner.run({16 language: 'javascript',17 code: 'console.log(JSON.stringify({a: 1}))'18 }, function(buffer) {19 console.log(buffer.stderr);20 expect(buffer.stdout).to.contain('{"a":1}');21 done();22 });23 });24 it('should handle importing files from a gist', function(done) {25 runner.run({26 language: 'javascript',27 code: 'console.log(require("./gist.js").name)',28 gist: '3acc7b81436ffe4ad20800e242ccaff6'29 }, function(buffer) {30 expect(buffer.stdout).to.contain('Example Test');31 done();32 });33 });34 it('should handle unicode characters', function(done) {35 runner.run({36 language: 'javascript',37 code: 'console.log("✓")'38 }, function(buffer) {39 expect(buffer.stdout).to.include("✓");40 done();41 });42 });43 it('should be able to access solution.txt', function(done) {44 runner.run({45 language: 'javascript',46 code: `47 console.log(1+4);48 console.log(require('fs').readFileSync('/home/codewarrior/solution.txt', 'utf8'));49 `50 }, function(buffer) {51 expect(buffer.stdout).to.contain("5");52 expect(buffer.stdout).to.contain("1+4");53 done();54 });55 });56 it('should allow a shell script to be ran', function(done) {57 runner.run({58 language: 'javascript',59 bash: 'echo "test 123" >> /home/codewarrior/test.txt ; ls',60 code: `61 console.log(require('fs').readFileSync('/home/codewarrior/test.txt', 'utf8'));62 `63 }, function(buffer) {64 expect(buffer.stdout).to.contain("test 123");65 expect(buffer.shell.stdout.length).to.be.gt(0);66 done();67 });68 });69 // it('should be able to handle large output data', function (done) {70 // runner.run({71 // language: 'javascript',72 // code: `73 // for(i = 0;i < 9999; i++){74 // console.log(i * 10);75 // }76 // `77 // }, function (buffer) {78 // expect(buffer.stderr).to.equal('');79 // done();80 // });81 // });82 it('should handle es6 code evaluation', function(done) {83 runner.run({84 language: 'javascript',85 code: 'let a = 42; console.log(42);'86 }, function(buffer) {87 expect(buffer.stdout).to.equal('42\n');88 done();89 });90 });91 it('should handle bad babel syntax', function(done) {92 runner.run({93 language: 'javascript',94 languageVersion: '6.x/babel',95 code: 'var a = function(){returns 42;};\na();'96 }, function(buffer) {97 expect(buffer.stderr).to.contain('Unexpected token');98 done();99 });100 });101 it('should handle mongodb service with mongoose', function(done) {102 runner.run({103 language: 'javascript',104 services: ['mongodb'],105 code: `106 var mongoose = require('mongoose');107 mongoose.Promise = global.Promise;108 mongoose.connect('mongodb://localhost/spec');109 var Cat = mongoose.model('Cat', { name: String });110 var kitty = new Cat({ name: 'Zildjian' });111 kitty.save(function (err) {112 if (err) {113 console.log(err);114 } else {115 console.log('meow');116 }117 process.exit();118 });119 `120 }, function(buffer) {121 expect(buffer.stdout).to.contain('meow');122 expect(buffer.stderr).to.be.empty;123 done();124 });125 });126 it('should handle redis service', function(done) {127 runner.run({128 language: 'javascript',129 services: ['redis'],130 code: `131 var redis = require('redis'),132 Promise = require('bluebird');133 Promise.promisifyAll(redis.RedisClient.prototype);134 var client = redis.createClient();135 client.setAsync("foo", "bar").then(_ => {136 client.getAsync("foo").then( v => {137 console.log(v);138 process.exit();139 })140 });141 `142 }, function(buffer) {143 expect(buffer.stdout).to.contain('bar');144 done();145 });146 });147 it('should handle react syntax', function(done) {148 runner.run({149 language: 'javascript',150 languageVersion: '6.6.0/babel',151 code: `152 var React = require("react");153 var ReactDOM = require("react-dom/server");154 let render = (el) => ReactDOM.renderToStaticMarkup(el);155 var div = <div><h3>Test</h3></div>;156 console.log(render(div));157 `158 }, function(buffer) {159 expect(buffer.stdout).to.contain('<div><h3>Test</h3></div>');160 done();161 });162 });163 it('should handle react syntax using 0.10.x', function(done) {164 runner.run({165 language: 'javascript',166 languageVersion: '0.10.x/babel',167 code: `168 var React = require("react");169 var ReactDOM = require("react-dom/server");170 let render = (el) => ReactDOM.renderToStaticMarkup(el);171 var div = <div><h3>Test</h3></div>;172 console.log(render(div));173 `174 }, function(buffer) {175 expect(buffer.stdout).to.contain('<div><h3>Test</h3></div>');176 done();177 });178 });179 it('should load libraries', function(done) {180 runner.run({181 language: 'javascript',182 code: 'var _ = require("lodash");console.log(_.map([1], n => n * 2));'183 }, function(buffer) {184 expect(buffer.stdout).to.contain('[ 2 ]');185 done();186 });187 });188 it('should work with SQLite', function(done) {189 runner.run({190 language: 'javascript',191 code: `192 var sqlite3 = require('sqlite3');193 var db = new sqlite3.Database(':memory:');194 db.serialize(function() {195 db.run("CREATE TABLE lorem (info TEXT)");196 var stmt = db.prepare("INSERT INTO lorem VALUES (?)");197 for (var i = 0; i < 10; i++) {198 stmt.run("Ipsum " + i);199 }200 stmt.finalize();201 db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {202 console.log(row.id + ": " + row.info);203 });204 });205 db.close();206 `207 }, function(buffer) {208 expect(buffer.stdout).to.contain('Ipsum 0');209 expect(buffer.stdout).to.contain('Ipsum 9');210 done();211 });212 });213 it('should handle stderr', function(done) {214 runner.run({215 language: 'javascript',216 code: 'console.error("404 Not Found")'217 }, function(buffer) {218 expect(buffer.stderr).to.equal('404 Not Found\n');219 done();220 });221 });222 it('should handle stdout and stderr', function(done) {223 runner.run({224 language: 'javascript',225 code: 'console.log("stdout"); console.error("stderr")'226 }, function(buffer) {227 expect(buffer.stdout).to.equal('stdout\n');228 expect(buffer.stderr).to.equal('stderr\n');229 done();230 });231 });...

Full Screen

Full Screen

testScriptRunner.js

Source:testScriptRunner.js Github

copy

Full Screen

...3describe('ScriptRunner', function() {4 describe('Default', function(){5 it('Basic', function(){6 let runner = new ScriptRunner();7 runner.run("var ryun = 1;");8 });9 it("Can't find variable", function(){10 assert.throws(function(){11 let runner = new ScriptRunner();12 runner.run('ryun');13 }, "ryun is not defined");14 });15 });16 describe('Sandbox', function(){17 it('With sandbox', function () {18 let runner = new ScriptRunner();19 let sandbox = {};20 runner.run('var ryun = "hello";', sandbox);21 assert.equal(sandbox.ryun, 'hello');22 });23 it('With sandbox', function () {24 let result = 0;25 let sandbox = { reply: (v) => { result = v; } };26 let runner = new ScriptRunner();27 runner.run('reply("Ryun");', sandbox);28 assert.equal(result, "Ryun");29 });30 it('With sandbox2', function () {31 let runner = new ScriptRunner();32 let sandbox = {name: 'Ryunhee han'};33 runner.run('name = "Ryun";', sandbox);34 assert.equal(sandbox.name, 'Ryun');35 });36 it('Init ScriptRunner with sandbox', function(){37 let sandbox = {};38 let runner = new ScriptRunner(sandbox);39 runner.run('var ryun = "hello";');40 assert.equal(sandbox.ryun, 'hello');41 });42 it('Init ScriptRunner with sandbox2', function(){43 let sandbox = {};44 let runner = new ScriptRunner(sandbox);45 runner.run('var ryun = "hello";');46 assert.equal(sandbox.ryun, 'hello');47 runner.run('ryun = "world"');48 assert.equal(sandbox.ryun, 'world');49 });50 });51 describe('node require module', function(){52 it('require by whitelist throws error', function(){53 assert.throws(function(){54 let runner = new ScriptRunner();55 runner.setRequires([]);56 runner.run('require("util")');57 }, "You can't load unauthorized script.");58 });59 it('require by whitelist does not throws', function(){60 assert.doesNotThrow(function(){61 let runner = new ScriptRunner();62 runner.setRequires(['util']);63 runner.run('require("util");');64 });65 });66 });67 describe('throws error', function(){68 it('throw syntax error', function(){69 assert.throws(function(){70 let runner = new ScriptRunner();71 runner.run('require("util"');72 }, SyntaxError);73 });74 it('throw syntax error2', function(){75 assert.throws(function(){76 let runner = new ScriptRunner();77 runner.run('require("util")2');78 }, SyntaxError);79 });80 // // 사실상 직접적으로 테스트 할 방법이 없는걸로...81 // // https://github.com/chaijs/chai/issues/41582 // it('throws in user script callback', function(){83 // assert.doesNotThrow(function(){84 // let runner = new ScriptRunner();85 // runner.setRequires(['request']);86 // let code = `87 // var request = require("request");88 // request.get({url:'http://www.myunsay.net/sale'}, function (error, response, body) {89 // throw new Error("haha");90 // });91 // `;92 // return runner.run(code);93 // });94 // });95 });96 describe('Attack', function(){97 it('Prevent infinite loop', function(){98 assert.throws(function(){99 let runner = new ScriptRunner();100 runner.run('while(true){};');101 }, "Script execution timed out.")102 });103 it('Prevent see through require function', function(){104 let runner = new ScriptRunner();105 let sandbox = {};106 runner.run('var func = require.toString()', sandbox);107 assert.equal(sandbox.func, 'You can\'t see function code.')108 });109 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { runner } = require("qawolf");2const { chromium } = require("playwright");3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await runner.run(page, "test.json");8 await browser.close();9})();10{11 {12 },13 {14 },15 {16 },17 {18 }19}20const { runner } = require("qawolf");21const { chromium } = require("playwright");22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await runner.run(page, "test.json");27 await browser.close();28})();29const { runner } = require("qawolf");30const { chromium } = require("playwright");31(async () => {32 const browser = await chromium.launch();33 const context = await browser.newContext();34 const page = await context.newPage();35 await runner.run(page, "test.json");36 await browser.close();37})();38const { runner } = require("qawolf");39const { chromium } = require("playwright");40(async () => {41 const browser = await chromium.launch();42 const context = await browser.newContext();43 const page = await context.newPage();44 await runner.run(page, "test.json");45 await browser.close();46})();47const {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { runner } = require('qawolf');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await runner.run(page, 'test');8 await browser.close();9})();10const { runner } = require('qawolf');11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await runner.run(page, 'test');17 await browser.close();18})();19const { runner } = require('qawolf');20const { chromium } = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await runner.run(page, 'test');26 await browser.close();27})();28const { runner } = require('qawolf');29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await runner.run(page, 'test');35 await browser.close();36})();37const { runner } = require('qawolf');38const { chromium } = require('playwright');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 await runner.run(page, 'test');44 await browser.close();45})();46const { runner } = require('qawolf');47const { chromium } = require('play

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require("qawolf");2const path = require("path");3const run = async () => {4 const browser = await qawolf.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await qawolf.register(page, path.join(__dirname, "google.json"));8 await browser.close();9};10run();11const qawolf = require("qawolf");12const path = require("path");13const run = async () => {14 const browser = await qawolf.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await qawolf.register(page, path.join(__dirname, "google.json"));18 await browser.close();19};20run();21import qawolf from "qawolf";22import path from "path";23const run = async () => {24 const browser = await qawolf.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await qawolf.register(page, path.join(__dirname, "google.json"));28 await browser.close();29};30run();31import qawolf from "qawolf";32import path from "path";33const run = async () => {34 const browser = await qawolf.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 await qawolf.register(page, path.join(__dirname, "google.json"));38 await browser.close();39};40run();41const qawolf = require("qawolf");42const path = require("path");43const run = async () => {44 const browser = await qawolf.launch();45 const context = await browser.newContext();46 const page = await context.newPage();47 await qawolf.register(page,

Full Screen

Using AI Code Generation

copy

Full Screen

1const { runner } = require('qawolf');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const test = await runner.run('test.json', context);7 await browser.close();8})();9{10 {11 "code": "await page.click(\"#click\");",12 },13 {14 "code": "await page.type(\"#type\", \"test\");",15 }16}17const { runner } = require('qawolf');18const { chromium } = require('playwright');19(async () => {20 const browser = await chromium.launch({ headless: false });21 const context = await browser.newContext();22 const test = await runner.run('test.json', context);23 await browser.close();24})();25{26 {27 "code": "await page.click(\"#click\");",28 },29 {30 "code": "await page.type(\"#type\", \"test\");",31 }32}

Full Screen

Using AI Code Generation

copy

Full Screen

1const qawolf = require('qawolf');2const browser = await qawolf.launch();3await qawolf.create();4const context = await browser.newContext();5const page = await context.newPage();6await page.click('input[name="q"]');7await page.fill('input[name="q"]', 'hello world');8await page.click('text=Google Search');9await page.waitForTimeout(5000);10await qawolf.stopVideos();11await browser.close(

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const browser = await qawolf.launch();3 const context = await browser.newContext();4 const page = await context.newPage();5 await page.click('input[name="q"]');6 await page.fill('input[name="q"]', 'hello world');7 await page.press('input[name="q"]', 'Enter');8 await page.waitForSelector('.g');9 await page.click('text=Hello world - Wikipedia');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { runner } = require("qawolf");2const path = require("path");3const { chromium } = require("playwright");4const { test } = require("@playwright/test");5test("test", async ({ page }) => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 await runner.run(path.join(__dirname, "test.json"), { page });10 await browser.close();11});12{13 {14 "code": "await page.type(\\"input[name=\\"q\\"]\\", \\"hello world\\");",15 },16 {17 "code": "await page.click(\\"input[type=\\"submit\\"]\\");",18 }19}20{21 {22 "code": "await page.type(\\"input[name=\\"q\\"]\\", \\"hello world\\");",23 },24 {25 "code": "await page.click(\\"input[type=\\"submit\\"]\\");",26 }27}28{29 {30 "code": "await page.type(\\"input[name=\\"q\\"]\\", \\"hello world\\");",31 },32 {33 "code": "await page.click(\\"input[type=\\"submit\\"]\\");",34 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const runner = require('qawolf');2runner.run({3 {4 },5 {6 },7});8const runner = require('qawolf');9const { launch } = require('qawolf');10const context = await launch();11const browser = await context.newBrowser();12const page = await browser.newPage();13await runner.run({14 {15 },16 {17 },18});19await browser.close();20await context.close();21import { launch } from 'qawolf';22import runner from 'qawolf';23const context = await launch();24const browser = await context.newBrowser();25const page = await browser.newPage();26await runner.run({27 {28 },29 {30 },31});32await browser.close();33await context.close();34const runner = require('qawolf');35const { launch } = require('qawolf');36const context = await launch();37const browser = await context.newBrowser();38const page = await browser.newPage();39await runner.run({40 {41 },42 {43 },44});45await browser.close();46await context.close();

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 qawolf 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