-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
build-test-vectors-fixture.js
107 lines (96 loc) · 2.85 KB
/
build-test-vectors-fixture.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
const { Buffer } = require('buffer');
const {
readdirSync,
readFileSync,
writeFileSync,
} = require('fs');
const {
dirname,
join,
} = require('path');
const HEADER_TYPES = [
'boolean',
'boolean',
'byte',
'short',
'integer',
'long',
'binary',
'string',
'timestamp',
'uuid',
];
const vectorsDir = join(dirname(__dirname), 'test_vectors');
let vectors = '';
for (const dirName of ['positive', 'negative']) {
const encodedVectorsDir = join(vectorsDir, 'encoded', dirName);
const decodedVectorsDir = join(vectorsDir, 'decoded', dirName);
for (const vectorName of readdirSync(encodedVectorsDir)) {
vectors +=
` ${vectorName}: {
expectation: '${dirName === 'positive' ? 'success' : 'failure'}',
encoded: toBuffer([${
readFileSync(join(encodedVectorsDir, vectorName))
.map(byte => byte.toString(10))
.join(', ')
}]),
`;
if (dirName === 'positive') {
const decoded = JSON.parse(
readFileSync(join(decodedVectorsDir, vectorName))
);
const headers = decoded.headers
.map(declaration =>
` '${declaration.name}': {
type: '${HEADER_TYPES[declaration.type]}',
value: ${headerValue(declaration.type, declaration.value)},
},`
)
.join('\n');
vectors +=
` decoded: {
headers: {
${headers}
},
body: ${writeBuffer(Buffer.from(decoded.payload, 'base64'))},
},
`;
}
vectors += ' },\n';
}
}
writeFileSync(
join(dirname(__dirname), 'test-vectors.fixture.js'),
`var Int64 = require('../../lib/event-stream/int64').Int64;
var toBuffer = require('../../lib/event-stream/to-buffer').toBuffer;
module.exports = {
vectors: {
${vectors.trim()}
}
};
`
);
function headerValue(type, vectorRepresentation) {
switch (type) {
case 0:
return 'true';
case 1:
return 'false';
case 5:
return `Int64.fromNumber(${vectorRepresentation})`;
case 6:
return writeBuffer(Buffer.from(vectorRepresentation, 'base64'));
case 7:
return `'${Buffer.from(vectorRepresentation, 'base64').toString()}'`;
case 8:
return `new Date(${vectorRepresentation})`;
case 9:
const hex = Buffer.from(vectorRepresentation, 'base64').toString('hex');
return `'${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}'`;
default:
return vectorRepresentation;
}
}
function writeBuffer(buffer) {
return `toBuffer([${buffer.map(byte => byte.toString(10)).join(', ')}])`;
}