isbuffer.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var test = require('tape');
  2. var mdeps = require('module-deps');
  3. var bpack = require('browser-pack');
  4. var insert = require('../');
  5. var concat = require('concat-stream');
  6. var vm = require('vm');
  7. // use is-buffer instead of builtin Buffer.isBuffer. The builtin
  8. // does `instanceof` which does not work on the browserified version
  9. var isBuffer = require('is-buffer');
  10. test('isbuffer', function (t) {
  11. t.plan(5);
  12. var deps = mdeps()
  13. var pack = bpack({ raw: true, hasExports: true });
  14. deps.pipe(pack).pipe(concat(function (src) {
  15. var c = { global: {} };
  16. vm.runInNewContext(src, c);
  17. t.equal(c.require('main')(Buffer('wow')), true, 'is a buffer');
  18. t.equal(c.require('main')('wow'), false, 'not a buffer (string)');
  19. t.equal(c.require('main')({}), false, 'not a buffer (object)');
  20. t.notOk(/require\("buffer"\)/.test(src), 'buffer not required in source')
  21. t.notOk(/require\("\//.test(src), 'absolute path not required in source')
  22. }));
  23. deps.write({ transform: inserter, global: true });
  24. deps.end({ id: 'main', file: __dirname + '/isbuffer/main.js' });
  25. });
  26. test('isbuffer (and Buffer.from)', function (t) {
  27. t.plan(5);
  28. var deps = mdeps()
  29. var pack = bpack({ raw: true, hasExports: true });
  30. deps.pipe(pack).pipe(concat(function (src) {
  31. var c = { global: {} };
  32. vm.runInNewContext(src, c);
  33. t.equal(c.require('main')(c.require('main').a()), true, 'is a buffer');
  34. t.equal(c.require('main')('wow'), false, 'is not a buffer');
  35. t.equal(isBuffer(c.require('main').a()), true, 'is a buffer');
  36. t.ok(/require\("buffer"\)/.test(src), 'buffer required in source')
  37. t.equal(c.require('main').a().toString('hex'), 'abcd', 'is a buffer');
  38. }));
  39. deps.write({ transform: inserter, global: true });
  40. deps.end({ id: 'main', file: __dirname + '/isbuffer/both.js' });
  41. });
  42. test('isbuffer (and new Buffer)', function (t) {
  43. t.plan(5);
  44. var deps = mdeps()
  45. var pack = bpack({ raw: true, hasExports: true });
  46. deps.pipe(pack).pipe(concat(function (src) {
  47. var c = { global: {} };
  48. vm.runInNewContext(src, c);
  49. t.equal(c.require('main')(c.require('main').a()), true, 'is a buffer');
  50. t.equal(c.require('main')('wow'), false, 'is not a buffer');
  51. t.equal(isBuffer(c.require('main').a()), true, 'is a buffer');
  52. t.ok(/require\("buffer"\)/.test(src), 'buffer required in source')
  53. t.equal(c.require('main').a().toString('utf8'), 'abcd', 'is a buffer');
  54. }));
  55. deps.write({ transform: inserter, global: true });
  56. deps.end({ id: 'main', file: __dirname + '/isbuffer/new.js' });
  57. });
  58. function inserter (file) {
  59. return insert(file, { basedir: __dirname + '/isbuffer' });
  60. }