Best JavaScript code snippet using jest
index.js
Source:index.js
...182 this.module = module;183 this.loc = loc;184 }185}186function reportError(parser, reportInvalidAs, message, loc) {187 if (reportInvalidAs === 'error') {188 parser.state.module.addError(new I18NGettextError(parser.state.module, message, loc));189 } else if (reportInvalidAs === 'warning') {190 parser.state.module.addError(new I18NGettextError(parser.state.module, message, loc));191 }192}193function pluralFactory(parser, pluralFunction, name, reportInvalidAs) {194 return (expr) => {195 if (expr.arguments.length != 0) {196 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 0 arguments', expr.loc);197 return false;198 }199 return ParserHelpers.toConstantDependency(parser, '(' + pluralFunction + ')')(expr);200 };201}202function gettext(parser, translate, name, reportInvalidAs) {203 return (expr) => {204 let singular;205 switch (expr.arguments.length) {206 case 1:207 singular = parser.evaluateExpression(expr.arguments[0]);208 if (!singular.isString()) {209 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 non-empty string literal as argument', expr.loc);210 return false;211 }212 singular = singular.string;213 if (!singular) {214 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 non-empty string literal as argument', expr.loc);215 return false;216 }217 break;218 default:219 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 non-empty string literal as argument', expr.loc);220 return false;221 }222 const result = translate(undefined, singular, undefined);223 return ParserHelpers.toConstantDependency(parser, result)(expr);224 };225}226function ngettext(parser, translate, name, reportInvalidAs) {227 return (expr) => {228 let singular;229 let plural;230 switch (expr.arguments.length) {231 case 2:232 singular = parser.evaluateExpression(expr.arguments[0]);233 if (!singular.isString()) {234 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);235 return false;236 }237 singular = singular.string;238 if (!singular) {239 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);240 return false;241 }242 plural = parser.evaluateExpression(expr.arguments[1]);243 if (!plural.isString()) {244 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);245 return false;246 }247 plural = plural.string;248 if (!plural) {249 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);250 return false;251 }252 break;253 default:254 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);255 return false;256 }257 const result = translate(undefined, singular, plural);258 return ParserHelpers.toConstantDependency(parser, result)(expr);259 };260}261function pgettext(parser, translate, name, reportInvalidAs) {262 return (expr) => {263 let context;264 let singular;265 switch (expr.arguments.length) {266 case 2:267 context = parser.evaluateExpression(expr.arguments[0]);268 if (!context.isString()) {269 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);270 return false;271 }272 context = context.string;273 if (!context) {274 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);275 return false;276 }277 singular = parser.evaluateExpression(expr.arguments[1]);278 if (!singular.isString()) {279 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);280 return false;281 }282 singular = singular.string;283 if (!singular) {284 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);285 return false;286 }287 break;288 default:289 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 non-empty string literals as argument', expr.loc);290 return false;291 }292 const result = translate(context, singular, undefined);293 return ParserHelpers.toConstantDependency(parser, result)(expr);294 };295}296function npgettext(parser, translate, name, reportInvalidAs) {297 return (expr) => {298 let context;299 let singular;300 let plural;301 switch (expr.arguments.length) {302 case 3:303 context = parser.evaluateExpression(expr.arguments[0]);304 if (!context.isString()) {305 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);306 return false;307 }308 context = context.string;309 if (!context) {310 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);311 return false;312 }313 singular = parser.evaluateExpression(expr.arguments[1]);314 if (!singular.isString()) {315 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);316 return false;317 }318 singular = singular.string;319 if (!singular) {320 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);321 return false;322 }323 plural = parser.evaluateExpression(expr.arguments[2]);324 if (!plural.isString()) {325 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);326 return false;327 }328 plural = plural.string;329 if (!plural) {330 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);331 return false;332 }333 break;334 default:335 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 3 non-empty string literals as argument', expr.loc);336 return false;337 }338 const result = translate(context, singular, plural);339 return ParserHelpers.toConstantDependency(parser, result)(expr);340 };341}342function gettextOverloadedN(parser, translate, name, reportInvalidAs) {343 return (expr) => {344 let singular;345 let plural;346 switch (expr.arguments.length) {347 case 2:348 singular = parser.evaluateExpression(expr.arguments[0]);349 if (!singular.isString()) {350 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);351 return false;352 }353 singular = singular.string;354 if (!singular) {355 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);356 return false;357 }358 plural = parser.evaluateExpression(expr.arguments[1]);359 if (!plural.isString()) {360 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);361 return false;362 }363 plural = plural.string;364 if (!plural) {365 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);366 return false;367 }368 break;369 case 1:370 singular = parser.evaluateExpression(expr.arguments[0]);371 if (!singular.isString()) {372 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);373 return false;374 }375 singular = singular.string;376 if (!singular) {377 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);378 return false;379 }380 break;381 default:382 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);383 return false;384 }385 const result = translate(undefined, singular, plural);386 return ParserHelpers.toConstantDependency(parser, result)(expr);387 };388}389function pgettextOverloadedN(parser, translate, name, reportInvalidAs) {390 return (expr) => {391 let context;392 let singular;393 let plural;394 switch (expr.arguments.length) {395 case 3:396 context = parser.evaluateExpression(expr.arguments[0]);397 if (!context.isString()) {398 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);399 return false;400 }401 context = context.string;402 if (!context) {403 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);404 return false;405 }406 singular = parser.evaluateExpression(expr.arguments[1]);407 if (!singular.isString()) {408 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);409 return false;410 }411 singular = singular.string;412 if (!singular) {413 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);414 return false;415 }416 plural = parser.evaluateExpression(expr.arguments[2]);417 if (!plural.isString()) {418 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);419 return false;420 }421 plural = plural.string;422 if (!plural) {423 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);424 return false;425 }426 break;427 case 2:428 context = parser.evaluateExpression(expr.arguments[0]);429 if (!context.isString()) {430 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);431 return false;432 }433 context = context.string;434 if (!context) {435 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);436 return false;437 }438 singular = parser.evaluateExpression(expr.arguments[1]);439 if (!singular.isString()) {440 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);441 return false;442 }443 singular = singular.string;444 if (!singular) {445 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);446 return false;447 }448 break;449 default:450 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);451 return false;452 }453 const result = translate(context, singular, plural);454 return ParserHelpers.toConstantDependency(parser, result)(expr);455 };456}457function gettextOverloadedP(parser, translate, name, reportInvalidAs) {458 return (expr) => {459 let context;460 let singular;461 switch (expr.arguments.length) {462 case 2:463 context = parser.evaluateExpression(expr.arguments[0]);464 if (!context.isString()) {465 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);466 return false;467 }468 context = context.string;469 if (!context) {470 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);471 return false;472 }473 singular = parser.evaluateExpression(expr.arguments[1]);474 if (!singular.isString()) {475 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);476 return false;477 }478 singular = singular.string;479 if (!singular) {480 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);481 return false;482 }483 break;484 case 1:485 singular = parser.evaluateExpression(expr.arguments[0]);486 if (!singular.isString()) {487 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);488 return false;489 }490 singular = singular.string;491 if (!singular) {492 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);493 return false;494 }495 break;496 default:497 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 1 or 2 non-empty string literals as argument', expr.loc);498 return false;499 }500 const result = translate(context, singular, undefined);501 return ParserHelpers.toConstantDependency(parser, result)(expr);502 };503}504function ngettextOverloadedP(parser, translate, name, reportInvalidAs) {505 return (expr) => {506 let context;507 let singular;508 let plural;509 switch (expr.arguments.length) {510 case 3:511 context = parser.evaluateExpression(expr.arguments[0]);512 if (!context.isString()) {513 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);514 return false;515 }516 context = context.string;517 if (!context) {518 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);519 return false;520 }521 singular = parser.evaluateExpression(expr.arguments[1]);522 if (!singular.isString()) {523 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);524 return false;525 }526 singular = singular.string;527 if (!singular) {528 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);529 return false;530 }531 plural = parser.evaluateExpression(expr.arguments[2]);532 if (!plural.isString()) {533 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);534 return false;535 }536 plural = plural.string;537 if (!plural) {538 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);539 return false;540 }541 break;542 case 2:543 singular = parser.evaluateExpression(expr.arguments[0]);544 if (!singular.isString()) {545 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);546 return false;547 }548 singular = singular.string;549 if (!singular) {550 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);551 return false;552 }553 plural = parser.evaluateExpression(expr.arguments[1]);554 if (!plural.isString()) {555 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);556 return false;557 }558 plural = plural.string;559 if (!plural) {560 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);561 return false;562 }563 break;564 default:565 reportError(parser, reportInvalidAs, 'The "' + name + '" function must receive 2 or 3 non-empty string literals as argument', expr.loc);566 return false;567 }568 const result = translate(context, singular, plural);569 return ParserHelpers.toConstantDependency(parser, result)(expr);570 };571}572function buidTranslationChain(transformToJS, f1, f2, f3) {573 if (f3) {574 return (context, singular, plural) => {575 let result = f1(context, singular, plural);576 if (result) {577 return transformToJS(result);578 }579 result = f2(context, singular, plural);...
node-foursquare-test.js
Source:node-foursquare-test.js
...5 config = require('./config');6log4js.configure(config.log4js);7var logger = log4js.getLogger("node-foursquare-test"),8 Foursquare = require('./../lib/node-foursquare')(config);9function reportError(test, message) {10 logger.error(test + " : \033[22;31mERROR: " + message + "\x1B[0m");11}12function ok(test) {13 logger.info(test + " : \033[22;32mOK\x1B[0m");14}15function TestSuite(accessToken) {16 var Tests = {17 "Users" : {},18 "Venues" : {},19 "Checkins" : {},20 "Tips" : {},21 "Lists" : {},22 "Updates" : {},23 "Photos" : {},24 "Settings" : {},25 "Specials" : {},26 "Events" : {}27 };28 Tests.Users.search = function() {29 var params = { "twitter": "naveen" },30 test = "Foursquare.Users.search(twitter=naveen)";31 32 Foursquare.Users.search(params, accessToken, function(error, data) {33 if(error) {34 reportError(test, error.message);35 }36 else {37 try {38 logger.trace(sys.inspect(data));39 assert.ok(data.results);40 assert.equal(data.results[0].id, "33");41 assert.equal(data.results[0].firstName, "naveen");42 ok(test);43 } catch (error) {44 reportError(test, error);45 }46 }47 });48 };49 Tests.Users.getLeaderboard = function() {50 var test = "Foursquare.Users.getLeaderboard()";51 Foursquare.Users.getLeaderboard({}, accessToken, function (error, data) {52 if(error) {53 reportError(test, error.message);54 }55 else {56 try {57 logger.trace(sys.inspect(data));58 assert.ok(data.leaderboard);59 assert.ok(data.leaderboard.count >= 0);60 assert.ok(data.leaderboard.items);61 ok(test);62 } catch (error) {63 reportError(test, error);64 }65 }66 });67 };68 Tests.Users.getUser = function() {69 var test = "Foursquare.Users.getUser(self)";70 Foursquare.Users.getUser("self", accessToken, function (error, data) {71 if(error) {72 reportError(test, error.message);73 }74 else {75 try {76 logger.trace(sys.inspect(data));77 assert.ok(data.user);78 assert.ok(data.user.id);79 assert.ok(data.user.firstName);80 ok(test);81 } catch (error) {82 reportError(test, error);83 }84 }85 });86 Foursquare.Users.getUser("33", accessToken, function (error, data) {87 var test = "Foursquare.Users.getUser(33)";88 if(error) {89 reportError(test, error.message);90 }91 else {92 try {93 logger.trace(sys.inspect(data));94 assert.ok(data.user);95 assert.equal(data.user.id, "33");96 assert.equal(data.user.firstName, "naveen");97 ok(test);98 } catch (error) {99 reportError(test, error);100 }101 }102 });103 };104 Tests.Users.getBadges = function() {105 var test = "Foursquare.Users.getBadges(self)";106 Foursquare.Users.getBadges(null, accessToken, function (error, data) {107 if(error) {108 reportError(test, error.message);109 }110 else {111 try {112 logger.trace(sys.inspect(data));113 assert.ok(data.badges);114 ok(test);115 } catch (error) {116 reportError(test, error);117 }118 }119 });120 };121 Tests.Users.getCheckins = function() {122 var test = "Foursquare.Users.getCheckins(self)";123 Foursquare.Users.getCheckins(null, null, accessToken, function (error, data) {124 if(error) {125 reportError(test, error);126 }127 else {128 try {129 logger.trace(sys.inspect(data));130 assert.ok(data.checkins);131 assert.ok(data.checkins.count >= 0);132 assert.ok(data.checkins.items);133 ok(test);134 } catch (error) {135 reportError(test, error);136 }137 }138 });139 };140 Tests.Users.getFriends = function() {141 var test = "Foursquare.Users.getFriends(self)";142 Foursquare.Users.getFriends(null, null, accessToken, function (error, data) {143 if(error) {144 reportError(test, error.message);145 }146 else {147 try {148 logger.trace(sys.inspect(data));149 assert.ok(data.friends);150 assert.ok(data.friends.count >= 0);151 assert.ok(data.friends.items);152 ok(test);153 } catch (error) {154 reportError(test, error);155 }156 }157 });158 };159 Tests.Users.getMayorships = function() {160 var test = "Foursquare.Users.getMayorships(self)";161 Foursquare.Users.getMayorships(null, null, accessToken, function (error, data) {162 if(error) {163 reportError(test, error.message);164 }165 else {166 try {167 logger.trace(sys.inspect(data));168 assert.ok(data.mayorships);169 assert.ok(data.mayorships.count >= 0);170 assert.ok(data.mayorships.items);171 ok(test);172 } catch (error) {173 reportError(test, error);174 }175 }176 });177 };178 Tests.Users.getTips = function() {179 var test = "Foursquare.Users.getTips(self)";180 Foursquare.Users.getTips(null, null, accessToken, function (error, data) {181 if(error) {182 reportError(test, error.message);183 }184 else {185 try {186 logger.trace(sys.inspect(data));187 assert.ok(data.tips);188 assert.ok(data.tips.count >= 0);189 assert.ok(data.tips.items);190 ok(test);191 } catch (error) {192 reportError(test, error);193 }194 }195 });196 };197 Tests.Users.getTodos = function() {198 var test = "Foursquare.Users.getTodos(self)";199 Foursquare.Users.getTodos(null, null, accessToken, function (error, data) {200 if(error) {201 reportError(test, error.message);202 }203 else {204 try {205 logger.trace(sys.inspect(data));206 assert.ok(data.todos);207 assert.ok(data.todos.count >= 0);208 assert.ok(data.todos.items);209 ok(test);210 } catch (error) {211 reportError(test, error);212 }213 }214 });215 };216 Tests.Users.getVenueHistory = function() {217 var test = "Foursquare.Users.getVenueHistory(self)";218 Foursquare.Users.getVenueHistory(null, null, accessToken, function (error, data) {219 if(error) {220 reportError(test, error.message);221 }222 else {223 try {224 logger.trace(sys.inspect(data));225 assert.ok(data.venues);226 assert.ok(data.venues.count >= 0);227 assert.ok(data.venues.items);228 ok(test);229 } catch (error) {230 reportError(test, error);231 }232 }233 });234 };235 Tests.Users.getRequests = function() {236 var test = "Foursquare.Users.getRequests()";237 Foursquare.Users.getRequests(accessToken, function (error, data) {238 if(error) {239 reportError(test, error.message);240 }241 else {242 try {243 logger.trace(sys.inspect(data));244 assert.ok(data.requests);245 ok(test);246 } catch (error) {247 reportError(test, error);248 }249 }250 });251 };252 Tests.Venues.search = function() {253 var test = "Foursquare.Venues.search(40.7, -74)";254 Foursquare.Venues.search("40.7", "-74", {}, accessToken, function (error, data) {255 if(error) {256 reportError(test, error);257 }258 else {259 try {260 logger.trace(sys.inspect(data));261 assert.ok(data.venues);262 ok(test);263 } catch (error) {264 reportError(test, error);265 }266 }267 });268 };269 Tests.Venues.getTrending = function() {270 var test = "Foursquare.Venues.getTrending(40.7, -74)";271 Foursquare.Venues.getTrending("40.7", "-74", {}, accessToken, function (error, data) {272 if(error) {273 reportError(test, error.message);274 }275 else {276 try {277 logger.trace(sys.inspect(data));278 assert.ok(data.venues);279 ok(test);280 } catch (error) {281 reportError(test, error);282 }283 }284 });285 };286 Tests.Venues.getCategories = function() {287 var test = "Foursquare.Venues.getCategories()";288 Foursquare.Venues.getCategories({}, accessToken, function (error, data) {289 if(error) {290 reportError(test, error.message);291 }292 else {293 try {294 logger.trace(sys.inspect(data));295 assert.ok(data.categories);296 ok(test);297 } catch (error) {298 reportError(test, error);299 }300 }301 });302 };303 Tests.Venues.explore = function() {304 var test = "Foursquare.Venues.explore(40.7, -74)";305 Foursquare.Venues.explore("40.7", "-74", {}, accessToken, function (error, data) {306 if(error) {307 reportError(test, error.message);308 }309 else {310 try {311 logger.trace(sys.inspect(data));312 assert.ok(data.keywords);313 assert.ok(data.groups);314 ok(test);315 } catch (error) {316 reportError(test, error);317 }318 }319 });320 };321 Tests.Venues.getVenue = function() {322 var test = "Foursquare.Venues.getVenue('5104')";323 Foursquare.Venues.getVenue("5104", accessToken, function (error, data) {324 if(error) {325 reportError(test, error.message);326 }327 else {328 try {329 logger.trace(sys.inspect(data));330 assert.ok(data.venue);331 assert.equal(data.venue.id, "40a55d80f964a52020f31ee3");332 ok(test);333 } catch (error) {334 reportError(test, error);335 }336 }337 });338 };339 Tests.Venues.getHereNow = function() {340 var test = "Foursquare.Venues.getHereNow('5104')";341 Foursquare.Venues.getHereNow("5104", null, accessToken, function (error, data) {342 if(error) {343 reportError(test, error.message);344 }345 else {346 try {347 logger.trace(sys.inspect(data));348 assert.ok(data.hereNow);349 assert.ok(data.hereNow.count >= 0);350 assert.ok(data.hereNow.items);351 ok(test);352 } catch (error) {353 reportError(test, error);354 }355 }356 });357 };358 Tests.Venues.getTips = function() {359 var test = "Foursquare.Venues.getTips('5104')";360 Foursquare.Venues.getTips("5104", null, accessToken, function (error, data) {361 if(error) {362 reportError(test, error.message);363 }364 else {365 try {366 logger.trace(sys.inspect(data));367 assert.ok(data.tips);368 assert.ok(data.tips.count >= 0);369 assert.ok(data.tips.items);370 ok(test);371 } catch (error) {372 reportError(test, error);373 }374 }375 });376 };377 Tests.Venues.getPhotos = function() {378 var test = "Foursquare.Venues.getPhotos('5104')";379 Foursquare.Venues.getPhotos("5104", null, null, accessToken, function (error, data) {380 if(error) {381 reportError(test, error.message);382 }383 else {384 try {385 logger.trace(sys.inspect(data));386 assert.ok(data.photos);387 assert.ok(data.photos.count >= 0);388 assert.ok(data.photos.items);389 ok(test);390 } catch (error) {391 reportError(test, error);392 }393 }394 });395 };396 Tests.Venues.getLinks = function() {397 var test = "Foursquare.Venues.getLinks('5104')";398 Foursquare.Venues.getLinks("5104", null, accessToken, function (error, data) {399 if(error) {400 reportError(test, error.message);401 }402 else {403 try {404 logger.trace(sys.inspect(data));405 assert.ok(data.links);406 assert.ok(data.links.count >= 0);407 assert.ok(data.links.items);408 ok(test);409 } catch (error) {410 reportError(test, error);411 }412 }413 });414 };415 Tests.Checkins.getCheckin = function() {416 var test = "Foursquare.Checkins.getCheckin(4dae3f9e4df0f639f248ca13)";417 Foursquare.Checkins.getCheckin("4dae3f9e4df0f639f248ca13", null, accessToken, function (error, data) {418 if(error) {419 reportError(test, error.message);420 }421 else {422 try {423 logger.trace(sys.inspect(data));424 assert.ok(data.checkin);425 assert.equal(data.checkin.id, "4dae3f9e4df0f639f248ca13");426 assert.equal(data.checkin.type, "checkin");427 ok(test);428 } catch (error) {429 reportError(test, error);430 }431 }432 });433 };434 Tests.Checkins.getRecentCheckins = function() {435 var test = "Foursquare.Checkins.getRecentCheckins()";436 Foursquare.Checkins.getRecentCheckins(null, accessToken, function (error, data) {437 if(error) {438 reportError(test, error.message);439 }440 else {441 try {442 logger.trace(sys.inspect(data));443 assert.ok(data.recent);444 ok(test);445 } catch (error) {446 reportError(test, error);447 }448 }449 });450 };451 Tests.Tips.getTip = function() {452 var test = "Foursquare.Tips.getTip(4b5e662a70c603bba7d790b4)";453 Foursquare.Tips.getTip("4b5e662a70c603bba7d790b4", accessToken, function (error, data) {454 if(error) {455 reportError(test, error.message);456 }457 else {458 try {459 logger.trace(sys.inspect(data));460 assert.ok(data.tip);461 assert.equal(data.tip.id, "4b5e662a70c603bba7d790b4");462 ok(test);463 } catch (error) {464 reportError(test, error);465 }466 }467 });468 };469 Tests.Lists.getList = function() {470 var test = "Foursquare.Lists.getList(4e4e804fd22daf51d267e1dd)";471 Foursquare.Lists.getList("4e4e804fd22daf51d267e1dd", accessToken, function (error, data) {472 if(error) {473 reportError(test, error.message);474 }475 else {476 try {477 logger.trace(sys.inspect(data));478 assert.ok(data.list);479 assert.equal(data.list.id, "4e4e804fd22daf51d267e1dd");480 ok(test);481 } catch (error) {482 reportError(test, error);483 }484 }485 });486 };487 Tests.Lists.getFollowers = function() {488 var test = "Foursquare.Lists.getFollowers(4e4e804fd22daf51d267e1dd)";489 Foursquare.Lists.getFollowers("4e4e804fd22daf51d267e1dd", accessToken, function (error, data) {490 if(error) {491 reportError(test, error.message);492 }493 else {494 try {495 logger.trace(sys.inspect(data));496 assert.ok(data.count);497 assert.ok(data.followers);498 ok(test);499 } catch (error) {500 reportError(test, error);501 }502 }503 });504 };505 Tests.Lists.getSuggestedVenues = function() {506 var test = "Foursquare.Lists.getSuggestedVenues(4e4e804fd22daf51d267e1dd)";507 Foursquare.Lists.getSuggestedVenues("4e4e804fd22daf51d267e1dd", accessToken, function (error, data) {508 if(error) {509 reportError(test, error.message);510 }511 else {512 try {513 logger.trace(sys.inspect(data));514 // TODO: This is a bug in 4sq; docs say the field should be "suggestedVenues".515 assert.ok(data.similarVenues);516 ok(test);517 } catch (error) {518 reportError(test, error);519 }520 }521 });522 };523 Tests.Lists.getSuggestedPhotos = function() {524 var test = "Foursquare.Lists.getSuggestedPhotos(4e4e804fd22daf51d267e1dd, v4bc49ceff8219c74ea97b710)";525 Foursquare.Lists.getSuggestedPhotos("4e4e804fd22daf51d267e1dd", "v4bc49ceff8219c74ea97b710", accessToken, function (error, data) {526 if(error) {527 reportError(test, error.message);528 }529 else {530 try {531 logger.trace(sys.inspect(data));532 assert.ok(data.photos);533 assert.ok(data.photos.user);534 assert.ok(data.photos.user.count);535 assert.ok(data.photos.user.items);536 assert.ok(data.photos.others);537 assert.ok(data.photos.others.count);538 assert.ok(data.photos.others.items);539 ok(test);540 } catch (error) {541 reportError(test, error);542 }543 }544 });545 };546 Tests.Lists.getSuggestedTips = function() {547 var test = "Foursquare.Lists.getSuggestedTips(4e4e804fd22daf51d267e1dd, v4bc49ceff8219c74ea97b710)";548 Foursquare.Lists.getSuggestedPhotos("4e4e804fd22daf51d267e1dd", "v4bc49ceff8219c74ea97b710", accessToken, function (error, data) {549 if(error) {550 reportError(test, error.message);551 }552 else {553 try {554 logger.trace(sys.inspect(data));555 assert.ok(data.photos);556 assert.ok(data.photos.user);557 assert.ok(data.photos.user.count);558 assert.ok(data.photos.user.items);559 assert.ok(data.photos.others);560 assert.ok(data.photos.others.count);561 assert.ok(data.photos.others.items);562 ok(test);563 } catch (error) {564 reportError(test, error);565 }566 }567 });568 };569 Tests.Updates.getUpdate = function() {570 var test = "Foursquare.Updates.getUpdate(4e4ad999ac6317362bd6b320)";571 Foursquare.Updates.getUpdate("4e4ad999ac6317362bd6b320", accessToken, function (error, data) {572 if(error) {573 reportError(test, error.message);574 }575 else {576 try {577 logger.trace(sys.inspect(data));578 assert.ok(data.notification);579 ok(test);580 } catch (error) {581 reportError(test, error);582 }583 }584 });585 };586 Tests.Updates.getNotifications = function() {587 var test = "Foursquare.Updates.getNotifications()";588 Foursquare.Updates.getNotifications({}, accessToken, function (error, data) {589 if(error) {590 reportError(test, error.message);591 }592 else {593 try {594 logger.trace(sys.inspect(data));595 assert.ok(data.notifications);596 assert.ok(data.notifications.count >= 0);597 assert.ok(data.notifications.items);598 ok(test);599 } catch (error) {600 reportError(test, error);601 }602 }603 });604 };605 Tests.Tips.search = function() {606 var test = "Foursquare.Tips.search(lat: 40.7, lng: -74)";607 Foursquare.Tips.search("40.7", "-74", null, accessToken, function (error, data) {608 if(error) {609 reportError(test, error.message);610 }611 else {612 try {613 logger.trace(sys.inspect(data));614 assert.ok(data.tips);615 ok(test);616 } catch (error) {617 reportError(test, error);618 }619 }620 });621 };622 Tests.Photos.getPhoto = function() {623 var test = "Foursquare.Photos.getPhoto(4d0fb8162d39a340637dc42b)";624 Foursquare.Photos.getPhoto("4d0fb8162d39a340637dc42b", accessToken, function (error, data) {625 if(error) {626 reportError(test, error.message);627 }628 else {629 try {630 logger.trace(sys.inspect(data));631 assert.ok(data.photo);632 assert.equal(data.photo.id, "4d0fb8162d39a340637dc42b");633 ok(test);634 } catch (error) {635 reportError(test, error);636 }637 }638 });639 };640 Tests.Settings.getSettings = function() {641 var test = "Foursquare.Settings.getSettings()";642 Foursquare.Settings.getSettings(accessToken, function (error, data) {643 if(error) {644 reportError(test, error.message);645 }646 else {647 try {648 logger.trace(sys.inspect(data));649 assert.ok(data.settings);650 ok(test);651 } catch (error) {652 reportError(test, error);653 }654 }655 });656 };657 Tests.Settings.getSetting = function() {658 var test = "Foursquare.Settings.getSetting('receivePings')";659 Foursquare.Settings.getSetting("receivePings", accessToken, function (error, data) {660 if(error) {661 reportError(test, error.message);662 }663 else {664 try {665 logger.trace(sys.inspect(data));666 assert.ok(typeof data.value !== "undefined");667 ok(test);668 } catch (error) {669 reportError(test, error);670 }671 }672 });673 };674 Tests.Specials.search = function() {675 var test = "Foursquare.Specials.search(40.7, -74)";676 Foursquare.Specials.search("40.7", "-74", {}, accessToken, function (error, data) {677 if(error) {678 reportError(test, error.message);679 }680 else {681 try {682 logger.trace(sys.inspect(data));683 assert.ok(data.specials);684 assert.ok(data.specials.count >= 0);685 assert.ok(data.specials.items);686 ok(test);687 } catch (error) {688 reportError(test, error);689 }690 }691 });692 };693 Tests.Events.getEvent = function() {694 var test = "Foursquare.Events.getEvent(4e173d2cbd412187aabb3c04)";695 Foursquare.Events.getEvent("4e173d2cbd412187aabb3c04", accessToken, function (error, data) {696 if(error) {697 reportError(test, error.message);698 }699 else {700 try {701 logger.trace(sys.inspect(data));702 assert.ok(data.event);703 assert.ok(data.event.id == "4e173d2cbd412187aabb3c04");704 ok(test);705 } catch (error) {706 reportError(test, error);707 }708 }709 });710 };711 Tests.Events.getCategories = function() {712 var test = "Foursquare.Events.getCategories()";713 Foursquare.Events.getCategories(null, accessToken, function (error, data) {714 if(error) {715 reportError(test, error.message);716 }717 else {718 try {719 logger.trace(sys.inspect(data));720 assert.ok(data.categories);721 assert.ok(data.categories.length > 0);722 ok(test);723 } catch (error) {724 reportError(test, error);725 }726 }727 });728 };729 Tests.Events.search = function() {730 var test = "Foursquare.Events.search()";731 Foursquare.Events.search({}, accessToken, function (error, data) {732 if(error) {733 reportError(test, error.message);734 }735 else {736 try {737 logger.trace(sys.inspect(data));738 assert.ok(data.specials);739 assert.ok(data.specials.count >= 0);740 assert.ok(data.specials.items);741 ok(test);742 } catch (error) {743 reportError(test, error);744 }745 }746 });747 };748 return {749 "Tests" : Tests,750 "execute" : function(testGroup, testName) {751 for(var group in Tests) {752 if(!testGroup || (testGroup && testGroup == group)) {753 for(var test in Tests[group]) {754 if(!testName ||(testName && testName == test)) {755 var t = Tests[group][test];756 if(t && typeof(t) == "function") {757 logger.debug("Running: " + test);758 t.call(this);759 }760 }761 }762 }763 }764 }765 }766}767function testDeprecated() {768 var depConfig = require("./config").config;769 depConfig.foursquare.version = "20110101";770 depConfig.log4js.levels["node-foursquare"] = "INFO";771 depConfig.log4js.levels["node-foursquare.core"] = "WARN";772 depConfig.foursquare.warnings = "WARN";773 774 var depFoursquare = Foursquare = require('./../lib/node-foursquare')(depConfig),775 test = "(Version 20110101, WARN) Foursquare.Venues.search(40.7, -74)";776 function run(error, data) {777 if(error) {778 reportError(test, error);779 }780 else {781 try {782 logger.trace(sys.inspect(data));783 assert.ok(data.groups);784 ok(test);785 } catch (error) {786 reportError(test, error);787 }788 }789 }790 depFoursquare.Venues.search("40.7", "-74", {}, null, function(error, data) {791 run(error, data);792 test = "(Version 20110101, ERROR) Foursquare.Venues.search(40.7, -74)",793 depConfig.foursquare.warnings = "ERROR";794 depFoursquare.Venues.search("40.7", "-74", {}, null, function(error, data) {795 run(error, data);796 });797 });798}799// Using express was just faster... *sigh*800var app = express.createServer();...
validate.js
Source:validate.js
...46 constructor(schema) {47 this._errors = [];48 this.schema = schema;49 }50 reportError(message, nodes) {51 const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes;52 this.addError(new GraphQLError(message, _nodes));53 }54 addError(error) {55 this._errors.push(error);56 }57 getErrors() {58 return this._errors;59 }60}61function validateRootTypes(context) {62 const schema = context.schema;63 const queryType = schema.getQueryType();64 if (!queryType) {65 context.reportError('Query root type must be provided.', schema.astNode);66 } else if (!isObjectType(queryType)) {67 context.reportError(`Query root type must be Object type, it cannot be ${inspect(queryType)}.`, getOperationTypeNode(schema, queryType, 'query'));68 }69 const mutationType = schema.getMutationType();70 if (mutationType && !isObjectType(mutationType)) {71 context.reportError('Mutation root type must be Object type if provided, it cannot be ' + `${inspect(mutationType)}.`, getOperationTypeNode(schema, mutationType, 'mutation'));72 }73 const subscriptionType = schema.getSubscriptionType();74 if (subscriptionType && !isObjectType(subscriptionType)) {75 context.reportError('Subscription root type must be Object type if provided, it cannot be ' + `${inspect(subscriptionType)}.`, getOperationTypeNode(schema, subscriptionType, 'subscription'));76 }77}78function getOperationTypeNode(schema, type, operation) {79 const operationNodes = getAllSubNodes(schema, node => node.operationTypes);80 for (const node of operationNodes) {81 if (node.operation === operation) {82 return node.type;83 }84 }85 return type.astNode;86}87function validateDirectives(context) {88 for (const directive of context.schema.getDirectives()) {89 // Ensure all directives are in fact GraphQL directives.90 if (!isDirective(directive)) {91 context.reportError(`Expected directive but got: ${inspect(directive)}.`, directive?.astNode);92 continue;93 } // Ensure they are named correctly.94 validateName(context, directive); // TODO: Ensure proper locations.95 // Ensure the arguments are valid.96 for (const arg of directive.args) {97 // Ensure they are named correctly.98 validateName(context, arg); // Ensure the type is an input type.99 if (!isInputType(arg.type)) {100 context.reportError(`The type of @${directive.name}(${arg.name}:) must be Input Type ` + `but got: ${inspect(arg.type)}.`, arg.astNode);101 }102 }103 }104}105function validateName(context, node) {106 // Ensure names are valid, however introspection types opt out.107 const error = isValidNameError(node.name);108 if (error) {109 context.addError(locatedError(error, node.astNode));110 }111}112function validateTypes(context) {113 const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context);114 const typeMap = context.schema.getTypeMap();115 for (const type of objectValues(typeMap)) {116 // Ensure all provided types are in fact GraphQL type.117 if (!isNamedType(type)) {118 context.reportError(`Expected GraphQL named type but got: ${inspect(type)}.`, type.astNode);119 continue;120 } // Ensure it is named correctly (excluding introspection types).121 if (!isIntrospectionType(type)) {122 validateName(context, type);123 }124 if (isObjectType(type)) {125 // Ensure fields are valid126 validateFields(context, type); // Ensure objects implement the interfaces they claim to.127 validateInterfaces(context, type);128 } else if (isInterfaceType(type)) {129 // Ensure fields are valid.130 validateFields(context, type); // Ensure interfaces implement the interfaces they claim to.131 validateInterfaces(context, type);132 } else if (isUnionType(type)) {133 // Ensure Unions include valid member types.134 validateUnionMembers(context, type);135 } else if (isEnumType(type)) {136 // Ensure Enums have valid values.137 validateEnumValues(context, type);138 } else if (isInputObjectType(type)) {139 // Ensure Input Object fields are valid.140 validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references141 validateInputObjectCircularRefs(type);142 }143 }144}145function validateFields(context, type) {146 const fields = objectValues(type.getFields()); // Objects and Interfaces both must define one or more fields.147 if (fields.length === 0) {148 context.reportError(`Type ${type.name} must define one or more fields.`, getAllNodes(type));149 }150 for (const field of fields) {151 // Ensure they are named correctly.152 validateName(context, field); // Ensure the type is an output type153 if (!isOutputType(field.type)) {154 context.reportError(`The type of ${type.name}.${field.name} must be Output Type ` + `but got: ${inspect(field.type)}.`, field.astNode?.type);155 } // Ensure the arguments are valid156 for (const arg of field.args) {157 const argName = arg.name; // Ensure they are named correctly.158 validateName(context, arg); // Ensure the type is an input type159 if (!isInputType(arg.type)) {160 context.reportError(`The type of ${type.name}.${field.name}(${argName}:) must be Input ` + `Type but got: ${inspect(arg.type)}.`, arg.astNode?.type);161 }162 }163 }164}165function validateInterfaces(context, type) {166 const ifaceTypeNames = Object.create(null);167 for (const iface of type.getInterfaces()) {168 if (!isInterfaceType(iface)) {169 context.reportError(`Type ${inspect(type)} must only implement Interface types, ` + `it cannot implement ${inspect(iface)}.`, getAllImplementsInterfaceNodes(type, iface));170 continue;171 }172 if (type === iface) {173 context.reportError(`Type ${type.name} cannot implement itself because it would create a circular reference.`, getAllImplementsInterfaceNodes(type, iface));174 continue;175 }176 if (ifaceTypeNames[iface.name]) {177 context.reportError(`Type ${type.name} can only implement ${iface.name} once.`, getAllImplementsInterfaceNodes(type, iface));178 continue;179 }180 ifaceTypeNames[iface.name] = true;181 validateTypeImplementsAncestors(context, type, iface);182 validateTypeImplementsInterface(context, type, iface);183 }184}185function validateTypeImplementsInterface(context, type, iface) {186 const typeFieldMap = type.getFields(); // Assert each interface field is implemented.187 for (const ifaceField of objectValues(iface.getFields())) {188 const fieldName = ifaceField.name;189 const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type.190 if (!typeField) {191 context.reportError(`Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, [ifaceField.astNode, ...getAllNodes(type)]);192 continue;193 } // Assert interface field type is satisfied by type field type, by being194 // a valid subtype. (covariant)195 if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) {196 context.reportError(`Interface field ${iface.name}.${fieldName} expects type ` + `${inspect(ifaceField.type)} but ${type.name}.${fieldName} ` + `is type ${inspect(typeField.type)}.`, [ifaceField.astNode.type, typeField.astNode.type]);197 } // Assert each interface field arg is implemented.198 for (const ifaceArg of ifaceField.args) {199 const argName = ifaceArg.name;200 const typeArg = find(typeField.args, arg => arg.name === argName); // Assert interface field arg exists on object field.201 if (!typeArg) {202 context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, [ifaceArg.astNode, typeField.astNode]);203 continue;204 } // Assert interface field arg type matches object field arg type.205 // (invariant)206 // TODO: change to contravariant?207 if (!isEqualType(ifaceArg.type, typeArg.type)) {208 context.reportError(`Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + `expects type ${inspect(ifaceArg.type)} but ` + `${type.name}.${fieldName}(${argName}:) is type ` + `${inspect(typeArg.type)}.`, [ifaceArg.astNode.type, typeArg.astNode.type]);209 } // TODO: validate default values?210 } // Assert additional arguments must not be required.211 for (const typeArg of typeField.args) {212 const argName = typeArg.name;213 const ifaceArg = find(ifaceField.args, arg => arg.name === argName);214 if (!ifaceArg && isRequiredArgument(typeArg)) {215 context.reportError(`Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, [typeArg.astNode, ifaceField.astNode]);216 }217 }218 }219}220function validateTypeImplementsAncestors(context, type, iface) {221 const ifaceInterfaces = type.getInterfaces();222 for (const transitive of iface.getInterfaces()) {223 if (ifaceInterfaces.indexOf(transitive) === -1) {224 context.reportError(transitive === type ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, [...getAllImplementsInterfaceNodes(iface, transitive), ...getAllImplementsInterfaceNodes(type, iface)]);225 }226 }227}228function validateUnionMembers(context, union) {229 const memberTypes = union.getTypes();230 if (memberTypes.length === 0) {231 context.reportError(`Union type ${union.name} must define one or more member types.`, getAllNodes(union));232 }233 const includedTypeNames = Object.create(null);234 for (const memberType of memberTypes) {235 if (includedTypeNames[memberType.name]) {236 context.reportError(`Union type ${union.name} can only include type ${memberType.name} once.`, getUnionMemberTypeNodes(union, memberType.name));237 continue;238 }239 includedTypeNames[memberType.name] = true;240 if (!isObjectType(memberType)) {241 context.reportError(`Union type ${union.name} can only include Object types, ` + `it cannot include ${inspect(memberType)}.`, getUnionMemberTypeNodes(union, String(memberType)));242 }243 }244}245function validateEnumValues(context, enumType) {246 const enumValues = enumType.getValues();247 if (enumValues.length === 0) {248 context.reportError(`Enum type ${enumType.name} must define one or more values.`, getAllNodes(enumType));249 }250 for (const enumValue of enumValues) {251 const valueName = enumValue.name; // Ensure valid name.252 validateName(context, enumValue);253 if (valueName === 'true' || valueName === 'false' || valueName === 'null') {254 context.reportError(`Enum type ${enumType.name} cannot include value: ${valueName}.`, enumValue.astNode);255 }256 }257}258function validateInputFields(context, inputObj) {259 const fields = objectValues(inputObj.getFields());260 if (fields.length === 0) {261 context.reportError(`Input Object type ${inputObj.name} must define one or more fields.`, getAllNodes(inputObj));262 } // Ensure the arguments are valid263 for (const field of fields) {264 // Ensure they are named correctly.265 validateName(context, field); // Ensure the type is an input type266 if (!isInputType(field.type)) {267 context.reportError(`The type of ${inputObj.name}.${field.name} must be Input Type ` + `but got: ${inspect(field.type)}.`, field.astNode?.type);268 }269 }270}271function createInputObjectCircularRefsValidator(context) {272 // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js.js'.273 // Tracks already visited types to maintain O(N) and to ensure that cycles274 // are not redundantly reported.275 const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors276 const fieldPath = []; // Position in the type path277 const fieldPathIndexByTypeName = Object.create(null);278 return detectCycleRecursive; // This does a straight-forward DFS to find cycles.279 // It does not terminate when a cycle was found but continues to explore280 // the graph to find all possible cycles.281 function detectCycleRecursive(inputObj) {282 if (visitedTypes[inputObj.name]) {283 return;284 }285 visitedTypes[inputObj.name] = true;286 fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;287 const fields = objectValues(inputObj.getFields());288 for (const field of fields) {289 if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) {290 const fieldType = field.type.ofType;291 const cycleIndex = fieldPathIndexByTypeName[fieldType.name];292 fieldPath.push(field);293 if (cycleIndex === undefined) {294 detectCycleRecursive(fieldType);295 } else {296 const cyclePath = fieldPath.slice(cycleIndex);297 const pathStr = cyclePath.map(fieldObj => fieldObj.name).join('.');298 context.reportError(`Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, cyclePath.map(fieldObj => fieldObj.astNode));299 }300 fieldPath.pop();301 }302 }303 fieldPathIndexByTypeName[inputObj.name] = undefined;304 }305}306function getAllNodes(object) {307 const {308 astNode,309 extensionASTNodes310 } = object;311 return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes ?? [];312}...
testUtil.js
Source:testUtil.js
...57 if (this.testRun.resultSet) {58 return;59 }60 if (this.obj != expected) {61 self.reportError(this.testRun, "should be: '" + expected + "', was: '" + this.obj + "'");62 }63 };64 Value.prototype.shouldBeEqual = Value.prototype.shouldBe;65 Value.prototype.shouldNotBe = function(expected) {66 if (this.testRun.resultSet) {67 return;68 }69 if (this.obj == expected) {70 self.reportError(this.testRun, "should not be: '" + expected + "', was: '" + this.obj + "'");71 }72 };73 Value.prototype.shouldNotBeEqual = Value.prototype.shouldNotBe;74 Value.prototype.shouldNotBeNull = function() {75 if (this.testRun.resultSet) {76 return;77 }78 if (this.obj === null) {79 self.reportError(this.testRun, "should not be null, was: " + this.obj);80 }81 };82 Value.prototype.shouldNotBeUndefined = function() {83 if (this.testRun.resultSet) {84 return;85 }86 if ((typeof this.obj) === "undefined") {87 self.reportError(this.testRun, "should not be undefined, was: " + (typeof this.obj));88 }89 };90 Value.prototype.shouldBeExactly = function(expected) {91 if (this.testRun.resultSet) {92 return;93 }94 if (this.obj !== expected) {95 self.reportError(this.testRun, "should be exactly: " + expected + ", was: " + this.obj);96 }97 };98 Value.prototype.shouldNotBeExactly = function(expected) {99 if (this.testRun.resultSet) {100 return;101 }102 if (this.obj === expected) {103 self.reportError(this.testRun, "should not be exactly: " + expected + ", was: " + this.obj);104 }105 };106 Value.prototype.shouldBeNull = function() {107 if (this.testRun.resultSet) {108 return;109 }110 if (this.obj !== null) {111 self.reportError(this.testRun, "should be null, was: " + this.obj);112 }113 };114 Value.prototype.shouldBeString = function() {115 if (this.testRun.resultSet) {116 return;117 }118 if ((typeof this.obj) !== "string") {119 self.reportError(this.testRun, "should be string, was: " + (typeof this.obj));120 }121 };122 Value.prototype.shouldBeUndefined = function() {123 if (this.testRun.resultSet) {124 return;125 }126 if ((typeof this.obj) !== "undefined") {127 self.reportError(this.testRun, "should be undefined, was: " + (typeof this.obj));128 }129 };130 Value.prototype.shouldBeFunction = function() {131 if (this.testRun.resultSet) {132 return;133 }134 if (((typeof this.obj) != "function") && !(this.obj instanceof Function)) {135 self.reportError(this.testRun, "should be a function, was: " + (typeof this.obj));136 }137 };138 Value.prototype.shouldBeObject = function() {139 if (this.testRun.resultSet) {140 return;141 }142 if (((typeof this.obj) != "object") && !(this.obj instanceof Object)) {143 self.reportError(this.testRun, "should be a object, was: " + (typeof this.obj));144 }145 };146 Value.prototype.shouldBeNumber = function() {147 if (this.testRun.resultSet) {148 return;149 }150 if ((typeof this.obj) != "number") {151 self.reportError(this.testRun, "should be a number, was: " + (typeof this.obj));152 }153 };154 Value.prototype.shouldBeBoolean = function() {155 if (this.testRun.resultSet) {156 return;157 }158 if ((typeof this.obj) != "boolean") {159 self.reportError(this.testRun, "should be a boolean, was: " + (typeof this.obj));160 }161 };162 Value.prototype.shouldBeTrue = function() {163 if (this.testRun.resultSet) {164 return;165 }166 if (this.obj !== true) {167 self.reportError(this.testRun, "should be true, was: " + this.obj);168 }169 };170 Value.prototype.shouldBeFalse = function() {171 if (this.testRun.resultSet) {172 return;173 }174 if (this.obj !== false) {175 self.reportError(this.testRun, "should be false, was: " + this.obj);176 }177 };178 Value.prototype.shouldBeZero = function() {179 if (this.testRun.resultSet) {180 return;181 }182 if (this.obj !== 0) {183 self.reportError(this.testRun, "should be 0 (zero), was: " + this.obj + " (" + typeof(this.obj) + ")");184 }185 };186 Value.prototype.shouldBeArray = function() {187 if (this.testRun.resultSet) {188 return;189 }190 var typeDescription = Object.prototype.toString.call(this.obj);191 if (typeDescription != "[object Array]") {192 self.reportError(this.testRun, "should be an array, was: " + typeDescription);193 }194 };195 // This function is required for Tizen's browser which does not support196 // indexOf for arrays.197 Value.prototype.shouldContainDeprecated = function(expected) {198 if (this.testRun.resultSet) {199 return;200 }201 for (var i = 0, len = this.obj.length; i < len; i++) {202 if (expected === this.obj[i]) {203 return;204 }205 }206 self.reportError(this.testRun, "should contain: " + expected + ", was: " + this.obj);207 }208 Value.prototype.shouldContain = function(expected) {209 if (this.testRun.resultSet) {210 return;211 }212 if (this.obj.indexOf(expected) == -1) {213 self.reportError(this.testRun, "should contain: " + expected + ", was: " + this.obj);214 }215 };216 Value.prototype.shouldBeOneOf = function(expected) {217 if (this.testRun.resultSet) {218 return;219 }220 if (expected.indexOf(this.obj) == -1) {221 self.reportError(this.testRun, "should contain one of: [" + expected.join(",") + "] was: " + this.obj);222 }223 };224 Value.prototype.shouldMatchArray = function(expected) {225 if (this.testRun.resultSet) {226 return;227 }228 if (this.obj.length && expected.length && this.obj.length == expected.length) {229 for (var i = 0; i < expected.length; i++) {230 if (expected[i] != this.obj[i]) {231 self.reportError(this.testRun, "element " + i + " should be: " + expected[i] + " was: " + this.obj[i]);232 }233 }234 } else {235 self.reportError(this.testRun, "array lengths differ, expected: " + expected + ", was: " + this.obj);236 }237 };238 Value.prototype.shouldBeGreaterThan = function(expected) {239 if (this.testRun.resultSet) {240 return;241 }242 if (this.obj <= expected) {243 self.reportError(this.testRun, "should be greater than, was " + this.obj + " <= " + expected);244 }245 };246 Value.prototype.shouldBeLessThan = function(expected) {247 if (this.testRun.resultSet) {248 return;249 }250 if (this.obj >= expected) {251 self.reportError(this.testRun, "should be less than, was " + this.obj + " >= " + expected);252 }253 };254 Value.prototype.shouldBeGreaterThanEqual = function(expected) {255 if (this.testRun.resultSet) {256 return;257 }258 if (this.obj < expected) {259 self.reportError(this.testRun, "should be greater than equal, was " + this.obj + " < " + expected);260 }261 };262 Value.prototype.shouldBeLessThanEqual = function(expected) {263 if (this.testRun.resultSet) {264 return;265 }266 if (this.obj > expected) {267 self.reportError(this.testRun, "should be greater than, was " + this.obj + " > " + expected);268 }269 };270 Value.prototype.shouldThrowException = function() {271 if (this.testRun.resultSet) {272 return;273 }274 if ((typeof this.obj) == "function") {275 try {276 this.obj();277 } catch (e) {278 return;279 }280 self.reportError(this.testRun, "should throw exception, but didn't");281 } else {282 self.reportError(this.testRun, "should throw exception, but target isn't a function");283 }284 };285 Value.prototype.shouldNotThrowException = function() {286 if (this.testRun.resultSet) {287 return;288 }289 if ((typeof this.obj) == "function") {290 try {291 this.obj();292 } catch (e) { 293 self.reportError(this.testRun, "should not throw exception, but did. Exception: " + e.message);294 }295 } else {296 self.reportError(this.testRun, "should not throw exception, but target isn't a function");297 }298 };...
LoggingTest.js
Source:LoggingTest.js
1/*2 * Copyright (C) 2013 salesforce.com, inc.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16Function.RegisterNamespace("Test.Aura");17[Fixture]18Test.Aura.LoggingTest = function() {19 var subscribe = Stubs.GetMethod("name", "fn");20 var eventHandler;21 var theWindow = {22 addEventListener: function(eventname, handler) { eventHandler = handler; }23 };24 Mocks.GetMocks(Object.Global(), {25 "$A" : {26 "logger": {27 "subscribe" : subscribe28 },29 },30 "window":theWindow31 })(function(){32 [Import("aura-impl/src/main/resources/aura/Logging.js")]33 });34 [Fixture]35 function initialization() {36 [Fact]37 function OnErrorIsSet() {38 Assert.NotNull(theWindow.onerror);39 }40 [Fact]41 function SubscribeCallsAreAsExpected() {42 Assert.Equal(5, subscribe.Calls.length);43 }44 }45 [Fixture]46 function onerror() {47 [Fact]48 function OnErrorCallsReportErrorWithBareMessage() {49 var reportError = Stubs.GetMethod("message", "err", true);50 var message = "message";51 var expectedMessage = message;52 var expectedError = "error";53 Mocks.GetMocks(Object.Global(), {54 "$A": {55 "reportError":reportError56 }57 })(function() {58 theWindow.onerror(message, null, null, null, expectedError);59 });60 // This is a bit bogus, but it gets rid of the warning.61 Assert.Equal({"message":expectedMessage, "err":expectedError}, reportError.Calls[0].Arguments);62 }63 [Fact]64 function OnErrorCallsReportErrorWithBareMessagePlusFile() {65 var reportError = Stubs.GetMethod("message", "err", true);66 var message = "message";67 var expectedError = "error";68 var file="file", line="line", col="col";69 var expectedMessage = message+"\nthrows at "+file+":"+line+":"+col;70 Mocks.GetMocks(Object.Global(), {71 "$A": {72 "reportError":reportError73 }74 })(function() {75 theWindow.onerror(message, file, line, col, expectedError);76 });77 // This is a bit bogus, but it gets rid of the warning.78 Assert.Equal({"message":expectedMessage, "err":expectedError}, reportError.Calls[0].Arguments);79 }80 [Fact]81 function OnErrorDoesNotCallsConsoleErrorIfReportAndNoExisting() {82 var reportError = Stubs.GetMethod("message", "err", true);83 var consoleError = Stubs.GetMethod("message", "err", undefined);84 var message = "message";85 var expectedError = "error";86 var file="file", line="line", col="col";87 var expectedMessage = message+"\nthrows at "+file+":"+line+":"+col;88 Mocks.GetMocks(Object.Global(), {89 "$A": {90 "reportError":reportError91 },92 "window": {93 "console":{94 "error":consoleError95 }96 }97 })(function() {98 theWindow.onerror(message, file, line, col, expectedError);99 });100 Assert.Equal(0, consoleError.Calls.length);101 }102 [Fact]103 function OnErrorCallsConsoleErrorIfNoReportAndNoExisting() {104 var reportError = Stubs.GetMethod("message", "err", false);105 var consoleError = Stubs.GetMethod("message", "err", undefined);106 var message = "message";107 var expectedError = "error";108 var file="file", line="line", col="col";109 var expectedMessage = message+"\nthrows at "+file+":"+line+":"+col;110 Mocks.GetMocks(Object.Global(), {111 "$A": {112 "reportError":reportError113 },114 "window": {115 "console":{116 "error":consoleError117 }118 }119 })(function() {120 theWindow.onerror(message, file, line, col, expectedError);121 });122 Assert.Equal({"message":expectedMessage, "err":expectedError}, consoleError.Calls[0].Arguments);123 }124 [Fact]125 function OnErrorHandlesConsoleMissing() {126 var reportError = Stubs.GetMethod("message", "err", false);127 var message = "message";128 var expectedError = "error";129 var file="file", line="line", col="col";130 var expectedMessage = message+"\nthrows at "+file+":"+line+":"+col;131 Mocks.GetMocks(Object.Global(), {132 "$A": {133 "reportError":reportError134 },135 "window": {136 }137 })(function() {138 theWindow.onerror(message, file, line, col, expectedError);139 });140 Assert.Equal(1, reportError.Calls.length);141 }142 [Fact]143 function OnErrorHandlesConsoleErrorMissing() {144 var reportError = Stubs.GetMethod("message", "err", false);145 var message = "message";146 var expectedError = "error";147 var file="file", line="line", col="col";148 var expectedMessage = message+"\nthrows at "+file+":"+line+":"+col;149 Mocks.GetMocks(Object.Global(), {150 "$A": {151 "reportError":reportError152 },153 "window": {154 "console": {155 "foo":function(){}156 }157 }158 })(function() {159 theWindow.onerror(message, file, line, col, expectedError);160 });161 Assert.Equal(1, reportError.Calls.length);162 }163 }164 [Fixture]165 function unhandledrejectionHandler() {166 [Fact]167 function CallsReportErrorWithEventReason() {168 var reportError = Stubs.GetMethod("message", "error", true);169 var expected = "error message";170 Mocks.GetMocks(Object.Global(), {171 "$A": {172 "reportError":reportError,173 "auraError": function(msg, err) {174 this.message = err.message;175 },176 }177 })(function() {178 eventHandler({reason:new Error(expected)});179 });180 var actual = reportError.Calls[0].Arguments["error"].message;181 Assert.Equal(expected, actual);182 }183 [Fact]184 function DoesNotCallConsoleErrorIfReportReturnsTrue() {185 var reportError = Stubs.GetMethod("message", "error", true);186 var consoleError = Stubs.GetMethod("message", "error", undefined);187 Mocks.GetMocks(Object.Global(), {188 "$A": {189 "reportError":reportError,190 "auraError": function(){}191 },192 "window": {193 "console":{194 "error":consoleError195 }196 }197 })(function() {198 eventHandler({reason:new Error()});199 });200 Assert.Equal(0, consoleError.Calls.length);201 }202 [Fact]203 function CallsConsoleErrorIfReportReturnsFalse() {204 var reportError = Stubs.GetMethod("message", "error", false);205 var consoleError = Stubs.GetMethod("message", "error", undefined);206 var expectedError = "bad reason";207 Mocks.GetMocks(Object.Global(), {208 "$A": {209 "reportError":reportError210 },211 "window": {212 "console":{213 "error":consoleError214 }215 }216 })(function() {217 eventHandler({reason:expectedError});218 });219 Assert.Equal({"message":null, "error":expectedError}, consoleError.Calls[0].Arguments);220 }221 }...
signup.js
Source:signup.js
...9};10const isNullOrEmpty = (id) => {11 const element = document.getElementById(id);12 if (element.value === '' || element.value === null || element.value === undefined) {13 reportError(id, 'add', 'Container empty');14 console.log(`Input is empty on element : ${id}`);15 return true;16 } else {17 console.log(`success on element : ${id}`);18 reportError(id, 'remove');19 return false;20 }21};22const nameValidator = (id) => {23 const elementValue = document.getElementById(id).value;24 if (!isNullOrEmpty(id)) {25 if (/[^a-zA-Z]/gi.test(elementValue)) {26 reportError(id, 'add', 'Invalid characters');27 isErrorInForm.name = true;28 } else {29 reportError(id, 'remove');30 isErrorInForm.name = false;31 }32 } else {33 reportError(id, 'remove');34 isErrorInForm.name = false;35 }36};37const emailValidator = (id) => {38 const elementValue = document.getElementById(id).value;39 if (!isNullOrEmpty(id)) {40 if (!/\@/gi.test(elementValue)) {41 reportError(id, 'add', "There is no '@' symbol in the email");42 isErrorInForm.email = true;43 } else if (!/\.com/gi.test(elementValue)) {44 reportError(id, 'add', "Email is incomplete. Missing '.com'");45 isErrorInForm.email = true;46 } else {47 reportError(id, 'remove');48 isErrorInForm.email = false;49 }50 } else {51 reportError(id, 'remove');52 isErrorInForm.email = false;53 }54};55const passwordValidator = (id) => {56 const element = document.getElementById(id);57 if (!isNullOrEmpty(id)) {58 if (element.value.length < 8) {59 reportError('password', 'add', 'Password must be at least 8 characters');60 isErrorInForm.password = true;61 } else if (!/[a-zA-z]/gi.test(element.value) || !/[0-9]/gi.test(element.value)) {62 reportError('password', 'add', 'Password must contain letters and digits');63 isErrorInForm.password = true;64 } else {65 reportError('password', 'remove');66 isErrorInForm.password = false;67 }68 } else {69 reportError('password', 'remove');70 isErrorInForm.password = false;71 }72};73const retypePasswordValidator = (id, confirmId) => {74 const password = document.getElementById(id);75 const confirmPassword = document.getElementById(confirmId);76 console.log(password.value, confirmPassword.value);77 console.log(password.value, confirmPassword.value);78 if (!isNullOrEmpty(confirmId)) {79 if (password.value !== confirmPassword.value) {80 reportError('confirm-password', 'add', 'Retyped password does not match');81 isErrorInForm.confirmPassword = true;82 } else {83 reportError('confirm-password', 'remove');84 isErrorInForm.confirmPassword = false;85 }86 } else {87 reportError('confirm-password', 'remove');88 isErrorInForm.confirmPassword = false;89 }90};91// ? Event Listeners //////////////////////////////////////////////////////////92document.getElementById('first-name').addEventListener('change', () => {93 reportError('first-name', 'remove');94 nameValidator('first-name');95});96document.getElementById('last-name').addEventListener('change', () => {97 reportError('last-name', 'remove');98 nameValidator('last-name');99});100document.getElementById('email').addEventListener('change', () => {101 reportError('email', 'remove');102 emailValidator('email');103});104document.getElementById('password').addEventListener('change', () => {105 reportError('password', 'remove');106 passwordValidator('password', 'password');107});108document.getElementById('confirm-password').addEventListener('change', () => {109 reportError('confirm-password', 'remove');110 retypePasswordValidator('password', 'confirm-password');111});112document.getElementById('form').addEventListener('submit', (e) => {113 if (114 isErrorInForm.name ||115 isErrorInForm.email ||116 isErrorInForm.password ||117 isErrorInForm.confirmPassword118 ) {119 e.preventDefault();120 } else {121 e.preventDefault();122 document.getElementById('submit').classList.add('submitting');123 document.getElementById('submit').value = 'SIGNING UP...';124 fetch('/signup', {125 method: 'POST',126 headers: {127 Accept: 'application/json',128 'Content-Type': 'application/json',129 'CSRF-Token': token,130 },131 body: JSON.stringify({132 firstName: document.getElementById('first-name').value,133 lastName: document.getElementById('last-name').value,134 birthday: document.getElementById('birthday').value,135 email: document.getElementById('email').value,136 password: document.getElementById('password').value,137 confirmPassword: document.getElementById('confirm-password').value,138 }),139 })140 .then((res) => res.json())141 .then((res) => {142 document.getElementById('submit').classList.remove('submitting');143 if (res.success) {144 window.location.replace('/profile');145 } else {146 document.getElementById('submit').value = 'Sign Up';147 res.errors.forEach((x) => {148 switch (x) {149 case 'emailExists':150 reportError('email', 'add', 'Email exists.');151 break;152 case 'nameExists':153 reportError('first-name', 'add', 'Name exists.');154 reportError('last-name', 'add', 'Name exists.');155 }156 });157 }158 });159 }160});161document.querySelector('.made-with-love .heart').addEventListener('click', async (e) => {162 fetch('/change-theme')163 .then((res) => res.json())164 .then((res) => console.log(res.message));165 document.querySelector('body').classList.toggle('dark-mode');166});...
report-infinite-recursion.spec.js
Source:report-infinite-recursion.spec.js
...5chai.use( helpers );6const expect = chai.expect;7describe( "compiler pass |reportInfiniteRecursion|", function () {8 it( "reports direct left recursion", function () {9 expect( pass ).to.reportError( "start = start", {10 message: "Possible infinite loop when parsing (left recursion: start -> start).",11 location: {12 start: { offset: 8, line: 1, column: 9 },13 end: { offset: 13, line: 1, column: 14 },14 },15 } );16 } );17 it( "reports indirect left recursion", function () {18 expect( pass ).to.reportError( [19 "start = stop",20 "stop = start",21 ].join( "\n" ), {22 message: "Possible infinite loop when parsing (left recursion: start -> stop -> start).",23 location: {24 start: { offset: 20, line: 2, column: 8 },25 end: { offset: 25, line: 2, column: 13 },26 },27 } );28 } );29 describe( "in sequences", function () {30 it( "reports left recursion if all preceding elements match empty string", function () {31 expect( pass ).to.reportError( "start = '' '' '' start" );32 } );33 it( "doesn't report left recursion if some preceding element doesn't match empty string", function () {34 expect( pass ).to.not.reportError( "start = 'a' '' '' start" );35 expect( pass ).to.not.reportError( "start = '' 'a' '' start" );36 expect( pass ).to.not.reportError( "start = '' '' 'a' start" );37 } );38 // Regression test for #359.39 it( "reports left recursion when rule reference is wrapped in an expression", function () {40 expect( pass ).to.reportError( "start = '' start?" );41 } );42 it( "computes expressions that always consume input on success correctly", function () {43 expect( pass ).to.reportError( [44 "start = a start",45 "a 'a' = ''",46 ].join( "\n" ) );47 expect( pass ).to.not.reportError( [48 "start = a start",49 "a 'a' = 'a'",50 ].join( "\n" ) );51 expect( pass ).to.reportError( "start = ('' / 'a' / 'b') start" );52 expect( pass ).to.reportError( "start = ('a' / '' / 'b') start" );53 expect( pass ).to.reportError( "start = ('a' / 'b' / '') start" );54 expect( pass ).to.not.reportError( "start = ('a' / 'b' / 'c') start" );55 expect( pass ).to.reportError( "start = ('' { }) start" );56 expect( pass ).to.not.reportError( "start = ('a' { }) start" );57 expect( pass ).to.reportError( "start = ('' '' '') start" );58 expect( pass ).to.not.reportError( "start = ('a' '' '') start" );59 expect( pass ).to.not.reportError( "start = ('' 'a' '') start" );60 expect( pass ).to.not.reportError( "start = ('' '' 'a') start" );61 expect( pass ).to.reportError( "start = a:'' start" );62 expect( pass ).to.not.reportError( "start = a:'a' start" );63 expect( pass ).to.reportError( "start = $'' start" );64 expect( pass ).to.not.reportError( "start = $'a' start" );65 expect( pass ).to.reportError( "start = &'' start" );66 expect( pass ).to.reportError( "start = &'a' start" );67 expect( pass ).to.reportError( "start = !'' start" );68 expect( pass ).to.reportError( "start = !'a' start" );69 expect( pass ).to.reportError( "start = ''? start" );70 expect( pass ).to.reportError( "start = 'a'? start" );71 expect( pass ).to.reportError( "start = ''* start" );72 expect( pass ).to.reportError( "start = 'a'* start" );73 expect( pass ).to.reportError( "start = ''+ start" );74 expect( pass ).to.not.reportError( "start = 'a'+ start" );75 expect( pass ).to.reportError( "start = ('') start" );76 expect( pass ).to.not.reportError( "start = ('a') start" );77 expect( pass ).to.reportError( "start = &{ } start" );78 expect( pass ).to.reportError( "start = !{ } start" );79 expect( pass ).to.reportError( [80 "start = a start",81 "a = ''",82 ].join( "\n" ) );83 expect( pass ).to.not.reportError( [84 "start = a start",85 "a = 'a'",86 ].join( "\n" ) );87 expect( pass ).to.reportError( "start = '' start" );88 expect( pass ).to.not.reportError( "start = 'a' start" );89 expect( pass ).to.not.reportError( "start = [a-d] start" );90 expect( pass ).to.not.reportError( "start = . start" );91 } );92 } );...
report-infinite-repetition.spec.js
Source:report-infinite-repetition.spec.js
...5chai.use( helpers );6const expect = chai.expect;7describe( "compiler pass |reportInfiniteRepetition|", function () {8 it( "reports infinite loops for zero_or_more", function () {9 expect( pass ).to.reportError( "start = ('')*", {10 message: "Possible infinite loop when parsing (repetition used with an expression that may not consume any input).",11 location: {12 start: { offset: 8, line: 1, column: 9 },13 end: { offset: 13, line: 1, column: 14 },14 },15 } );16 } );17 it( "reports infinite loops for one_or_more", function () {18 expect( pass ).to.reportError( "start = ('')+", {19 message: "Possible infinite loop when parsing (repetition used with an expression that may not consume any input).",20 location: {21 start: { offset: 8, line: 1, column: 9 },22 end: { offset: 13, line: 1, column: 14 },23 },24 } );25 } );26 it( "computes expressions that always consume input on success correctly", function () {27 expect( pass ).to.reportError( [28 "start = a*",29 "a 'a' = ''",30 ].join( "\n" ) );31 expect( pass ).to.not.reportError( [32 "start = a*",33 "a 'a' = 'a'",34 ].join( "\n" ) );35 expect( pass ).to.reportError( "start = ('' / 'a' / 'b')*" );36 expect( pass ).to.reportError( "start = ('a' / '' / 'b')*" );37 expect( pass ).to.reportError( "start = ('a' / 'b' / '')*" );38 expect( pass ).to.not.reportError( "start = ('a' / 'b' / 'c')*" );39 expect( pass ).to.reportError( "start = ('' { })*" );40 expect( pass ).to.not.reportError( "start = ('a' { })*" );41 expect( pass ).to.reportError( "start = ('' '' '')*" );42 expect( pass ).to.not.reportError( "start = ('a' '' '')*" );43 expect( pass ).to.not.reportError( "start = ('' 'a' '')*" );44 expect( pass ).to.not.reportError( "start = ('' '' 'a')*" );45 expect( pass ).to.reportError( "start = (a:'')*" );46 expect( pass ).to.not.reportError( "start = (a:'a')*" );47 expect( pass ).to.reportError( "start = ($'')*" );48 expect( pass ).to.not.reportError( "start = ($'a')*" );49 expect( pass ).to.reportError( "start = (&'')*" );50 expect( pass ).to.reportError( "start = (&'a')*" );51 expect( pass ).to.reportError( "start = (!'')*" );52 expect( pass ).to.reportError( "start = (!'a')*" );53 expect( pass ).to.reportError( "start = (''?)*" );54 expect( pass ).to.reportError( "start = ('a'?)*" );55 expect( pass ).to.reportError( "start = (''*)*" );56 expect( pass ).to.reportError( "start = ('a'*)*" );57 expect( pass ).to.reportError( "start = (''+)*" );58 expect( pass ).to.not.reportError( "start = ('a'+)*" );59 expect( pass ).to.reportError( "start = ('')*" );60 expect( pass ).to.not.reportError( "start = ('a')*" );61 expect( pass ).to.reportError( "start = (&{ })*" );62 expect( pass ).to.reportError( "start = (!{ })*" );63 expect( pass ).to.reportError( [64 "start = a*",65 "a = ''",66 ].join( "\n" ) );67 expect( pass ).to.not.reportError( [68 "start = a*",69 "a = 'a'",70 ].join( "\n" ) );71 expect( pass ).to.reportError( "start = ''*" );72 expect( pass ).to.not.reportError( "start = 'a'*" );73 expect( pass ).to.not.reportError( "start = [a-d]*" );74 expect( pass ).to.not.reportError( "start = .*" );75 } );...
LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.
|<p>it('check_object_of_Car', () => {</p><p>
expect(newCar()).toBeInstanceOf(Car);</p><p>
});</p>|
| :- |
Get 100 minutes of automation test minutes FREE!!