forked from digitalbazaar/rdf-canonize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conformance-test.js
409 lines (369 loc) · 9.89 KB
/
conformance-test.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
/**
* Test runner for rdf-canonize.
*
* @author Dave Longley
*
* Copyright (c) 2016 Digital Bazaar, Inc. All rights reserved.
*/
(function() {
'use strict';
// detect node.js (vs. phantomJS)
const _nodejs = (typeof process !== 'undefined' &&
process.versions && process.versions.node);
const fs = require('fs');
let program;
let assert;
let path;
if(_nodejs) {
path = require('path');
assert = require('assert');
/*
program = require('commander');
program
.option('--earl [filename]', 'Output an earl report')
.option('--bail', 'Bail when a test fails')
.option('--test-dir', 'Test directory')
.parse(process.argv);
*/
program = {};
program.earl = process.env.EARL;
program.bail = process.env.BAIL === 'true';
program.testDir = process.env.TEST_DIR;
} else {
const system = require('system');
require('./setImmediate');
window.Promise = require('es6-promise').Promise;
assert = require('chai').assert;
require('mocha/mocha');
require('mocha-phantomjs/lib/mocha-phantomjs/core_extensions');
program = {};
for(let i = 0; i < system.args.length; ++i) {
const arg = system.args[i];
if(arg.indexOf('--') === 0) {
const argname = arg.substr(2);
switch(argname) {
case 'earl':
program[argname] = system.args[i + 1];
++i;
break;
default:
program[argname] = true;
}
}
}
mocha.setup({
reporter: 'spec',
ui: 'bdd'
});
}
const canonize = require('.');
const EarlReport = require('./EarlReport');
const NQuads = require('./lib/NQuads');
const _TEST_SUITE_PATHS = [
program['testDir'],
'../normalization/tests',
'./test-suites/normalization/tests',
];
const TEST_SUITE = _TEST_SUITE_PATHS.find(pathExists);
if(!TEST_SUITE) {
throw new Error('Test suite not found.');
}
const ROOT_MANIFEST_DIR = resolvePath(TEST_SUITE);
const TEST_TYPES = {
'rdfn:Urgna2012EvalTest': {
params: [
parseNQuads(readTestNQuads('action')),
createTestOptions({
algorithm: 'URGNA2012',
inputFormat: 'application/nquads',
format: 'application/nquads'
})
],
compare: compareExpectedNQuads
},
'rdfn:Urdna2015EvalTest': {
params: [
parseNQuads(readTestNQuads('action')),
createTestOptions({
algorithm: 'URDNA2015',
inputFormat: 'application/nquads',
format: 'application/nquads'
})
],
compare: compareExpectedNQuads
},
};
const SKIP_TESTS = [];
// create earl report
const earl = new EarlReport(_nodejs ? 'node.js' : 'browser');
// run tests
describe('rdf-canonize', function() {
const filename = joinPath(ROOT_MANIFEST_DIR, 'manifest.jsonld');
const rootManifest = readJson(filename);
rootManifest.filename = filename;
addManifest(rootManifest);
if(program.earl) {
const filename = resolvePath(program.earl);
describe('Writing EARL report to: ' + filename, function() {
it('should print the earl report', function(done) {
earl.write(filename);
done();
});
});
}
});
if(!_nodejs) {
mocha.run(() => phantom.exit());
}
/**
* Adds the tests for all entries in the given manifest.
*
* @param manifest the manifest.
*/
function addManifest(manifest) {
describe(manifest.name || manifest.label, function() {
// get entries and sequence (alias for entries)
const entries = [].concat(
getJsonLdValues(manifest, 'entries'),
getJsonLdValues(manifest, 'sequence')
);
const includes = getJsonLdValues(manifest, 'include');
// add includes to sequence as jsonld files
for(let i = 0; i < includes.length; ++i) {
entries.push(includes[i] + '.jsonld');
}
// process entries
for(let i = 0; i < entries.length; ++i) {
const entry = readManifestEntry(manifest, entries[i]);
if(isJsonLdType(entry, 'mf:Manifest')) {
// entry is another manifest
addManifest(entry);
} else {
// assume entry is a test
addTest(manifest, entry);
}
}
});
}
function addTest(manifest, test) {
// skip unknown and explicitly skipped test types
const testTypes = Object.keys(TEST_TYPES);
if(!isJsonLdType(test, testTypes) || isJsonLdType(test, SKIP_TESTS)) {
const type = [].concat(
getJsonLdValues(test, '@type'),
getJsonLdValues(test, 'type')
);
console.log('Skipping test "' + test.name + '" of type: ' + type);
}
// expand @id and input base
const test_id = test['@id'] || test['id'];
test['@id'] = manifest.baseIri + basename(manifest.filename) + test_id;
test.base = manifest.baseIri + test.input;
test.manifest = manifest;
const description = test_id + ' ' + (test.purpose || test.name);
const testInfo = TEST_TYPES[getTestType(test)];
const params = testInfo.params.map(param => param(test));
// custom params for js only async mode
const jsParams = testInfo.params.map(param => param(test));
jsParams[1].usePureJavaScript = true;
// custom params for native only async mode (if available)
const nativeParams = testInfo.params.map(param => param(test));
nativeParams[1].usePureJavaScript = false;
const createCallback = done => (err, result) => {
try {
if(err) {
throw err;
}
testInfo.compare(test, result);
earl.addAssertion(test, true);
return done();
} catch(ex) {
if(program.bail) {
if(ex.name !== 'AssertionError') {
console.log('\nError: ', JSON.stringify(ex, null, 2));
}
if(_nodejs) {
process.exit();
} else {
phantom.exit();
}
}
earl.addAssertion(test, false);
return done(ex);
}
};
// run async js test
it(description + ' (asynchronous js)', function(done) {
this.timeout(5000);
const callback = createCallback(done);
const promise = canonize.canonize.apply(null, jsParams);
promise.then(callback.bind(null, null), callback);
});
if(params[1].algorithm === 'URDNA2015') {
// run async native test
it(description + ' (asynchronous native)', function(done) {
this.timeout(5000);
const callback = createCallback(done);
const promise = canonize.canonize.apply(null, nativeParams);
promise.then(callback.bind(null, null), callback);
});
}
// run sync test
it(description + ' (synchronous js)', function(done) {
this.timeout(5000);
const callback = createCallback(done);
let result;
try {
result = canonize.canonizeSync.apply(null, jsParams);
} catch(e) {
return callback(e);
}
callback(null, result);
});
if(params[1].algorithm === 'URDNA2015') {
// run sync test
it(description + ' (synchronous native)', function(done) {
this.timeout(5000);
const callback = createCallback(done);
let result;
try {
result = canonize.canonizeSync.apply(null, nativeParams);
} catch(e) {
return callback(e);
}
callback(null, result);
});
}
}
function getTestType(test) {
const types = Object.keys(TEST_TYPES);
for(let i = 0; i < types.length; ++i) {
if(isJsonLdType(test, types[i])) {
return types[i];
}
}
return null;
}
function readManifestEntry(manifest, entry) {
const dir = dirname(manifest.filename);
if(typeof entry === 'string') {
const filename = joinPath(dir, entry);
entry = readJson(filename);
entry.filename = filename;
}
entry.dirname = dirname(entry.filename || manifest.filename);
return entry;
}
function readTestNQuads(property) {
return test => {
if(!test[property]) {
return null;
}
const filename = joinPath(test.dirname, test[property]);
return readFile(filename);
};
}
function parseNQuads(fn) {
return test => NQuads.parse(fn(test));
}
function createTestOptions(opts) {
return test => {
const testOptions = test.option || {};
const options = Object.assign({}, testOptions);
if(opts) {
// extend options
Object.assign(options, opts);
}
return options;
};
}
// find the expected output property or throw error
function _getExpectProperty(test) {
if('expect' in test) {
return 'expect';
} else if('result' in test) {
return 'result';
} else {
throw Error('No expected output property found');
}
}
function compareExpectedNQuads(test, result) {
let expect;
try {
expect = readTestNQuads(_getExpectProperty(test))(test);
assert.equal(result, expect);
} catch(ex) {
if(program.bail) {
console.log('\nTEST FAILED\n');
console.log('EXPECTED:\n' + expect);
console.log('ACTUAL:\n' + result);
}
throw ex;
}
}
function isJsonLdType(node, type) {
const nodeType = [].concat(
getJsonLdValues(node, '@type'),
getJsonLdValues(node, 'type')
);
type = Array.isArray(type) ? type : [type];
for(let i = 0; i < type.length; ++i) {
if(nodeType.indexOf(type[i]) !== -1) {
return true;
}
}
return false;
}
function getJsonLdValues(node, property) {
let rval = [];
if(property in node) {
rval = [].concat(node[property]);
}
return rval;
}
function readJson(filename) {
return JSON.parse(readFile(filename));
}
function pathExists(filename) {
if(_nodejs) {
return fs.existsSync(filename);
}
return fs.exists(filename);
}
function readFile(filename) {
if(_nodejs) {
return fs.readFileSync(filename, 'utf8');
}
return fs.read(filename);
}
function resolvePath(to) {
if(_nodejs) {
return path.resolve(to);
}
return fs.absolute(to);
}
function joinPath() {
return (_nodejs ? path : fs).join.apply(
null, Array.prototype.slice.call(arguments));
}
function dirname(filename) {
if(_nodejs) {
return path.dirname(filename);
}
const idx = filename.lastIndexOf(fs.separator);
if(idx === -1) {
return filename;
}
return filename.substr(0, idx);
}
function basename(filename) {
if(_nodejs) {
return path.basename(filename);
}
const idx = filename.lastIndexOf(fs.separator);
if(idx === -1) {
return filename;
}
return filename.substr(idx + 1);
}
})();