-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhapi.js
More file actions
2666 lines (2474 loc) · 84.8 KB
/
hapi.js
File metadata and controls
2666 lines (2474 loc) · 84.8 KB
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
/*
* hapi-doc-test - HTTP API documentation generator and test tool
* Each API has two sections: request and response.
* 1) The request section describes the input to the API in terms of which
* variables are required to run the API; in other words, the each API
* may consume some set of variables.
* 2) The response section describes the output of the API in terms of the
* variables that are produced.
* The variables consumed and produced by the APIs are used to arrange the
* APIs in a tree structure, which defines the order in which the APIs are to
* be run.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var request = require('request');
var url = require('url');
var async = require('async');
var moduleClone = require('clone');
var lodash = require('lodash');
var util = require('util');
var common = require(__dirname+'/common');
var tv4 = require('tv4');
var glob = require('glob');
var log;
var APP_JSON = 'application/json';
var FORMAT_IGNORE = 'format_ignore';
var SCHEMA_REFS = false;
// Custom validator function to ignore
tv4.addFormat(FORMAT_IGNORE, function(data,schema) { return null; });
common.extendJS();
// The main HAPI tester object
function Hapi(vars) {
this.setVars(vars);
this.virtualHosts = [];
this.mapis = [];
this.apis = [];
this.rootApis = [];
this.referencedApis = [];
this.errors = [];
this.inDir = this.outDir = process.cwd();
this.serialQueues = {};
}
//Set the log level
Hapi.prototype.setVars = function(vars) {
this.vars = vars || {};
if (log.isDebugEnabled()) log.debug("Hapi.setVars to %j",vars);
};
// Get the current log level
Hapi.prototype.getLogLevel = function() {
return log.getLevel();
};
// Set the log level
Hapi.prototype.setLogLevel = function(level) {
log.setLevel(level);
};
// Get the input directory
Hapi.prototype.getInputDir = function() {
return this.inDir;
};
// Set the input directory
Hapi.prototype.setInputDir = function(dir) {
this.inDir = dir;
};
// Get the output directory
Hapi.prototype.getOutputDir = function() {
return this.outDir;
};
// Set the output directory
Hapi.prototype.setOutputDir = function(dir) {
this.outDir = dir;
};
// Load HAPIs from a directory
Hapi.prototype.loadFromDir = function(dir) {
var self = this;
if (dir) self.setInputDir(dir);
var loader = new HapiLoader();
loader.loadFromDir(self.getInputDir());
self.errors = loader.getErrors();
if (self.errors.length === 0) {
this.loadInfo(loader.getInfo(),null,normalizeVars(self.vars));
}
};
Hapi.prototype.loadInfo = function(info,vhost,vars) {
var self = this;
if (info.variables) {
vars = merge(vars,info.variables);
for (var key in info.variables) {
if (!self.vars.hasOwnProperty(key) && info.variables[key].hasOwnProperty('value')) {
self.vars[key] = info.variables[key].value;
}
}
}
if (info.virtual_host) {
if (vhost) throw Error("multiple levels of virtual hosts are not permitted");
vhost = new VirtualHost(self,info.virtual_host,vars);
self.virtualHosts.push(vhost);
if (log.isDebugEnabled()) log.debug("loaded virtual host %s",vhost.getName());
}
if (info.elements) {
for (var i = 0; i < info.elements.length; i++) {
var ele = info.elements[i];
var type = ele.type;
var name = ele.name;
var val = ele.value;
switch(type) {
case 'api':
try {
if (!vhost) throw Error(util.format("no virtual host for API %s",name));
val.name = name;
val.vars = vars;
val.vhost = vhost;
var mra = new MultiResponseApi(self,val);
self.mapis.push(mra);
vhost.mapis.push(mra);
} catch (err) {
var apiErr = log.isTraceEnabled() ? err.stack : err;
self.errors.push(util.format("%s: %s",name,apiErr));
}
break;
case 'elements':
self.loadInfo(val,vhost,vars);
break;
default:
throw Error("invalid type: "+type);
}
}
}
};
Hapi.prototype.addMapi = function(info,vhost,vars) {
var self = this;
if (info.variables) {
vars = merge(vars,info.variables);
for (var key in info.variables) {
if (!self.vars.hasOwnProperty(key) && info.variables[key].hasOwnProperty('value')) {
self.vars[key] = info.variables[key].value;
}
}
}
if (info.virtual_host) {
if (vhost) throw Error("multiple levels of virtual hosts are not permitted");
vhost = new VirtualHost(self,info.virtual_host,vars);
self.virtualHosts.push(vhost);
if (log.isDebugEnabled()) log.debug("loaded virtual host %s",vhost.getName());
}
if (info.elements) {
for (var i = 0; i < info.elements.length; i++) {
var ele = info.elements[i];
var type = ele.type;
var name = ele.name;
var val = ele.value;
switch(type) {
case 'api':
try {
if (!vhost) throw Error(util.format("no virtual host for API %s",name));
val.name = name;
val.vars = vars;
val.vhost = vhost;
var mra = new MultiResponseApi(self,val);
self.mapis.push(mra);
vhost.mapis.push(mra);
} catch (err) {
var apiErr = log.isTraceEnabled() ? err.stack : err;
self.errors.push(util.format("%s: %s",name,apiErr));
}
break;
case 'elements':
self.loadInfo(val,vhost,vars);
break;
default:
throw Error("invalid type: "+type);
}
}
}
};
// Generate swagger documentation for APIs
Hapi.prototype.gendoc = function() {
var self = this;
var result = 0;
if (log.isInfoEnabled()) log.info("generating doc ...");
for (var i = 0; i < self.virtualHosts.length; i++) {
var vhost = self.virtualHosts[i];
try {
var doc = vhost.gendoc();
var file = self.outDir + "/swagger-" + vhost.getName() + ".json";
fs.writeFileSync(file,JSON.stringify(doc,null,3));
if (log.isInfoEnabled()) log.info("created %s",file);
} catch (err) {
var apiErr = log.isTraceEnabled() ? err.stack : err;
self.errors.push(util.format("failure generating %s virtual host documentation: %s",vhost.getName(),apiErr));
result = 2;
}
}
if (self.errors.length > 0) {
self.logErrors("Documentation Errors");
result = 3;
}
return result;
};
// Compile the HAPIs associated with 'names' which can be an individual test name or group name
// Compilation involves building a test tree based on the dependency graph associated with:
// 1) what a HAPI consumes (i.e. the variables that it takes as input) and
// 2) what a HAPI produces (i.e. the variables that it sets as output).
Hapi.prototype.compile = function(testNames) {
if (log.isDebugEnabled()) log.debug("compiling %s",testNames?testNames:"all tests");
var self = this;
var i,api;
var apisToInsert = [];
for (i = 0; i < self.mapis.length; i++) {
var mapi = self.mapis[i];
var match = mapi.matches(testNames);
var apis = mapi.getApis();
for (var j = 0; j < apis.length; j++) {
api = apis[j];
self.apis.push(api);
for (var k = 0; !match && testNames && k < testNames.length; k++) {
match = api.name.startsWith(testNames[k]);
}
if (match) apisToInsert.push(api);
}
}
// Insert all of the HAPI's which match the name of the test (or all if null) into a tree
// rooted at 'root'
var root = new Node(this,null);
for (i = 0; i < apisToInsert.length; i++) {
api = apisToInsert[i];
try {
root.insertApi(api);
} catch (err) {
var apiErr = log.isTraceEnabled() ? err.stack : err;
self.errors.push(util.format("%s: %s",api.name,apiErr));
}
}
if (log.isTraceEnabled()) {
log.trace("TEST TREE:");
root.dump();
}
self.logErrors("COMPILATION ERRORS");
return root;
};
// Run the HAPIs which match 'testNames', or all if 'testNames' is undefined
Hapi.prototype.run = function(testNames) {
var self = this;
try {
var root = self.compile(testNames);
if (!root || self.errors.length > 0) return;
log.info("\nBEGIN TESTS (%s)",Date.format("dddd, mmmm dS, yyyy, h:MM:ss TT"));
log.addTimeStamp = true;
self.cookieJar = request.jar();
var ctx = new RunContext(self.vars,root,0,1);
ctx.run();
} catch (err) {
var apiErr = log.isTraceEnabled() ? err.stack : err;
log.error(apiErr);
}
self.logErrors("Runtime Errors");
};
Hapi.prototype.findApi = function(name,where) {
var self = this;
for (var i = 0; i < self.apis.length; i++) {
var api = self.apis[i];
if (api.name === name) {
log.debug("findAPI: %s (referenced in %s) was found",name,where);
return api;
}
}
var msg = util.format("findAPI: '%s' (referenced in %s) was NOT found",name,where);
log.error(msg);
throw new Error(msg);
};
// Determine if an API can be inserted by itself in the tree
// APIs that are referenced by other APIs are not insertable
Hapi.prototype.isInsertableApi = function(api) {
var refs = this.referencedApis;
var name = api.name;
for (var i = 0; i < refs.length; i++) {
if (name.startsWith(refs[i])) return false;
}
return true;
};
Hapi.prototype.getTimeout = function() {
return this.timeout;
};
Hapi.prototype.setTimeout = function(timeout) {
this.timeout = timeout;
};
Hapi.prototype.getApiProducers = function(varName) {
var self = this;
var apis = [];
for (var i = 0; i < self.apis.length; i++) {
var api = self.apis[i];
if (api.produces.includes(varName)) {
apis.addUniq(api);
}
}
return apis;
};
Hapi.prototype.getPredefinedVars = function() {
return Object.keys(this.vars);
};
Hapi.prototype.predefinesVar = function(varName) {
return this.vars.hasOwnProperty(varName);
};
Hapi.prototype.logErrors = function(prefix) {
var self = this;
var errors = self.getErrors();
if (errors.length > 0) {
console.log("%s: %s",prefix,pretty(errors));
}
};
Hapi.prototype.getErrors = function() {
return this.errors;
};
function VirtualHost(hapi,info,vars) {
this.hapi = hapi;
this.info = info;
this.vars = vars;
this.mapis = [];
}
VirtualHost.prototype.getName = function() {
return this.info.name || this.getHostVariable();
};
VirtualHost.prototype.getHostVariable = function() {
return this.info.host_variable;
};
VirtualHost.prototype.gendoc = function() {
var self = this;
var errors = self.hapi.errors;
if (log.isDebugEnabled()) log.debug("generating doc for vhost %s ...",self.getName());
var doc = {};
var swagger = self.info.swagger;
if (!swagger) throw Error(util.format("no swagger info found for virtual host %s",self.info.name));
for (var key in swagger) {
doc[key] = swagger[key];
}
doc.paths = {};
if (SCHEMA_REFS) {
doc.definitions = {};
}
var state = {};
for (var i = 0; i < self.mapis.length; i++) {
var mapi = self.mapis[i];
try {
if (!mapi.private) mapi.addDoc(doc,state);
} catch(err) {
var errStr = log.isTraceEnabled() ? err.stack : err.toString();
errStr = util.format("Failure in %s: %s",mapi.name,errStr);
errors.push(errStr);
}
}
if (errors.length > 0) {
if (log.isInfoEnabled()) log.info("ERRORS generating swagger doc for %s: %s",self.getName(),pretty(errors));
}
return doc;
};
/**
* There are two flavors of Api objects:
* 1) MultiResponseApi - This is created initially from input and is all that is needed to generate documentation
* as it is most resembles the swagger structure. The MultiResponseApi.gendoc function operates on this type of Api object.
* 2) Api - This has a single response code and is used for compile and run of tests. Calling MultiResponseApi.getApis returns
* and array of Api objects, one for each of the responses in MultiResponseApi. The Api object is required for compile and run
* of tests.
*/
function MultiResponseApi(hapi, info) {
var self = this;
self.hapi = hapi;
self.name = info.name;
self.private = info.private;
self.vars = info.vars;
self.varValues = getVarValues(info.vars);
self.vhost = info.vhost;
if (!info.request) throw Error(util.format("no 'request' field found in %s",pretty(info)));
if (!info.request.path) throw Error("no 'request.path' field found");
if (!info.responses) throw Error("no 'responses' field found");
if (!info.tags) throw Error("no 'tags' field found");
self.description = info.description;
self.tags = info.tags;
self.request = info.request;
self.request.method = self.request.method || 'GET';
self.responses = info.responses;
self.groups = info.groups || [];
self.groups.push(self.name);
self.onBeforeRun = info.onBeforeRun;
self.onAfterRun = info.onAfterRun;
self.before = info.before;
self.afterApi = info.afterApi;
self.afterAll = info.afterAll;
self.consumes = info.consumes;
self.produces = info.produces;
}
MultiResponseApi.prototype.getVirtualHost = function() {
return this.vhost;
};
MultiResponseApi.prototype.getUrl = function() {
return url.parse("http://host"+this.request.path);
};
// Determine if this Api matches any of the Api names or group names
// If 'names' is undefined, always match.
MultiResponseApi.prototype.matches = function(names) {
var self = this;
if (!names) return true;
var groups = self.groups;
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (group.startsWith(name)) {
if (log.isDebugEnabled()) log.debug("match: %s, group %s matches %s",self.name,group,name);
return true;
}
}
}
if (log.isDebugEnabled()) log.debug("no match: %s, groups=%j, names=%j",self.name,groups,names);
return false;
};
MultiResponseApi.prototype.addDoc = function(doc,state) {
var self = this;
var defs = doc.definitions;
var url = self.getUrl();
var path = url.pathname;
path = normalizePathForDoc(path);
doc = doc.paths;
if (!doc[path]) doc[path] = {};
doc = doc[path];
if (!state[path]) state[path] = {};
state = state[path];
var method = self.request.method;
method = method.toLowerCase();
if (doc[method]) {
var name1 = state[method].name;
var name2 = self.name;
throw Error(util.format("multiple definitions for method %s of %s; %s and %s",method,url.path,name1,name2));
}
doc = doc[method] = {};
state[method] = self;
doc.tags = self.tags;
doc.description = self.description;
doc.parameters = self.getParameters(defs);
if (!doc.responses) doc.responses = {};
if (doc.responses[self.status]) throw Error("multiple APIs defined for "+self.name);
doc = doc.responses;
for (var scode in self.responses) {
var response = self.responses[scode];
doc[scode] = { description: response.description };
doc[scode].schema = getSchemaRef(getBodySchema(response),defs);
}
};
/*
* Get parameters for an API used for doc generation
*/
MultiResponseApi.prototype.getParameters = function(defs) {
var self = this;
var req = self.request;
var parms = [];
var path = req.path.split('?');
// Get variables from the URL's path
getVarNames(path[0]).forEach(function(name) {
parms.push(self.getDocParm(name,name,'path',true));
});
// Get variables from the URL's query parameters
if (path.length > 0) {
getVarNames(path[1]).forEach(function(name) {
parms.push(self.getDocParm(name,name,'query',false));
});
}
// Get variables from request headers
var hdrs = req.headers;
forAll(hdrs,function(hdrName,hdrVal) {
getVarNames(hdrVal).forEach(function(varName) {
parms.push(self.getDocParm(hdrName,varName,'header',true));
});
});
// The request module's auth entry refers to the "Authorization" header
getVarNames(req.auth).forEach(function(name) {
parms.push(self.getDocParm('Authorization',name,'header',true));
});
// Add body parameter
var bodySchema = getSchemaRef(getBodySchema(req,self.vars),defs);
if (bodySchema) {
parms.push({
name: 'body',
in: 'body',
description: 'The request body',
required: true,
schema: bodySchema
});
}
return parms;
};
MultiResponseApi.prototype.getDocParm = function(parmName,varName,type,required) {
var ref = this.vars[varName];
if (!ref) {
throw Error(util.format("undefined variable '%s' is referenced in %s",varName,this.name));
}
if (!ref.description) {
throw Error(util.format("variable '%s' referenced in %s does not have a description",varName,this.name));
}
return {
name: parmName,
in: type,
description: ref.description,
required: required,
type: ref.type || "string"
};
};
/*
* Create API objects from this object based on:
* 1) Number of responses
* 2) Number of 'test' elements (if any) in each response
*/
MultiResponseApi.prototype.getApis = function() {
var self = this;
var test;
var apis = [];
for (var scode in self.responses) {
var req = self.request;
var res = self.responses[scode];
var name = self.name + '-' + scode;
// There is typically a single response w/o a 'tests' for the successful response case.
// All other responses will typically have a 'tests' section defining replacement variable
// values used to generate an error.
var testList = [];
var tests = res.tests;
if (tests) {
if (!isArray(tests)) tests = [tests];
for (var i = 0; i < tests.length; i++) {
test = tests[i];
test.name = test.name || name;
test.request = getTestReq(test.request,test.vars,req);
test.onBeforeRun = self.onBeforeRun;
test.onAfterRun = self.onAfterRun;
test.before = test.before || self.before;
test.afterApi = test.afterApi || self.afterApi;
test.afterAll = test.afterAll || self.afterAll;
test.consumes = (self.consumes || []).dup();
// test.produces = (self.produces || []).dup();
testList.push(test);
}
}
if (testList.length === 0) {
var tmpReq = getTestReq(res.request,res.vars,req);
testList.push({name:name,request:tmpReq,response:res});
}
// For each of these requests, get all possible compile time values for the variables
// and then generate a request for each combination of these values.
// For example, if the "$authHdr" and "$grantType" variables are both used
// where "$authHdr" can be "$basicAuthHdr" or "$tokenAuthHdr" and "$grantType" can be
// one of "password" or "client_credentials", the total number of combinations is 4
for (var j = 0; j < testList.length; j++) {
test = testList[j];
test.onBeforeRun = test.onBeforeRun || self.onBeforeRun;
test.onAfterRun = test.onAfterRun || self.onAfterRun;
self.setHook(test,'before');
self.setHook(test,'afterApi');
self.setHook(test,'afterAll');
test.consumes = test.consumes || (self.consumes || []).dup();
test.produces = test.produces || (self.produces || []).dup();
var requestBodyVars = getVarNames(test.request.body);
var combinations = getVarCombinations(self.varValues,getVarNames(test.request));
for (var k = 0; k < combinations.length; k++) {
var req2 = getObjectWithVarsReplaced(test.request,combinations[k]);
var name2 = k ? test.name + '-' + k : test.name;
apis.push(new Api(self,name2,req2,scode,test,requestBodyVars));
}
}
}
if (log.isDebugEnabled()) log.debug("getApis name=%s",self.name);
return apis;
};
MultiResponseApi.prototype.setHook = function(test,hook) {
if (!test[hook]) {
if (test.response && test.response[hook]) test[hook] = test.response[hook];
else test[hook] = this[hook];
}
};
MultiResponseApi.prototype.getPredefinedVars = function() {
var self = this;
var vars = self.hapi.getPredefinedVars();
for (var key in this.vars) {
if (this.vars[key].hasOwnProperty('value')) {
vars.push(key);
}
}
return vars;
};
MultiResponseApi.prototype.predefinesVar = function(varName) {
var val = this.vars[varName];
return val && (val.hasOwnProperty('value') || this.hapi.predefinesVar(varName));
};
function Api(mapi,name,req,scode,test,requestBodyVars) {
var self = this;
self.mapi = mapi;
self.hapi = mapi.hapi;
self.vars = mapi.vars;
self.requestBodyVars = requestBodyVars;
self.vhost = mapi.vhost;
name = common.trim(name, '/ ');
if (!name.startsWith(self.vhost.getName()) && !name.contains('/')) {
name = self.vhost.getName() + '/' + name;
}
self.name = name;
self.request = clone(req);
self.request.url = '$' + mapi.getVirtualHost().getHostVariable() + self.request.path;
delete self.request.path;
self.response = clone(mapi.responses[scode]);
self.response.status = scode;
self.serial_vars = self.response.serial_vars;
self.groups = mapi.groups;
self.groups.push(self.name);
self.consumes = common.union(getVarNames(self.request),(test.consumes || []));
self.produces = common.uniq(test.produces || []);
self.deletes = [];
self.actions = [];
self.scanActions(self.response.body,"");
self.scanActions(test);
self.onBeforeRun = test.onBeforeRun;
self.onAfterRun = test.onAfterRun;
self.before = test.before;
self.afterApi = test.afterApi;
self.afterAll = test.afterAll;
self.scanHook(self.before);
self.scanHook(self.afterApi);
self.scanHook(self.afterAll);
}
Api.prototype.getMethod = function() {
return this.request.method;
};
Api.prototype.getUrl = function() {
return url.parse("http://host"+this.request.path);
};
Api.prototype.getVirtualHost = function() {
return this.vhost;
};
Api.prototype.getPredefinedVars = function() {
return this.mapi.getPredefinedVars();
};
Api.prototype.predefinesVar = function(varName) {
return this.mapi.predefinesVar(varName);
};
Api.prototype.getOpts = function(request,vars) {
var self = this;
if (!request.url && request.path) {
request.url = '$' + self.getVirtualHost().getHostVariable() + request.path;
delete request.path;
}
var opts = resolve(request,vars);
opts.method = opts.method || 'GET';
opts.timeout = opts.timeout || self.hapi.getTimeout();
opts.headers = opts.headers || {};
opts.headers.accept = opts.headers.accept || APP_JSON;
opts.json = isObject(opts.body);
opts.jar = self.cookieJar;
return opts;
};
// Throw an error if a field is not defined
Api.prototype.actionCheck = function(action,name,field) {
if (isArray(field)) {
var found = false;
for (var i = 0; i < field.length; i++) {
if (action[name].hasOwnProperty(field[i])) {
found = true;
break;
}
}
if (!found) {
throw Error(util.format("'%s' has a '%s' without any of the following fields: %j (%j)",this.name,name,field,action));
}
} else {
if (!action[name].hasOwnProperty(field)) {
throw Error(util.format("'%s' has a '%s' without a '%s' field",this.name,name,field));
}
}
};
Api.prototype.scanActions = function(toScan,path) {
var self = this;
if (!toScan) return;
if (isArray(toScan)) {
for (var idx = 0; idx < toScan.length; idx++) {
self.scanActions(toScan[idx],path?path+'[]':undefined);
}
} else if (isObject(toScan)) {
var keys = Object.keys(toScan);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
switch(key) {
case 'var_new':
self.actionCheck(toScan,'var_new','name'); // The name of the variable that will contain the id or guid of the new object
self.actionCheck(toScan,'var_new','get');
self.actionCheck(toScan,'var_new','delete');
if (self.var_new) throw Error(util.format("%s contains multiple 'var_new' are not allowed in a single HTTP API",self.name));
self.var_new = toScan.var_new;
if (!self.var_new.path) {
if (!path || path.length === 0) throw Error(util.format("%s contains 'var_new' without a path",self.name));
self.var_new.path = path;
}
self.produces.push(toScan.var_new.name);
self.hapi.referencedApis.addUniq(toScan.var_new.get);
self.hapi.referencedApis.addUniq(toScan.var_new['delete']);
self.actions.push(toScan);
// By default, the name of the queue which we serialize on when creating an object is the value of all variables
// that are referenced in the request body. If there is a case in which there is no request body or if for some
// reason, there are additional variables in the request body or for some other reason, the default algorithm is
// not correct, then we require the 'serial_vars' to be explicitly specified in the var_new section.
if (self.var_new.serial_vars) {
self.serial_vars = self.var_new.serial_vars;
} else if (self.requestBodyVars) {
self.serial_vars = self.requestBodyVars;
} else {
throw Error(util.format("var_new for %s needs a 'serial_vars' field",self.name));
}
break;
case 'var_set':
if (!toScan.var_set.path && !toScan.var_set.fcn) {
if (!path || path.length === 0) {
throw Error(util.format("%s contains a 'var_set' without a path: %j",self.name,toScan.var_set));
}
if (isString(toScan.var_set)) {
toScan.var_set = {
name: toScan.var_set,
path: path
};
} else {
toScan.var_set.path = path;
}
}
self.produces.push(toScan.var_set.name);
self.actions.push(toScan);
break;
case 'var_rename':
self.actionCheck(toScan,'var_rename','from');
self.actionCheck(toScan,'var_rename','to');
self.deletes.push(toScan.var_rename.from);
self.produces.push(toScan.var_rename.to);
self.actions.push(toScan);
break;
case 'var_delete':
var delName = toScan.var_delete;
toScan.var_delete = { name: delName };
self.deletes.push(delName);
self.hapi.varDeleteApis[delName] = self;
self.actions.push(toScan);
break;
}
var tmpPath = path;
if (isString(tmpPath) && key !== '__') {
if (tmpPath.length > 0) tmpPath += '.';
tmpPath += key;
} else if (key === 'body') {
tmpPath = "";
}
self.scanActions(toScan[key],tmpPath);
}
}
};
// Scan a hook to and insert referenced APIs so that these APIs are not otherwise run.
Api.prototype.scanHook = function(hook) {
var self = this;
if (!hook) return;
if (isArray(hook)) {
for (var idx = 0; idx < hook.length; idx++) {
self.scanHook(hook[idx]);
}
} else if (isObject(hook)) {
if (!hook.hook) throw Error("object missing 'hook' field");
self.scanHook(hook.hook);
} else if (isString(hook)) {
self.hapi.referencedApis.addUniq(hook);
} else if (common.isFunction(hook)) {
// do nothing
} else {
throw Error("invalid hook: "+hook.toString());
}
};
Api.prototype.getVar = function(name) {
var val = this.hapi.vars[name];
if (!val) new Error(util.format("variable '%s' is not set in %s",name,this.name));
return val;
};
Api.prototype.produces = function(varName) {
return this.produces.indexOf(varName) >= 0;
};
Api.prototype.toString = function() {
if (this.var_new) {
return util.format("%s: consumes=%j, produces=%j, deletes=%j, getApi=%s, deleteApi=%s",
this.name,this.consumes,this.produces,this.deletes,
this.var_new.get,this.var_new['delete']);
} else {
return util.format("%s: consumes=%j, produces=%j, deletes=%j",
this.name,this.consumes,this.produces,this.deletes);
}
};
function Node(hapi,api,parent) {
this.hapi = hapi;
this.vhost = api ? api.vhost : undefined;
this.api = api;
this.name = api ? api.name : "";
if (parent) {
this.path = parent.getPath() + '/' + this.name;
this.depth = parent.depth + 1;
} else {
this.path = this.name;
this.depth = 0;
}
this.indent = this.depth + ": ";
for (var i = 1; i < this.depth; i++) this.indent += " ";
this.path = parent ? parent.getPath() + '/' + api.name : "";
this.parent = parent;
this.children = [];
this.ancestors = [];
this.produces = []; // produced by all nodes from here to the root
this.subTreeProduces = []; // produced by all nodes from here to leaves
if (api) {
this.addProduces(api.produces.dup());
this.subTreeProduces.addAllUniq(api.produces);
}
}
// The 'produces' array of a node contains all the variables that are created
// in the subtree rooted at this node.
Node.prototype.addProduces = function(varNames) {
if (this.api && this.api.deletes) {
varNames.pullAll(this.api.deletes);
}
this.produces.addAllUniq(varNames);
if (this.parent) {
this.parent.addProduces(varNames);
}
};
Node.prototype.getPath = function() {
return this.path;
};
// Recursively march down the tree and insert 'api' into every place that produces a variable
// used by this API. This allows us to get the most complete test coverage.
Node.prototype.insertApi = function(api) {
var self = this;
var hapi = self.hapi;
// Prevent the API from being inserted multiple times
if (!self.inserting) self.inserting = {};
if (self.inserting[api.name]) {
if (log.isDebugEnabled()) log.debug("already inserting API %s",api.name);
return;
}
self.inserting[api.name] = true;
// If this API is a 'get' or 'delete' associated with a var_new (a constructor), then we don't
// insert it here. It is only associated with the API which references it as the getter or destructor
if (!self.hapi.isInsertableApi(api)) {
if (log.isDebugEnabled()) log.debug("api '%s' is not insertable", api.name);
return;
}
// If this API is already inserted further up the tree, don't do so again
if (self.usesApi(api)) {
return;
}
// If this API has no undefined variables, insert it here
var undefinedVars = self.getUndefinedVars(api);
if (log.isDebugEnabled()) log.debug("check '%s' to insert '%s', undefinedVars=%s",self.path,api.name,pretty(undefinedVars));
if (undefinedVars.length === 0) {
// All variables are defined, so insert it here
self.addChild(api);
return;
}
// Insert into all subtrees which produce one or more of the undefined variables
var found = false;
for (var i = 0; i < self.children.length; i++) {
var child = self.children[i];
if (child.producesVar(undefinedVars)) {
// This child producers one of the variables needed by this API, so insert it here
child.insertApi(api);
found = true;
}
}
// If no subtree was found that produces any of the needed variables, then add all producers of the 1st variable
if (!found) {
var varName = undefinedVars[0];
var producers = hapi.getApiProducers(varName);
if (producers.length === 0) throw Error(util.format("There are no producers of the '%s' variable",varName));
for (var j = 0; j < producers.length; j++) {
self.insertApi(producers[j]);
}
self.inserting[api.name] = false; // allow it again because we have now added API producers
self.insertApi(api);
}
};
// Determine if this Api is used in this node or any of the ancestor nodes
Node.prototype.usesApi = function(api) {
var node = this;
while (node) {
if (node.api === api) return true;
node = node.parent;
}
return false;
};
// Determine if this subtree produces one of the var names
Node.prototype.producesVar = function(varNames) {
var self = this;
for (var i = 0; i < varNames.length; i++) {
if (self.subTreeProduces.includes(varNames[i])) return true;
}
return false;
};
Node.prototype.getUndefinedVars = function(api) {
var self = this;
var undefinedVars = api.consumes.dup();
var node = self;
while (node) {
if (node.api) undefinedVars.pullAll(node.api.produces);
node = node.parent;
}
undefinedVars.pullAll(api.getPredefinedVars());
return undefinedVars;
};
Node.prototype.addChild = function(api) {
var self = this;
var node;
for (var i = 0; i < self.children.length; i++) {
if (self.children[i].api === api) {
node = self.children[i];
if (log.isDebugEnabled()) log.debug("previously inserted %s",node.path);
return node;
}
}
if (self.postRun && api === self.postRun.api) {
// This API is a delete API and must be run last
if (log.isDebugEnabled()) log.debug("delete API: %s",self.postRun.path);
return self.postRun;
}
node = new Node(self.hapi,api,self);
// If there was a var_new on this API, it means this API creates a new object
// In this case, we init preRun to clean up the object if it was left lying around from a previous run,