-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathis.js
2084 lines (1914 loc) · 63.1 KB
/
is.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const fs = require('fs')
const path = require('path')
const diff = require('deep-diff').diff
const moment = require('moment')
const Validator = require('jsonschema').Validator
const schemaURL = 'https://github.com/hapi-server/verifier-nodejs/tree/master/schemas'
const wikiURL = 'https://github.com/hapi-server/verifier-nodejs/wiki'
const requestURL = 'https://github.com/request/request#requestoptions-callback'
const jsonLintLink = "<a href='http://jsonlint.org/'>http://jsonlint.org/</a>"
const unitsAndLabels = 'https://github.com/hapi-server/data-specification/blob/master/hapi-dev/HAPI-data-access-spec-dev.md#369-unit-and-label-arrays'
const deepDiffLink = '<a href="https://www.npmjs.com/package/deep-diff">deep-diff</a>'
const base = path.join(__dirname, 'data-specification-schema/')
const schemas = {}
fs.readdirSync(base).forEach(file => {
if (file.startsWith('HAPI-data-access-schema') && path.extname(file) === '.json') {
const version = path.basename(file, '.json').split('schema-').pop();
schemas[version] = require(path.join(base, file))
}
})
const schemaVersions = Object.keys(schemas).sort()
exports.schemaVersions = schemaVersions
function schema (version) {
const json = schemas[version]
if (!json) {
return false
} else {
return schemas[version]
}
}
function prod (arr) {
// TODO: Also in tests.js. Move to lib.js (and create lib.js)
// Compute product of array elements.
return arr.reduce(function (a, b) { return a * b })
}
function callerName () {
return 'is.' + callerName.caller.name + '(): '
}
function isinteger (str) {
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())
}
function isfloat (str) {
return str.trim() === "NaN" || Math.abs(parseFloat(str)) < Number.MAX_VALUE &&
/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]{1,3})?$/.test(str.trim())
}
function nFields (header, pn) {
let nf = 1
if (pn === 0) {
// Primary time parameter
return nf
}
if (pn !== undefined && pn !== null) {
// One parameter
// nf = number of fields (columns) counter (start at 1 since time checked already)
if (!header.parameters[pn].size) {
nf = nf + 1 // Width of field (number of columns of field)
} else {
nf = nf + prod(header.parameters[pn].size)
}
} else {
// All parameters
nf = 0 // Number of fields (columns) counter
for (let i = 0; i < header.parameters.length; i++) {
if (!header.parameters[i].size) {
nf = nf + 1 // Width of field (number of columns of field)
} else {
nf = nf + prod(header.parameters[i].size)
}
}
}
return nf
}
function csvToArray (text) {
// https://stackoverflow.com/a/41563966/1491619
let p = ''; let row = ['']; const ret = [row]; let i = 0; let r = 0; let s = !0; let l
for (l of text) {
if (l === '"') {
if (s && l === p) row[i] += l
s = !s
} else if (l === ',' && s) l = row[++i] = ''
else if (l === '\n' && s) {
if (p === '\r') row[i] = row[i].slice(0, -1)
row = ret[++r] = [l = '']; i = 0
} else row[i] += l
p = l
}
return ret
}
function versionWarning (version) {
if (parseFloat(version) >= 3.2) {
// GitHub does not allow link to milestone string. Instead, it uses the milestone number.
// To link directly, would need to create a label that is same as milestone string.
const verifierMileStone = `<a href="https://github.com/hapi-server/verifier-nodejs/issues?q=is%3Aissue+is%3Aopen+label%3A3.2">verifier ${version} milestone issues</a>`
const schemaMileStone = `<a href="https://github.com/hapi-server/data-specification-schema/issues?q=is%3Aissue+is%3Aopen+label%3A3.2">schema ${version} milestone issues</a>`
return `; <span style="background-color: yellow">Warning: HAPI schema version ${version} is in development. ` +
`See ${verifierMileStone} and ${schemaMileStone}</span>`
}
return ''
}
function HAPIVersionSame (url, version, urlLast, versionLast) {
const des = 'Expect HAPI version to match that from previous requests when given.'
let got = `Current: '<code>${version}</code>' and Last: '<code>${versionLast}</code>'`
let err = false
if (version !== versionLast) {
got = `<code>${version}</code> for ${url}\n<code>${versionLast}</code> for ${urlLast}`
err = true
}
return {
description: callerName() + des,
error: err,
got
}
}
exports.HAPIVersionSame = HAPIVersionSame
function HAPIVersion (version, ignoreVersionError) {
let got = '<code>' + version + '</code>'
let err = false
if (!schemaVersions.includes(version)) {
err = true
got = "'<code>" + version + "</code>', which is not valid or not implemented by verifier."
if (ignoreVersionError) {
got += ' Will use latest version implemented by verifier: ' + schemaVersions.pop()
}
}
const des = 'Expect HAPI version in JSON response to be one of ' +
'<code>' +
JSON.stringify(schemaVersions) +
'</code>'
return {
description: callerName() + des,
error: err,
got
}
}
exports.HAPIVersion = HAPIVersion
function JSONParsable (text) {
const ret = {
description: callerName() + 'Expect <code>JSON.parse(response)</code> to not throw error',
error: false,
got: ''
}
try {
const json = JSON.parse(text)
ret.json = json
return ret
} catch (error) {
ret.got = 'JSON.parse of:\n\n' + text + '\n\nresulted in ' + error +
'. Use ' + jsonLintLink +
' for a more detailed error report. '
ret.error = true
return ret
}
}
exports.JSONParsable = JSONParsable
function HAPIJSON (text, version, part, ignoreVersionError) {
const s = schema(version)
if (s === false) {
const known = JSON.stringify(Object.keys(schemas))
const desc = 'Expect HAPI version to be one of <code>' + known + '</code>'
const got = `Schema version '<code>${version}</code>' is not one of <code>${known}</code>`
return {
description: callerName() + desc,
error: true,
got
}
}
let json = text
if (typeof (text) !== 'object') {
json = JSON.parse(text)
}
const v = new Validator()
// Look for all top-level elements that have an id starting with a /.
// These are subschemas that are used.
for (const key in s) {
if (s[key].id && s[key].id[0] === '/') {
// console.log("Adding schema " + s[key]["id"]);
v.addSchema(s[key], s[key].id)
}
}
if (part === 'error' && parseInt(version.split('.')) < 3) {
// In version 3+, error is a top-level element.
part = 'HAPIStatus'
}
if (ignoreVersionError && !s[part]) {
return
}
if (!s[part]) {
const desc = `Expect HAPI JSON schema to have a element named '${part}'.`
const got = `No element named '${part}' in HAPI schema. Is HAPI schema version '${version}' correct?`
return {
description: callerName() + desc,
error: true,
got
}
}
let vr
try {
vr = v.validate(json, s[part])
} catch (e) {
console.log(json)
console.log(part)
console.log(e)
return {
description: callerName() + 'Call to JSON validator failed.',
error: true,
got: e.toString()
}
}
const ve = vr.errors
let got = 'JSON is valid with respect to JSON schema.'
const err = []
if (ve.length !== 0) {
for (let i = 0; i < ve.length; i++) {
if (ignoreVersionError && ve[i].property === 'instance.HAPI') {
continue
}
err[i] = ve[i].property.replace('instance.', '') +
' ' + ve[i].message.replace(/"/g, "'")
}
if (err.length > 0) {
got = '\n <pre>' + JSON.stringify(err, null, 4) + '</pre>'
}
}
const url = schemaURL + '/HAPI-data-access-schema-' + version + '.json'
const desc = 'Expect body to be valid ' +
"<a href='" + url + "'>HAPI " +
version + " '" + part + "' schema</a>." +
versionWarning(version)
return {
description: callerName() + desc,
error: err.length !== 0,
got
}
}
exports.HAPIJSON = HAPIJSON
function timeregexes (version) {
const json = schemas[version]
if (!json) {
return false
}
const tmp = json.HAPIDateTime.anyOf
const regexes = []
for (let i = 0; i < tmp.length; i++) {
regexes[i] = tmp[i].pattern
}
return regexes
}
exports.timeregexes = timeregexes
function trailingZfix (str) {
// moment.js does not consider date only with trailing Z to be valid ISO8601
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)) {
str = str.slice(0, -1) + 'T00Z'
}
return str
}
exports.trailingZfix = trailingZfix
function RequestError (err, res, timeoutInfo) {
const tout = timeoutInfo.value
const when = timeoutInfo.when
if (!err) {
// Remove extra precision on timings.
const timings = res.timings
for (const key in timings) {
timings[key] = timings[key].toFixed(1)
}
const timingPhases = res.timingPhases
for (const key in timingPhases) {
timingPhases[key] = timingPhases[key].toFixed(1)
}
let timeInfo = ''
if (timingPhases && timings) {
timeInfo = JSON.stringify(timings) + ', ' + JSON.stringify(timingPhases)
timeInfo = ` <a href='${requestURL}'>Timing info [ms]</a>: ${timeInfo}`
}
return {
description: callerName() + 'Expect no request error for timeout of ' + tout + ' ms when ' + when,
error: false,
got: timeInfo
}
}
if (err.code === 'ETIMEDOUT') {
// https://github.com/request/request/blob/master/request.js#L846
return {
description: callerName() + 'Expect HTTP headers and start of response body in less than ' + tout + ' ms when ' + when,
error: true,
got: err.code
}
} else if (err.code === 'ESOCKETTIMEDOUT') {
// https://github.com/request/request/blob/master/request.js#L811
return {
description: callerName() + 'Expect time interval between bytes sent to be less than ' + tout + ' ms when ' + when,
error: true,
got: err.code
}
} else if (err.code === 'ECONNRESET') {
return {
description: callerName() + 'Expect connection to not be reset by server',
error: true,
got: 'ECONNRESET'
}
} else if (err.code === 'ECONNREFUSED') {
return {
description: callerName() + 'Expect connection to not be refused by server',
error: true,
got: err.code
}
} else {
return {
description: callerName() + 'URL is malformed?',
error: true,
got: err
}
}
}
exports.RequestError = RequestError
function CadenceGiven (cadence) {
const base = 'https://github.com/hapi-server/data-specification/'
const url = base + 'blob/master/hapi-dev/HAPI-data-access-spec-dev.md'
const desc = 'Expect the nominal cadence to be given ' +
`(see <a href='${url}'>` +
'the HAPI spec for definition</a>). A nominal cadence is useful ' +
'for clients and obviates the need for it to be inferred programatically.'
return {
description: callerName() + desc,
error: typeof (cadence) !== 'string',
got: cadence || 'no cadence'
}
}
exports.CadenceGiven = CadenceGiven
function CadenceValid (cadence) {
// https://stackoverflow.com/a/53140944/1491619
// TODO: Move to JSON schema.
const re = /^P(?!$)((\d+Y)|(\d+\.\d+Y$))?((\d+M)|(\d+\.\d+M$))?((\d+W)|(\d+\.\d+W$))?((\d+D)|(\d+\.\d+D$))?(T(?=\d)((\d+H)|(\d+\.\d+H$))?((\d+M)|(\d+\.\d+M$))?(\d+(\.\d+)?S)?)??$/
const t = re.test(cadence) === true
let got = cadence + ' valid.'
if (t === false) {
got = cadence + ' is invalid.'
if (typeof (cadence) === 'string' && cadence.toUpperCase() === cadence) {
got = got + ' (Letters in cadence should be uppercase.)'
}
}
const desc = 'Expect cadence to be a valid ISO8601 duration ' +
'(regular expression tested: ' + re.toString() + ').'
return {
description: callerName() + desc,
error: t === false,
got
}
}
exports.CadenceValid = CadenceValid
function CadenceOK (cadence, start, stop, what) {
if (!cadence) return // Don't do test; no cadence given.
if (!stop) {
const desc = 'Need more than two lines to do cadence ' +
'comparison with consecutive samples.'
return {
description: callerName() + desc,
error: true,
got: 'One line.'
}
}
// console.log(start)
// console.log(stop)
start = trailingZfix(start)
stop = trailingZfix(stop)
const t1 = moment(trailingZfix(start), moment.ISO_8601).isValid()
const t2 = moment(trailingZfix(stop), moment.ISO_8601).isValid()
if (!t1 || !t2) {
return {
description: callerName() + `Could not parse start = '${start}' or stop = '${stop}'`,
error: true,
got: `start = '${start}' and stop = '${stop}'`
}
}
const startms = moment(start).valueOf()
const stopms = moment(stop).valueOf()
const md = moment.duration(cadence)
const R = (stopms - startms) / md._milliseconds
if (what === 'start/stop') {
const t = R > 1
const got = '(stopDate-startDate)/cadence = ' + (stopms - startms) / md._milliseconds
return {
description: callerName() + 'Expect (stopDate-startDate)/cadence > 1',
error: t !== true,
got
}
}
if (what === 'sampleStart/sampleStop') {
const t = R > 10
const got = '(sampleStartDate-sampleStopDate)/cadence = ' + (stopms - startms) / md._milliseconds
const desc = 'Expect (sampleStopDate-sampleStartDate)/cadence > 10'
return {
description: callerName() + desc,
error: t !== true,
got
}
}
if (what === 'consecsamples') {
const t = R > 10
const got = 'Cadence/(time[i+1]-time[i]) = ' + (stopms - startms) / md._milliseconds
return {
description: callerName() + 'Expect (t[i+1]-t[i])/cadence > 10',
error: t !== true,
got
}
}
}
exports.CadenceOK = CadenceOK
function CIdentifier (arr, type) {
// https://stackoverflow.com/questions/14953861/
// representing-identifiers-using-regular-expression
const reString = '[_a-zA-Z][_a-zA-Z0-9]{1,30}'
let arrayFail = []
const re = new RegExp(reString)
for (let i = 0; i < arr.length; i++) {
const m = arr[i].id.match(re)
if (m) {
const t = m[0] === m.input
if (!t) {
arrayFail.push(arr[i].id)
}
} else {
// Happens with Unicode in id.
arrayFail.push(arr[i].id)
}
}
let got = 'All ' + type + '(s) match.'
if (arrayFail.length > 0) {
const No = arrayFail.length
if (arrayFail.length > 10) {
arrayFail = arrayFail.slice(0, 10)
arrayFail.push('\n ... (' + (No - 10) + ') more.')
}
got = No + ' datasets ids that are not c identfiers:\n\n' + arrayFail.join('\n')
}
const desc = `Prefer ${type} to match c identifier regex '<code>${reString}</code>'.`
return {
description: callerName() + desc,
error: arrayFail.length > 0,
got
}
}
exports.CIdentifier = CIdentifier
function ErrorCorrect (code, wanted, what) {
if (what === 'httpcode') {
const desc = 'Expect HTTP code in JSON to be <code>' + wanted + '</code>'
return {
description: callerName() + desc,
error: code !== wanted,
got: code !== wanted ? code : ''
}
}
if (what === 'hapicode') {
const t = code === wanted
const got = `<code>${code}</code>`
const desc = 'Expect HAPI code in JSON to be <code>' + wanted + '</code>'
return {
description: callerName() + desc,
error: t !== true,
got
}
}
}
exports.ErrorCorrect = ErrorCorrect
function StatusInformative (message, wanted, what) {
const re = new RegExp(wanted)
const err = re.test(message) === false
const got = `'${message}'.`
const link = `<a href='${wikiURL}#status-informative'>(Explanation.)</a>`
const post = `to contain the string '${wanted}' (default HAPI error message). ${link}`
let desc = 'Want HAPI status message in JSON response' + post
if (what === 'httpstatus') {
desc = 'Want HTTP status message ' + post
}
return {
description: callerName() + desc,
error: err,
got
}
}
exports.StatusInformative = StatusInformative
function HeaderParsable (body) {
const desc = 'Expect header lines in data stream to' +
' be JSON parsable after removal of leading #s.'
const ret = {
description: callerName() + desc,
error: false,
got: ''
}
let csvparts
try {
csvparts = splitCSV(body)
} catch (error) {
ret.got = 'Could not split CSV into header and data parts.'
ret.error = true
return ret
}
ret.csvparts = csvparts
try {
ret.csvparts.header = JSON.parse(csvparts.header)
return ret
} catch (error) {
ret.got = '<code>JSON.parse()</code> of \n\n' + csvparts.header + '\n\nresulted in ' +
error + `. Use ${jsonLintLink} for a more detailed error report.`
ret.error = true
return ret
}
function splitCSV (bodyString) {
let headerString = ''
const bodyLines = bodyString.split(/\r?\n/)
let i
for (i = 0; i < bodyLines.length; i++) {
if (bodyLines[i][0] === '#') {
headerString = headerString + bodyLines[i].slice(1)
} else {
break
}
}
const dataString = bodyLines.slice(i).join('\n')
return {
header: headerString,
data: dataString
}
}
}
exports.HeaderParsable = HeaderParsable
function TypeCorrect (header, body, pn) {
const nf = nFields(header, pn)
const lines = csvToArray(body)
// TODO: Check all lines?
const line1 = lines[0]
let err = false
let got = ''
let rObj = {}
for (let j = 0; j < nf; j++) {
const extra = ' in column ' + j + ' on first line '
let type = header.parameters[pn].type
if (j === 0) {
type = header.parameters[0].type
}
if (type === 'isotime') {
rObj = ISO8601(line1[j].trim(), extra)
if (rObj.error) {
got = rObj.description + `\ngave '<code>${rObj.got}'</code>\n`
err = rObj.error
}
}
if (type === 'integer') {
rObj = Integer(line1[j], extra)
if (rObj.error) {
got = rObj.description + `\ngave '<code>${rObj.got}'</code>\n`
err = rObj.error
}
}
if (type === 'double') {
rObj = Float(line1[j], extra)
if (rObj.error) {
got = rObj.description + '\ngave <code>' + rObj.got + '<code>\n'
err = rObj.error
}
}
}
if (got !== '') {
sline= "" + line1;
if ( sline.length>200 ) {
sline= sline.substring(0,200)+'...('+(sline.length)+' chars)';
}
got = got + 'Line 1: <code>' + sline + '</code>'
}
return {
description: callerName() + 'Expect values on first line of CSV to have correct type.',
error: err,
got: got || 'Correct length and type.'
}
}
exports.TypeCorrect = TypeCorrect
function NumberOfColumnsCorrect (header, body, pn) {
const nf = nFields(header, pn)
const lines = csvToArray(body)
let t = false
let got = '<code>(' + nf + ')' + ' - (' + nf + ')</code>'
if (lines.length === 0) {
got = '<code>(0)' + ' - (' + nf + ')</code>'
}
for (let i = 0; i < lines.length - 1; i++) {
t = nf !== lines[i].length
if (t) {
got = '<code>(' + lines[i].length + ')' + ' - (' + nf + ')</code>'
got = got + ' on line <code>' + (i + 1) + '</code>'
break
}
}
const desc = 'Expect (# of columns in CSV) - ' +
'(# computed from length and size metadata) = 0.'
return {
description: callerName() + desc,
error: t,
got
}
}
exports.NumberOfColumnsCorrect = NumberOfColumnsCorrect
function FileContentSameOrConsistent (header, body, bodyAll, what, pn) {
if (bodyAll === undefined && body !== undefined) {
return {
description: callerName() + 'Consistency with empty response.',
error: true,
got: 'Content differs. One is empty and other is not.'
}
}
if (bodyAll !== undefined && body === undefined) {
return {
description: callerName() + 'Consistency with empty response.',
error: true,
got: 'Content differs. One is empty and other is not.'
}
}
const nf = nFields(header, pn)
const lines = csvToArray(body)
const linesAll = csvToArray(bodyAll)
// var lines = body.split("\n");
// var linesAll = bodyAll.split("\n");
if (what === 'same') {
const desc = 'Expect data response for to be same as previous request with different but equivalent request URL.'
if (bodyAll !== body) { // byte equivalent
if (lines.length !== linesAll.length) {
const got = '<code>' + lines.length + '</code> rows here vs. <code>' +
linesAll.length + '</code> rows previously.'
return {
description: callerName() + desc,
error: true,
got
}
}
// Look for location of difference.
let line = ''
let lineAll = ''
let e1 = false
let e2 = false
let i
for (i = 0; i < lines.length - 1; i++) {
// line = lines[i].split(",");
// lineAll = linesAll[i].split(",");
line = lines[i]
lineAll = linesAll[i]
if (line.length !== lineAll.length) {
e1 = true
break
}
for (let j = 0; j < line.length - 1; j++) {
if (line[j].trim() !== lineAll[j].trim()) {
e2 = true
break
}
}
if (e2) { break }
}
if (e1) {
const got = line.length + ' columns vs. ' +
lineAll.length + ' columns on line ' + (i + 1) + '.'
return {
description: callerName() + desc,
error: true,
got
}
}
if (e2) {
const got = 'Difference on line ' + (i + 1) + ' column ' + (nf + 1) + '.'
return {
description: callerName() + desc,
error: true,
got
}
}
// TODO: Can e1 and e2 be false?
}
return {
description: callerName() + desc,
error: false,
got: 'Match'
}
}
if (what === 'consistent') {
if (lines.length !== linesAll.length) {
const desc = 'Expect number of rows from one parameter request to' +
' match data from all parameter request.'
const got = ' # rows in single parameter request = <code>' + lines.length + '</code>' +
' # in all parameter request = <code>' + linesAll.length + '</code>'
return {
description: callerName() + desc,
error: true,
got
}
}
// Find first column of parameter being checked.
let fc = 0 // First column of parameter.
for (let i = 0; i < header.parameters.length; i++) {
if (header.parameters[i].name === header.parameters[pn].name) {
break
}
if (!header.parameters[i].size) {
fc = fc + 1
} else {
fc = fc + prod(header.parameters[i].size)
}
}
const desc = 'Expect content from one parameter request to' +
' match content from all parameter request.'
let t = false
let got = 'Consistent content'
let gotCount=0
let gotLimit=4
for (let i = 0; i < lines.length - 1; i++) {
// let line = lines[i].split(",");
// let lineAll = linesAll[i].split(",");
const line = lines[i]
const lineAll = linesAll[i]
// Time
if (line[0].trim() !== lineAll[0].trim()) {
t = true
got += '\nTime column does not match at time ' +
line[0] + ": Single parameter request: '" + line[1] +
"'; All parameter request: '" + lineAll[0] + "'."
}
if (pn === 0) {
continue
}
// Number of columns
if (line.length > lineAll.length) {
const desc = 'Expect number of columns from one parameter request to be' +
' equal to or less than number of columns in all parameter request.'
got += '\n# columns in single parameter request = ' + line.length +
' # in all parameter request = <code>' + lineAll.length +
'</code>.'
return {
description: callerName() + desc,
error: true,
got
}
}
// Parameter
// nf = number of fields for parameter
// fc = first column of field for parameter
for (let j = 0; j < nf - 1; j++) {
if (!line[1 + j] || !lineAll[fc + j]) {
t = true
if ( gotCount<gotLimit ) {
got += '\nProblem with line <code>' + (i) + '</code>:\n' +
'Single parameter request: <code>' + line[1 + j] +
'</code>; All parameter request: <code>' + lineAll[fc + j] +
'</code>.'
}
gotCount++
break
}
if (line[1 + j].trim() !== lineAll[fc + j].trim()) {
let name = '#' + header.parameters[pn].name
if (header.parameters[pn].name) {
name = "'" + header.parameters[pn].name + "'"
}
if (nf === 2) {
t = true
if ( gotCount<gotLimit ) {
got += '\nParameter <code>' + name + '</code> does not match at time ' +
line[0] + ': Single parameter request: <code>' + line[1] +
'</code>; All parameter request: <code>' + lineAll[fc + j] +
'</code>.\n'
}
gotCount++
} else {
if ( gotCount<gotLimit ) {
got += '\nParameter <code>' + name + '</code> field #<code>' + j +
'</code> does not match at time <code>' + line[0] +
'</code>: Single parameter request: <code>' + line[1 + j] +
'</code>; All parameter request: <code>' + lineAll[fc + j] +
'</code>.\n'
}
gotCount++
}
}
}
}
if ( gotCount>gotLimit ) {
got += "\n("+(gotCount-gotLimit)+" additional messages suppressed.)\n"
}
return {
description: callerName() + desc,
error: t,
got
}
}
}
exports.FileContentSameOrConsistent = FileContentSameOrConsistent
function FileStructureOK (body, what, statusMessage, emptyExpected) {
if (what === 'empty') {
const link = `<a href='${wikiURL}#empty-body'> (Details.)</a>`
const emptyIndicated = /HAPI 1201/.test(statusMessage)
if (!body || body.length === 0) {
if (emptyExpected) {
const desc = "If data part of response has zero length, prefer '<code>HAPI 1201</code>'" +
' (no data in time range) in HTTP header status message' +
' (if possible).' + link
return {
description: callerName() + desc,
error: emptyIndicated === false,
got: "Zero bytes and HTTP header status message of '<code>" + statusMessage + "</code>'"
}
} else {
const desc = 'The verifier should have enough information to make a' +
' request that returns data. Avoid this error by adding or' +
' modifying sample{Start,Stop} in /info response (preferred)' +
' or set a start/stop where there are data in the verifier' +
' query parameters (or command-line arguments). ' + link
return {
description: callerName() + desc,
error: true,
got: 'Zero bytes.'
}
}
}
if (body && body.length !== 0 && emptyIndicated) {
const desc = 'A data part of response with zero bytes was expected' +
" because '<code>HAPI 1201</code>' (no data in time range) in HTTP header" +
' status message.' + link
return {
description: callerName() + desc,
error: false,
got: "'<code>HAPI 1201</code>' in HTTP header status message and <code>" + body.length + '</code> bytes.'
}
}
return {
description: callerName() + 'Expect nonzero length for data part of response.',
error: false,
got: `<code>${body.length}</code> bytes.`
}
}
let desc, t, got
if (what === 'firstchar') {
desc = 'Expect first character of CSV response to be an integer.'
t = !/^[0-9]/.test(body.substring(0, 1))
got = `<code>${body.substring(0, 1)}</code>`
}
if (what === 'lastchar') {
desc = 'Expect last character of CSV response be a newline.'
t = !/\n$/.test(body.slice(-1))
got = body.slice(-1).replace(/\n/g, '\\n')
if (t) {
got = "The character '<code>" + got + "'</code>"
} else {
got = ''
}
}
if (what === 'extranewline') {
desc = 'Expect last two characters of CSV response to not be newlines.'
t = /\n\n$/.test(body.slice(-2))
got = body.slice(-2).replace(/\n/g, '\\n')
if (t) {
got = ''
} else {
got = "The characters '<code>" + got + "</code>'"
}
}
if (what === 'numlines') {
const lines = body.split('\n')
got = lines.length + ' newlines'
if (lines.length === 0) {
got = 'No lines.'
} else {
got = lines.length + ' newlines'
}
desc = 'Expect at least one newline in CSV response.'
t = lines.length === 0
}
return {
description: callerName() + desc,
error: t,
got
}
}
exports.FileStructureOK = FileStructureOK
function LengthOK (header, body, pn) {
const nf = nFields(header, pn)
const lines = csvToArray(body)
// TODO: Check all lines?
const line1 = lines[0]
if (pn === 0) {
const len = header.parameters[0].length
const name = header.parameters[0].name
const desc = `Expect (length of '<code>${name}</code>' in CSV) == (<code>parameters['${name}'].length</code>).`
const err = len !== line1[0].length
return {
description: callerName() + desc,
error: err,
got: err ? `${len} != ${line1[0].length}` : `${len} == ${line1[0].length}`
}
}
const type = header.parameters[pn].type
if (!(type === 'string' || type === 'isotime')) {
return
}
const len = header.parameters[pn].length
const name = header.parameters[pn].name
let desc = `Expect (length of '<code>${name}</code>' in CSV) ≤ (<code>parameters['name'].length</code>).`
if (nf > 1) {
desc = `Expect (length of '<code>${name}</code>' components in CSV) ≤ (<code>parameters['name'].length</code>).`
}
let got = ''
let err = false
for (let j = 1; j < nf; j++) {
const extra = ' in column ' + j + ' on first line'
err = Buffer.byteLength(line1[j], 'utf8') > len
if (err) {
got = '(' + (line1[j].length) + ') > (' + (len) + ') ' + extra + '\n'
}