You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.0 KiB

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