raspberryGPIOhtmlserver/node_modules/formidable/test/legacy/integration/test-multipart-parser.js
node_modules/formidable/test/legacy/integration/test-multipart-parser.jsRaw
1var common = require('../common');
2var CHUNK_LENGTH = 10,
3 multipartParser = require(common.lib + '/multipart_parser'),
4 MultipartParser = multipartParser.MultipartParser,
5 parser = new MultipartParser(),
6 fixtures = require(TEST_FIXTURES + '/multipart'),
7 Buffer = require('buffer').Buffer;
8
9Object.keys(fixtures).forEach(function(name) {
10 var fixture = fixtures[name],
11 buffer = new Buffer(Buffer.byteLength(fixture.raw, 'binary')),
12 offset = 0,
13 chunk,
14 nparsed,
15
16 parts = [],
17 part = null,
18 headerField,
19 headerValue,
20 endCalled = '';
21
22 parser.initWithBoundary(fixture.boundary);
23 parser.onPartBegin = function() {
24 part = {headers: {}, data: ''};
25 parts.push(part);
26 headerField = '';
27 headerValue = '';
28 };
29
30 parser.onHeaderField = function(b, start, end) {
31 headerField += b.toString('ascii', start, end);
32 };
33
34 parser.onHeaderValue = function(b, start, end) {
35 headerValue += b.toString('ascii', start, end);
36 }
37
38 parser.onHeaderEnd = function() {
39 part.headers[headerField] = headerValue;
40 headerField = '';
41 headerValue = '';
42 };
43
44 parser.onPartData = function(b, start, end) {
45 var str = b.toString('ascii', start, end);
46 part.data += b.slice(start, end);
47 }
48
49 parser.onEnd = function() {
50 endCalled = true;
51 }
52
53 buffer.write(fixture.raw, 'binary', 0);
54
55 while (offset < buffer.length) {
56 if (offset + CHUNK_LENGTH < buffer.length) {
57 chunk = buffer.slice(offset, offset+CHUNK_LENGTH);
58 } else {
59 chunk = buffer.slice(offset, buffer.length);
60 }
61 offset = offset + CHUNK_LENGTH;
62
63 nparsed = parser.write(chunk);
64 if (nparsed != chunk.length) {
65 if (fixture.expectError) {
66 return;
67 }
68 puts('-- ERROR --');
69 p(chunk.toString('ascii'));
70 throw new Error(chunk.length+' bytes written, but only '+nparsed+' bytes parsed!');
71 }
72 }
73
74 if (fixture.expectError) {
75 throw new Error('expected parse error did not happen');
76 }
77
78 assert.ok(endCalled);
79 assert.deepEqual(parts, fixture.parts);
80});