| 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 |
3x
3x
3x
3x
3x
3x
228x
228x
228x
228x
228x
228x
210x
228x
3x
228x
228x
228x
228x
285x
285x
228x
3x
285x
285x
285x
285x
285x
285x
18x
3x
1x
1x
1x
1x
3x
227x
3x
1x
1x
1x
3x
228x
228x
285x
285x
285x
228x
228x
228x
3x
72x
72x
72x
72x
3x
74x
3x
82x
3x
82x
82x
82x
82x
82x
3x
60x
3x
74x
3x
73x
73x
73x
73x
3x
111x
3x
3x
3x
3x
3x
3x
30x
22x
3x
137x
137x
55x
137x
3x
72x
72x
72x
3x
3x
3x
3x
3x
132x
3x
132x
3x
66x
66x
66x
66x
66x
66x
66x
66x
66x
66x
66x
3x
4x
8x
8x
3x
14x
14x
66x
14x
3x
14x
14x
14x
3x
15x
15x
3x
14x
66x
3x
3x
3x
14x
14x
14x
3x
3x
3x
3x
3x
3x
| /**
GPII Testing (full lifecycle of FlowManager)
Copyright 2013-2016 Raising the Floor International
Copyright 2013 OCAD University
Copyright 2014 Lucendo Development Ltd.
Licensed under the New BSD license. You may not use this file except in
compliance with this License.
The research leading to these results has received funding from the European Union's
Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 289016.
You may obtain a copy of the License at
https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var fluid = fluid || require("infusion"),
jqUnit = jqUnit || fluid.require("node-jqunit", require, "jqUnit"),
path = typeof(require) === "undefined" ? null : require("path"), // courtesy to allow use in browser-based tests
kettle = fluid.registerNamespace("kettle"),
gpii = fluid.registerNamespace("gpii");
// TODO: Move all of this file into a more specific namespace - "test" is too generic
// Given a promise-containing structure, return a promise yielding the structure with all promises replaced by their
// resolution, or else a rejection for the first to reject. The supplied structure will be modified.
// TODO: This algorithm will go into FluidPromises.js in the end
gpii.test.settleStructure = function (structure) {
Iif (fluid.isPromise(structure)) {
return structure;
}
var settleRec = {
// This flag is an awkward consequence of our choice to allow synchronous promise resolution
inSync: true, // Are we still in synchronous scanning - necessary to avoid double resolution on hitting unresolved === 0 on initial scan
unresolved: 0,
depth: 0,
togo: fluid.promise(),
structure: structure,
resolve: function () {
settleRec.togo.resolve(structure);
}
};
gpii.test.settleStructureRecurse(structure, settleRec);
settleRec.inSync = false;
if (settleRec.unresolved === 0) { // Case of 0 asynchronous promises found
settleRec.resolve();
}
return settleRec.togo;
};
gpii.test.settleStructureRecurse = function (structure, settleRec) {
++settleRec.depth;
Iif (settleRec.depth > fluid.strategyRecursionBailout) {
fluid.fail("Recursion exceeded for value " + JSON.stringify(structure) + " overall structure " + JSON.stringify(settleRec.structure, null, 2));
}
Eif (fluid.isPlainObject(structure)) {
fluid.each(structure, function (value, key) {
Eif (fluid.isPromise(value)) {
gpii.test.settleStructurePush(settleRec, structure, value, key);
} else {
gpii.test.settleStructureRecurse(value, settleRec);
}
});
}
--settleRec.depth;
};
gpii.test.settleStructurePush = function (settleRec, holder, promise, key) {
++settleRec.unresolved;
promise.then(function (value) {
fluid.log("settleStructure received response " + fluid.prettyPrintJSON(value));
holder[key] = value;
--settleRec.unresolved;
if (settleRec.unresolved === 0 && !settleRec.inSync) {
settleRec.resolve();
}
}, function (err) {
settleRec.togo.reject(kettle.upgradeError(err, " while resolving promise with key " + key));
});
};
// END ALGORITHM gpii.test.settleStructure
// TODO: Move this utility into KettleTestUtils.http.js
/** Asserts that a successful response with a JSON payload body has been received, which will be tested using `jqUnit.assertLeftHand`
* In addition to the core fields listed KettleTestUtils.http.js HTTP response assertion functions, options contains:
* expected {Object} The expected response body as JSON, supplied as the `expected` argument to `jqUnit.assertLeftHand`
*/
gpii.test.assertJSONResponseSubset = function (options) {
var data;
try {
data = kettle.JSON.parse(options.string);
} catch (e) {
throw kettle.upgradeError(e, "\nwhile parsing HTTP response as JSON");
}
jqUnit.assertLeftHand(options.message, options.expected, data);
kettle.test.assertResponseStatusCode(options, 200);
};
/** Given a settingsHandler payload, return a promise which resolves to the current state of each
* settingsHandler block within it. Called from `gpii.test.snapshotSettings`, `gpii.test.checkConfiguration` and `gpii.test.checkRestoredConfiguration`
* @param settingsHandlers {Object} A map of settings handler names to `settingsHandler` blocks as seen in the `settingsHandlers`
* option of a `gpii.test.common.testCaseHolder`
* @param nameResolver {NameResolver|Null} A `nameResolver` mapping global names onto alternatives for use in a testing context
* @return {Promise} A promise resolving to the fetched settings (a fatal error handler will be registered on reject)
*/
gpii.test.getSettings = function (settingsHandlers, nameResolver) {
return gpii.test.operateSettings(settingsHandlers, nameResolver, "get");
};
/** As for `gpii.test.getSettings` but performing a `set` action for the settingsHandler payloads, and accepting an
* `onSuccess` callback
*/
gpii.test.setSettings = function (settingsHandlers, nameResolver, onSuccess) {
var promise = gpii.test.operateSettings(settingsHandlers, nameResolver, "set");
promise.then(onSuccess);
return promise;
};
/** Common utility forwarded to by `gpii.test.getSettings` and `gpii.test.setSettings`.
* See documentation for all parameters other than:
* @param method {String} Either `"get"` or `"set"` depending on whether the settingsHandler `get` or `set` action is to be invoked
*/
gpii.test.operateSettings = function (settingsHandlers, nameResolver, method) {
var ret = {};
fluid.each(settingsHandlers, function (handlerBlock, handlerID) {
var resolvedName = nameResolver ? nameResolver.resolveName(handlerID, "settingsHandler") : handlerID;
var response = fluid.invokeGlobalFunction(resolvedName + "." + method, [handlerBlock]);
ret[handlerID] = response;
});
var togo = gpii.test.settleStructure(ret);
togo.then(null, function (err) {
fluid.fail("Error when operating settings handler: ", err);
});
return togo;
};
/** Snapshot the state of all settingsHandlers by stashing them in a member named `orig` on the supplied settingsStore
* @param settingsHandlers {Object} A map of settings handler names to `settingsHandler` blocks as seen in the `settingsHandlers`
* option of a `gpii.test.common.testCaseHolder`
* @param settingStore {Object} The `settingsStore` member of a `gpii.test.common.testCaseHolder`. This will have a snapshot of
* the state of the supplied settingsHandlers stored in a member named `orig`
* @param nameResolver {NameResolver|Null} A `nameResolver` mapping global names onto alternatives for use in a testing context
* @param onComplete {Function} A callback to be notified when the state of all the supplied settingsHandlers have been read
*/
gpii.test.snapshotSettings = function (settingsHandlers, settingsStore, nameResolver, onComplete) {
var origPromise = gpii.test.getSettings(settingsHandlers, nameResolver);
origPromise.then(function (origSettings) {
settingsStore.orig = origSettings;
onComplete();
});
};
gpii.test.loginRequestListen = function (data) {
jqUnit.assertNotEquals("Successful login message returned " + data, -1,
data.indexOf("was successfully logged in."));
};
gpii.test.extractSettingsBlocks = function (settingsHandlers) {
return fluid.transform(settingsHandlers, gpii.settingsHandlers.extractSettingsBlocks);
};
gpii.test.checkConfiguration = function (settingsHandlers, nameResolver, onComplete) {
var configPromise = gpii.test.getSettings(settingsHandlers, nameResolver);
configPromise.then(function (config) {
var noOptions = gpii.test.extractSettingsBlocks(settingsHandlers);
jqUnit.assertDeepEq("Checking that settings are set", noOptions, config);
onComplete();
});
};
gpii.test.onExecExit = function (result, processSpec) {
jqUnit.assertTrue("Checking the process with command: " + processSpec, result);
};
gpii.test.logoutRequestListen = function (data) {
jqUnit.assertNotEquals("Successful logout message returned " + data, -1,
data.indexOf("was successfully logged out."));
};
gpii.test.checkRestoredConfiguration = function (settingsHandlers, settingsStore, nameResolver, onComplete) {
var currentSettingsPromise = gpii.test.getSettings(settingsHandlers, nameResolver);
currentSettingsPromise.then(function (currentSettings) {
jqUnit.assertDeepEq("Checking that settings are properly reset", settingsStore.orig, currentSettings);
onComplete();
});
};
gpii.test.common.receiveVariableResolver = function (testCaseHolder, variableResolver) {
testCaseHolder.variableResolver = variableResolver;
};
/** The base testCaseHolder for the straightforward family of login/logout system test cases - for example
* the very simple DevelopmentTests.js, integration tests and acceptance tests. These all operate the
* stereotypical workflow of snapshotting the initial settings handler state, logging in a user,
* checking that expected settings are set, logging out the user, and then verifying that the initial
* state is restored.
*
* This takes its place in the standard IoC Testing Framework environment structure rooted at "kettle.test.serverEnvironment"
* defined in kettle/lib/test/KettleTestUtils.js as the member named `test`. This structure is constructed via
* kettle.test.bootstrapServer which is kicked off from the standard launcher gpii.test.runTests
*/
fluid.defaults("gpii.test.common.loginRequestComponent", { // named oddly to avoid name conflicts with component whose member name is `loginRequest`
gradeNames: "kettle.test.request.http",
path: "/user/%userToken/login",
termMap: {
userToken: "{testCaseHolder}.options.userToken"
}
});
fluid.defaults("gpii.test.common.logoutRequestComponent", {
gradeNames: "kettle.test.request.http",
path: "/user/%userToken/logout",
termMap: {
userToken: "{testCaseHolder}.options.userToken"
}
});
fluid.defaults("gpii.test.common.testCaseHolder", {
gradeNames: ["kettle.test.testCaseHolder"],
members: {
// The "orig" member of this area will be written by gpii.test.snapshotSettings, and read back by gpii.test.checkRestoredConfiguration
settingsStore: {}
},
mergePolicy: {
"settingsHandlers": "noexpand"
},
events: {
onSnapshotComplete: null,
onCheckConfigurationComplete: null,
onCheckRestoredConfigurationComplete: null
},
distributeOptions: {
"common.testCaseHolder.variableResolver": {
record: {
funcName: "gpii.test.common.receiveVariableResolver",
args: ["{testCaseHolder}", "{arguments}.0"]
},
target: "{that lifecycleManager variableResolver}.options.listeners.onCreate"
},
"common.testCaseHolder.port": {
record: "{configuration}.options.mainServerPort",
target: "{that kettle.test.request}.options.port"
}
},
components: {
// The following configuration should be valid:
// variableResolver: "{tests}.configuration.server.flowManager.lifecycleManager.variableResolver" but clearly stresses
// ginger resolution in the framework too much.
// In fact, a proper solution would allow us to directly write:
// variableResolver: "{that lifecycleManager variableResolver}" without the listener hack above - this requires FLUID-5556
loginRequest: {
type: "gpii.test.common.loginRequestComponent"
},
logoutRequest: {
type: "gpii.test.common.logoutRequestComponent"
}
}
});
/** mixin grades to hoist out the lifecycleManager, to a location where it can be
* easily resolved by various test fixtures. This will become unnecessary after the FLUID-4892 rewrite of Infusion
*/
fluid.defaults("gpii.test.common.lifecycleManagerReceiver", {
distributeOptions: {
record: {
funcName: "gpii.test.common.receiveComponent",
args: ["{testCaseHolder}", "{arguments}.0", "lifecycleManager"]
},
target: "{that lifecycleManager}.options.listeners.onCreate"
}
});
fluid.defaults("gpii.test.common.untrusted.lifecycleManagerReceiver", {
distributeOptions: {
record: {
funcName: "gpii.test.common.receiveComponent",
args: ["{testCaseHolder}", "{arguments}.0", "lifecycleManager"]
},
target: "{that localConfig lifecycleManager}.options.listeners.onCreate"
}
});
gpii.test.common.receiveComponent = function (testCaseHolder, component, name) {
if (!testCaseHolder[name]) {
fluid.globalInstantiator.recordKnownComponent(testCaseHolder, component, name, false);
}
};
// Will return the part of a test sequence that tests for the process state based on the
// 'expectedKey' parameter
gpii.test.createProcessChecks = function (processList, expectedKey) {
var sequence = [];
// For each process, run the command, then check that we get the expected output
fluid.each(processList, function (process, pindex) {
sequence.push({
func: "{exec}.exec",
args: [
fluid.model.composeSegments("{tests}.options.processes", pindex),
fluid.model.composeSegments("{tests}.options.processes", pindex, expectedKey)
]
}, {
event: "{exec}.events.onExecExit",
listener: "gpii.test.onExecExit"
});
});
return sequence;
};
/** Expand material in a `gpii.test.common.testCaseHolder` fixture's options using the variableResolver fished out of the real implementation,
* and place it at a public member for the assertions to use
* @param testCaseHolder {gpii.test.common.testCaseHolder} a testCaseHolder with some expandable material in its options
* @param members {String|Array of String} one or more paths in the options to be expanded
* @return *side-effect* - expanded material is placed at top-level in the supplied `testCaseHolder` at the paths given in the `members` argument
*/
gpii.test.expandSettings = function (testCaseHolder, members) {
members = fluid.makeArray(members);
fluid.each(members, function (val) {
testCaseHolder[val] = testCaseHolder.variableResolver.resolve(testCaseHolder.options[val]);
});
};
// TODO: remove these clumsy constants once https://issues.fluidproject.org/browse/FLUID-5903 is implemented
gpii.test.initialSequence = fluid.freezeRecursive([
{
func: "gpii.test.expandSettings",
args: [ "{tests}", "settingsHandlers" ]
}, {
func: "gpii.test.snapshotSettings",
args: ["{tests}.settingsHandlers", "{tests}.settingsStore", "{nameResolver}", "{testCaseHolder}.events.onSnapshotComplete.fire"]
}, {
event: "{testCaseHolder}.events.onSnapshotComplete",
listener: "fluid.identity"
}
]);
gpii.test.loginSequence = fluid.freezeRecursive([
{
func: "{loginRequest}.send"
}, {
event: "{loginRequest}.events.onComplete",
listener: "gpii.test.loginRequestListen"
}, {
func: "gpii.test.checkConfiguration",
args: ["{tests}.settingsHandlers", "{nameResolver}", "{testCaseHolder}.events.onCheckConfigurationComplete.fire"]
}, {
event: "{testCaseHolder}.events.onCheckConfigurationComplete",
listener: "fluid.identity"
}
]);
gpii.test.logoutSequence = fluid.freezeRecursive([
{
func: "{logoutRequest}.send"
}, {
event: "{logoutRequest}.events.onComplete",
listener: "gpii.test.logoutRequestListen"
}
]);
gpii.test.checkSequence = fluid.freezeRecursive([
{
func: "gpii.test.checkRestoredConfiguration",
args: ["{tests}.settingsHandlers", "{tests}.settingsStore", "{nameResolver}", "{testCaseHolder}.events.onCheckRestoredConfigurationComplete.fire"]
}, {
event: "{testCaseHolder}.events.onCheckRestoredConfigurationComplete",
listener: "fluid.identity"
}
]);
gpii.test.unshift = function (array, elements) {
array.unshift.apply(array, elements);
};
gpii.test.push = function (array, elements) {
array.push.apply(array, elements);
};
/** Build a test fixture for integration/acceptance tests operating the stereotypical workflow -
* snapshot, login, expectConfigured, logout and expectRestored
*/
gpii.test.buildSingleTestFixture = function (testDef, rootGrades) {
var processes = testDef.processes || [];
testDef.gradeNames = fluid.makeArray(testDef.gradeNames).concat(fluid.makeArray(rootGrades));
testDef.expect = 4 + processes.length * 2;
testDef.sequence = fluid.makeArray(testDef.sequence);
gpii.test.unshift(testDef.sequence, gpii.test.loginSequence);
gpii.test.unshift(testDef.sequence, gpii.test.initialSequence);
// For each process, run the command, then check that we get the expected output
testDef.sequence = testDef.sequence.concat(gpii.test.createProcessChecks(processes, "expectConfigured"));
gpii.test.push(testDef.sequence, gpii.test.logoutSequence);
// Check that the processes are in the expected state after logout
testDef.sequence = testDef.sequence.concat(gpii.test.createProcessChecks(processes, "expectRestored"));
gpii.test.push(testDef.sequence, gpii.test.checkSequence);
return testDef;
};
/** Build a fixture set suitable for sending to kettle.test.bootstrapServer that includes a non-flat
* array of sequences within the member `sequenceSegments` as well as a base record to be merged into each testDef
* @param fixtures {Array} An array of proto-testDefs, each members `name` and `expect` with the same semantic
* as a standard testDefa, and a member `sequenceSegments` whose elements may themselves be arrays of sequences
* @param baseTestDef {TestDef} A base test def record, holding members `configName`, `configPath` and other
* members appropriate for this options structure
*/
// TODO: Review that we shouldn't use gradeNames and unify with buildSingleTestFixture's "rootGrades" pattern
gpii.test.buildSegmentedFixtures = function (fixtures, baseTestDef) {
return fluid.transform(fixtures, function (fixture) {
var overlay = {
name: fixture.name,
expect: fixture.expect,
sequence: fluid.flatten(fixture.sequenceSegments)
};
return fluid.extend(true, {}, baseTestDef, overlay);
});
};
// Convert a record as returned by a "portable test" into a full testDefs structure as accepted by gpii.test.buildTests
// TODO better docs and explanation
gpii.test.recordToTestDefs = function (record) {
var testDefs = fluid.copy(fluid.getGlobalValue(record.testDefs));
fluid.each(testDefs, function (testDef) {
testDef.config = {
configName: record.configName,
configPath: record.configPath
};
});
return testDefs;
};
gpii.test.runTests = function (record, rootGrades) {
var testDefs = gpii.test.recordToTestDefs(record);
var testDefs2 = gpii.test.buildTests(testDefs, rootGrades);
return kettle.test.bootstrapServer(testDefs2);
};
// Run from the base of every platform-specific acceptance/integration test fixture file as its per-file bootstrap.
// The long argument list is required in order to detect whether the file is being run as a top-level
// node executable - if it is, we default to running it as an integration test - otherwise, we just
// return its record.
gpii.test.bootstrap = function (record, rootGrades, foreignModule, foreignRequire) {
Iif (foreignRequire.main === foreignModule) { // the file was executed directly from the command line - run integration tests immediately
return gpii.test.runTests(record, rootGrades);
} else { // otherwise just return its record for processing
return record;
}
};
gpii.test.buildTests = function (testDefs, rootGrades) {
return fluid.transform(fluid.copy(testDefs), function (testDef) {
return gpii.test.buildSingleTestFixture(testDef, rootGrades);
});
};
/** Runs a suite of integration or acceptance tests as indexed by a platform-specific root
* such as "index-windows.js".
* @param files {Array} the array of test fixture files, as returned by the index module
* @param baseDir {String} the base directory holding the index module
* @param rootGrades {Array} an array of grade names to be contributed to the component root
* (currently testCaseHolder) of the fixtures. This controls the variety of test which is executed -
* e.g. a mocked Windows environment integration test, or a full acceptance test (the default)
*/
gpii.test.runSuite = function (files, baseDir, rootGrades) {
fluid.log("Running test suites:\n", JSON.stringify(files, null, 2));
fluid.each(files, function (oneFile) {
var filePath = path.resolve(baseDir, "platform", oneFile);
var record = require(filePath);
gpii.test.runTests(record, rootGrades);
});
};
// simple utility to select a set of test suites to run based on presence of substrings in their names
// these are ANDed together - i.e. they must each appear in a selected suite's name
gpii.test.filterSuites = function (files, specs) {
fluid.each(specs, function (spec) {
files = fluid.remove_if(fluid.copy(files), function (file) {
return file.indexOf(spec) === -1;
});
});
return files;
};
gpii.test.filterSuitesByArgs = function (files, args) {
return args.length === 2 ? files : gpii.test.filterSuites(files, args.slice(2));
};
gpii.test.runSuitesWithFiltering = function (files, baseDir, rootGrades) {
var filtered = gpii.test.filterSuitesByArgs(files, process.argv);
gpii.test.runSuite(filtered, baseDir, rootGrades);
};
|