Best JavaScript code snippet using fast-check-monorepo
is.js
Source:is.js
1var fs = require('fs');2var moment = require('moment');3var Validator = require('jsonschema').Validator;4var diff = require('deep-diff').diff;5// Note that for reporting to have correct line numbers, must start functions with6// function FNAME( and start description with 'is.FNAME()'.7// TODO: Get this list by reading directory.8var schemas = {};9schemas["1.1"] = require("./schemas/HAPI-data-access-schema-1.1.json");10schemas["2.0"] = require("./schemas/HAPI-data-access-schema-2.0-1.json");11schemas["2.1"] = require("./schemas/HAPI-data-access-schema-2.1.json");12schemas["3.0"] = require("./schemas/HAPI-data-access-schema-3.0.json");13schemas["3.1"] = require("./schemas/HAPI-data-access-schema-3.1.json");14function prod(arr) {15 // TODO: Also in tests.js. Move to lib.js (and create lib.js)16 // Compute product of array elements.17 return arr.reduce(function(a,b){return a*b;})18}19function callerName() {20 return "is." + callerName.caller.name + "()";21}22function versions() {23 arr = [];24 for (key in schemas) {25 arr.push(key);26 }27 return arr.sort();28}29exports.versions = versions;30function HAPIVersion(version) {31 var got = version;32 var t = false;33 if (versions().includes(version)) {34 t = true;35 } else {36 got = "'" + version + "', which is not valid or not implemented by verifier. Will use " + versions().pop();37 }38 return {"description": "is.HAPIVersion(): Expect HAPI version in JSON response to be one of " + JSON.stringify(versions()), "error": t != true, "got": got}; 39}40exports.HAPIVersion = HAPIVersion;41function schema(version) {42 var json = schemas[version];43 if (!json) {44 return false;45 } else {46 return schemas[version];47 }48}49exports.schema = schema;50function timeregexes(version) {51 json = schemas[version];52 if (!json) {53 return false;54 }55 var tmp = json.HAPIDateTime.anyOf;56 var regexes = [];57 for (var i = 0;i < tmp.length;i++) {58 regexes[i] = tmp[i].pattern;59 }60 return regexes;61}62exports.timeregexes = timeregexes;63function trailingZfix(str) {64 // moment.js does not consider date only with trailing Z to be valid ISO860165 if (/^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]Z$|^[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]Z$/.test(str)) {66 str = str.slice(0, -1) + "T00Z";67 } 68 return str;69}70exports.trailingZfix = trailingZfix;71function isinteger(str) {72 return parseInt(str) < 2^31 - 1 && parseInt(str) > -2^31 && parseInt(str) == parseFloat(str) && /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]{1,3})?$/.test(str.trim());73}74function isfloat(str) {75 return Math.abs(parseFloat(str)) < Number.MAX_VALUE && /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]{1,3})?$/.test(str.trim())76}77function RequestError(err,res,timeoutType,timeoutObj) {78 var tout = timeoutObj[timeoutType]["timeout"];79 var when = timeoutObj[timeoutType]["when"];80 if (!err) {81 // Remove nonsense extra precision on timings.82 var timings = res.timings;83 for (var key in timings) {84 timings[key] = timings[key].toFixed(1);85 }86 var timingPhases = res.timingPhases;87 for (var key in timingPhases) {88 timingPhases[key] = timingPhases[key].toFixed(1);89 }90 var timeInfo = "";91 if (timingPhases && timings) {92 timeInfo = JSON.stringify(timings) + ", " + JSON.stringify(timingPhases);93 timeInfo = " <a href='https://github.com/request/request#requestoptions-callback'>Timing info [ms]</a>: " + timeInfo;94 }95 return {"description":"is.RequestError(): Expect no request error for timeout of " + tout + " ms used when " + when,"error": false,"got": "No error." + timeInfo};96 }97 if (err.code === "ETIMEDOUT") {98 // https://github.com/request/request/blob/master/request.js#L84699 return {"description":"is.RequestError(): Expect HTTP headers and start of response body in less than " + tout + " ms when " + when,"error": true,"got": "ETIMEDOUT"};100 } else if (err.code === "ESOCKETTIMEDOUT") {101 //https://github.com/request/request/blob/master/request.js#L811102 return {"description":"is.RequestError(): Expect time interval between bytes sent to be less than " + tout + " ms when " + when,"error": true,"got": "ESOCKETTIMEDOUT"};103 } else if (err.code === "ECONNRESET") {104 return {"description":"is.RequestError(): Expect connection to not be reset by server","error": true,"got": "ECONNRESET"};105 } else if (err.code === "ECONNREFUSED") {106 return {"description":"is.RequestError(): Expect connection to not be refused by server","error": true,"got": "ECONNREFUSED"};107 } else {108 return {"description":"is.RequestError(): Probably URL is malformed.","error":true,"got":err};109 }110}111exports.RequestError = RequestError;112function CadenceValid(cadence) {113 var md = moment.duration(cadence);114 var t = md._isValid;115 // moment.duration("PT720") gives md._isValid = true and116 // md._milliseconds = 0. (Need H, M, S at end)117 if (md._milliseconds == 0 && md._days == 0 && md._months == 0) {118 t = false;119 }120 return {"description": "is.CadenceValid(): Expect cadence to be a valid ISO8601 duration", "error": t == false, "got": cadence};121}122exports.CadenceValid = CadenceValid;123function CadenceOK(cadence,start,stop,what) {124 if (!cadence) return; // Don't do test; no cadence given.125 if (!stop) return {"description":"is.CadenceOK(): Need more than two lines to do cadence comparison with consecutive samples.","error":true,"got":"One line."}126 //console.log(start)127 //console.log(stop)128 start = trailingZfix(start);129 stop = trailingZfix(stop);130 var startms = moment(start).valueOf();131 var stopms = moment(stop).valueOf();132 var md = moment.duration(cadence);133 var R = (stopms-startms)/md._milliseconds;134 if (what === "start/stop") {135 t = R > 1;136 var got = "(stopDate-startDate)/cadence = " + (stopms-startms)/md._milliseconds;137 return {"description":"is.CadenceOK(): Expect (stopDate-startDate)/cadence > 1","error":t != true,"got":got}138 }139 if (what === "sampleStart/sampleStop") {140 t = R > 10;141 var got = "(sampleStartDate-sampleStopDate)/cadence = " + (stopms-startms)/md._milliseconds;142 return {"description":"is.CadenceOK(): Expect (sampleStopDate-sampleStartDate)/cadence > 10","error":t != true,"got":got}143 }144 if (what === "consecsamples") {145 t = R > 10;146 var got = "Cadence/(time[i+1]-time[i]) = " + (stopms-startms)/md._milliseconds;147 return {"description":"is.CadenceOK(): Expect (t[i+1]-t[i])/cadence > 10","error":t != true,"got":got}148 }149}150exports.CadenceOK = CadenceOK;151function CIdentifier(arr,type) {152 var re_str = "[_a-zA-Z][_a-zA-Z0-9]{1,30}";153 var arr_fail = [];154 for (var i = 0; i < arr.length;i++) {155 var re = new RegExp(re_str);156 var t = re.test(arr[i]);157 if (!t) {158 arr_fail.push(arr[i]);159 }160 }161 var got = "All " + type + "(s) match.";162 if (arr_fail.length > 0) {163 console.log(arr_fail);164 got = "Non-matching " + type + "(s):" + JSON.stringify(arr_fail);165 }166 return {"description": "is.CIdentifier(): Expect " + type + " to match c identifier regex '" + re_str + "'.", "error": arr_fail.length > 0, "got": got};167}168exports.CIdentifier = CIdentifier;169function ErrorCorrect(code,wanted,what) {170 if (what === "httpcode") {171 return {"description": "is.ErrorCorrect(): Expect HTTP code in JSON to be " + wanted, "error": code != wanted, "got": code};172 }173 if (what === "hapicode") {174 t = code == wanted175 var got = code;176 if (t != true) {got = code + "."}177 return {"description": "is.ErrorCorrect(): Expect HAPI code in JSON to be " + wanted, "error": t != true, "got": got};178 }179}180exports.ErrorCorrect = ErrorCorrect;181function StatusInformative(message,wanted,what) {182 var re = new RegExp(wanted);183 var t = re.test(message);184 var got = message;185 if (t !== true) {got = message + "."}186 if (what === "hapistatus") {187 var l = "<a href='https://github.com/hapi-server/verifier-nodejs/wiki#status-informative'>(Explanation.)</a>";188 return {"description": "is.StatusInformative(): Want HAPI status message in JSON response to contain the string '" + wanted + "' (default HAPI error message). " + l, "error": t !== true, "got": "'" + message + "'"};189 }190 if (what === "httpstatus") {191 var l = "<a href='https://github.com/hapi-server/verifier-nodejs/wiki#status-informative'>(Explanation.)</a>";192 return {"description": "is.StatusInformative(): Want HTTP status message to contain the string '" + wanted + "' (default HAPI error message). " + l, "error": t !== true, "got": "'" + message + "'"};193 }194}195exports.StatusInformative = StatusInformative;196function nFields(header, pn) {197 if (pn !== undefined && pn !== null) {198 // One parameter199 var nf = 1; // Number of fields (columns) counter (start at 1 since time checked already)200 if (!header.parameters[pn]["size"]) {201 nf = nf + 1; // Width of field (number of columns of field)202 } else {203 nf = nf + prod(header.parameters[pn]["size"]);204 }205 } else {206 // All parameters207 var nf = 0; // Number of fields (columns) counter208 for (var i = 0;i < header.parameters.length;i++) {209 if (!header.parameters[i]["size"]) {210 nf = nf + 1; // Width of field (number of columns of field)211 } else {212 nf = nf + prod(header.parameters[i]["size"]);213 } 214 }215 }216 return nf; 217}218function csvToArray(text) {219 // https://stackoverflow.com/a/41563966/1491619220 let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;221 for (l of text) {222 if ('"' === l) {223 if (s && l === p) row[i] += l;224 s = !s;225 } else if (',' === l && s) l = row[++i] = '';226 else if ('\n' === l && s) {227 if ('\r' === p) row[i] = row[i].slice(0, -1);228 row = ret[++r] = [l = '']; i = 0;229 } else row[i] += l;230 p = l;231 }232 return ret;233}234function FileLineOK(header,body,pn,what) {235 var nf = nFields(header, pn);236 var lines = csvToArray(body);237 if (what === "Ncolumns") {238 let t = false;239 let got = "(" + nf + ")" + " - (" + nf + ")";240 if (lines.length == 0) {241 got = "(0)" + " - (" + nf + ")";242 }243 for (var i = 0;i<lines.length-1;i++) {244 t = nf != lines[i].length;245 if (t) {246 got = "(" + line.length + ")" + " - (" + nf + ")";247 got = got + " on line " + (i+1);248 break;249 }250 }251 return {"description": callerName() + ': Expect (# of columns in CSV) - (# computed from length and size metadata) = 0.',"error":t,"got":got};252 }253 if (what === "fields") {254 if (type === "string") {255 line1 = csvToArray(lines[0])[0];256 }257 var len = header.parameters[pn]["length"];258 var type = header.parameters[pn]["type"];259 var name = header.parameters[pn]["name"];260 var size = header.parameters[pn]["size"];261 var nf = 1; // Number of fields (columns) counter262 // (start at 1 since time checked already)263 if (!size) {264 nf = nf + 1; // Width of field (number of columns of field)265 } else {266 nf = nf + prod(size);267 }268 // TODO: Check all lines?269 for (var j=1;j < nf;j++) {270 if (j == 1 || j == nf-1) {var shush = false} else {shush = true}271 var extra = ' in column ' + j + ' on first line.'272 if (type === "string") {273 report(url,is.CorrectLength(line1[j],len,name,extra),{"warn":true,"shush":shush});274 }275 if (type === "isotime") {276 report(url,is.ISO8601(line1[j].trim(),extra));277 report(url,is.CorrectLength(line1[j],len,name,extra),{"warn":true,"shush":shush});278 }279 if (type === "integer") {280 report(url,is.Integer(line1[j],extra),{"shush":shush});281 }282 if (type === "double") {283 report(url,is.Float(line1[j],extra),{"shush":shush});284 }285 }286 //report(url,is.FileLineOK(header,body,bodyAll,pn,'Ncolumns'));287 // Note line.length - 1 = because split() adds extra empty288 // element at end if trailing newline.289 }290}291exports.FileLineOK = FileLineOK;292function FileContentSame(header,body,bodyAll,pn,what) {293 var nf = nFields(header, pn);294 var lines = body.split("\n");295 var linesAll = bodyAll.split("\n");296 if (what === "contentsame") {297 var e = false;298 var got = "Match";299 var desc = callerName() + ": Expect data response to be same as previous request given differing request URLs.";300 if (bodyAll !== body) { // byte equivalent301 if (lines.length != linesAll.length) { // # lines not same.302 e = true;303 got = lines.length + " rows here vs. " + linesAll.length + " rows previously.";304 return {"description": desc, "error": e, "got": got}; 305 }306 // Look for location of difference.307 var line = "";308 var lineAll = "";309 var e1 = false;310 var e2 = false;311 for (var i=0;i<lines.length-1;i++) {312 line = lines[i].split(",");313 lineAll = linesAll[i].split(",");314 if (line.length != lineAll.length) {315 e1 = true;316 break;317 }318 for (var j=0;j<line.length-1;j++) {319 if (line[j].trim() !== lineAll[j].trim()) {320 e2 = true;321 break;322 }323 }324 if (e2) {break;}325 }326 if (e1) {327 got = line.length + " columns vs. " + lineAll.length + " columns on line " + (i+1) + ".";328 e = true;329 return {"description":desc, "error": e, "got": got}; 330 }331 if (e2) {332 got = "Difference on line " + (i+1) + " column " + (nf+1) + ".";333 e = true;334 return {"description":desc, "error": e, "got": got}; 335 }336 // TODO: Can e1 and e2 be false?337 }338 return {"description": desc, "error": e, "got": got}; 339 }340 if (what === "subsetsame") {341 var lines = body.split("\n");342 var desc = callerName() + ": Expect data from one parameter request to match data from all parameter request.";343 var t = false;344 var got = "Match";345 var fc = 0; // First column of parameter.346 for (var i = 0;i < header.parameters.length;i++) {347 if (header.parameters[i]["name"] === header.parameters[pn]["name"]) {348 break;349 }350 if (!header.parameters[i]["size"]) {351 fc = fc + 1;352 } else {353 fc = fc + prod(header.parameters[i]["size"]);354 }355 }356 var desc = "Expect number of rows from one parameter request to match data from all parameter request.";357 var t = lines.length != linesAll.length;358 //console.log(lines)359 //console.log(linesAll) 360 var got = "Match";361 if (t) {362 got = " # rows in single parameter request = " + lines.length + " # in all parameter request = " + linesAll.length;363 return {"description": callerName() + ": " + desc,"error":t,"got":got};364 }365 var desc = callerName() + ": Expect content from one parameter request to match content from all parameter request.";366 t = false;367 var line = "";368 var lineAll = "";369 for (var i=0;i<lines.length-1;i++) {370 line = lines[i].split(",");371 lineAll = linesAll[i].split(",");372 if (line.length != lineAll.length) {373 // This error will be caught by Ncolumns test.374 return;375 }376 // Time377 if (line[0].trim() !== lineAll[0].trim()) {378 t = true;379 got = "Time column for parameter " + name + " does not match at time " + line[0] + ": Single parameter request: " + line[1] + "; All parameter request: " + lineAll[0] + ".";380 }381 var desc = "Expect number of columns from one parameter request to be equal to or less than number of columns in all parameter request.";382 var t = line.length > lineAll.length;383 got = " # columns in single parameter request = " + line.length + " # in all parameter request = " + lineAll.length;384 if (t) {385 return {"description": callerName() + ": " + desc,"error":t,"got":got};386 }387 var desc = "Expect data from one parameter request to match data from all parameter request.";388 got = "Match";389 t = false;390 // Parameter391 for (var j=0;j<nf-1;j++) {392 if (!line[1+j] || !lineAll[fc+1]) {393 t = false;394 got = "Problem with line " + (j) + ": " + line[1+j];395 break;396 }397 if (line[1+j].trim() !== lineAll[fc+j].trim()) {398 if (header.parameters[pn].name) {399 var name = "'" + header.parameters[pn].name + "'";400 } else {401 var name = "#" + header.parameters[pn].name;402 }403 if (nf == 2) {404 t = true;405 got = got + ". Parameter " + name + " does not match at time " + line[0] + ": Single parameter request: " + line[1] + "; All parameter request: " + lineAll[fc+j] + ".";406 } else {407 got = got + ". Parameter " + name + " field #" + j + " does not match at time " + line[0] + ": Single parameter request: " + line[1+j] + "; All parameter request: " + lineAll[fc+j] + ".";408 }409 }410 }411 }412 return {"description": callerName() + ": " + desc, "error": t,"got": got};413 }414}415exports.FileContentSame = FileContentSame;416function FileStructureOK(body,what,other,emptyExpected) {417 418 var desc,t,got;419 if (what === "emptyconsistent") {420 if (body === null || other === null) {421 return; // Can't do test due to previous failure.422 }423 if (body.length == 0 || other.length == 0) {424 if (body.length == 0 && other.length != 0) {425 return {"description": callerName() + ': If empty response for single parameter, expect empty response for all parameters.',"error": true,"got": "Single parameter body: " + body.length + " bytes. All parameter body: " + other.length + " bytes."};426 } else {427 return {"description": callerName() + ': If empty response for single parameter, expect empty response for all parameters.',"error": false,"got": "Both empty."};428 }429 } else {430 return; // Test is not relevant.431 } 432 }433 if (what === "empty") {434 var l = "<a href='https://github.com/hapi-server/verifier-nodejs/wiki#status-informative'>(Explanation.)</a>";435 var l2 = "<a href='https://github.com/hapi-server/verifier-nodejs/wiki#empty-body'>(Explanation.)</a>";436 var emptyIndicated = /HAPI 1201/.test(other);437 if (!body || body.length === 0) {438 if (emptyExpected && !emptyIndicated) {439 return {"description": callerName() + ": If data part of response has zero length, want 'HAPI 1201' in HTTP header status message. " + l2,"error": true,"got": "Zero bytes and HTTP header status message of '" + other + "'"};440 }441 if (!emptyExpected) {442 if (emptyIndicated) {443 return {"description": callerName() + ": A data part of response with zero bytes was not expected. " + l2,"error": false,"got": "Zero bytes (but 'HAPI 1201' is in HTTP header status message)."};444 } else {445 return {"description": callerName() + ": A data part of response with zero bytes was not expected. " + l2,"error": true,"got": "Zero bytes and no 'HAPI 1201' in HTTP header status message."};446 }447 }448 }449 if (body && body.length != 0 && emptyIndicated) {450 return {"description": callerName() + ": A data part of response with zero bytes was expected because 'HAPI 1201 in HTTP header status messsage." + l2,"error": false,"got": "'HAPI 1201' in HTTP header status message and " + body.length + " bytes."};451 }452 return {"description": callerName() + ": Expect nonzero-length data part of response.", "error": false,"got": body.length + " bytes."}; 453 }454 if (what === "firstchar") {455 desc = "Expect first character of CSV response to be an integer.";456 t = !/^[0-9]/.test(body.substring(0,1));457 got = body.substring(0,1);458 }459 if (what === "lastchar") {460 desc = "Expect last character of CSV response be a newline.";461 t = !/\n$/.test(body.slice(-1));462 got = body.slice(-1).replace(/\n/g,"\\n");463 if (t) {464 got = "The character '" + got + "'";465 } else {466 got = "A newline.";467 }468 }469 if (what === "extranewline") { 470 desc = "Expect last two characters of CSV response to not be newlines.";471 t = /\n\n$/.test(body.slice(-2));472 got = body.slice(-2).replace(/\n/g,"\\n");473 if (t) {474 got = "Two newlines.";475 } else {476 got = "The characters '" + got + "'";477 }478 }479 if (what === "numlines") {480 var lines = body.split("\n");481 got = lines.length + " newlines";482 if (lines.length == 0) {483 got = "No lines.";484 } else {485 got = lines.length + " newlines";486 }487 desc = "Expect at least one newline in CSV response.";488 t = lines.length == 0489 }490 return {"description": callerName() + ": " + desc, "error": t,"got": got};491}492exports.FileStructureOK = FileStructureOK;493function LengthAppropriate(len,type,name) {494 var got = "Type = " + type + " and length = " + len + " for parameter " + name;495 if (/isotime|string/.test(type) && !len) {496 obj = {"description": "If type = string or isotime, length must be given", "error":true, "got": got};497 } else if (!/isotime|string/.test(type) && len) {498 obj = {"description": "If type = string or isotime, length must not be given", "error":true, "got": got};499 } else {500 obj = {"description": "Length may only be given for types string and isotime", "error":false, "got": got};501 }502 obj["description"] = "is.LengthAppropriate(): " + obj["description"];503 return obj;504}505exports.LengthAppropriate = LengthAppropriate;506function HeaderSame(headerInfo, headerBody) {507 // Compare header from info response with header in data response508 var differences = diff(headerInfo, headerBody); 509 var keptDiffs = [];510 //console.log(headerInfo);511 //console.log(headerBody);512 //console.log(differences);513 if (differences) {514 for (var i = 0; i < differences.length; i++) {515 if (differences[i].path[0] !== 'format' && differences[i].path[0] !== 'creationDate') {516 //console.log('path: ' + differences[i].path);517 var keep = true;518 for (j = 0; j < differences[i].path.length; j++) {519 //console.log("path[" + j + "] = " + differences[i].path[j]);520 if (typeof(differences[i].path[j]) === 'string' && differences[i].path[j].substring(0,2) === 'x_') {521 keep = false;522 break;523 }524 }525 if (keep) {526 keptDiffs.push(differences[i]);527 }528 }529 }530 }531 var desc = "is.HeaderSame(): Expect header in info response to match header in data response when 'include=header' requested.";532 if (keptDiffs.length == 0) {533 return {"description": desc, "error": false, "got": "Matching headers."};534 } else {535 var got = "Differences:\n" + JSON.stringify(keptDiffs);536 return {"description": desc, "error": true, "got": got};537 }538}539exports.HeaderSame = HeaderSame;540function FormatInHeader(header,type) {541 // https://github.com/hapi-server/data-specification/blob/master/hapi-2.1.1/HAPI-data-access-spec-2.1.1.md#info542 if (type == "nodata") {543 var t = 'format' in header;544 var got = 'No format given.'545 if (t) {546 got = "Format of '" + header.format + "' specified."547 }548 return {"description": "is.FormatInHeader(): Info response should not have 'format' specified.", "error": t, "got": got}; 549 }550 if (type == "data") {551 var t = !('format' in header);552 var got = 'No format given.'553 if (!t) {554 got = "Format of '" + header.format + "' specified."555 }556 return {"description": "is.FormatInHeader(): Header in csv response should have 'format: csv' specified.", "error": t, "got": got}; 557 }558}559exports.FormatInHeader = FormatInHeader;560function FirstParameterOK(header,what) {561 if (what == "name") {562 return {"description": "is.FirstParameterOK(): First parameter should (not must) be named 'Time' b/c clients will likely label first parameter as 'Time' on plot to protect against first parameter names that are not sensible.", "error": header.parameters[0].name !== "Time", "got": header.parameters[0].name};563 }564 if (what == "fill") {565 var t = false;566 var got = 'null';567 if (!('fill' in header.parameters[0])) {568 got = 'No fill entry.'569 }570 if (header.parameters[0].fill != null) {571 t = true;572 got = header.parameters[0].fill;573 }574 return {"description": "is.FirstParameterOK(): First parameter must have a fill of null or it should not be specified.", "error": t, "got": got};575 }576}577exports.FirstParameterOK = FirstParameterOK;578function BinsOK(name,bins,size) {579 if (!bins) {580 return;581 }582 var desc = "Expect bin units, label, centers, and ranges to have correct number of elements.";583 var err = false;584 var got = "";585 // Recursive check586 if (false && Array.isArray(bins[0])) {587 size.shift();588 BinsOK(name,bins[0],size);589 return {}; 590 }591 var err = false;592 var k = 1;593 if (size.length == 1) {594 k = 0;595 }596 if (size.length == 1 && bins.length != 1) {597 err = true;598 got = "Parameter " + name + ": bins.length = " + bins.length + " but should equal 1. ";599 }600 if (size.length > 1 && bins.length != size.length) {601 err = true;602 got = "Parameter " + name + ": bins.length (= " + bins.length + ") != size.length (= " + size.length + "). ";603 }604 if (size.length <= 2) {605 for (i=0; i < bins.length; i++) {606 if (bins[i].units && Array.isArray(bins[i].units) && bins[i].units.length > 1 && bins[i].units.length != size[k]) {607 err = true; 608 got = got + "Parameter " + name + ": wrong number of elements in units. Got " + bins[i].units.length + ". Expected 1 or " + size[k] + ". ";609 }610 if (bins[i].label && Array.isArray(bins[i].label) && bins[i].label.length > 1 && bins[i].label.length != size[k]) {611 err = true;612 got = got + "Parameter " + name + ": wrong number of elements in labels. Got " + bins[i].label.length + ". Expected 1 or " + size[k] + ". ";613 }614 if (bins[i].centers && bins[i].centers.length != size[i]) {615 err = true;616 got = got + "Parameter " + name + ": wrong number of elements in centers. Got " + bins[i].centers.length + ". Expected " + size[i] + ". ";617 }618 if (bins[i].ranges && bins[i].ranges.length != size[i]) {619 err = true;620 got = got + "Parameter " + name + ": wrong number of elements in ranges. Got " + bins[i].ranges.length + ". Expected " + size[i] + ". ";621 }622 }623 }624 if (got === "") {got = "Parameter " + name + " has correct number of elements."}625 if (units.length > 1 && size.length > 2) {626 got = "<span style='background-color:yellow'>size.length > 2 for parameter " + name + ". Check not implemented.</span>" 627 }628 return {"description": "is.BinsOK(): " + desc, "error": err, "got": got};629}630exports.BinsOK = BinsOK;631function ArrayOK(name,units,size,type,version) {632 if (version !== "2.1") {633 return;634 }635 // "units": [["nT"],["nT","degrees","nT"]],636 // size = [N]637 // units = "u" 638 // units = ["u"]639 // units = ['u1','u2',...,'uN']640 // size = [N,M]641 // units = "u"642 // units = ["u"]643 // units = ['uN','uM']644 // units = [['u1',...,'u1M'],['u2',...,'uM'],...,['uN',...,'uNM']]645 if (Array.isArray(units)) {646 var desc = "Expect " + type + " to be a string or an array with appropriate structure. ";647 var err = false;648 var got = "";649 if (units.length > 1 && size.length == 1 && units.length != size[0]) {650 // size = [N], units = ['u1','u2',...,'uN'] case651 err = true;652 got = got + "if size.length == 1, " + type + " should have 1 element or size[0] elements. ";653 }654 if (units.length > 1 && size.length == 2) {655 for (var j = 0; j < units.length; j++) {656 if (Array.isArray(units[j])) {657 if (units[j].length != 1 && units[j].length != size[1]) {658 err = true;659 got = got + type + "[" + j + "] contains array; it should have 1 element or size[" + (1) + "] elements. ";660 }661 }662 }663 }664 if (got === "") {665 got = "parameter '" + name + "' " + type + " has appropriate structure.";666 } else {667 got = "parameter '" + name + "', size = " + JSON.stringify(size) + ", " + type + " = " + JSON.stringify(units) + ". " + got; 668 }669 if (units.length > 1 && size.length > 2) {670 got = "<span style='background-color:yellow'>size.length > 2 for parameter " + name + ". Check not implemented.</span>" 671 }672 return {"description": "is.ArrayOK(): " + desc, "error": err, "got": got};673 }674}675exports.ArrayOK = ArrayOK;676// TODO: Use this677function checkdims(units,size,version) {678 var err = false;679 if (units && units !== null && typeof(units) !== "string") {680 // units is an array.681 // size passed assumed to always be an array682 var err = false;683 if (size.length == 1 && units.length == size[0]) {684 // e.g., size = [2] and units = ["m", "km"] is OK685 // So is size = [1] and units = ["m"] (but this should really be size = 1 and units = "m")686 } else {687 if (units.length !== size.length) {688 // Check that number of elements in units matches number in size.689 err = true;690 } else if (typeof(units[0]) !== 'object') {691 // If here, then size.length > 1. This checks for, e.g.,692 // units = ["m", "km"] and size = [1,2], which is wrong693 err = true;694 } else {695 // Check that ith subarray of units has length equal to ith value in size.696 for (var i = 0; i < units.length; i++) {697 if (units[i].length !== size[i]) {698 err = true;699 break;700 } 701 }702 }703 }704 return err;705 }706}707function UnitsOK(name,units,type,size) {708 if (type === 'isotime') {709 var err = false;710 if (typeof(units) === 'object') {711 for (var i = 0; i < units.length; i++) {712 for (var j = 0; j < units[i].length; j++) {713 if (units[i][j] !== "UTC") {714 err = true;715 break;716 }717 }718 }719 } else {720 var got = "type = '" + type + "' and units = '" + units + "' for parameter " + name + ".";721 if (units !== "UTC") {722 err = true;723 } 724 }725 return {"description": "is.UnitsOK(): Expect isotime units to be 'UTC'.", "error": err,"got": got};726 }727}728exports.UnitsOK = UnitsOK;729function FillOK(fill,type,len,name,what) {730 if (!fill) {return;} // No fill or fill=null so no test needed.731 var t = false;732 if (typeof(fill) === 'string') {733 var got = "fill = '" + fill + "' for parameter " + name + ".";734 } else {735 var got = "fill = " + fill + " for parameter " + name + ".";736 }737 var desc = "";738 if (what === "nullstring") {739 desc = "is.FillOK(): Expect fill value to not be the string 'null'.";740 if (fill === "null") {741 t = true;742 got = " The string 'null'; Probably fill=null and not fill='null' was intended.";743 }744 }745 if (what === "isotime") {746 desc = "is.FillOK(): Expect length of fill value for a isotime parameter to be equal to length of the string parameter";747 if (len === fill.length && name !== "Time") {748 t = true;749 got = got;750 }751 }752 if (what === "string") {753 desc = "is.FillOK(): Expect length of fill value for a string parameter to be <= length of the string parameter";754 if (len > fill.length) {755 t = true;756 got = got + " string length = " + len + "; fill length = " + fill.length;757 }758 }759 if (what === "stringparse") {760 desc = "is.FillOK(): Expect fill value for a string parameter to not parse to an integer or float";761 if (isinteger(fill) || isfloat(fill)) {762 t = true;763 got = got + " This was probably not intended.";764 }765 }766 if (what === "integer") {767 desc = "is.FillOK(): Expect fill value for a integer parameter to not have a decimal point";768 if (/\./.test(fill)) {769 t = true;770 got = got + " This was probably not intended.";771 }772 }773 if (what === "double") {774 desc = "is.FillOK(): Expect fill value for a double parameter to not have a two or more non-zero decimal places.";775 if (/\.[1-9][1-9]/.test(fill)) {776 t = true;777 got = got + " This is uncommon and was probably not intended.";778 }779 }780 return {"description": desc, "error": t,"got": got};781}782exports.FillOK = FillOK;783function SizeCorrect(nc,nf,header) {784 var t = nc == nf785 if (header.size) {786 var extra = "product of elements in size array " + JSON.stringify(header.size);787 var got = nc + " commas and " + extra + " = " + nf;788 } else {789 if (nf == 0) {790 var extra = "0 because only Time requested.";791 } else {792 var extra = "1 because no size given.";793 }794 var got = nc + " commas";795 }796 return {"description": "is.SizeCorrect(): Expect number of commas on first line to be " + extra, "error": t !=true,"got": got};797}798exports.SizeCorrect = SizeCorrect;799function SizeAppropriate(size,name,what) {800 if (!size) return; // Test not appropriate.801 if (typeof(size) !== 'object') return; // Test not appropriate.802 if (what === "needed") {803 // Test if all elements of size are 1.804 t = 0;805 for (var i=0;i<size.length;i++) {806 t = t + size[i];807 }808 t = t == size.length;809 return {"description": "is.SizeAppropriate(): Size is not needed if all elements are 1.", "error": t, "got": "size = " + JSON.stringify(size) + " for parameter " + name};810 }811 if (what === "2D+") {812 // Test size array has 2 or more elements.813 t = false;814 if (size) {815 t = (size.length > 1)816 }817 return {"description": "is.SizeAppropriate(): Size arrays with more than one element are experimental.", "error": t, "got": "size = " + JSON.stringify(size) + " for parameter " + name};818 }819}820exports.SizeAppropriate = SizeAppropriate;821function HTTP200(res){822 var body = "";823 if (res.statusCode != 200) {824 try {825 var json = JSON.parse(res.body);826 var body = " and JSON body\n\t" + JSON.stringify(body,null,4).replace(/\n/g,"\n\t");827 } catch (error) {828 }829 if (!body) {830 var body = " and non JSON.parse()-able body:\n" + res.body.replace(/\n/g,"\n\t");831 } else {832 var body = "";833 }834 }835 return {"description": "is.HTTP200(): Expect HTTP status code to be 200", "error": 200 != res.statusCode, "got": "HTTP status " + res.statusCode + body};836}837exports.HTTP200 = HTTP200;838function CorrectLength(str,len,name,required) {839 var extra = extra || ""840 var required = required || false841 var got = "(" + (str.length) + ") - (" + (len) + ")"842 var t = str.length != len;843 if (t && !required) {844 got = got + extra + " Not an error for format=csv, but will cause error for format=binary."845 }846 return {"description": 'is.CorrectLength(): Expect (trimmed length of ' + name + ' string parameter in CSV) - (parameters.'+ name + '.length) = 0.', "error": t, "got": got}847}848exports.CorrectLength = CorrectLength;849function TimeInBounds(lines,start,stop) {850 // Remove Z from all times so Date().getTime() gives local timezone time for all.851 // Javascript Date assumes all date/times are in local timezone.852 var start = start.trim().replace(/Z$/,"");853 var stop = stop.trim().replace(/Z$/,"");854 var firstTime = lines[0].split(",").shift().trim().replace(/Z$/,"");855 var lastTime = firstTime;856 // Find the last line with content.857 for (var i = 0;i<lines.length-1;i++) {858 if (lines[lines.length-i-1] !== '') {859 lastTime = lines[lines.length-i-1].split(",").shift().trim().replace(/Z$/,"");860 break;861 }862 }863 var got = "First time = " + firstTime + "; LastTime = " + lastTime;864 var t = moment(firstTime).valueOf() >= moment(start).valueOf() && moment(lastTime).valueOf() < moment(stop).valueOf();865 return {"description": "is.TimeInBounds(): Expect first time in CSV >= " + start + " and last time in CSV < " + stop + " (only checks to ms)","error": t != true,"got":got};866}867exports.TimeInBounds = TimeInBounds;868function TimeIncreasing(header,what) {869 if (what === "CSV") {870 var got = "Monotonically increasing time in CSV"871 var starttest = new Date().getTime();872 var ts = got;873 // Remove blanks (caused by extra newlines)874 header = header.filter(function(n){ return n != '' });875 // Don't run test if only one record.876 if (header.length == 1) {return;} 877 878 for (i = 0;i < header.length-1;i++) {879 var line = header[i].split(",");880 var linenext = header[i+1].split(",");881 //var t = new Date(linenext[0].trim()).getTime() > new Date(line[0].trim()).getTime();882 if (!line || !linenext) {883 t = false;884 got = "Problem with line " + (i) + " or " + (i+1);885 break;886 }887 try {888 var t = moment( trailingZfix(linenext[0].trim()) ).valueOf() > moment( trailingZfix(line[0].trim()) ).valueOf();889 } catch (e) {890 t = false;891 got = "Was not able to parse either " + linenext[0].trim() + " or " + line[0].trim();892 break;893 }894 //console.log(linenext[0].trim())895 //console.log(moment.valueOf(linenext[0].trim()))896 if (!t) {897 var ts = "Time(line="+(i+1)+") > Time(line="+i+")";898 var got = "line " + (i+1) + " = "+ linenext[0] + "; line " + (i) + " = " + line[0];899 break; 900 }901 if (new Date().getTime() - starttest > 10) {902 // Stop testing after 10 ms.903 got = got + " in first " + (i+1) + " lines.";904 break;905 }906 }907 }908 if (what === "{start,stop}Date") {909 var start = trailingZfix(header.startDate);910 var stop = trailingZfix(header.stopDate);911 var ts = "info.startDate < info.stopDate";912 //var t = new Date(start).getTime() < new Date(stop).getTime();913 var t = moment(start).valueOf() < moment(stop).valueOf();914 var got = "startDate = " + start + "; stopDate = " + stop;915 }916 if (what === "sample{Start,Stop}Date") {917 var start = trailingZfix(header.sampleStartDate);918 var stop = trailingZfix(header.sampleStopDate);919 if (!start && !stop) return false;920 if (start && stop) {921 //var t = new Date(start).getTime() < new Date(stop).getTime();922 var t = moment(start).valueOf() < moment(stop).valueOf();923 var ts = "info.sampleStartDate < info.sampleStopDate";924 var got = "sampleStartDate = " + start + "; sampleStopDate = " + stop;925 } else {926 if (!stop) {927 var ts = "info.sampleStartDate does not have a matching sampleStopDate";928 var t = false;929 var got = "a missing date";930 } else {931 var ts = "info.sampleStopDate does not have a matching sampleStartDate";932 var t = false;933 var got = "a missing date"; 934 }935 }936 }937 if (t) {938 got = got.replace(">","<");939 }940 return {"description": "is.TimeIncreasing(): Expect " + ts, "error": t != true, "got":got};941}942exports.TimeIncreasing = TimeIncreasing;943function ISO8601(str,extra) {944 // TODO: Change to HAPIISO8601.945 // https://github.com/hapi-server/data-specification/issues/54946 var extra = extra || ""947 var t = moment(trailingZfix(str),moment.ISO_8601).isValid();948 var ts = "moment('" + trailingZfix(str) + "',moment.ISO_8601).isValid() == true"+extra;949 return {"description":"is.ISO8601(): Expect " + ts,"error":t != true,"got":"moment(" + trailingZfix(str) + ",moment.ISO_8601).isValid() = " + t};950}951exports.ISO8601 = ISO8601;952function HAPITime(isostr,version) {953 schemaregexes = timeregexes(version);954 // schemaregexes come from list in a schema file in ./schemas.955 var got,str,result;956 var t = true;957 if (typeof(isostr) === 'object') {958 var starttest = new Date().getTime();959 got = "Valid HAPI Time strings";960 for (var i = 0; i < isostr.length; i++) {961 if (isostr[i] === '') {break};962 str = isostr[i].split(",")[0].trim();963 result = HAPITime(str,version);964 if (result.error == true) {965 t = false;966 got = "'" + str + "'" + " is not a valid HAPI Time string.";967 if (!/Z$/.test(str)) {968 got = got + " (Missing trailing Z.)";969 }970 if (!/^[0-9]$/.test(str)) {971 got = got + " (First character is not [0-9].)";972 }973 break;974 }975 if (new Date().getTime() - starttest > 10) {976 // Stop testing after 10 ms.977 got = got + " in first " + (i+1) + " lines.";978 break;979 }980 //console.log(isostr[i] + " " + t)981 }982 var url = "https://github.com/hapi-server/verifier-nodejs/tree/master/schemas/HAPI-data-access-schema-"+version+".json";983 return {"description":"is.HAPITime(): Expect time column to contain valid <a href='"+url+"'>HAPI " + version + " HAPITime strings</a>","error":t != true,"got":got};984 }985 // Tests if a string is a valid HAPI time representation, which is a subset of ISO 8601.986 // Two tests are made: (1) A set of regular expressions in the JSON schema (see ./schemas)987 // and (2) A set of semantic tests.988 // The semantic tests are that:989 // (1) DOY can be no more than 365 on non-leap years, 366 on leap years,990 // (2) DOM must be valid991 function isleap(year) {return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)}992 var regex_pass = false;993 var re;994 for (var i = 0;i < schemaregexes.length;i++) {995 re = new RegExp(schemaregexes[i]);996 regex_pass = re.test(isostr);997 if (regex_pass) {998 //console.log(' Passing pattern:' + schemaregexes[i])999 break;1000 }1001 }1002 //console.log(" Regex pass: " + regex_pass);1003 var semantic_pass = true;1004 if (regex_pass) { // Only check semantic rules if regular expression test passed.1005 var year = parseInt(isostr.slice(0,4));1006 var isostr_split = isostr.split(/-|T/);1007 if (isostr_split.length > 1) {1008 if (isostr_split[1].length == 3) {1009 var doy = parseInt(isostr_split[1]);1010 } else {1011 var mo = parseInt(isostr_split[1]);1012 isostr_split = isostr.split(/-/);1013 if (isostr_split.length > 2) {1014 var day = parseInt(isostr_split[2]);1015 }1016 }1017 }1018 // DOY can be no more than 365 on non-leap years, 366 on leap years1019 if (doy == 366 && isleap(year) == false) {1020 semantic_pass = false;1021 }1022 if (doy > 366) {1023 semantic_pass = false;1024 }1025 // DOM must be correct1026 if (day) {1027 if ([4,6,9,11].includes(mo) && day > 30) {1028 semantic_pass = false;1029 }1030 if (mo == 2 && isleap(year) && day > 29) {1031 semantic_pass = false;1032 }1033 if (mo == 2 && !isleap(year) && day > 28) {1034 semantic_pass = false;1035 }1036 }1037 }1038 //console.log(" Semantic pass: " + regex_pass);1039 var e = !(regex_pass && semantic_pass);1040 //if (t==false) {console.log("x" + isostr)}1041 return {"description":"is.HAPITime(): Expect time value to be a valid HAPI time string.", "error": e, "got": got};1042}1043exports.HAPITime = HAPITime;1044function Integer(str,extra) {1045 var extra = extra || ""1046 var t = isinteger(str);1047 var ts = "(parseInt('"+str+"') < 2^31 - 1 || parseInt('"+str+"') > -2^31) && parseInt(" + str + ") == parseFloat(" + str + ")"+extra;1048 return {"description":"is.Integer(): Expect " + ts, "error":t != true, "got":"parseInt(" + str + ") = " + parseInt(str) + " and " + "parseFloat(" + str + ") = " + parseFloat(str)};1049}1050exports.Integer = Integer;1051function Float(str,extra) {1052 var extra = extra || ""1053 var t = isfloat(str);1054 var ts = "Math.abs(parseFloat('"+str+"')) < " + Number.MAX_VALUE + " && /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]{1,3})?$/.test('"+str+"'.trim()) == true"+extra;1055 return {"description":"is.Float(): Expect " + ts, "error":t != true, "got": t};1056}1057exports.Float = Float;1058function NaN(str,extra) {1059 var extra = extra || ""1060 t = str.trim().toLowerCase();1061 ts = "'" + str + "'.trim().toLowerCase() === 'nan'"+extra;1062 return {"description":"is.NaN(): Expect " + ts,"error":t !== "nan","got":"'" + str + "'.trim().toLowerCase() = " + t};1063}1064exports.NaN = NaN;1065function Unique(arr,arrstr,idstr){1066 if (!arr.length) {1067 return {"description":"is.Unique(): Expect " + arrstr + " to be an array","error":true,"got": typeof(arr)};1068 }1069 var ids = [];1070 var rids = [];1071 for (var i = 0;i<arr.length;i++) {1072 if (!arr[i][idstr]) continue;1073 if (ids.indexOf(arr[i][idstr]) > -1 && rids.indexOf(arr[i][idstr])) {1074 rids.push(arr[i][idstr]);1075 }1076 ids[i] = arr[i][idstr];1077 }1078 var uids = Array.from(new Set(ids)); // Unique values1079 1080 var e = !(uids.length == ids.length);1081 if (e) {1082 var got ="Repeated at least once: " + rids.join(",");1083 } else {1084 var got ="All unique.";1085 }1086 return {"description":"is.Unique(): Expect all '" + idstr + "' values in objects in " + arrstr + " array to be unique","error":e,"got": got};1087}1088exports.Unique = Unique;1089function TooLong(arr,arrstr,idstr,elstr,N){1090 // idstr = "id" for datasets and "name" for parameter.1091 var ids = [];1092 for (var i = 0;i<arr.length;i++) {1093 if (!arr[i][elstr]) continue;1094 if (arr[i][elstr]) {1095 if (arr[i][elstr].length > N) {1096 ids.push(arr[i][idstr]);1097 }1098 }1099 }1100 var got = "All objects in " + arrstr + " are shorter than " + N + " characters"1101 if (ids.length > 0) {1102 got = arrstr + " has " + ids.length + " object(s) (" + ids.join(",") + ") with " + elstr + " longer than " + N + " characters"1103 }1104 return {"description":"is.TooLong(): Prefer " + elstr + "s in objects to be <= 40 characters","error":ids.length != 0,"got": got};1105}1106exports.TooLong = TooLong;1107function CORSAvailable(head) {1108 var ahead = "Access-Control-Allow-Origin";1109 var astr = head[ahead.toLowerCase()];1110 var a = /\*/.test(astr);1111 var bhead = "Access-Control-Allow-Methods";1112 var bstr = head[bhead.toLowerCase()];1113 var b = /GET/.test(bstr);1114 var want = "Access-Control-Allow-{Origin,Methods} = " + "{*, GET}";1115 var got = "Access-Control-Allow-{Origin,Methods} = {" + astr + ", " + bstr + "}";1116 var e = !(a && b);1117 return {"description":"is.CORSAvailable(): To enable AJAX clients, want CORS HTTP Headers: " + want,"error":e,"got":got};1118}1119exports.CORSAvailable = CORSAvailable;1120function CompressionAvailable(headers){1121 var available = false;1122 // Note: request module used for http requests only allows gzip to be specified in Accept-Encoding,1123 // so error here may be misleading if server can use compress or deflate compression algorithms but not gzip (should be a rare occurence).1124 var got = "No gzip in Content-Encoding header. Compression will usually speed up transfer of data."1125 var re = /gzip/;1126 if (headers["content-encoding"]) {1127 var available = re.test(headers["content-encoding"]);1128 if (available) {got = headers["content-encoding"]}1129 }1130 return {"description":"is.CompressionAvailable(): Expect HTTP Accept-Encoding to match " + re + ". (Note, only compression tested for is gzip.)", "error": !available, "got": got};1131}1132exports.CompressionAvailable = CompressionAvailable;1133function ContentType(re,given){1134 return {"description":"is.ContentType(): Expect HTTP Content-Type to match " + re,"error":!re.test(given),"got":given || "No Content-Type header."};1135}1136exports.ContentType = ContentType;1137function JSONparsable(text) {1138 var ret = {"description":"is.JSONparsable(): Expect JSON.parse(response) to not throw error","error":false,"got":"no error"};1139 try {1140 JSON.parse(text);1141 return ret;1142 } catch (error) {1143 ret.got = error + " See http://jsonlint.org/ for a more detailed error report";1144 ret.error = true;1145 return ret;1146 }1147}1148exports.JSONparsable = JSONparsable;1149function HAPIJSON(text,version,part){1150 s = schema(version);1151 if (!s) {1152 return {1153 "description": "is.HAPIJSON(): Expect HAPI version to be one of " + JSON.stringify(Object.keys(schemas)),1154 "error": true,1155 "got": "Schema version " + version + " not one of " + JSON.stringify(Object.keys(schemas))1156 };1157 }1158 if (typeof(text) === "object") {1159 var json = text;1160 } else {1161 var json = JSON.parse(text);1162 }1163 1164 var v = new Validator();1165 // Look for all top-level elements that have an id starting with a /.1166 // These are subschemas that are used.1167 for (key in s) {1168 if (s[key]["id"] && s[key]["id"][0] === "/") {1169 v.addSchema(s[key], s[key]["id"]);1170 }1171 }1172 try {1173 var vr = v.validate(json, s[part]);1174 } catch (e) {1175 return {1176 "description": "is.HAPIJSON(): Call to JSON validator failed",1177 "error": true,1178 "got": "Schema version " + e1179 };1180 }1181 var ve = vr.errors;1182 var got = "is valid"1183 if (ve.length != 0) {1184 var err = [];1185 for (var i = 0;i< ve.length;i++) {1186 //err[i] = ve[i].property.replace("instance","object") + " " + ve[i].message.replace(/\"/g,"'");1187 err[i] = ve[i].property.replace("instance.","") + " " + ve[i].message.replace(/\"/g,"'");1188 }1189 got = "\n\t" + JSON.stringify(err,null,4).replace(/\n/g,"\n\t")1190 }1191 var url = "https://github.com/hapi-server/verifier-nodejs/tree/master/schemas/HAPI-data-access-schema-"+version+".json";1192 return {"description":"is.HAPIJSON(): Expect body to be valid <a href='"+url+"'>HAPI " + version + " " + part + " schema</a>","error":ve.length != 0,"got":got};1193}...
FilterNonEligibleDiffs.ts
Source:FilterNonEligibleDiffs.ts
1import { PoisoningFreeArray, PushSymbol } from './PoisoningFreeArray';2import { GlobalDetails } from './types/AllGlobals';3export type SubDiffOnGlobal = {4 keyName: string;5 globalDetails: Pick<GlobalDetails, 'depth' | 'name' | 'rootAncestors'>;6};7/** Create a new arrays of diffs containing only eligible ones */8export function filterNonEligibleDiffs<TDiff extends SubDiffOnGlobal>(9 diffs: TDiff[],10 ignoredRootRegex: RegExp11): TDiff[] {12 const keptDiffs = PoisoningFreeArray.from<TDiff>([]);13 for (let index = 0; index !== diffs.length; ++index) {14 const diff = diffs[index];15 switch (diff.globalDetails.depth) {16 case 0: {17 if (!ignoredRootRegex.test(diff.keyName)) {18 keptDiffs[PushSymbol](diff);19 }20 break;21 }22 case 1: {23 if (!ignoredRootRegex.test(diff.globalDetails.name)) {24 keptDiffs[PushSymbol](diff);25 }26 break;27 }28 default: {29 let allRootsIgnored = true;30 const allRoots = [...diff.globalDetails.rootAncestors];31 for (let rootIndex = 0; rootIndex !== allRoots.length; ++rootIndex) {32 allRootsIgnored = allRootsIgnored && ignoredRootRegex.test(allRoots[rootIndex]);33 }34 if (!allRootsIgnored) {35 keptDiffs[PushSymbol](diff);36 }37 break;38 }39 }40 }41 return keptDiffs;...
Using AI Code Generation
1const keptDiffs = require('fast-check-monorepo').keptDiffs;2const fc = require('fast-check');3const assert = require('assert');4fc.assert(5 fc.property(fc.integer(), fc.integer(), (a, b) => {6 assert.notStrictEqual(a, b);7 keptDiffs(a, b);8 })9);
Using AI Code Generation
1const keptDiffs = require('fast-check').keptDiffs;2const fs = require('fs');3const test = require('ava');4const { check, property } = require('ava-fast-check');5const { diffChars } = require('diff');6const { JsonParser } = require('json2csv');7const { keptDiffs: keptDiffs2 } = require('fast-check');8const { keptDiffs: keptDiffs3 } = require('fast-check-monorepo');9const { keptDiffs: keptDiffs4 } = require('../lib');10const { keptDiffs: keptDiffs5 } = require('../lib/index');11const { keptDiffs: keptDiffs6 } = require('../lib/index.js');12const { keptDiffs: keptDiffs7 } = require('../lib/index.ts');13const { keptDiffs: keptDiffs8 } = require('../lib/index.tsx');14const { keptDiffs: keptDiffs9 } = require('../lib/index.d.ts');15const { keptDiffs: keptDiffs10 } = require('../lib/index.d.tsx');16const { keptDiffs: keptDiffs11 } = require('../lib/index.json');17const { keptDiffs: keptDiffs12 } = require('../lib/index.yaml');18const { keptDiffs: keptDiffs13 } = require('../lib/index.yml');19const { keptDiffs: keptDiffs14 } = require('../lib/index.css');20const { keptDiffs: keptDiffs15 } = require('../lib/index.scss');21const { keptDiffs: keptDiffs16 } = require('../lib/index.less');22const { keptDiffs: keptDiffs17 } = require('../lib/index.html');23const { keptDiffs: keptDiffs18 } = require('../lib/index.md');24const { keptDiffs: keptDiffs19 } = require('../lib/index.txt');25const { keptDiffs: keptDiffs20 } = require('../lib/index.js.map');26const { keptDiffs: keptDiffs21 } = require('../lib/index.ts.map');27const { keptDiffs: keptDiffs22 } = require('../lib/index.tsx.map');28const { keptDiffs: keptDiffs23 } = require('../lib/index.d.ts.map');
Using AI Code Generation
1const keptDiffs = require('fast-check-monorepo/kept-diffs');2const keptDiffs = require('fast-check-monorepo/kept-diffs');3const keptDiffs = require('fast-check-monorepo/kept-diffs');4const keptDiffs = require('fast-check-monorepo/kept-diffs');5const keptDiffs = require('fast-check-monorepo/kept-diffs');6const keptDiffs = require('fast-check-monorepo/kept-diffs');7const keptDiffs = require('fast-check-monorepo/kept-diffs');8const keptDiffs = require('fast-check-monorepo/kept-diffs');9const keptDiffs = require('fast-check-monorepo/kept-diffs');10const keptDiffs = require('fast-check-monorepo/kept-diffs');11const keptDiffs = require('fast-check-monorepo/kept-diffs');12const keptDiffs = require('fast-check-monorepo/kept-diffs');13const keptDiffs = require('fast-check-monorepo/kept-diffs');14const keptDiffs = require('fast-check-monorepo/kept-diffs');15const keptDiffs = require('fast
Using AI Code Generation
1const { keptDiffs } = require('fast-check-monorepo');2const { property } = require('fast-check');3const { strictEqual } = require('assert');4const isEven = (n) => n % 2 === 0;5const isOdd = (n) => n % 2 !== 0;6property(isOdd, isEven).check({ numRuns: 1000 }).then((result) => {7 keptDiffs(result, { maxNbDiffs: 10 }).forEach((diff) => {8 console.log('---');9 console.log('seed: ' + diff.seed);10 console.log('counterexample: ' + diff.counterexample);11 });12});
Using AI Code Generation
1const { keptDiffs } = require('fast-check-monorepo');2const { check, property } = require('fast-check');3const { keptDiffs } = require('fast-check-monorepo');4check(property(keptDiffs(), (diffs) => {5}), { numRuns: 1000 });6const { keptDiffs } = require('fast-check-monorepo');7const { check, property } = require('fast-check');8const { keptDiffs } = require('fast-check-monorepo');9check(property(keptDiffs(), (diffs) => {10}), { numRuns: 1000 });11const { keptDiffs } = require('fast-check-monorepo');12const { check, property } = require('fast-check');13const { keptDiffs } = require('fast-check-monorepo');14check(property(keptDiffs(), (diffs) => {15}), { numRuns: 1000 });16const { keptDiffs } = require('fast-check-monorepo');17const { check, property } = require('fast-check');18const { keptDiffs } = require('fast-check-monorepo');19check(property(keptDiffs(), (diffs) => {20}), { numRuns: 1000 });21const { keptDiffs } = require('fast-check-monorepo');22const { check, property } = require('fast-check');23const { keptDiffs } = require('fast-check-monorepo');24check(property(keptDiffs(), (diffs) => {25}), { numRuns: 1000 });26const { keptDiffs } = require('fast-check-monorepo');27const { check, property } = require('fast-check');28const { keptDiffs } = require('fast-check-monorepo');29check(property(keptDiffs(), (diffs) => {
Using AI Code Generation
1import { keptDiffs } from 'fast-check-monorepo';2import { Arbitrary } from 'fast-check';3const myArbitrary: Arbitrary<number> = keptDiffs(4 {5 },6 (a, b) => a - b,7 (a, b) => a - b8);9myArbitrary.generate(mrng => mrng.nextInt());10import { keptDiffs } from 'fast-check-monorepo';11import { Arbitrary } from 'fast-check';12const myArbitrary: Arbitrary<number> = keptDiffs(13 {14 },15 (a, b) => a - b,16 (a, b) => a - b17);18myArbitrary.generate(mrng => mrng.nextInt());19import { keptDiffs } from 'fast-check-monorepo';20import { Arbitrary } from 'fast-check';21const myArbitrary: Arbitrary<number> = keptDiffs(22 {23 },24 (a, b) => a - b,25 (a, b) => a - b26);27myArbitrary.generate(mrng => mrng.nextInt());28function keptDiffs<T>(29 diff: (a: T, b: T) => number,30 diff2: (a: T, b: T) => number31): Arbitrary<T>;
Using AI Code Generation
1const fc = require('fast-check');2const { keptDiffs } = require('fast-check-monorepo');3const obj1 = {4};5const obj2 = {6};7const compare = (a, b) => {8 return keptDiffs(a, b);9};10 .tuple(11 fc.string(),12 fc.integer(),13 fc.boolean(),14 fc.float(),15 fc.date(),16 fc.array(fc.string()),17 fc.record({18 a: fc.string(),19 b: fc.integer(),20 })21 .map(([a, b, c, d, e, f, g]) => {22 return { a, b, c, d, e, f, g };23 });24fc.assert(25 fc.property(objArb, objArb, (a, b) => {26 return compare(a, b);27 })28);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!